3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
30 * Removes <noinclude> sections, and <includeonly> tags.
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
50 * Update this version number when the ParserOutput format
51 * changes in an incompatible way, so the parser cache
52 * can automatically discard old data.
54 const VERSION
= '1.6.4';
56 # Flags for Parser::setFunctionHook
57 # Also available as global constants from Defines.php
58 const SFH_NO_HASH
= 1;
59 const SFH_OBJECT_ARGS
= 2;
61 # Constants needed for external link processing
62 # Everything except bracket, space, or control characters
63 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
64 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
65 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
67 # State constants for the definition list colon extraction
68 const COLON_STATE_TEXT
= 0;
69 const COLON_STATE_TAG
= 1;
70 const COLON_STATE_TAGSTART
= 2;
71 const COLON_STATE_CLOSETAG
= 3;
72 const COLON_STATE_TAGSLASH
= 4;
73 const COLON_STATE_COMMENT
= 5;
74 const COLON_STATE_COMMENTDASH
= 6;
75 const COLON_STATE_COMMENTDASHDASH
= 7;
77 # Flags for preprocessToDom
78 const PTD_FOR_INCLUSION
= 1;
80 # Allowed values for $this->mOutputType
81 # Parameter to startExternalParse().
82 const OT_HTML
= 1; # like parse()
83 const OT_WIKI
= 2; # like preSaveTransform()
84 const OT_PREPROCESS
= 3; # like preprocess()
86 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
88 # Marker Suffix needs to be accessible staticly.
89 const MARKER_SUFFIX
= "-QINU\x7f";
92 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
93 var $mSubstWords, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex;
94 var $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList;
95 var $mVarCache, $mConf, $mFunctionTagHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; # empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; # number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions; # ParserOptions object
110 var $mTitle; # Title context, used for self-link rendering and similar things
111 var $mOutputType; # Output type, one of the OT_xxx constants
112 var $ot; # Shortcut alias, see setOutputType()
113 var $mRevisionId; # ID to display in {{REVISIONID}} tags
114 var $mRevisionTimestamp; # The timestamp of the specified revision ID
115 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
122 function __construct( $conf = array() ) {
123 $this->mConf
= $conf;
124 $this->mTagHooks
= array();
125 $this->mTransparentTagHooks
= array();
126 $this->mFunctionHooks
= array();
127 $this->mFunctionTagHooks
= array();
128 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
129 $this->mDefaultStripList
= $this->mStripList
= array();
130 $this->mUrlProtocols
= wfUrlProtocols();
131 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
133 $this->mVarCache
= array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass
= $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'domxml' ) ) {
137 # PECL extension that conflicts with the core DOM extension (bug 13770)
138 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
139 $this->mPreprocessorClass
= 'Preprocessor_Hash';
140 } elseif ( extension_loaded( 'dom' ) ) {
141 $this->mPreprocessorClass
= 'Preprocessor_DOM';
143 $this->mPreprocessorClass
= 'Preprocessor_Hash';
145 $this->mMarkerIndex
= 0;
146 $this->mFirstCall
= true;
150 * Reduce memory usage to reduce the impact of circular references
152 function __destruct() {
153 if ( isset( $this->mLinkHolders
) ) {
154 $this->mLinkHolders
->__destruct();
156 foreach ( $this as $name => $value ) {
157 unset( $this->$name );
162 * Do various kinds of initialisation on the first call of the parser
164 function firstCallInit() {
165 if ( !$this->mFirstCall
) {
168 $this->mFirstCall
= false;
170 wfProfileIn( __METHOD__
);
172 CoreParserFunctions
::register( $this );
173 CoreTagHooks
::register( $this );
174 $this->initialiseVariables();
176 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
177 wfProfileOut( __METHOD__
);
185 function clearState() {
186 wfProfileIn( __METHOD__
);
187 if ( $this->mFirstCall
) {
188 $this->firstCallInit();
190 $this->mOutput
= new ParserOutput
;
191 $this->mAutonumber
= 0;
192 $this->mLastSection
= '';
193 $this->mDTopen
= false;
194 $this->mIncludeCount
= array();
195 $this->mStripState
= new StripState
;
196 $this->mArgStack
= false;
197 $this->mInPre
= false;
198 $this->mLinkHolders
= new LinkHolderArray( $this );
200 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
201 $this->mVarCache
= array();
204 * Prefix for temporary replacement strings for the multipass parser.
205 * \x07 should never appear in input as it's disallowed in XML.
206 * Using it at the front also gives us a little extra robustness
207 * since it shouldn't match when butted up against identifier-like
210 * Must not consist of all title characters, or else it will change
211 * the behaviour of <nowiki> in a link.
213 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
214 # Changed to \x7f to allow XML double-parsing -- TS
215 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
221 $this->mShowToc
= true;
222 $this->mForceTocPosition
= false;
223 $this->mIncludeSizes
= array(
227 $this->mPPNodeCount
= 0;
228 $this->mDefaultSort
= false;
229 $this->mHeadings
= array();
230 $this->mDoubleUnderscores
= array();
231 $this->mExpensiveFunctionCount
= 0;
234 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
235 $this->mPreprocessor
= null;
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
243 * Convert wikitext to HTML
244 * Do not call this function recursively.
246 * @param $text String: text we want to parse
247 * @param $title A title object
248 * @param $options ParserOptions
249 * @param $linestart boolean
250 * @param $clearState boolean
251 * @param $revid Int: number to pass in {{REVISIONID}}
252 * @return ParserOutput a ParserOutput
254 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
256 * First pass--just handle <nowiki> sections, pass the rest off
257 * to internalParse() which does all the real work.
260 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
261 $fname = __METHOD__
.'-' . wfGetCaller();
262 wfProfileIn( __METHOD__
);
263 wfProfileIn( $fname );
269 $this->mOptions
= $options;
270 $this->setTitle( $title ); # Page title has to be set for the pre-processor
272 $oldRevisionId = $this->mRevisionId
;
273 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
274 if ( $revid !== null ) {
275 $this->mRevisionId
= $revid;
276 $this->mRevisionTimestamp
= null;
278 $this->setOutputType( self
::OT_HTML
);
279 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
281 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
282 $text = $this->internalParse( $text );
284 $text = $this->mStripState
->unstripGeneral( $text );
286 # Clean up special characters, only run once, next-to-last before doBlockLevels
288 # french spaces, last one Guillemet-left
289 # only if there is something before the space
290 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
291 # french spaces, Guillemet-right
292 '/(\\302\\253) /' => '\\1 ',
293 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
295 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
297 $text = $this->doBlockLevels( $text, $linestart );
299 $this->replaceLinkHolders( $text );
302 * The page doesn't get language converted if
304 * b) Content isn't converted
305 * c) It's a conversion table
307 if ( !( $wgDisableLangConversion
308 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
309 ||
$this->mTitle
->isConversionTable() ) ) {
311 # The position of the convert() call should not be changed. it
312 # assumes that the links are all replaced and the only thing left
313 # is the <nowiki> mark.
315 $text = $wgContLang->convert( $text );
319 * A page get its title converted except:
320 * a) Language conversion is globally disabled
321 * b) Title convert is globally disabled
322 * c) The page is a redirect page
323 * d) User request with a "linkconvert" set to "no"
324 * e) A "nocontentconvert" magic word has been set
325 * f) A "notitleconvert" magic word has been set
326 * g) User sets "noconvertlink" in his/her preference
328 * Note that if a user tries to set a title in a conversion
329 * rule but content conversion was not done, then the parser
330 * won't pick it up. This is probably expected behavior.
332 if ( !( $wgDisableLangConversion
333 ||
$wgDisableTitleConversion
334 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
335 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
336 ||
$this->mOutput
->getDisplayTitle() !== false ) )
338 $convruletitle = $wgContLang->getConvRuleTitle();
339 if ( $convruletitle ) {
340 $this->mOutput
->setTitleText( $convruletitle );
342 $titleText = $wgContLang->convertTitle( $title );
343 $this->mOutput
->setTitleText( $titleText );
347 $text = $this->mStripState
->unstripNoWiki( $text );
349 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
351 //!JF Move to its own function
353 $uniq_prefix = $this->mUniqPrefix
;
355 $elements = array_keys( $this->mTransparentTagHooks
);
356 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
358 foreach ( $matches as $marker => $data ) {
359 list( $element, $content, $params, $tag ) = $data;
360 $tagName = strtolower( $element );
361 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
362 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
366 $this->mStripState
->general
->setPair( $marker, $output );
368 $text = $this->mStripState
->unstripGeneral( $text );
370 $text = Sanitizer
::normalizeCharReferences( $text );
372 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
373 $text = MWTidy
::tidy( $text );
375 # attempt to sanitize at least some nesting problems
376 # (bug #2702 and quite a few others)
378 # ''Something [http://www.cool.com cool''] -->
379 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
380 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
381 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
382 # fix up an anchor inside another anchor, only
383 # at least for a single single nested link (bug 3695)
384 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
385 '\\1\\2</a>\\3</a>\\1\\4</a>',
386 # fix div inside inline elements- doBlockLevels won't wrap a line which
387 # contains a div, so fix it up here; replace
388 # div with escaped text
389 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
390 '\\1\\3<div\\5>\\6</div>\\8\\9',
391 # remove empty italic or bold tag pairs, some
392 # introduced by rules above
393 '/<([bi])><\/\\1>/' => '',
396 $text = preg_replace(
397 array_keys( $tidyregs ),
398 array_values( $tidyregs ),
401 global $wgExpensiveParserFunctionLimit;
402 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
403 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
406 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
408 # Information on include size limits, for the benefit of users who try to skirt them
409 if ( $this->mOptions
->getEnableLimitReport() ) {
410 $max = $this->mOptions
->getMaxIncludeSize();
411 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
413 "NewPP limit report\n" .
414 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
415 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
416 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
418 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
419 $text .= "\n<!-- \n$limitReport-->\n";
421 $this->mOutput
->setText( $text );
423 $this->mRevisionId
= $oldRevisionId;
424 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
425 wfProfileOut( $fname );
426 wfProfileOut( __METHOD__
);
428 return $this->mOutput
;
432 * Recursive parser entry point that can be called from an extension tag
435 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
437 * @param $text String: text extension wants to have parsed
438 * @param $frame PPFrame: The frame to use for expanding any template variables
440 function recursiveTagParse( $text, $frame=false ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text, false, $frame );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if ( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Process the wikitext for the ?preload= feature. (bug 5210)
473 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
474 * comments, templates, arguments, tags hooks and parser functions are untouched.
476 public function getPreloadText( $text, $title, $options ) {
477 # Parser (re)initialisation
479 $this->setOutputType( self
::OT_PLAIN
);
480 $this->mOptions
= $options;
481 $this->setTitle( $title );
483 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
484 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
485 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
489 * Get a random string
494 function getRandomString() {
495 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
499 * Accessor for mUniqPrefix.
503 public function uniqPrefix() {
504 if ( !isset( $this->mUniqPrefix
) ) {
505 # @todo Fixme: this is probably *horribly wrong*
506 # LanguageConverter seems to want $wgParser's uniqPrefix, however
507 # if this is called for a parser cache hit, the parser may not
508 # have ever been initialized in the first place.
509 # Not really sure what the heck is supposed to be going on here.
511 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
513 return $this->mUniqPrefix
;
517 * Set the context title
519 function setTitle( $t ) {
520 if ( !$t ||
$t instanceof FakeTitle
) {
521 $t = Title
::newFromText( 'NO TITLE' );
524 if ( strval( $t->getFragment() ) !== '' ) {
525 # Strip the fragment to avoid various odd effects
526 $this->mTitle
= clone $t;
527 $this->mTitle
->setFragment( '' );
534 * Accessor for the Title object
536 * @return Title object
538 function &getTitle() {
539 return $this->mTitle
;
543 * Accessor/mutator for the Title object
545 * @param $x New Title object or null to just get the current one
546 * @return Title object
548 function Title( $x = null ) {
549 return wfSetVar( $this->mTitle
, $x );
553 * Set the output type
555 * @param $ot Integer: new value
557 function setOutputType( $ot ) {
558 $this->mOutputType
= $ot;
561 'html' => $ot == self
::OT_HTML
,
562 'wiki' => $ot == self
::OT_WIKI
,
563 'pre' => $ot == self
::OT_PREPROCESS
,
564 'plain' => $ot == self
::OT_PLAIN
,
569 * Accessor/mutator for the output type
571 * @param $x New value or null to just get the current one
574 function OutputType( $x = null ) {
575 return wfSetVar( $this->mOutputType
, $x );
579 * Get the ParserOutput object
581 * @return ParserOutput object
583 function getOutput() {
584 return $this->mOutput
;
588 * Get the ParserOptions object
590 * @return ParserOptions object
592 function getOptions() {
593 return $this->mOptions
;
597 * Accessor/mutator for the ParserOptions object
599 * @param $x New value or null to just get the current one
600 * @return Current ParserOptions object
602 function Options( $x = null ) {
603 return wfSetVar( $this->mOptions
, $x );
606 function nextLinkID() {
607 return $this->mLinkID++
;
610 function getFunctionLang() {
611 global $wgLang, $wgContLang;
613 $target = $this->mOptions
->getTargetLanguage();
614 if ( $target !== null ) {
617 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
622 * Get a preprocessor object
624 * @return Preprocessor instance
626 function getPreprocessor() {
627 if ( !isset( $this->mPreprocessor
) ) {
628 $class = $this->mPreprocessorClass
;
629 $this->mPreprocessor
= new $class( $this );
631 return $this->mPreprocessor
;
635 * Replaces all occurrences of HTML-style comments and the given tags
636 * in the text with a random marker and returns the next text. The output
637 * parameter $matches will be an associative array filled with data in
639 * 'UNIQ-xxxxx' => array(
642 * array( 'param' => 'x' ),
643 * '<element param="x">tag content</element>' ) )
645 * @param $elements list of element names. Comments are always extracted.
646 * @param $text Source text string.
647 * @param $matches Out parameter, Array: extarcted tags
648 * @param $uniq_prefix
649 * @return String: stripped text
653 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
658 $taglist = implode( '|', $elements );
659 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
661 while ( $text != '' ) {
662 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
664 if ( count( $p ) < 5 ) {
667 if ( count( $p ) > 5 ) {
681 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
682 $stripped .= $marker;
684 if ( $close === '/>' ) {
685 # Empty element tag, <tag />
690 if ( $element === '!--' ) {
693 $end = "/(<\\/$element\\s*>)/i";
695 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
697 if ( count( $q ) < 3 ) {
698 # No end tag -- let it run out to the end of the text.
707 $matches[$marker] = array( $element,
709 Sanitizer
::decodeTagAttributes( $attributes ),
710 "<$element$attributes$close$content$tail" );
716 * Get a list of strippable XML-like elements
718 function getStripList() {
719 return $this->mStripList
;
723 * @deprecated use replaceVariables
725 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
730 * Restores pre, math, and other extensions removed by strip()
732 * always call unstripNoWiki() after this one
734 * @deprecated use $this->mStripState->unstrip()
736 function unstrip( $text, $state ) {
737 return $state->unstripGeneral( $text );
741 * Always call this after unstrip() to preserve the order
744 * @deprecated use $this->mStripState->unstrip()
746 function unstripNoWiki( $text, $state ) {
747 return $state->unstripNoWiki( $text );
751 * @deprecated use $this->mStripState->unstripBoth()
753 function unstripForHTML( $text ) {
754 return $this->mStripState
->unstripBoth( $text );
758 * Add an item to the strip state
759 * Returns the unique tag which must be inserted into the stripped text
760 * The tag will be replaced with the original text in unstrip()
764 function insertStripItem( $text ) {
765 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
766 $this->mMarkerIndex++
;
767 $this->mStripState
->general
->setPair( $rnd, $text );
772 * Interface with html tidy
773 * @deprecated Use MWTidy::tidy()
775 public static function tidy( $text ) {
776 wfDeprecated( __METHOD__
);
777 return MWTidy
::tidy( $text );
781 * parse the wiki syntax used to render tables
785 function doTableStuff( $text ) {
786 wfProfileIn( __METHOD__
);
788 $lines = StringUtils
::explode( "\n", $text );
791 $td_history = array(); # Is currently a td tag open?
792 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
793 $tr_history = array(); # Is currently a tr tag open?
794 $tr_attributes = array(); # history of tr attributes
795 $has_opened_tr = array(); # Did this table open a <tr> element?
796 $indent_level = 0; # indent level of the table
798 foreach ( $lines as $outLine ) {
799 $line = trim( $outLine );
801 if ( $line === '' ) { # empty line, go to next line
802 $out .= $outLine."\n";
806 $first_character = $line[0];
809 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
810 # First check if we are starting a new table
811 $indent_level = strlen( $matches[1] );
813 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
814 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
816 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
817 array_push( $td_history , false );
818 array_push( $last_tag_history , '' );
819 array_push( $tr_history , false );
820 array_push( $tr_attributes , '' );
821 array_push( $has_opened_tr , false );
822 } elseif ( count( $td_history ) == 0 ) {
823 # Don't do any of the following
824 $out .= $outLine."\n";
826 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
827 # We are ending a table
828 $line = '</table>' . substr( $line , 2 );
829 $last_tag = array_pop( $last_tag_history );
831 if ( !array_pop( $has_opened_tr ) ) {
832 $line = "<tr><td></td></tr>{$line}";
835 if ( array_pop( $tr_history ) ) {
836 $line = "</tr>{$line}";
839 if ( array_pop( $td_history ) ) {
840 $line = "</{$last_tag}>{$line}";
842 array_pop( $tr_attributes );
843 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
844 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
845 # Now we have a table row
846 $line = preg_replace( '#^\|-+#', '', $line );
848 # Whats after the tag is now only attributes
849 $attributes = $this->mStripState
->unstripBoth( $line );
850 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
851 array_pop( $tr_attributes );
852 array_push( $tr_attributes, $attributes );
855 $last_tag = array_pop( $last_tag_history );
856 array_pop( $has_opened_tr );
857 array_push( $has_opened_tr , true );
859 if ( array_pop( $tr_history ) ) {
863 if ( array_pop( $td_history ) ) {
864 $line = "</{$last_tag}>{$line}";
868 array_push( $tr_history , false );
869 array_push( $td_history , false );
870 array_push( $last_tag_history , '' );
871 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
872 # This might be cell elements, td, th or captions
873 if ( substr( $line , 0 , 2 ) === '|+' ) {
874 $first_character = '+';
875 $line = substr( $line , 1 );
878 $line = substr( $line , 1 );
880 if ( $first_character === '!' ) {
881 $line = str_replace( '!!' , '||' , $line );
884 # Split up multiple cells on the same line.
885 # FIXME : This can result in improper nesting of tags processed
886 # by earlier parser steps, but should avoid splitting up eg
887 # attribute values containing literal "||".
888 $cells = StringUtils
::explodeMarkup( '||' , $line );
892 # Loop through each table cell
893 foreach ( $cells as $cell ) {
895 if ( $first_character !== '+' ) {
896 $tr_after = array_pop( $tr_attributes );
897 if ( !array_pop( $tr_history ) ) {
898 $previous = "<tr{$tr_after}>\n";
900 array_push( $tr_history , true );
901 array_push( $tr_attributes , '' );
902 array_pop( $has_opened_tr );
903 array_push( $has_opened_tr , true );
906 $last_tag = array_pop( $last_tag_history );
908 if ( array_pop( $td_history ) ) {
909 $previous = "</{$last_tag}>{$previous}";
912 if ( $first_character === '|' ) {
914 } elseif ( $first_character === '!' ) {
916 } elseif ( $first_character === '+' ) {
917 $last_tag = 'caption';
922 array_push( $last_tag_history , $last_tag );
924 # A cell could contain both parameters and data
925 $cell_data = explode( '|' , $cell , 2 );
927 # Bug 553: Note that a '|' inside an invalid link should not
928 # be mistaken as delimiting cell parameters
929 if ( strpos( $cell_data[0], '[[' ) !== false ) {
930 $cell = "{$previous}<{$last_tag}>{$cell}";
931 } elseif ( count( $cell_data ) == 1 ) {
932 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
934 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
935 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
936 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
940 array_push( $td_history , true );
943 $out .= $outLine . "\n";
946 # Closing open td, tr && table
947 while ( count( $td_history ) > 0 ) {
948 if ( array_pop( $td_history ) ) {
951 if ( array_pop( $tr_history ) ) {
954 if ( !array_pop( $has_opened_tr ) ) {
955 $out .= "<tr><td></td></tr>\n" ;
958 $out .= "</table>\n";
961 # Remove trailing line-ending (b/c)
962 if ( substr( $out, -1 ) === "\n" ) {
963 $out = substr( $out, 0, -1 );
966 # special case: don't return empty table
967 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
971 wfProfileOut( __METHOD__
);
977 * Helper function for parse() that transforms wiki markup into
978 * HTML. Only called for $mOutputType == self::OT_HTML.
982 function internalParse( $text, $isMain = true, $frame=false ) {
983 wfProfileIn( __METHOD__
);
987 # Hook to suspend the parser in this state
988 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
989 wfProfileOut( __METHOD__
);
993 # if $frame is provided, then use $frame for replacing any variables
995 # use frame depth to infer how include/noinclude tags should be handled
996 # depth=0 means this is the top-level document; otherwise it's an included document
997 if ( !$frame->depth
) {
1000 $flag = Parser
::PTD_FOR_INCLUSION
;
1002 $dom = $this->preprocessToDom( $text, $flag );
1003 $text = $frame->expand( $dom );
1005 # if $frame is not provided, then use old-style replaceVariables
1006 $text = $this->replaceVariables( $text );
1009 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1010 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1012 # Tables need to come after variable replacement for things to work
1013 # properly; putting them before other transformations should keep
1014 # exciting things like link expansions from showing up in surprising
1016 $text = $this->doTableStuff( $text );
1018 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1020 $text = $this->doDoubleUnderscore( $text );
1022 $text = $this->doHeadings( $text );
1023 if ( $this->mOptions
->getUseDynamicDates() ) {
1024 $df = DateFormatter
::getInstance();
1025 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1027 $text = $this->doAllQuotes( $text );
1028 $text = $this->replaceInternalLinks( $text );
1029 $text = $this->replaceExternalLinks( $text );
1031 # replaceInternalLinks may sometimes leave behind
1032 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1033 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1035 $text = $this->doMagicLinks( $text );
1036 $text = $this->formatHeadings( $text, $origText, $isMain );
1038 wfProfileOut( __METHOD__
);
1043 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1044 * magic external links.
1049 function doMagicLinks( $text ) {
1050 wfProfileIn( __METHOD__
);
1051 $prots = $this->mUrlProtocols
;
1052 $urlChar = self
::EXT_LINK_URL_CLASS
;
1053 $text = preg_replace_callback(
1055 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1056 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1057 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1058 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1059 ISBN\s+(\b # m[5]: ISBN, capture number
1060 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1061 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1062 [0-9Xx] # check digit
1064 )!x', array( &$this, 'magicLinkCallback' ), $text );
1065 wfProfileOut( __METHOD__
);
1069 function magicLinkCallback( $m ) {
1070 if ( isset( $m[1] ) && $m[1] !== '' ) {
1073 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1076 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1077 # Free external link
1078 return $this->makeFreeExternalLink( $m[0] );
1079 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1082 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1085 $CssClass = 'mw-magiclink-rfc';
1087 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1089 $urlmsg = 'pubmedurl';
1090 $CssClass = 'mw-magiclink-pmid';
1093 throw new MWException( __METHOD__
.': unrecognised match type "' .
1094 substr( $m[0], 0, 20 ) . '"' );
1096 $url = wfMsg( $urlmsg, $id);
1097 $sk = $this->mOptions
->getSkin();
1098 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1099 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1100 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1103 $num = strtr( $isbn, array(
1108 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1110 $titleObj->escapeLocalUrl() .
1111 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1118 * Make a free external link, given a user-supplied URL
1122 function makeFreeExternalLink( $url ) {
1124 wfProfileIn( __METHOD__
);
1126 $sk = $this->mOptions
->getSkin();
1129 # The characters '<' and '>' (which were escaped by
1130 # removeHTMLtags()) should not be included in
1131 # URLs, per RFC 2396.
1133 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1134 $trail = substr( $url, $m2[0][1] ) . $trail;
1135 $url = substr( $url, 0, $m2[0][1] );
1138 # Move trailing punctuation to $trail
1140 # If there is no left bracket, then consider right brackets fair game too
1141 if ( strpos( $url, '(' ) === false ) {
1145 $numSepChars = strspn( strrev( $url ), $sep );
1146 if ( $numSepChars ) {
1147 $trail = substr( $url, -$numSepChars ) . $trail;
1148 $url = substr( $url, 0, -$numSepChars );
1151 $url = Sanitizer
::cleanUrl( $url );
1153 # Is this an external image?
1154 $text = $this->maybeMakeExternalImage( $url );
1155 if ( $text === false ) {
1156 # Not an image, make a link
1157 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1158 $this->getExternalLinkAttribs( $url ) );
1159 # Register it in the output object...
1160 # Replace unnecessary URL escape codes with their equivalent characters
1161 $pasteurized = self
::replaceUnusualEscapes( $url );
1162 $this->mOutput
->addExternalLink( $pasteurized );
1164 wfProfileOut( __METHOD__
);
1165 return $text . $trail;
1170 * Parse headers and return html
1174 function doHeadings( $text ) {
1175 wfProfileIn( __METHOD__
);
1176 for ( $i = 6; $i >= 1; --$i ) {
1177 $h = str_repeat( '=', $i );
1178 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1179 "<h$i>\\1</h$i>", $text );
1181 wfProfileOut( __METHOD__
);
1186 * Replace single quotes with HTML markup
1188 * @return string the altered text
1190 function doAllQuotes( $text ) {
1191 wfProfileIn( __METHOD__
);
1193 $lines = StringUtils
::explode( "\n", $text );
1194 foreach ( $lines as $line ) {
1195 $outtext .= $this->doQuotes( $line ) . "\n";
1197 $outtext = substr( $outtext, 0,-1 );
1198 wfProfileOut( __METHOD__
);
1203 * Helper function for doAllQuotes()
1205 public function doQuotes( $text ) {
1206 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1207 if ( count( $arr ) == 1 ) {
1210 # First, do some preliminary work. This may shift some apostrophes from
1211 # being mark-up to being text. It also counts the number of occurrences
1212 # of bold and italics mark-ups.
1216 foreach ( $arr as $r ) {
1217 if ( ( $i %
2 ) == 1 ) {
1218 # If there are ever four apostrophes, assume the first is supposed to
1219 # be text, and the remaining three constitute mark-up for bold text.
1220 if ( strlen( $arr[$i] ) == 4 ) {
1223 } elseif ( strlen( $arr[$i] ) > 5 ) {
1224 # If there are more than 5 apostrophes in a row, assume they're all
1225 # text except for the last 5.
1226 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1229 # Count the number of occurrences of bold and italics mark-ups.
1230 # We are not counting sequences of five apostrophes.
1231 if ( strlen( $arr[$i] ) == 2 ) {
1233 } elseif ( strlen( $arr[$i] ) == 3 ) {
1235 } elseif ( strlen( $arr[$i] ) == 5 ) {
1243 # If there is an odd number of both bold and italics, it is likely
1244 # that one of the bold ones was meant to be an apostrophe followed
1245 # by italics. Which one we cannot know for certain, but it is more
1246 # likely to be one that has a single-letter word before it.
1247 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1249 $firstsingleletterword = -1;
1250 $firstmultiletterword = -1;
1252 foreach ( $arr as $r ) {
1253 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1254 $x1 = substr( $arr[$i-1], -1 );
1255 $x2 = substr( $arr[$i-1], -2, 1 );
1256 if ( $x1 === ' ' ) {
1257 if ( $firstspace == -1 ) {
1260 } elseif ( $x2 === ' ') {
1261 if ( $firstsingleletterword == -1 ) {
1262 $firstsingleletterword = $i;
1265 if ( $firstmultiletterword == -1 ) {
1266 $firstmultiletterword = $i;
1273 # If there is a single-letter word, use it!
1274 if ( $firstsingleletterword > -1 ) {
1275 $arr[$firstsingleletterword] = "''";
1276 $arr[$firstsingleletterword-1] .= "'";
1277 } elseif ( $firstmultiletterword > -1 ) {
1278 # If not, but there's a multi-letter word, use that one.
1279 $arr[$firstmultiletterword] = "''";
1280 $arr[$firstmultiletterword-1] .= "'";
1281 } elseif ( $firstspace > -1 ) {
1282 # ... otherwise use the first one that has neither.
1283 # (notice that it is possible for all three to be -1 if, for example,
1284 # there is only one pentuple-apostrophe in the line)
1285 $arr[$firstspace] = "''";
1286 $arr[$firstspace-1] .= "'";
1290 # Now let's actually convert our apostrophic mush to HTML!
1295 foreach ( $arr as $r ) {
1296 if ( ( $i %
2 ) == 0 ) {
1297 if ( $state === 'both' ) {
1303 if ( strlen( $r ) == 2 ) {
1304 if ( $state === 'i' ) {
1305 $output .= '</i>'; $state = '';
1306 } elseif ( $state === 'bi' ) {
1307 $output .= '</i>'; $state = 'b';
1308 } elseif ( $state === 'ib' ) {
1309 $output .= '</b></i><b>'; $state = 'b';
1310 } elseif ( $state === 'both' ) {
1311 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1312 } else { # $state can be 'b' or ''
1313 $output .= '<i>'; $state .= 'i';
1315 } elseif ( strlen( $r ) == 3 ) {
1316 if ( $state === 'b' ) {
1317 $output .= '</b>'; $state = '';
1318 } elseif ( $state === 'bi' ) {
1319 $output .= '</i></b><i>'; $state = 'i';
1320 } elseif ( $state === 'ib' ) {
1321 $output .= '</b>'; $state = 'i';
1322 } elseif ( $state === 'both' ) {
1323 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1324 } else { # $state can be 'i' or ''
1325 $output .= '<b>'; $state .= 'b';
1327 } elseif ( strlen( $r ) == 5 ) {
1328 if ( $state === 'b' ) {
1329 $output .= '</b><i>'; $state = 'i';
1330 } elseif ( $state === 'i' ) {
1331 $output .= '</i><b>'; $state = 'b';
1332 } elseif ( $state === 'bi' ) {
1333 $output .= '</i></b>'; $state = '';
1334 } elseif ( $state === 'ib' ) {
1335 $output .= '</b></i>'; $state = '';
1336 } elseif ( $state === 'both' ) {
1337 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1338 } else { # ($state == '')
1339 $buffer = ''; $state = 'both';
1345 # Now close all remaining tags. Notice that the order is important.
1346 if ( $state === 'b' ||
$state === 'ib' ) {
1349 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1352 if ( $state === 'bi' ) {
1355 # There might be lonely ''''', so make sure we have a buffer
1356 if ( $state === 'both' && $buffer ) {
1357 $output .= '<b><i>'.$buffer.'</i></b>';
1364 * Replace external links (REL)
1366 * Note: this is all very hackish and the order of execution matters a lot.
1367 * Make sure to run maintenance/parserTests.php if you change this code.
1371 function replaceExternalLinks( $text ) {
1373 wfProfileIn( __METHOD__
);
1375 $sk = $this->mOptions
->getSkin();
1377 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1378 $s = array_shift( $bits );
1381 while ( $i<count( $bits ) ) {
1383 $protocol = $bits[$i++
];
1384 $text = $bits[$i++
];
1385 $trail = $bits[$i++
];
1387 # The characters '<' and '>' (which were escaped by
1388 # removeHTMLtags()) should not be included in
1389 # URLs, per RFC 2396.
1391 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1392 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1393 $url = substr( $url, 0, $m2[0][1] );
1396 # If the link text is an image URL, replace it with an <img> tag
1397 # This happened by accident in the original parser, but some people used it extensively
1398 $img = $this->maybeMakeExternalImage( $text );
1399 if ( $img !== false ) {
1405 # Set linktype for CSS - if URL==text, link is essentially free
1406 $linktype = ( $text === $url ) ?
'free' : 'text';
1408 # No link text, e.g. [http://domain.tld/some.link]
1409 if ( $text == '' ) {
1410 # Autonumber if allowed. See bug #5918
1411 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1412 $langObj = $this->getFunctionLang();
1413 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1414 $linktype = 'autonumber';
1416 # Otherwise just use the URL
1417 $text = htmlspecialchars( $url );
1421 # Have link text, e.g. [http://domain.tld/some.link text]s
1423 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1426 $text = $wgContLang->markNoConversion( $text );
1428 $url = Sanitizer
::cleanUrl( $url );
1430 # Use the encoded URL
1431 # This means that users can paste URLs directly into the text
1432 # Funny characters like ö aren't valid in URLs anyway
1433 # This was changed in August 2004
1434 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1435 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1437 # Register link in the output object.
1438 # Replace unnecessary URL escape codes with the referenced character
1439 # This prevents spammers from hiding links from the filters
1440 $pasteurized = self
::replaceUnusualEscapes( $url );
1441 $this->mOutput
->addExternalLink( $pasteurized );
1444 wfProfileOut( __METHOD__
);
1449 * Get an associative array of additional HTML attributes appropriate for a
1450 * particular external link. This currently may include rel => nofollow
1451 * (depending on configuration, namespace, and the URL's domain) and/or a
1452 * target attribute (depending on configuration).
1454 * @param $url String: optional URL, to extract the domain from for rel =>
1455 * nofollow if appropriate
1456 * @return Array: associative array of HTML attributes
1458 function getExternalLinkAttribs( $url = false ) {
1460 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1461 $ns = $this->mTitle
->getNamespace();
1462 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1463 $attribs['rel'] = 'nofollow';
1465 global $wgNoFollowDomainExceptions;
1466 if ( $wgNoFollowDomainExceptions ) {
1467 $bits = wfParseUrl( $url );
1468 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1469 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1470 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1471 unset( $attribs['rel'] );
1478 if ( $this->mOptions
->getExternalLinkTarget() ) {
1479 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1486 * Replace unusual URL escape codes with their equivalent characters
1488 * @param $url String
1491 * @todo This can merge genuinely required bits in the path or query string,
1492 * breaking legit URLs. A proper fix would treat the various parts of
1493 * the URL differently; as a workaround, just use the output for
1494 * statistical records, not for actual linking/output.
1496 static function replaceUnusualEscapes( $url ) {
1497 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1498 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1502 * Callback function used in replaceUnusualEscapes().
1503 * Replaces unusual URL escape codes with their equivalent character
1505 private static function replaceUnusualEscapesCallback( $matches ) {
1506 $char = urldecode( $matches[0] );
1507 $ord = ord( $char );
1508 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1509 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1510 # No, shouldn't be escaped
1513 # Yes, leave it escaped
1519 * make an image if it's allowed, either through the global
1520 * option, through the exception, or through the on-wiki whitelist
1523 function maybeMakeExternalImage( $url ) {
1524 $sk = $this->mOptions
->getSkin();
1525 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1526 $imagesexception = !empty( $imagesfrom );
1528 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1529 if ( $imagesexception && is_array( $imagesfrom ) ) {
1530 $imagematch = false;
1531 foreach ( $imagesfrom as $match ) {
1532 if ( strpos( $url, $match ) === 0 ) {
1537 } elseif ( $imagesexception ) {
1538 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1540 $imagematch = false;
1542 if ( $this->mOptions
->getAllowExternalImages()
1543 ||
( $imagesexception && $imagematch ) ) {
1544 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1546 $text = $sk->makeExternalImage( $url );
1549 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1550 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1551 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1552 foreach ( $whitelist as $entry ) {
1553 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1554 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1557 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1558 # Image matches a whitelist entry
1559 $text = $sk->makeExternalImage( $url );
1568 * Process [[ ]] wikilinks
1569 * @return processed text
1573 function replaceInternalLinks( $s ) {
1574 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1579 * Process [[ ]] wikilinks (RIL)
1580 * @return LinkHolderArray
1584 function replaceInternalLinks2( &$s ) {
1587 wfProfileIn( __METHOD__
);
1589 wfProfileIn( __METHOD__
.'-setup' );
1590 static $tc = FALSE, $e1, $e1_img;
1591 # the % is needed to support urlencoded titles as well
1593 $tc = Title
::legalChars() . '#%';
1594 # Match a link having the form [[namespace:link|alternate]]trail
1595 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1596 # Match cases where there is no "]]", which might still be images
1597 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1600 $sk = $this->mOptions
->getSkin();
1601 $holders = new LinkHolderArray( $this );
1603 # split the entire text string on occurences of [[
1604 $a = StringUtils
::explode( '[[', ' ' . $s );
1605 # get the first element (all text up to first [[), and remove the space we added
1608 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1609 $s = substr( $s, 1 );
1611 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1613 if ( $useLinkPrefixExtension ) {
1614 # Match the end of a line for a word that's not followed by whitespace,
1615 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1616 $e2 = wfMsgForContent( 'linkprefix' );
1619 if ( is_null( $this->mTitle
) ) {
1620 wfProfileOut( __METHOD__
.'-setup' );
1621 wfProfileOut( __METHOD__
);
1622 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1624 $nottalk = !$this->mTitle
->isTalkPage();
1626 if ( $useLinkPrefixExtension ) {
1628 if ( preg_match( $e2, $s, $m ) ) {
1629 $first_prefix = $m[2];
1631 $first_prefix = false;
1637 if ( $wgContLang->hasVariants() ) {
1638 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1640 $selflink = array( $this->mTitle
->getPrefixedText() );
1642 $useSubpages = $this->areSubpagesAllowed();
1643 wfProfileOut( __METHOD__
.'-setup' );
1645 # Loop for each link
1646 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1647 # Check for excessive memory usage
1648 if ( $holders->isBig() ) {
1650 # Do the existence check, replace the link holders and clear the array
1651 $holders->replace( $s );
1655 if ( $useLinkPrefixExtension ) {
1656 wfProfileIn( __METHOD__
.'-prefixhandling' );
1657 if ( preg_match( $e2, $s, $m ) ) {
1664 if ( $first_prefix ) {
1665 $prefix = $first_prefix;
1666 $first_prefix = false;
1668 wfProfileOut( __METHOD__
.'-prefixhandling' );
1671 $might_be_img = false;
1673 wfProfileIn( __METHOD__
."-e1" );
1674 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1676 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1677 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1678 # the real problem is with the $e1 regex
1681 # Still some problems for cases where the ] is meant to be outside punctuation,
1682 # and no image is in sight. See bug 2095.
1684 if ( $text !== '' &&
1685 substr( $m[3], 0, 1 ) === ']' &&
1686 strpos( $text, '[' ) !== false
1689 $text .= ']'; # so that replaceExternalLinks($text) works later
1690 $m[3] = substr( $m[3], 1 );
1692 # fix up urlencoded title texts
1693 if ( strpos( $m[1], '%' ) !== false ) {
1694 # Should anchors '#' also be rejected?
1695 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1698 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1699 $might_be_img = true;
1701 if ( strpos( $m[1], '%' ) !== false ) {
1702 $m[1] = urldecode( $m[1] );
1705 } else { # Invalid form; output directly
1706 $s .= $prefix . '[[' . $line ;
1707 wfProfileOut( __METHOD__
."-e1" );
1710 wfProfileOut( __METHOD__
."-e1" );
1711 wfProfileIn( __METHOD__
."-misc" );
1713 # Don't allow internal links to pages containing
1714 # PROTO: where PROTO is a valid URL protocol; these
1715 # should be external links.
1716 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1717 $s .= $prefix . '[[' . $line ;
1718 wfProfileOut( __METHOD__
."-misc" );
1722 # Make subpage if necessary
1723 if ( $useSubpages ) {
1724 $link = $this->maybeDoSubpageLink( $m[1], $text );
1729 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1731 # Strip off leading ':'
1732 $link = substr( $link, 1 );
1735 wfProfileOut( __METHOD__
."-misc" );
1736 wfProfileIn( __METHOD__
."-title" );
1737 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1738 if ( $nt === null ) {
1739 $s .= $prefix . '[[' . $line;
1740 wfProfileOut( __METHOD__
."-title" );
1744 $ns = $nt->getNamespace();
1745 $iw = $nt->getInterWiki();
1746 wfProfileOut( __METHOD__
."-title" );
1748 if ( $might_be_img ) { # if this is actually an invalid link
1749 wfProfileIn( __METHOD__
."-might_be_img" );
1750 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1753 # look at the next 'line' to see if we can close it there
1755 $next_line = $a->current();
1756 if ( $next_line === false ||
$next_line === null ) {
1759 $m = explode( ']]', $next_line, 3 );
1760 if ( count( $m ) == 3 ) {
1761 # the first ]] closes the inner link, the second the image
1763 $text .= "[[{$m[0]}]]{$m[1]}";
1766 } elseif ( count( $m ) == 2 ) {
1767 # if there's exactly one ]] that's fine, we'll keep looking
1768 $text .= "[[{$m[0]}]]{$m[1]}";
1770 # if $next_line is invalid too, we need look no further
1771 $text .= '[[' . $next_line;
1776 # we couldn't find the end of this imageLink, so output it raw
1777 # but don't ignore what might be perfectly normal links in the text we've examined
1778 $holders->merge( $this->replaceInternalLinks2( $text ) );
1779 $s .= "{$prefix}[[$link|$text";
1780 # note: no $trail, because without an end, there *is* no trail
1781 wfProfileOut( __METHOD__
."-might_be_img" );
1784 } else { # it's not an image, so output it raw
1785 $s .= "{$prefix}[[$link|$text";
1786 # note: no $trail, because without an end, there *is* no trail
1787 wfProfileOut( __METHOD__
."-might_be_img" );
1790 wfProfileOut( __METHOD__
."-might_be_img" );
1793 $wasblank = ( $text == '' );
1798 # Link not escaped by : , create the various objects
1802 wfProfileIn( __METHOD__
."-interwiki" );
1803 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1804 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1805 $s = rtrim( $s . $prefix );
1806 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1807 wfProfileOut( __METHOD__
."-interwiki" );
1810 wfProfileOut( __METHOD__
."-interwiki" );
1812 if ( $ns == NS_FILE
) {
1813 wfProfileIn( __METHOD__
."-image" );
1814 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1816 # if no parameters were passed, $text
1817 # becomes something like "File:Foo.png",
1818 # which we don't want to pass on to the
1822 # recursively parse links inside the image caption
1823 # actually, this will parse them in any other parameters, too,
1824 # but it might be hard to fix that, and it doesn't matter ATM
1825 $text = $this->replaceExternalLinks( $text );
1826 $holders->merge( $this->replaceInternalLinks2( $text ) );
1828 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1829 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1831 $s .= $prefix . $trail;
1833 $this->mOutput
->addImage( $nt->getDBkey() );
1834 wfProfileOut( __METHOD__
."-image" );
1839 if ( $ns == NS_CATEGORY
) {
1840 wfProfileIn( __METHOD__
."-category" );
1841 $s = rtrim( $s . "\n" ); # bug 87
1844 $sortkey = $this->getDefaultSort();
1848 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1849 $sortkey = str_replace( "\n", '', $sortkey );
1850 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1851 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1854 * Strip the whitespace Category links produce, see bug 87
1855 * @todo We might want to use trim($tmp, "\n") here.
1857 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1859 wfProfileOut( __METHOD__
."-category" );
1864 # Self-link checking
1865 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1866 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1867 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1872 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1873 # FIXME: Should do batch file existence checks, see comment below
1874 if ( $ns == NS_MEDIA
) {
1875 wfProfileIn( __METHOD__
."-media" );
1876 # Give extensions a chance to select the file revision for us
1877 $skip = $time = false;
1878 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1880 $link = $sk->link( $nt );
1882 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1884 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1885 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1886 $this->mOutput
->addImage( $nt->getDBkey() );
1887 wfProfileOut( __METHOD__
."-media" );
1891 wfProfileIn( __METHOD__
."-always_known" );
1892 # Some titles, such as valid special pages or files in foreign repos, should
1893 # be shown as bluelinks even though they're not included in the page table
1895 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1896 # batch file existence checks for NS_FILE and NS_MEDIA
1897 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1898 $this->mOutput
->addLink( $nt );
1899 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1901 # Links will be added to the output link list after checking
1902 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1904 wfProfileOut( __METHOD__
."-always_known" );
1906 wfProfileOut( __METHOD__
);
1911 * Make a link placeholder. The text returned can be later resolved to a real link with
1912 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1913 * parsing of interwiki links, and secondly to allow all existence checks and
1914 * article length checks (for stub links) to be bundled into a single query.
1918 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1919 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1923 * Render a forced-blue link inline; protect against double expansion of
1924 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1925 * Since this little disaster has to split off the trail text to avoid
1926 * breaking URLs in the following text without breaking trails on the
1927 * wiki links, it's been made into a horrible function.
1930 * @param $text String
1931 * @param $query String
1932 * @param $trail String
1933 * @param $prefix String
1934 * @return String: HTML-wikitext mix oh yuck
1936 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1937 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1938 $sk = $this->mOptions
->getSkin();
1939 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1940 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1941 return $this->armorLinks( $link ) . $trail;
1945 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1946 * going to go through further parsing steps before inline URL expansion.
1948 * Not needed quite as much as it used to be since free links are a bit
1949 * more sensible these days. But bracketed links are still an issue.
1951 * @param $text String: more-or-less HTML
1952 * @return String: less-or-more HTML with NOPARSE bits
1954 function armorLinks( $text ) {
1955 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1956 "{$this->mUniqPrefix}NOPARSE$1", $text );
1960 * Return true if subpage links should be expanded on this page.
1963 function areSubpagesAllowed() {
1964 # Some namespaces don't allow subpages
1965 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1969 * Handle link to subpage if necessary
1971 * @param $target String: the source of the link
1972 * @param &$text String: the link text, modified as necessary
1973 * @return string the full name of the link
1976 function maybeDoSubpageLink( $target, &$text ) {
1977 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1981 * Used by doBlockLevels()
1984 function closeParagraph() {
1986 if ( $this->mLastSection
!= '' ) {
1987 $result = '</' . $this->mLastSection
. ">\n";
1989 $this->mInPre
= false;
1990 $this->mLastSection
= '';
1995 * getCommon() returns the length of the longest common substring
1996 * of both arguments, starting at the beginning of both.
1999 function getCommon( $st1, $st2 ) {
2000 $fl = strlen( $st1 );
2001 $shorter = strlen( $st2 );
2002 if ( $fl < $shorter ) {
2006 for ( $i = 0; $i < $shorter; ++
$i ) {
2007 if ( $st1{$i} != $st2{$i} ) {
2015 * These next three functions open, continue, and close the list
2016 * element appropriate to the prefix character passed into them.
2019 function openList( $char ) {
2020 $result = $this->closeParagraph();
2022 if ( '*' === $char ) {
2023 $result .= '<ul><li>';
2024 } elseif ( '#' === $char ) {
2025 $result .= '<ol><li>';
2026 } elseif ( ':' === $char ) {
2027 $result .= '<dl><dd>';
2028 } elseif ( ';' === $char ) {
2029 $result .= '<dl><dt>';
2030 $this->mDTopen
= true;
2032 $result = '<!-- ERR 1 -->';
2040 * @param $char String
2043 function nextItem( $char ) {
2044 if ( '*' === $char ||
'#' === $char ) {
2046 } elseif ( ':' === $char ||
';' === $char ) {
2048 if ( $this->mDTopen
) {
2051 if ( ';' === $char ) {
2052 $this->mDTopen
= true;
2053 return $close . '<dt>';
2055 $this->mDTopen
= false;
2056 return $close . '<dd>';
2059 return '<!-- ERR 2 -->';
2064 * @param $char String
2067 function closeList( $char ) {
2068 if ( '*' === $char ) {
2069 $text = '</li></ul>';
2070 } elseif ( '#' === $char ) {
2071 $text = '</li></ol>';
2072 } elseif ( ':' === $char ) {
2073 if ( $this->mDTopen
) {
2074 $this->mDTopen
= false;
2075 $text = '</dt></dl>';
2077 $text = '</dd></dl>';
2080 return '<!-- ERR 3 -->';
2087 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2089 * @param $text String
2090 * @param $linestart Boolean: whether or not this is at the start of a line.
2092 * @return string the lists rendered as HTML
2094 function doBlockLevels( $text, $linestart ) {
2095 wfProfileIn( __METHOD__
);
2097 # Parsing through the text line by line. The main thing
2098 # happening here is handling of block-level elements p, pre,
2099 # and making lists from lines starting with * # : etc.
2101 $textLines = StringUtils
::explode( "\n", $text );
2103 $lastPrefix = $output = '';
2104 $this->mDTopen
= $inBlockElem = false;
2106 $paragraphStack = false;
2108 foreach ( $textLines as $oLine ) {
2110 if ( !$linestart ) {
2120 $lastPrefixLength = strlen( $lastPrefix );
2121 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2122 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2123 # If not in a <pre> element, scan for and figure out what prefixes are there.
2124 if ( !$this->mInPre
) {
2125 # Multiple prefixes may abut each other for nested lists.
2126 $prefixLength = strspn( $oLine, '*#:;' );
2127 $prefix = substr( $oLine, 0, $prefixLength );
2130 # ; and : are both from definition-lists, so they're equivalent
2131 # for the purposes of determining whether or not we need to open/close
2133 $prefix2 = str_replace( ';', ':', $prefix );
2134 $t = substr( $oLine, $prefixLength );
2135 $this->mInPre
= (bool)$preOpenMatch;
2137 # Don't interpret any other prefixes in preformatted text
2139 $prefix = $prefix2 = '';
2144 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2145 # Same as the last item, so no need to deal with nesting or opening stuff
2146 $output .= $this->nextItem( substr( $prefix, -1 ) );
2147 $paragraphStack = false;
2149 if ( substr( $prefix, -1 ) === ';') {
2150 # The one nasty exception: definition lists work like this:
2151 # ; title : definition text
2152 # So we check for : in the remainder text to split up the
2153 # title and definition, without b0rking links.
2155 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2157 $output .= $term . $this->nextItem( ':' );
2160 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2161 # We need to open or close prefixes, or both.
2163 # Either open or close a level...
2164 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2165 $paragraphStack = false;
2167 # Close all the prefixes which aren't shared.
2168 while ( $commonPrefixLength < $lastPrefixLength ) {
2169 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2170 --$lastPrefixLength;
2173 # Continue the current prefix if appropriate.
2174 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2175 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2178 # Open prefixes where appropriate.
2179 while ( $prefixLength > $commonPrefixLength ) {
2180 $char = substr( $prefix, $commonPrefixLength, 1 );
2181 $output .= $this->openList( $char );
2183 if ( ';' === $char ) {
2184 # FIXME: This is dupe of code above
2185 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2187 $output .= $term . $this->nextItem( ':' );
2190 ++
$commonPrefixLength;
2192 $lastPrefix = $prefix2;
2195 # If we have no prefixes, go to paragraph mode.
2196 if ( 0 == $prefixLength ) {
2197 wfProfileIn( __METHOD__
."-paragraph" );
2198 # No prefix (not in list)--go to paragraph mode
2199 # XXX: use a stack for nestable elements like span, table and div
2200 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2201 $closematch = preg_match(
2202 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2203 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2204 if ( $openmatch or $closematch ) {
2205 $paragraphStack = false;
2206 #Â TODO bug 5718: paragraph closed
2207 $output .= $this->closeParagraph();
2208 if ( $preOpenMatch and !$preCloseMatch ) {
2209 $this->mInPre
= true;
2211 if ( $closematch ) {
2212 $inBlockElem = false;
2214 $inBlockElem = true;
2216 } elseif ( !$inBlockElem && !$this->mInPre
) {
2217 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2219 if ( $this->mLastSection
!== 'pre' ) {
2220 $paragraphStack = false;
2221 $output .= $this->closeParagraph().'<pre>';
2222 $this->mLastSection
= 'pre';
2224 $t = substr( $t, 1 );
2227 if ( trim( $t ) === '' ) {
2228 if ( $paragraphStack ) {
2229 $output .= $paragraphStack.'<br />';
2230 $paragraphStack = false;
2231 $this->mLastSection
= 'p';
2233 if ( $this->mLastSection
!== 'p' ) {
2234 $output .= $this->closeParagraph();
2235 $this->mLastSection
= '';
2236 $paragraphStack = '<p>';
2238 $paragraphStack = '</p><p>';
2242 if ( $paragraphStack ) {
2243 $output .= $paragraphStack;
2244 $paragraphStack = false;
2245 $this->mLastSection
= 'p';
2246 } elseif ( $this->mLastSection
!== 'p' ) {
2247 $output .= $this->closeParagraph().'<p>';
2248 $this->mLastSection
= 'p';
2253 wfProfileOut( __METHOD__
."-paragraph" );
2255 # somewhere above we forget to get out of pre block (bug 785)
2256 if ( $preCloseMatch && $this->mInPre
) {
2257 $this->mInPre
= false;
2259 if ( $paragraphStack === false ) {
2263 while ( $prefixLength ) {
2264 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2267 if ( $this->mLastSection
!= '' ) {
2268 $output .= '</' . $this->mLastSection
. '>';
2269 $this->mLastSection
= '';
2272 wfProfileOut( __METHOD__
);
2277 * Split up a string on ':', ignoring any occurences inside tags
2278 * to prevent illegal overlapping.
2280 * @param $str String: the string to split
2281 * @param &$before String: set to everything before the ':'
2282 * @param &$after String: set to everything after the ':'
2283 * return String: the position of the ':', or false if none found
2285 function findColonNoLinks( $str, &$before, &$after ) {
2286 wfProfileIn( __METHOD__
);
2288 $pos = strpos( $str, ':' );
2289 if ( $pos === false ) {
2291 wfProfileOut( __METHOD__
);
2295 $lt = strpos( $str, '<' );
2296 if ( $lt === false ||
$lt > $pos ) {
2297 # Easy; no tag nesting to worry about
2298 $before = substr( $str, 0, $pos );
2299 $after = substr( $str, $pos+
1 );
2300 wfProfileOut( __METHOD__
);
2304 # Ugly state machine to walk through avoiding tags.
2305 $state = self
::COLON_STATE_TEXT
;
2307 $len = strlen( $str );
2308 for( $i = 0; $i < $len; $i++
) {
2312 # (Using the number is a performance hack for common cases)
2313 case 0: # self::COLON_STATE_TEXT:
2316 # Could be either a <start> tag or an </end> tag
2317 $state = self
::COLON_STATE_TAGSTART
;
2320 if ( $stack == 0 ) {
2322 $before = substr( $str, 0, $i );
2323 $after = substr( $str, $i +
1 );
2324 wfProfileOut( __METHOD__
);
2327 # Embedded in a tag; don't break it.
2330 # Skip ahead looking for something interesting
2331 $colon = strpos( $str, ':', $i );
2332 if ( $colon === false ) {
2333 # Nothing else interesting
2334 wfProfileOut( __METHOD__
);
2337 $lt = strpos( $str, '<', $i );
2338 if ( $stack === 0 ) {
2339 if ( $lt === false ||
$colon < $lt ) {
2341 $before = substr( $str, 0, $colon );
2342 $after = substr( $str, $colon +
1 );
2343 wfProfileOut( __METHOD__
);
2347 if ( $lt === false ) {
2348 # Nothing else interesting to find; abort!
2349 # We're nested, but there's no close tags left. Abort!
2352 # Skip ahead to next tag start
2354 $state = self
::COLON_STATE_TAGSTART
;
2357 case 1: # self::COLON_STATE_TAG:
2362 $state = self
::COLON_STATE_TEXT
;
2365 # Slash may be followed by >?
2366 $state = self
::COLON_STATE_TAGSLASH
;
2372 case 2: # self::COLON_STATE_TAGSTART:
2375 $state = self
::COLON_STATE_CLOSETAG
;
2378 $state = self
::COLON_STATE_COMMENT
;
2381 # Illegal early close? This shouldn't happen D:
2382 $state = self
::COLON_STATE_TEXT
;
2385 $state = self
::COLON_STATE_TAG
;
2388 case 3: # self::COLON_STATE_CLOSETAG:
2393 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2394 wfProfileOut( __METHOD__
);
2397 $state = self
::COLON_STATE_TEXT
;
2400 case self
::COLON_STATE_TAGSLASH
:
2402 # Yes, a self-closed tag <blah/>
2403 $state = self
::COLON_STATE_TEXT
;
2405 # Probably we're jumping the gun, and this is an attribute
2406 $state = self
::COLON_STATE_TAG
;
2409 case 5: # self::COLON_STATE_COMMENT:
2411 $state = self
::COLON_STATE_COMMENTDASH
;
2414 case self
::COLON_STATE_COMMENTDASH
:
2416 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2418 $state = self
::COLON_STATE_COMMENT
;
2421 case self
::COLON_STATE_COMMENTDASHDASH
:
2423 $state = self
::COLON_STATE_TEXT
;
2425 $state = self
::COLON_STATE_COMMENT
;
2429 throw new MWException( "State machine error in " . __METHOD__
);
2433 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2436 wfProfileOut( __METHOD__
);
2441 * Return value of a magic variable (like PAGENAME)
2445 function getVariableValue( $index, $frame=false ) {
2446 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2447 global $wgScriptPath, $wgStylePath;
2450 * Some of these require message or data lookups and can be
2451 * expensive to check many times.
2453 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2454 if ( isset( $this->mVarCache
[$index] ) ) {
2455 return $this->mVarCache
[$index];
2459 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2460 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2463 global $wgLocaltimezone;
2464 if ( isset( $wgLocaltimezone ) ) {
2465 $oldtz = date_default_timezone_get();
2466 date_default_timezone_set( $wgLocaltimezone );
2469 $localTimestamp = date( 'YmdHis', $ts );
2470 $localMonth = date( 'm', $ts );
2471 $localMonth1 = date( 'n', $ts );
2472 $localMonthName = date( 'n', $ts );
2473 $localDay = date( 'j', $ts );
2474 $localDay2 = date( 'd', $ts );
2475 $localDayOfWeek = date( 'w', $ts );
2476 $localWeek = date( 'W', $ts );
2477 $localYear = date( 'Y', $ts );
2478 $localHour = date( 'H', $ts );
2479 if ( isset( $wgLocaltimezone ) ) {
2480 date_default_timezone_set( $oldtz );
2484 case 'currentmonth':
2485 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2487 case 'currentmonth1':
2488 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2490 case 'currentmonthname':
2491 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2493 case 'currentmonthnamegen':
2494 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2496 case 'currentmonthabbrev':
2497 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2500 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2503 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2506 $value = $wgContLang->formatNum( $localMonth );
2509 $value = $wgContLang->formatNum( $localMonth1 );
2511 case 'localmonthname':
2512 $value = $wgContLang->getMonthName( $localMonthName );
2514 case 'localmonthnamegen':
2515 $value = $wgContLang->getMonthNameGen( $localMonthName );
2517 case 'localmonthabbrev':
2518 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2521 $value = $wgContLang->formatNum( $localDay );
2524 $value = $wgContLang->formatNum( $localDay2 );
2527 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2530 $value = $this->mTitle
->getPartialURL();
2532 case 'fullpagename':
2533 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2535 case 'fullpagenamee':
2536 $value = $this->mTitle
->getPrefixedURL();
2539 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2541 case 'subpagenamee':
2542 $value = $this->mTitle
->getSubpageUrlForm();
2544 case 'basepagename':
2545 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2547 case 'basepagenamee':
2548 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2550 case 'talkpagename':
2551 if ( $this->mTitle
->canTalk() ) {
2552 $talkPage = $this->mTitle
->getTalkPage();
2553 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2558 case 'talkpagenamee':
2559 if ( $this->mTitle
->canTalk() ) {
2560 $talkPage = $this->mTitle
->getTalkPage();
2561 $value = $talkPage->getPrefixedUrl();
2566 case 'subjectpagename':
2567 $subjPage = $this->mTitle
->getSubjectPage();
2568 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2570 case 'subjectpagenamee':
2571 $subjPage = $this->mTitle
->getSubjectPage();
2572 $value = $subjPage->getPrefixedUrl();
2575 # Let the edit saving system know we should parse the page
2576 # *after* a revision ID has been assigned.
2577 $this->mOutput
->setFlag( 'vary-revision' );
2578 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2579 $value = $this->mRevisionId
;
2582 # Let the edit saving system know we should parse the page
2583 # *after* a revision ID has been assigned. This is for null edits.
2584 $this->mOutput
->setFlag( 'vary-revision' );
2585 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2586 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2588 case 'revisionday2':
2589 # Let the edit saving system know we should parse the page
2590 # *after* a revision ID has been assigned. This is for null edits.
2591 $this->mOutput
->setFlag( 'vary-revision' );
2592 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2593 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2595 case 'revisionmonth':
2596 # Let the edit saving system know we should parse the page
2597 # *after* a revision ID has been assigned. This is for null edits.
2598 $this->mOutput
->setFlag( 'vary-revision' );
2599 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2600 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2602 case 'revisionmonth1':
2603 # Let the edit saving system know we should parse the page
2604 # *after* a revision ID has been assigned. This is for null edits.
2605 $this->mOutput
->setFlag( 'vary-revision' );
2606 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2607 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2609 case 'revisionyear':
2610 # Let the edit saving system know we should parse the page
2611 # *after* a revision ID has been assigned. This is for null edits.
2612 $this->mOutput
->setFlag( 'vary-revision' );
2613 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2614 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2616 case 'revisiontimestamp':
2617 # Let the edit saving system know we should parse the page
2618 # *after* a revision ID has been assigned. This is for null edits.
2619 $this->mOutput
->setFlag( 'vary-revision' );
2620 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2621 $value = $this->getRevisionTimestamp();
2623 case 'revisionuser':
2624 # Let the edit saving system know we should parse the page
2625 # *after* a revision ID has been assigned. This is for null edits.
2626 $this->mOutput
->setFlag( 'vary-revision' );
2627 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2628 $value = $this->getRevisionUser();
2631 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2634 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2637 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2640 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2642 case 'subjectspace':
2643 $value = $this->mTitle
->getSubjectNsText();
2645 case 'subjectspacee':
2646 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2648 case 'currentdayname':
2649 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2652 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2655 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2658 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2661 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2662 # int to remove the padding
2663 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2666 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2668 case 'localdayname':
2669 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2672 $value = $wgContLang->formatNum( $localYear, true );
2675 $value = $wgContLang->time( $localTimestamp, false, false );
2678 $value = $wgContLang->formatNum( $localHour, true );
2681 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2682 # int to remove the padding
2683 $value = $wgContLang->formatNum( (int)$localWeek );
2686 $value = $wgContLang->formatNum( $localDayOfWeek );
2688 case 'numberofarticles':
2689 $value = $wgContLang->formatNum( SiteStats
::articles() );
2691 case 'numberoffiles':
2692 $value = $wgContLang->formatNum( SiteStats
::images() );
2694 case 'numberofusers':
2695 $value = $wgContLang->formatNum( SiteStats
::users() );
2697 case 'numberofactiveusers':
2698 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2700 case 'numberofpages':
2701 $value = $wgContLang->formatNum( SiteStats
::pages() );
2703 case 'numberofadmins':
2704 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2706 case 'numberofedits':
2707 $value = $wgContLang->formatNum( SiteStats
::edits() );
2709 case 'numberofviews':
2710 $value = $wgContLang->formatNum( SiteStats
::views() );
2712 case 'currenttimestamp':
2713 $value = wfTimestamp( TS_MW
, $ts );
2715 case 'localtimestamp':
2716 $value = $localTimestamp;
2718 case 'currentversion':
2719 $value = SpecialVersion
::getVersion();
2726 return $wgServerName;
2728 return $wgScriptPath;
2730 return $wgStylePath;
2731 case 'directionmark':
2732 return $wgContLang->getDirMark();
2733 case 'contentlanguage':
2734 global $wgContLanguageCode;
2735 return $wgContLanguageCode;
2738 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2746 $this->mVarCache
[$index] = $value;
2752 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2756 function initialiseVariables() {
2757 wfProfileIn( __METHOD__
);
2758 $variableIDs = MagicWord
::getVariableIDs();
2759 $substIDs = MagicWord
::getSubstIDs();
2761 $this->mVariables
= new MagicWordArray( $variableIDs );
2762 $this->mSubstWords
= new MagicWordArray( $substIDs );
2763 wfProfileOut( __METHOD__
);
2767 * Preprocess some wikitext and return the document tree.
2768 * This is the ghost of replace_variables().
2770 * @param $text String: The text to parse
2771 * @param $flags Integer: bitwise combination of:
2772 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2773 * included. Default is to assume a direct page view.
2775 * The generated DOM tree must depend only on the input text and the flags.
2776 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2778 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2779 * change in the DOM tree for a given text, must be passed through the section identifier
2780 * in the section edit link and thus back to extractSections().
2782 * The output of this function is currently only cached in process memory, but a persistent
2783 * cache may be implemented at a later date which takes further advantage of these strict
2784 * dependency requirements.
2788 function preprocessToDom( $text, $flags = 0 ) {
2789 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2794 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2796 public static function splitWhitespace( $s ) {
2797 $ltrimmed = ltrim( $s );
2798 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2799 $trimmed = rtrim( $ltrimmed );
2800 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2802 $w2 = substr( $ltrimmed, -$diff );
2806 return array( $w1, $trimmed, $w2 );
2810 * Replace magic variables, templates, and template arguments
2811 * with the appropriate text. Templates are substituted recursively,
2812 * taking care to avoid infinite loops.
2814 * Note that the substitution depends on value of $mOutputType:
2815 * self::OT_WIKI: only {{subst:}} templates
2816 * self::OT_PREPROCESS: templates but not extension tags
2817 * self::OT_HTML: all templates and extension tags
2819 * @param $text String: the text to transform
2820 * @param $frame PPFrame Object describing the arguments passed to the template.
2821 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2822 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2823 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2826 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2827 # Is there any text? Also, Prevent too big inclusions!
2828 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2831 wfProfileIn( __METHOD__
);
2833 if ( $frame === false ) {
2834 $frame = $this->getPreprocessor()->newFrame();
2835 } elseif ( !( $frame instanceof PPFrame
) ) {
2836 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2837 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2840 $dom = $this->preprocessToDom( $text );
2841 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2842 $text = $frame->expand( $dom, $flags );
2844 wfProfileOut( __METHOD__
);
2848 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2849 static function createAssocArgs( $args ) {
2850 $assocArgs = array();
2852 foreach ( $args as $arg ) {
2853 $eqpos = strpos( $arg, '=' );
2854 if ( $eqpos === false ) {
2855 $assocArgs[$index++
] = $arg;
2857 $name = trim( substr( $arg, 0, $eqpos ) );
2858 $value = trim( substr( $arg, $eqpos+
1 ) );
2859 if ( $value === false ) {
2862 if ( $name !== false ) {
2863 $assocArgs[$name] = $value;
2872 * Warn the user when a parser limitation is reached
2873 * Will warn at most once the user per limitation type
2875 * @param $limitationType String: should be one of:
2876 * 'expensive-parserfunction' (corresponding messages:
2877 * 'expensive-parserfunction-warning',
2878 * 'expensive-parserfunction-category')
2879 * 'post-expand-template-argument' (corresponding messages:
2880 * 'post-expand-template-argument-warning',
2881 * 'post-expand-template-argument-category')
2882 * 'post-expand-template-inclusion' (corresponding messages:
2883 * 'post-expand-template-inclusion-warning',
2884 * 'post-expand-template-inclusion-category')
2885 * @param $current Current value
2886 * @param $max Maximum allowed, when an explicit limit has been
2887 * exceeded, provide the values (optional)
2889 function limitationWarn( $limitationType, $current=null, $max=null) {
2890 # does no harm if $current and $max are present but are unnecessary for the message
2891 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2892 $this->mOutput
->addWarning( $warning );
2893 $this->addTrackingCategory( "$limitationType-category" );
2897 * Return the text of a template, after recursively
2898 * replacing any variables or templates within the template.
2900 * @param $piece Array: the parts of the template
2901 * $piece['title']: the title, i.e. the part before the |
2902 * $piece['parts']: the parameter array
2903 * $piece['lineStart']: whether the brace was at the start of a line
2904 * @param $frame PPFrame The current frame, contains template arguments
2905 * @return String: the text of the template
2908 function braceSubstitution( $piece, $frame ) {
2909 global $wgContLang, $wgNonincludableNamespaces;
2910 wfProfileIn( __METHOD__
);
2911 wfProfileIn( __METHOD__
.'-setup' );
2914 $found = false; # $text has been filled
2915 $nowiki = false; # wiki markup in $text should be escaped
2916 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2917 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2918 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2919 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2921 # Title object, where $text came from
2924 # $part1 is the bit before the first |, and must contain only title characters.
2925 # Various prefixes will be stripped from it later.
2926 $titleWithSpaces = $frame->expand( $piece['title'] );
2927 $part1 = trim( $titleWithSpaces );
2930 # Original title text preserved for various purposes
2931 $originalTitle = $part1;
2933 # $args is a list of argument nodes, starting from index 0, not including $part1
2934 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2935 wfProfileOut( __METHOD__
.'-setup' );
2938 wfProfileIn( __METHOD__
.'-modifiers' );
2941 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2943 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2944 # Decide whether to expand template or keep wikitext as-is.
2945 if ( $this->ot
['wiki'] ) {
2946 if ( $substMatch === false ) {
2947 $literal = true; # literal when in PST with no prefix
2949 $literal = false; # expand when in PST with subst: or safesubst:
2952 if ( $substMatch == 'subst' ) {
2953 $literal = true; # literal when not in PST with plain subst:
2955 $literal = false; # expand when not in PST with safesubst: or no prefix
2959 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2966 if ( !$found && $args->getLength() == 0 ) {
2967 $id = $this->mVariables
->matchStartToEnd( $part1 );
2968 if ( $id !== false ) {
2969 $text = $this->getVariableValue( $id, $frame );
2970 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2971 $this->mOutput
->mContainsOldMagic
= true;
2977 # MSG, MSGNW and RAW
2980 $mwMsgnw = MagicWord
::get( 'msgnw' );
2981 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2984 # Remove obsolete MSG:
2985 $mwMsg = MagicWord
::get( 'msg' );
2986 $mwMsg->matchStartAndRemove( $part1 );
2990 $mwRaw = MagicWord
::get( 'raw' );
2991 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2992 $forceRawInterwiki = true;
2995 wfProfileOut( __METHOD__
.'-modifiers' );
2999 wfProfileIn( __METHOD__
. '-pfunc' );
3001 $colonPos = strpos( $part1, ':' );
3002 if ( $colonPos !== false ) {
3003 # Case sensitive functions
3004 $function = substr( $part1, 0, $colonPos );
3005 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3006 $function = $this->mFunctionSynonyms
[1][$function];
3008 # Case insensitive functions
3009 $function = $wgContLang->lc( $function );
3010 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3011 $function = $this->mFunctionSynonyms
[0][$function];
3017 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3018 $initialArgs = array( &$this );
3019 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3020 if ( $flags & SFH_OBJECT_ARGS
) {
3021 # Add a frame parameter, and pass the arguments as an array
3022 $allArgs = $initialArgs;
3023 $allArgs[] = $frame;
3024 for ( $i = 0; $i < $args->getLength(); $i++
) {
3025 $funcArgs[] = $args->item( $i );
3027 $allArgs[] = $funcArgs;
3029 # Convert arguments to plain text
3030 for ( $i = 0; $i < $args->getLength(); $i++
) {
3031 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3033 $allArgs = array_merge( $initialArgs, $funcArgs );
3036 # Workaround for PHP bug 35229 and similar
3037 if ( !is_callable( $callback ) ) {
3038 wfProfileOut( __METHOD__
. '-pfunc' );
3039 wfProfileOut( __METHOD__
);
3040 throw new MWException( "Tag hook for $function is not callable\n" );
3042 $result = call_user_func_array( $callback, $allArgs );
3045 $preprocessFlags = 0;
3047 if ( is_array( $result ) ) {
3048 if ( isset( $result[0] ) ) {
3050 unset( $result[0] );
3053 # Extract flags into the local scope
3054 # This allows callers to set flags such as nowiki, found, etc.
3060 $text = $this->preprocessToDom( $text, $preprocessFlags );
3065 wfProfileOut( __METHOD__
. '-pfunc' );
3068 # Finish mangling title and then check for loops.
3069 # Set $title to a Title object and $titleText to the PDBK
3072 # Split the title into page and subpage
3074 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3075 if ( $subpage !== '' ) {
3076 $ns = $this->mTitle
->getNamespace();
3078 $title = Title
::newFromText( $part1, $ns );
3080 $titleText = $title->getPrefixedText();
3081 # Check for language variants if the template is not found
3082 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3083 $wgContLang->findVariantLink( $part1, $title, true );
3085 # Do recursion depth check
3086 $limit = $this->mOptions
->getMaxTemplateDepth();
3087 if ( $frame->depth
>= $limit ) {
3089 $text = '<span class="error">'
3090 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3096 # Load from database
3097 if ( !$found && $title ) {
3098 wfProfileIn( __METHOD__
. '-loadtpl' );
3099 if ( !$title->isExternal() ) {
3100 if ( $title->getNamespace() == NS_SPECIAL
3101 && $this->mOptions
->getAllowSpecialInclusion()
3102 && $this->ot
['html'] )
3104 $text = SpecialPage
::capturePath( $title );
3105 if ( is_string( $text ) ) {
3108 $this->disableCache();
3110 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3111 $found = false; # access denied
3112 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3114 list( $text, $title ) = $this->getTemplateDom( $title );
3115 if ( $text !== false ) {
3121 # If the title is valid but undisplayable, make a link to it
3122 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3123 $text = "[[:$titleText]]";
3126 } elseif ( $title->isTrans() ) {
3127 # Interwiki transclusion
3128 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3129 $text = $this->interwikiTransclude( $title, 'render' );
3132 $text = $this->interwikiTransclude( $title, 'raw' );
3133 # Preprocess it like a template
3134 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3140 # Do infinite loop check
3141 # This has to be done after redirect resolution to avoid infinite loops via redirects
3142 if ( !$frame->loopCheck( $title ) ) {
3144 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3145 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3147 wfProfileOut( __METHOD__
. '-loadtpl' );
3150 # If we haven't found text to substitute by now, we're done
3151 # Recover the source wikitext and return it
3153 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3154 wfProfileOut( __METHOD__
);
3155 return array( 'object' => $text );
3158 # Expand DOM-style return values in a child frame
3159 if ( $isChildObj ) {
3160 # Clean up argument array
3161 $newFrame = $frame->newChild( $args, $title );
3164 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3165 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3166 # Expansion is eligible for the empty-frame cache
3167 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3168 $text = $this->mTplExpandCache
[$titleText];
3170 $text = $newFrame->expand( $text );
3171 $this->mTplExpandCache
[$titleText] = $text;
3174 # Uncached expansion
3175 $text = $newFrame->expand( $text );
3178 if ( $isLocalObj && $nowiki ) {
3179 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3180 $isLocalObj = false;
3183 # Replace raw HTML by a placeholder
3184 # Add a blank line preceding, to prevent it from mucking up
3185 # immediately preceding headings
3187 $text = "\n\n" . $this->insertStripItem( $text );
3188 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3189 # Escape nowiki-style return values
3190 $text = wfEscapeWikiText( $text );
3191 } elseif ( is_string( $text )
3192 && !$piece['lineStart']
3193 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3195 # Bug 529: if the template begins with a table or block-level
3196 # element, it should be treated as beginning a new line.
3197 # This behaviour is somewhat controversial.
3198 $text = "\n" . $text;
3201 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3202 # Error, oversize inclusion
3203 if ( $titleText !== false ) {
3204 # Make a working, properly escaped link if possible (bug 23588)
3205 $text = "[[:$titleText]]";
3207 # This will probably not be a working link, but at least it may
3208 # provide some hint of where the problem is
3209 preg_replace( '/^:/', '', $originalTitle );
3210 $text = "[[:$originalTitle]]";
3212 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3213 $this->limitationWarn( 'post-expand-template-inclusion' );
3216 if ( $isLocalObj ) {
3217 $ret = array( 'object' => $text );
3219 $ret = array( 'text' => $text );
3222 wfProfileOut( __METHOD__
);
3227 * Get the semi-parsed DOM representation of a template with a given title,
3228 * and its redirect destination title. Cached.
3230 function getTemplateDom( $title ) {
3231 $cacheTitle = $title;
3232 $titleText = $title->getPrefixedDBkey();
3234 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3235 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3236 $title = Title
::makeTitle( $ns, $dbk );
3237 $titleText = $title->getPrefixedDBkey();
3239 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3240 return array( $this->mTplDomCache
[$titleText], $title );
3243 # Cache miss, go to the database
3244 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3246 if ( $text === false ) {
3247 $this->mTplDomCache
[$titleText] = false;
3248 return array( false, $title );
3251 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3252 $this->mTplDomCache
[ $titleText ] = $dom;
3254 if ( !$title->equals( $cacheTitle ) ) {
3255 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3256 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3259 return array( $dom, $title );
3263 * Fetch the unparsed text of a template and register a reference to it.
3265 function fetchTemplateAndTitle( $title ) {
3266 $templateCb = $this->mOptions
->getTemplateCallback();
3267 $stuff = call_user_func( $templateCb, $title, $this );
3268 $text = $stuff['text'];
3269 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3270 if ( isset( $stuff['deps'] ) ) {
3271 foreach ( $stuff['deps'] as $dep ) {
3272 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3275 return array( $text, $finalTitle );
3278 function fetchTemplate( $title ) {
3279 $rv = $this->fetchTemplateAndTitle( $title );
3284 * Static function to get a template
3285 * Can be overridden via ParserOptions::setTemplateCallback().
3287 static function statelessFetchTemplate( $title, $parser=false ) {
3288 $text = $skip = false;
3289 $finalTitle = $title;
3292 # Loop to fetch the article, with up to 1 redirect
3293 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3294 # Give extensions a chance to select the revision instead
3295 $id = false; # Assume current
3296 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3302 'page_id' => $title->getArticleID(),
3306 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3307 $rev_id = $rev ?
$rev->getId() : 0;
3308 # If there is no current revision, there is no page
3309 if ( $id === false && !$rev ) {
3310 $linkCache = LinkCache
::singleton();
3311 $linkCache->addBadLinkObj( $title );
3316 'page_id' => $title->getArticleID(),
3317 'rev_id' => $rev_id );
3320 $text = $rev->getText();
3321 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3323 $message = $wgContLang->lcfirst( $title->getText() );
3324 $text = wfMsgForContentNoTrans( $message );
3325 if ( wfEmptyMsg( $message, $text ) ) {
3332 if ( $text === false ) {
3336 $finalTitle = $title;
3337 $title = Title
::newFromRedirect( $text );
3341 'finalTitle' => $finalTitle,
3346 * Transclude an interwiki link.
3348 function interwikiTransclude( $title, $action ) {
3349 global $wgEnableScaryTranscluding;
3351 if ( !$wgEnableScaryTranscluding ) {
3352 return wfMsg('scarytranscludedisabled');
3355 $url = $title->getFullUrl( "action=$action" );
3357 if ( strlen( $url ) > 255 ) {
3358 return wfMsg( 'scarytranscludetoolong' );
3360 return $this->fetchScaryTemplateMaybeFromCache( $url );
3363 function fetchScaryTemplateMaybeFromCache( $url ) {
3364 global $wgTranscludeCacheExpiry;
3365 $dbr = wfGetDB( DB_SLAVE
);
3366 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3367 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3368 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3370 return $obj->tc_contents
;
3373 $text = Http
::get( $url );
3375 return wfMsg( 'scarytranscludefailed', $url );
3378 $dbw = wfGetDB( DB_MASTER
);
3379 $dbw->replace( 'transcache', array('tc_url'), array(
3381 'tc_time' => $dbw->timestamp( time() ),
3382 'tc_contents' => $text)
3389 * Triple brace replacement -- used for template arguments
3392 function argSubstitution( $piece, $frame ) {
3393 wfProfileIn( __METHOD__
);
3396 $parts = $piece['parts'];
3397 $nameWithSpaces = $frame->expand( $piece['title'] );
3398 $argName = trim( $nameWithSpaces );
3400 $text = $frame->getArgument( $argName );
3401 if ( $text === false && $parts->getLength() > 0
3405 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3408 # No match in frame, use the supplied default
3409 $object = $parts->item( 0 )->getChildren();
3411 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3412 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3413 $this->limitationWarn( 'post-expand-template-argument' );
3416 if ( $text === false && $object === false ) {
3418 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3420 if ( $error !== false ) {
3423 if ( $object !== false ) {
3424 $ret = array( 'object' => $object );
3426 $ret = array( 'text' => $text );
3429 wfProfileOut( __METHOD__
);
3434 * Return the text to be used for a given extension tag.
3435 * This is the ghost of strip().
3437 * @param $params Associative array of parameters:
3438 * name PPNode for the tag name
3439 * attr PPNode for unparsed text where tag attributes are thought to be
3440 * attributes Optional associative array of parsed attributes
3441 * inner Contents of extension element
3442 * noClose Original text did not have a close tag
3443 * @param $frame PPFrame
3445 function extensionSubstitution( $params, $frame ) {
3446 global $wgRawHtml, $wgContLang;
3448 $name = $frame->expand( $params['name'] );
3449 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3450 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3451 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3453 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3454 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3455 if ( $isFunctionTag ) {
3456 $markerType = 'none';
3458 $markerType = 'general';
3460 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3461 $name = strtolower( $name );
3462 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3463 if ( isset( $params['attributes'] ) ) {
3464 $attributes = $attributes +
$params['attributes'];
3467 if ( isset( $this->mTagHooks
[$name] ) ) {
3468 # Workaround for PHP bug 35229 and similar
3469 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3470 throw new MWException( "Tag hook for $name is not callable\n" );
3472 $output = call_user_func_array( $this->mTagHooks
[$name],
3473 array( $content, $attributes, $this, $frame ) );
3474 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3475 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3476 if ( !is_callable( $callback ) ) {
3477 throw new MWException( "Tag hook for $name is not callable\n" );
3480 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3482 $output = '<span class="error">Invalid tag extension name: ' .
3483 htmlspecialchars( $name ) . '</span>';
3486 if ( is_array( $output ) ) {
3487 # Extract flags to local scope (to override $markerType)
3489 $output = $flags[0];
3494 if ( is_null( $attrText ) ) {
3497 if ( isset( $params['attributes'] ) ) {
3498 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3499 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3500 htmlspecialchars( $attrValue ) . '"';
3503 if ( $content === null ) {
3504 $output = "<$name$attrText/>";
3506 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3507 $output = "<$name$attrText>$content$close";
3511 if ( $markerType === 'none' ) {
3513 } elseif ( $markerType === 'nowiki' ) {
3514 $this->mStripState
->nowiki
->setPair( $marker, $output );
3515 } elseif ( $markerType === 'general' ) {
3516 $this->mStripState
->general
->setPair( $marker, $output );
3518 throw new MWException( __METHOD__
.': invalid marker type' );
3524 * Increment an include size counter
3526 * @param $type String: the type of expansion
3527 * @param $size Integer: the size of the text
3528 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3530 function incrementIncludeSize( $type, $size ) {
3531 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3534 $this->mIncludeSizes
[$type] +
= $size;
3540 * Increment the expensive function count
3542 * @return Boolean: false if the limit has been exceeded
3544 function incrementExpensiveFunctionCount() {
3545 global $wgExpensiveParserFunctionLimit;
3546 $this->mExpensiveFunctionCount++
;
3547 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3554 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3555 * Fills $this->mDoubleUnderscores, returns the modified text
3557 function doDoubleUnderscore( $text ) {
3558 wfProfileIn( __METHOD__
);
3560 # The position of __TOC__ needs to be recorded
3561 $mw = MagicWord
::get( 'toc' );
3562 if ( $mw->match( $text ) ) {
3563 $this->mShowToc
= true;
3564 $this->mForceTocPosition
= true;
3566 # Set a placeholder. At the end we'll fill it in with the TOC.
3567 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3569 # Only keep the first one.
3570 $text = $mw->replace( '', $text );
3573 # Now match and remove the rest of them
3574 $mwa = MagicWord
::getDoubleUnderscoreArray();
3575 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3577 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3578 $this->mOutput
->mNoGallery
= true;
3580 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3581 $this->mShowToc
= false;
3583 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3584 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3585 $this->addTrackingCategory( 'hidden-category-category' );
3587 # (bug 8068) Allow control over whether robots index a page.
3589 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3590 # is not desirable, the last one on the page should win.
3591 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3592 $this->mOutput
->setIndexPolicy( 'noindex' );
3593 $this->addTrackingCategory( 'noindex-category' );
3595 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3596 $this->mOutput
->setIndexPolicy( 'index' );
3597 $this->addTrackingCategory( 'index-category' );
3600 wfProfileOut( __METHOD__
);
3605 * Add a tracking category, getting the title from a system message,
3606 * or print a debug message if the title is invalid.
3608 * @param $msg String: message key
3609 * @return Boolean: whether the addition was successful
3611 protected function addTrackingCategory( $msg ) {
3612 $cat = wfMsgForContent( $msg );
3614 # Allow tracking categories to be disabled by setting them to "-"
3615 if ( $cat === '-' ) {
3619 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3620 if ( $containerCategory ) {
3621 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3624 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3630 * This function accomplishes several tasks:
3631 * 1) Auto-number headings if that option is enabled
3632 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3633 * 3) Add a Table of contents on the top for users who have enabled the option
3634 * 4) Auto-anchor headings
3636 * It loops through all headlines, collects the necessary data, then splits up the
3637 * string and re-inserts the newly formatted headlines.
3639 * @param $text String
3640 * @param $origText String: original, untouched wikitext
3641 * @param $isMain Boolean
3644 function formatHeadings( $text, $origText, $isMain=true ) {
3645 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3647 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3648 $showEditLink = $this->mOptions
->getEditSection();
3650 # Do not call quickUserCan unless necessary
3651 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3655 # Inhibit editsection links if requested in the page
3656 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3660 # Get all headlines for numbering them and adding funky stuff like [edit]
3661 # links - this is for later, but we need the number of headlines right now
3663 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3665 # if there are fewer than 4 headlines in the article, do not show TOC
3666 # unless it's been explicitly enabled.
3667 $enoughToc = $this->mShowToc
&&
3668 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3670 # Allow user to stipulate that a page should have a "new section"
3671 # link added via __NEWSECTIONLINK__
3672 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3673 $this->mOutput
->setNewSection( true );
3676 # Allow user to remove the "new section"
3677 # link via __NONEWSECTIONLINK__
3678 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3679 $this->mOutput
->hideNewSection( true );
3682 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3683 # override above conditions and always show TOC above first header
3684 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3685 $this->mShowToc
= true;
3689 # We need this to perform operations on the HTML
3690 $sk = $this->mOptions
->getSkin();
3696 # Ugh .. the TOC should have neat indentation levels which can be
3697 # passed to the skin functions. These are determined here
3701 $sublevelCount = array();
3702 $levelCount = array();
3708 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3709 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3710 $oldType = $this->mOutputType
;
3711 $this->setOutputType( self
::OT_WIKI
);
3712 $frame = $this->getPreprocessor()->newFrame();
3713 $root = $this->preprocessToDom( $origText );
3714 $node = $root->getFirstChild();
3718 foreach ( $matches[3] as $headline ) {
3719 $isTemplate = false;
3721 $sectionIndex = false;
3723 $markerMatches = array();
3724 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3725 $serial = $markerMatches[1];
3726 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3727 $isTemplate = ( $titleText != $baseTitleText );
3728 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3732 $prevlevel = $level;
3733 $prevtoclevel = $toclevel;
3735 $level = $matches[1][$headlineCount];
3737 if ( $level > $prevlevel ) {
3738 # Increase TOC level
3740 $sublevelCount[$toclevel] = 0;
3741 if ( $toclevel<$wgMaxTocLevel ) {
3742 $prevtoclevel = $toclevel;
3743 $toc .= $sk->tocIndent();
3746 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3747 # Decrease TOC level, find level to jump to
3749 for ( $i = $toclevel; $i > 0; $i-- ) {
3750 if ( $levelCount[$i] == $level ) {
3751 # Found last matching level
3754 } elseif ( $levelCount[$i] < $level ) {
3755 # Found first matching level below current level
3763 if ( $toclevel<$wgMaxTocLevel ) {
3764 if ( $prevtoclevel < $wgMaxTocLevel ) {
3765 # Unindent only if the previous toc level was shown :p
3766 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3767 $prevtoclevel = $toclevel;
3769 $toc .= $sk->tocLineEnd();
3773 # No change in level, end TOC line
3774 if ( $toclevel<$wgMaxTocLevel ) {
3775 $toc .= $sk->tocLineEnd();
3779 $levelCount[$toclevel] = $level;
3781 # count number of headlines for each level
3782 @$sublevelCount[$toclevel]++
;
3784 for( $i = 1; $i <= $toclevel; $i++
) {
3785 if ( !empty( $sublevelCount[$i] ) ) {
3789 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3794 # The safe header is a version of the header text safe to use for links
3795 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3796 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3798 # Remove link placeholders by the link text.
3799 # <!--LINK number-->
3801 # link text with suffix
3802 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3804 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3805 $tocline = preg_replace(
3806 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3807 array( '', '<$1>' ),
3810 $tocline = trim( $tocline );
3812 # For the anchor, strip out HTML-y stuff period
3813 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3814 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3815 $safeHeadline = trim( $safeHeadline );
3817 # Save headline for section edit hint before it's escaped
3818 $headlineHint = $safeHeadline;
3820 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3821 # For reverse compatibility, provide an id that's
3822 # HTML4-compatible, like we used to.
3824 # It may be worth noting, academically, that it's possible for
3825 # the legacy anchor to conflict with a non-legacy headline
3826 # anchor on the page. In this case likely the "correct" thing
3827 # would be to either drop the legacy anchors or make sure
3828 # they're numbered first. However, this would require people
3829 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3830 # manually, so let's not bother worrying about it.
3831 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3832 array( 'noninitial', 'legacy' ) );
3833 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3835 if ( $legacyHeadline == $safeHeadline ) {
3836 # No reason to have both (in fact, we can't)
3837 $legacyHeadline = false;
3840 $legacyHeadline = false;
3841 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3845 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3846 # Does this apply to Unicode characters? Because we aren't
3847 # handling those here.
3848 $arrayKey = strtolower( $safeHeadline );
3849 if ( $legacyHeadline === false ) {
3850 $legacyArrayKey = false;
3852 $legacyArrayKey = strtolower( $legacyHeadline );
3855 # count how many in assoc. array so we can track dupes in anchors
3856 if ( isset( $refers[$arrayKey] ) ) {
3857 $refers[$arrayKey]++
;
3859 $refers[$arrayKey] = 1;
3861 if ( isset( $refers[$legacyArrayKey] ) ) {
3862 $refers[$legacyArrayKey]++
;
3864 $refers[$legacyArrayKey] = 1;
3867 # Don't number the heading if it is the only one (looks silly)
3868 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3869 # the two are different if the line contains a link
3870 $headline = $numbering . ' ' . $headline;
3873 # Create the anchor for linking from the TOC to the section
3874 $anchor = $safeHeadline;
3875 $legacyAnchor = $legacyHeadline;
3876 if ( $refers[$arrayKey] > 1 ) {
3877 $anchor .= '_' . $refers[$arrayKey];
3879 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3880 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3882 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3883 $toc .= $sk->tocLine( $anchor, $tocline,
3884 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3887 # Add the section to the section tree
3888 # Find the DOM node for this header
3889 while ( $node && !$isTemplate ) {
3890 if ( $node->getName() === 'h' ) {
3891 $bits = $node->splitHeading();
3892 if ( $bits['i'] == $sectionIndex )
3895 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3896 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3897 $node = $node->getNextSibling();
3900 'toclevel' => $toclevel,
3903 'number' => $numbering,
3904 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3905 'fromtitle' => $titleText,
3906 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3907 'anchor' => $anchor,
3910 # give headline the correct <h#> tag
3911 if ( $showEditLink && $sectionIndex !== false ) {
3912 if ( $isTemplate ) {
3913 # Put a T flag in the section identifier, to indicate to extractSections()
3914 # that sections inside <includeonly> should be counted.
3915 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3917 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3922 $head[$headlineCount] = $sk->makeHeadline( $level,
3923 $matches['attrib'][$headlineCount], $anchor, $headline,
3924 $editlink, $legacyAnchor );
3929 $this->setOutputType( $oldType );
3931 # Never ever show TOC if no headers
3932 if ( $numVisible < 1 ) {
3937 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3938 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3940 $toc = $sk->tocList( $toc );
3941 $this->mOutput
->setTOCHTML( $toc );
3945 $this->mOutput
->setSections( $tocraw );
3948 # split up and insert constructed headlines
3950 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3953 foreach ( $blocks as $block ) {
3954 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3955 # This is the [edit] link that appears for the top block of text when
3956 # section editing is enabled
3958 # Disabled because it broke block formatting
3959 # For example, a bullet point in the top line
3960 # $full .= $sk->editSectionLink(0);
3963 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3964 # Top anchor now in skin
3968 if ( !empty( $head[$i] ) ) {
3973 if ( $this->mForceTocPosition
) {
3974 return str_replace( '<!--MWTOC-->', $toc, $full );
3981 * Merge $tree2 into $tree1 by replacing the section with index
3982 * $section in $tree1 and its descendants with the sections in $tree2.
3983 * Note that in the returned section tree, only the 'index' and
3984 * 'byteoffset' fields are guaranteed to be correct.
3986 * @param $tree1 Array: section tree from ParserOutput::getSectons()
3987 * @param $tree2 Array: section tree
3988 * @param $section Integer: section index
3989 * @param $title Title: Title both section trees come from
3990 * @param $len2 Integer: length of the original wikitext for $tree2
3991 * @return Array: merged section tree
3993 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3996 $targetLevel = false;
4000 $numbering = array( 0 );
4001 $titletext = $title->getPrefixedDBkey();
4002 foreach ( $tree1 as $s ) {
4003 if ( $targetLevel !== false ) {
4004 if ( $s['level'] <= $targetLevel ) {
4005 # We've skipped enough
4006 $targetLevel = false;
4011 if ( $s['index'] != $section ||
4012 $s['fromtitle'] != $titletext ) {
4013 self
::incrementNumbering( $numbering,
4014 $s['toclevel'], $lastLevel );
4016 # Rewrite index, byteoffset and number
4017 if ( $s['fromtitle'] == $titletext ) {
4018 $s['index'] = $nextIndex++
;
4020 $s['byteoffset'] +
= $len2;
4023 $s['number'] = implode( '.', array_map(
4024 array( $wgContLang, 'formatnum' ),
4026 $lastLevel = $s['toclevel'];
4030 # Insert sections from $tree2 here
4031 foreach ( $tree2 as $s2 ) {
4032 # Rewrite the fields in $s2
4033 # before inserting it
4034 $s2['toclevel'] +
= $s['toclevel'] - 1;
4035 $s2['level'] +
= $s['level'] - 1;
4036 $s2['index'] = $nextIndex++
;
4037 $s2['byteoffset'] +
= $s['byteoffset'];
4039 self
::incrementNumbering( $numbering,
4040 $s2['toclevel'], $lastLevel );
4041 $s2['number'] = implode( '.', array_map(
4042 array( $wgContLang, 'formatnum' ),
4044 $lastLevel = $s2['toclevel'];
4047 # Skip all descendants of $section in $tree1
4048 $targetLevel = $s['level'];
4056 * Increment a section number. Helper function for mergeSectionTrees()
4058 * @param $number Array representing a section number
4059 * @param $level Integer: current TOC level (depth)
4060 * @param $lastLevel Integer: level of previous TOC entry
4062 private static function incrementNumbering( &$number, $level, $lastLevel ) {
4063 if ( $level > $lastLevel ) {
4064 $number[$level - 1] = 1;
4065 } elseif ( $level < $lastLevel ) {
4066 foreach ( $number as $key => $unused )
4067 if ( $key >= $level ) {
4068 unset( $number[$key] );
4070 $number[$level - 1]++
;
4072 $number[$level - 1]++
;
4077 * Transform wiki markup when saving a page by doing \r\n -> \n
4078 * conversion, substitting signatures, {{subst:}} templates, etc.
4080 * @param $text String: the text to transform
4081 * @param &$title Title: the Title object for the current article
4082 * @param $user User: the User object describing the current user
4083 * @param $options ParserOptions: parsing options
4084 * @param $clearState Boolean: whether to clear the parser state first
4085 * @return String: the altered wiki markup
4087 public function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4088 $this->mOptions
= $options;
4089 $this->setTitle( $title );
4090 $this->setOutputType( self
::OT_WIKI
);
4092 if ( $clearState ) {
4093 $this->clearState();
4099 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4100 $text = $this->pstPass2( $text, $user );
4101 $text = $this->mStripState
->unstripBoth( $text );
4106 * Pre-save transform helper function
4109 function pstPass2( $text, $user ) {
4110 global $wgContLang, $wgLocaltimezone;
4112 # Note: This is the timestamp saved as hardcoded wikitext to
4113 # the database, we use $wgContLang here in order to give
4114 # everyone the same signature and use the default one rather
4115 # than the one selected in each user's preferences.
4116 # (see also bug 12815)
4117 $ts = $this->mOptions
->getTimestamp();
4118 if ( isset( $wgLocaltimezone ) ) {
4119 $tz = $wgLocaltimezone;
4121 $tz = date_default_timezone_get();
4124 $unixts = wfTimestamp( TS_UNIX
, $ts );
4125 $oldtz = date_default_timezone_get();
4126 date_default_timezone_set( $tz );
4127 $ts = date( 'YmdHis', $unixts );
4128 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4130 # Allow translation of timezones through wiki. date() can return
4131 # whatever crap the system uses, localised or not, so we cannot
4132 # ship premade translations.
4133 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4134 $value = wfMsgForContent( $key );
4135 if ( !wfEmptyMsg( $key, $value ) ) {
4139 date_default_timezone_set( $oldtz );
4141 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4143 # Variable replacement
4144 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4145 $text = $this->replaceVariables( $text );
4148 $sigText = $this->getUserSig( $user );
4149 $text = strtr( $text, array(
4151 '~~~~' => "$sigText $d",
4155 # Context links: [[|name]] and [[name (context)|]]
4156 global $wgLegalTitleChars;
4157 $tc = "[$wgLegalTitleChars]";
4158 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4160 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4161 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4162 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4163 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4165 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4166 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4167 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4168 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4170 $t = $this->mTitle
->getText();
4172 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4173 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4174 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4175 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4177 # if there's no context, don't bother duplicating the title
4178 $text = preg_replace( $p2, '[[\\1]]', $text );
4181 # Trim trailing whitespace
4182 $text = rtrim( $text );
4188 * Fetch the user's signature text, if any, and normalize to
4189 * validated, ready-to-insert wikitext.
4190 * If you have pre-fetched the nickname or the fancySig option, you can
4191 * specify them here to save a database query.
4194 * @param $nickname String: nickname to use or false to use user's default nickname
4195 * @param $fancySig Boolean: whether the nicknname is the complete signature
4196 * or null to use default value
4199 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4200 global $wgMaxSigChars;
4202 $username = $user->getName();
4204 # If not given, retrieve from the user object.
4205 if ( $nickname === false )
4206 $nickname = $user->getOption( 'nickname' );
4208 if ( is_null( $fancySig ) ) {
4209 $fancySig = $user->getBoolOption( 'fancysig' );
4212 $nickname = $nickname == null ?
$username : $nickname;
4214 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4215 $nickname = $username;
4216 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4217 } elseif ( $fancySig !== false ) {
4218 # Sig. might contain markup; validate this
4219 if ( $this->validateSig( $nickname ) !== false ) {
4220 # Validated; clean up (if needed) and return it
4221 return $this->cleanSig( $nickname, true );
4223 # Failed to validate; fall back to the default
4224 $nickname = $username;
4225 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4229 # Make sure nickname doesnt get a sig in a sig
4230 $nickname = $this->cleanSigInSig( $nickname );
4232 # If we're still here, make it a link to the user page
4233 $userText = wfEscapeWikiText( $username );
4234 $nickText = wfEscapeWikiText( $nickname );
4235 if ( $user->isAnon() ) {
4236 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4238 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4243 * Check that the user's signature contains no bad XML
4245 * @param $text String
4246 * @return mixed An expanded string, or false if invalid.
4248 function validateSig( $text ) {
4249 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4253 * Clean up signature text
4255 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4256 * 2) Substitute all transclusions
4258 * @param $text String
4259 * @param $parsing Whether we're cleaning (preferences save) or parsing
4260 * @return String: signature text
4262 function cleanSig( $text, $parsing = false ) {
4265 $this->clearState();
4266 $this->setTitle( $wgTitle );
4267 $this->mOptions
= new ParserOptions
;
4268 $this->setOutputType
= self
::OT_PREPROCESS
;
4271 # Option to disable this feature
4272 if ( !$this->mOptions
->getCleanSignatures() ) {
4276 # FIXME: regex doesn't respect extension tags or nowiki
4277 # => Move this logic to braceSubstitution()
4278 $substWord = MagicWord
::get( 'subst' );
4279 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4280 $substText = '{{' . $substWord->getSynonym( 0 );
4282 $text = preg_replace( $substRegex, $substText, $text );
4283 $text = $this->cleanSigInSig( $text );
4284 $dom = $this->preprocessToDom( $text );
4285 $frame = $this->getPreprocessor()->newFrame();
4286 $text = $frame->expand( $dom );
4289 $text = $this->mStripState
->unstripBoth( $text );
4296 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4298 * @param $text String
4299 * @return String: signature text with /~{3,5}/ removed
4301 function cleanSigInSig( $text ) {
4302 $text = preg_replace( '/~{3,5}/', '', $text );
4307 * Set up some variables which are usually set up in parse()
4308 * so that an external function can call some class members with confidence
4310 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4311 $this->setTitle( $title );
4312 $this->mOptions
= $options;
4313 $this->setOutputType( $outputType );
4314 if ( $clearState ) {
4315 $this->clearState();
4320 * Wrapper for preprocess()
4322 * @param $text String: the text to preprocess
4323 * @param $options ParserOptions: options
4326 public function transformMsg( $text, $options ) {
4328 static $executing = false;
4330 # Guard against infinite recursion
4336 wfProfileIn( __METHOD__
);
4337 $text = $this->preprocess( $text, $wgTitle, $options );
4340 wfProfileOut( __METHOD__
);
4345 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4346 * The callback should have the following form:
4347 * function myParserHook( $text, $params, $parser ) { ... }
4349 * Transform and return $text. Use $parser for any required context, e.g. use
4350 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4352 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4353 * @param $callback Mixed: the callback function (and object) to use for the tag
4354 * @return The old value of the mTagHooks array associated with the hook
4356 public function setHook( $tag, $callback ) {
4357 $tag = strtolower( $tag );
4358 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4359 $this->mTagHooks
[$tag] = $callback;
4360 if ( !in_array( $tag, $this->mStripList
) ) {
4361 $this->mStripList
[] = $tag;
4367 function setTransparentTagHook( $tag, $callback ) {
4368 $tag = strtolower( $tag );
4369 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4370 $this->mTransparentTagHooks
[$tag] = $callback;
4376 * Remove all tag hooks
4378 function clearTagHooks() {
4379 $this->mTagHooks
= array();
4380 $this->mStripList
= $this->mDefaultStripList
;
4384 * Create a function, e.g. {{sum:1|2|3}}
4385 * The callback function should have the form:
4386 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4388 * Or with SFH_OBJECT_ARGS:
4389 * function myParserFunction( $parser, $frame, $args ) { ... }
4391 * The callback may either return the text result of the function, or an array with the text
4392 * in element 0, and a number of flags in the other elements. The names of the flags are
4393 * specified in the keys. Valid flags are:
4394 * found The text returned is valid, stop processing the template. This
4396 * nowiki Wiki markup in the return value should be escaped
4397 * isHTML The returned text is HTML, armour it against wikitext transformation
4399 * @param $id String: The magic word ID
4400 * @param $callback Mixed: the callback function (and object) to use
4401 * @param $flags Integer: a combination of the following flags:
4402 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4404 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4405 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4406 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4407 * the arguments, and to control the way they are expanded.
4409 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4410 * arguments, for instance:
4411 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4413 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4414 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4415 * working if/when this is changed.
4417 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4420 * Please read the documentation in includes/parser/Preprocessor.php for more information
4421 * about the methods available in PPFrame and PPNode.
4423 * @return The old callback function for this name, if any
4425 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4428 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4429 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4431 # Add to function cache
4432 $mw = MagicWord
::get( $id );
4434 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4436 $synonyms = $mw->getSynonyms();
4437 $sensitive = intval( $mw->isCaseSensitive() );
4439 foreach ( $synonyms as $syn ) {
4441 if ( !$sensitive ) {
4442 $syn = $wgContLang->lc( $syn );
4445 if ( !( $flags & SFH_NO_HASH
) ) {
4448 # Remove trailing colon
4449 if ( substr( $syn, -1, 1 ) === ':' ) {
4450 $syn = substr( $syn, 0, -1 );
4452 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4458 * Get all registered function hook identifiers
4462 function getFunctionHooks() {
4463 return array_keys( $this->mFunctionHooks
);
4467 * Create a tag function, e.g. <test>some stuff</test>.
4468 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4469 * Unlike parser functions, their content is not preprocessed.
4471 function setFunctionTagHook( $tag, $callback, $flags ) {
4472 $tag = strtolower( $tag );
4473 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4474 $this->mFunctionTagHooks
[$tag] : null;
4475 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4477 if ( !in_array( $tag, $this->mStripList
) ) {
4478 $this->mStripList
[] = $tag;
4485 * FIXME: update documentation. makeLinkObj() is deprecated.
4486 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4487 * Placeholders created in Skin::makeLinkObj()
4488 * Returns an array of link CSS classes, indexed by PDBK.
4490 function replaceLinkHolders( &$text, $options = 0 ) {
4491 return $this->mLinkHolders
->replace( $text );
4495 * Replace <!--LINK--> link placeholders with plain text of links
4496 * (not HTML-formatted).
4498 * @param $text String
4501 function replaceLinkHoldersText( $text ) {
4502 return $this->mLinkHolders
->replaceText( $text );
4506 * Renders an image gallery from a text with one line per image.
4507 * text labels may be given by using |-style alternative text. E.g.
4508 * Image:one.jpg|The number "1"
4509 * Image:tree.jpg|A tree
4510 * given as text will return the HTML of a gallery with two images,
4511 * labeled 'The number "1"' and
4514 function renderImageGallery( $text, $params ) {
4515 $ig = new ImageGallery();
4516 $ig->setContextTitle( $this->mTitle
);
4517 $ig->setShowBytes( false );
4518 $ig->setShowFilename( false );
4519 $ig->setParser( $this );
4520 $ig->setHideBadImages();
4521 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4522 $ig->useSkin( $this->mOptions
->getSkin() );
4523 $ig->mRevisionId
= $this->mRevisionId
;
4525 if ( isset( $params['showfilename'] ) ) {
4526 $ig->setShowFilename( true );
4528 $ig->setShowFilename( false );
4530 if ( isset( $params['caption'] ) ) {
4531 $caption = $params['caption'];
4532 $caption = htmlspecialchars( $caption );
4533 $caption = $this->replaceInternalLinks( $caption );
4534 $ig->setCaptionHtml( $caption );
4536 if ( isset( $params['perrow'] ) ) {
4537 $ig->setPerRow( $params['perrow'] );
4539 if ( isset( $params['widths'] ) ) {
4540 $ig->setWidths( $params['widths'] );
4542 if ( isset( $params['heights'] ) ) {
4543 $ig->setHeights( $params['heights'] );
4546 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4548 $lines = StringUtils
::explode( "\n", $text );
4549 foreach ( $lines as $line ) {
4550 # match lines like these:
4551 # Image:someimage.jpg|This is some image
4553 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4555 if ( count( $matches ) == 0 ) {
4559 if ( strpos( $matches[0], '%' ) !== false ) {
4560 $matches[1] = urldecode( $matches[1] );
4562 $tp = Title
::newFromText( $matches[1] );
4564 if ( is_null( $nt ) ) {
4565 # Bogus title. Ignore these so we don't bomb out later.
4568 if ( isset( $matches[3] ) ) {
4569 $label = $matches[3];
4574 $html = $this->recursiveTagParse( trim( $label ) );
4576 $ig->add( $nt, $html );
4578 # Only add real images (bug #5586)
4579 if ( $nt->getNamespace() == NS_FILE
) {
4580 $this->mOutput
->addImage( $nt->getDBkey() );
4583 return $ig->toHTML();
4586 function getImageParams( $handler ) {
4588 $handlerClass = get_class( $handler );
4592 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4593 # Initialise static lists
4594 static $internalParamNames = array(
4595 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4596 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4597 'bottom', 'text-bottom' ),
4598 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4599 'upright', 'border', 'link', 'alt' ),
4601 static $internalParamMap;
4602 if ( !$internalParamMap ) {
4603 $internalParamMap = array();
4604 foreach ( $internalParamNames as $type => $names ) {
4605 foreach ( $names as $name ) {
4606 $magicName = str_replace( '-', '_', "img_$name" );
4607 $internalParamMap[$magicName] = array( $type, $name );
4612 # Add handler params
4613 $paramMap = $internalParamMap;
4615 $handlerParamMap = $handler->getParamMap();
4616 foreach ( $handlerParamMap as $magic => $paramName ) {
4617 $paramMap[$magic] = array( 'handler', $paramName );
4620 $this->mImageParams
[$handlerClass] = $paramMap;
4621 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4623 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4627 * Parse image options text and use it to make an image
4629 * @param $title Title
4630 * @param $options String
4631 * @param $holders LinkHolderArray
4633 function makeImage( $title, $options, $holders = false ) {
4634 # Check if the options text is of the form "options|alt text"
4636 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4637 # * left no resizing, just left align. label is used for alt= only
4638 # * right same, but right aligned
4639 # * none same, but not aligned
4640 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4641 # * center center the image
4642 # * frame Keep original image size, no magnify-button.
4643 # * framed Same as "frame"
4644 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4645 # * upright reduce width for upright images, rounded to full __0 px
4646 # * border draw a 1px border around the image
4647 # * alt Text for HTML alt attribute (defaults to empty)
4648 # * link Set the target of the image link. Can be external, interwiki, or local
4649 # vertical-align values (no % or length right now):
4659 $parts = StringUtils
::explode( "|", $options );
4660 $sk = $this->mOptions
->getSkin();
4662 # Give extensions a chance to select the file revision for us
4663 $skip = $time = $descQuery = false;
4664 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4667 return $sk->link( $title );
4671 $imagename = $title->getDBkey();
4672 $file = wfFindFile( $title, array( 'time' => $time ) );
4674 $handler = $file ?
$file->getHandler() : false;
4676 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4678 # Process the input parameters
4680 $params = array( 'frame' => array(), 'handler' => array(),
4681 'horizAlign' => array(), 'vertAlign' => array() );
4682 foreach ( $parts as $part ) {
4683 $part = trim( $part );
4684 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4686 if ( isset( $paramMap[$magicName] ) ) {
4687 list( $type, $paramName ) = $paramMap[$magicName];
4689 # Special case; width and height come in one variable together
4690 if ( $type === 'handler' && $paramName === 'width' ) {
4692 # (bug 13500) In both cases (width/height and width only),
4693 # permit trailing "px" for backward compatibility.
4694 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4695 $width = intval( $m[1] );
4696 $height = intval( $m[2] );
4697 if ( $handler->validateParam( 'width', $width ) ) {
4698 $params[$type]['width'] = $width;
4701 if ( $handler->validateParam( 'height', $height ) ) {
4702 $params[$type]['height'] = $height;
4705 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4706 $width = intval( $value );
4707 if ( $handler->validateParam( 'width', $width ) ) {
4708 $params[$type]['width'] = $width;
4711 } # else no validation -- bug 13436
4713 if ( $type === 'handler' ) {
4714 # Validate handler parameter
4715 $validated = $handler->validateParam( $paramName, $value );
4717 # Validate internal parameters
4718 switch( $paramName ) {
4721 # @todo Fixme: possibly check validity here for
4722 # manualthumb? downstream behavior seems odd with
4723 # missing manual thumbs.
4725 $value = $this->stripAltText( $value, $holders );
4728 $chars = self
::EXT_LINK_URL_CLASS
;
4729 $prots = $this->mUrlProtocols
;
4730 if ( $value === '' ) {
4731 $paramName = 'no-link';
4734 } elseif ( preg_match( "/^$prots/", $value ) ) {
4735 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4736 $paramName = 'link-url';
4737 $this->mOutput
->addExternalLink( $value );
4741 $linkTitle = Title
::newFromText( $value );
4743 $paramName = 'link-title';
4744 $value = $linkTitle;
4745 $this->mOutput
->addLink( $linkTitle );
4751 # Most other things appear to be empty or numeric...
4752 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4757 $params[$type][$paramName] = $value;
4761 if ( !$validated ) {
4766 # Process alignment parameters
4767 if ( $params['horizAlign'] ) {
4768 $params['frame']['align'] = key( $params['horizAlign'] );
4770 if ( $params['vertAlign'] ) {
4771 $params['frame']['valign'] = key( $params['vertAlign'] );
4774 $params['frame']['caption'] = $caption;
4776 # Will the image be presented in a frame, with the caption below?
4777 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4778 isset( $params['frame']['framed'] ) ||
4779 isset( $params['frame']['thumbnail'] ) ||
4780 isset( $params['frame']['manualthumb'] );
4782 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4783 # came to also set the caption, ordinary text after the image -- which
4784 # makes no sense, because that just repeats the text multiple times in
4785 # screen readers. It *also* came to set the title attribute.
4787 # Now that we have an alt attribute, we should not set the alt text to
4788 # equal the caption: that's worse than useless, it just repeats the
4789 # text. This is the framed/thumbnail case. If there's no caption, we
4790 # use the unnamed parameter for alt text as well, just for the time be-
4791 # ing, if the unnamed param is set and the alt param is not.
4793 # For the future, we need to figure out if we want to tweak this more,
4794 # e.g., introducing a title= parameter for the title; ignoring the un-
4795 # named parameter entirely for images without a caption; adding an ex-
4796 # plicit caption= parameter and preserving the old magic unnamed para-
4798 if ( $imageIsFramed ) { # Framed image
4799 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4800 # No caption or alt text, add the filename as the alt text so
4801 # that screen readers at least get some description of the image
4802 $params['frame']['alt'] = $title->getText();
4804 # Do not set $params['frame']['title'] because tooltips don't make sense
4806 } else { # Inline image
4807 if ( !isset( $params['frame']['alt'] ) ) {
4808 # No alt text, use the "caption" for the alt text
4809 if ( $caption !== '') {
4810 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4812 # No caption, fall back to using the filename for the
4814 $params['frame']['alt'] = $title->getText();
4817 # Use the "caption" for the tooltip text
4818 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4821 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4823 # Linker does the rest
4824 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4826 # Give the handler a chance to modify the parser object
4828 $handler->parserTransformHook( $this, $file );
4834 protected function stripAltText( $caption, $holders ) {
4835 # Strip bad stuff out of the title (tooltip). We can't just use
4836 # replaceLinkHoldersText() here, because if this function is called
4837 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4839 $tooltip = $holders->replaceText( $caption );
4841 $tooltip = $this->replaceLinkHoldersText( $caption );
4844 # make sure there are no placeholders in thumbnail attributes
4845 # that are later expanded to html- so expand them now and
4847 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4848 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4854 * Set a flag in the output object indicating that the content is dynamic and
4855 * shouldn't be cached.
4857 function disableCache() {
4858 wfDebug( "Parser output marked as uncacheable.\n" );
4859 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4860 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4864 * Callback from the Sanitizer for expanding items found in HTML attribute
4865 * values, so they can be safely tested and escaped.
4867 * @param $text String
4868 * @param $frame PPFrame
4872 function attributeStripCallback( &$text, $frame = false ) {
4873 $text = $this->replaceVariables( $text, $frame );
4874 $text = $this->mStripState
->unstripBoth( $text );
4881 function getTags() {
4882 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4886 * Break wikitext input into sections, and either pull or replace
4887 * some particular section's text.
4889 * External callers should use the getSection and replaceSection methods.
4891 * @param $text String: Page wikitext
4892 * @param $section String: a section identifier string of the form:
4893 * <flag1> - <flag2> - ... - <section number>
4895 * Currently the only recognised flag is "T", which means the target section number
4896 * was derived during a template inclusion parse, in other words this is a template
4897 * section edit link. If no flags are given, it was an ordinary section edit link.
4898 * This flag is required to avoid a section numbering mismatch when a section is
4899 * enclosed by <includeonly> (bug 6563).
4901 * The section number 0 pulls the text before the first heading; other numbers will
4902 * pull the given section along with its lower-level subsections. If the section is
4903 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4905 * @param $mode String: one of "get" or "replace"
4906 * @param $newText String: replacement text for section data.
4907 * @return String: for "get", the extracted section text.
4908 * for "replace", the whole page with the section replaced.
4910 private function extractSections( $text, $section, $mode, $newText='' ) {
4912 $this->clearState();
4913 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4914 $this->mOptions
= new ParserOptions
;
4915 $this->setOutputType( self
::OT_PLAIN
);
4917 $frame = $this->getPreprocessor()->newFrame();
4919 # Process section extraction flags
4921 $sectionParts = explode( '-', $section );
4922 $sectionIndex = array_pop( $sectionParts );
4923 foreach ( $sectionParts as $part ) {
4924 if ( $part === 'T' ) {
4925 $flags |
= self
::PTD_FOR_INCLUSION
;
4928 # Preprocess the text
4929 $root = $this->preprocessToDom( $text, $flags );
4931 # <h> nodes indicate section breaks
4932 # They can only occur at the top level, so we can find them by iterating the root's children
4933 $node = $root->getFirstChild();
4935 # Find the target section
4936 if ( $sectionIndex == 0 ) {
4937 # Section zero doesn't nest, level=big
4938 $targetLevel = 1000;
4941 if ( $node->getName() === 'h' ) {
4942 $bits = $node->splitHeading();
4943 if ( $bits['i'] == $sectionIndex ) {
4944 $targetLevel = $bits['level'];
4948 if ( $mode === 'replace' ) {
4949 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4951 $node = $node->getNextSibling();
4957 if ( $mode === 'get' ) {
4964 # Find the end of the section, including nested sections
4966 if ( $node->getName() === 'h' ) {
4967 $bits = $node->splitHeading();
4968 $curLevel = $bits['level'];
4969 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4973 if ( $mode === 'get' ) {
4974 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4976 $node = $node->getNextSibling();
4979 # Write out the remainder (in replace mode only)
4980 if ( $mode === 'replace' ) {
4981 # Output the replacement text
4982 # Add two newlines on -- trailing whitespace in $newText is conventionally
4983 # stripped by the editor, so we need both newlines to restore the paragraph gap
4984 # Only add trailing whitespace if there is newText
4985 if ( $newText != "" ) {
4986 $outText .= $newText . "\n\n";
4990 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4991 $node = $node->getNextSibling();
4995 if ( is_string( $outText ) ) {
4996 # Re-insert stripped tags
4997 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5004 * This function returns the text of a section, specified by a number ($section).
5005 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5006 * the first section before any such heading (section 0).
5008 * If a section contains subsections, these are also returned.
5010 * @param $text String: text to look in
5011 * @param $section String: section identifier
5012 * @param $deftext String: default to return if section is not found
5013 * @return string text of the requested section
5015 public function getSection( $text, $section, $deftext='' ) {
5016 return $this->extractSections( $text, $section, "get", $deftext );
5019 public function replaceSection( $oldtext, $section, $text ) {
5020 return $this->extractSections( $oldtext, $section, "replace", $text );
5024 * Get the ID of the revision we are parsing
5026 * @return Mixed: integer or null
5028 function getRevisionId() {
5029 return $this->mRevisionId
;
5033 * Get the timestamp associated with the current revision, adjusted for
5034 * the default server-local timestamp
5036 function getRevisionTimestamp() {
5037 if ( is_null( $this->mRevisionTimestamp
) ) {
5038 wfProfileIn( __METHOD__
);
5040 $dbr = wfGetDB( DB_SLAVE
);
5041 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5042 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
5044 # Normalize timestamp to internal MW format for timezone processing.
5045 # This has the added side-effect of replacing a null value with
5046 # the current time, which gives us more sensible behavior for
5048 $timestamp = wfTimestamp( TS_MW
, $timestamp );
5050 # The cryptic '' timezone parameter tells to use the site-default
5051 # timezone offset instead of the user settings.
5053 # Since this value will be saved into the parser cache, served
5054 # to other users, and potentially even used inside links and such,
5055 # it needs to be consistent for all visitors.
5056 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5058 wfProfileOut( __METHOD__
);
5060 return $this->mRevisionTimestamp
;
5064 * Get the name of the user that edited the last revision
5066 * @return String: user name
5068 function getRevisionUser() {
5069 # if this template is subst: the revision id will be blank,
5070 # so just use the current user's name
5071 if ( $this->mRevisionId
) {
5072 $revision = Revision
::newFromId( $this->mRevisionId
);
5073 $revuser = $revision->getUserText();
5076 $revuser = $wgUser->getName();
5082 * Mutator for $mDefaultSort
5084 * @param $sort New value
5086 public function setDefaultSort( $sort ) {
5087 $this->mDefaultSort
= $sort;
5091 * Accessor for $mDefaultSort
5092 * Will use the title/prefixed title if none is set
5096 public function getDefaultSort() {
5097 global $wgCategoryPrefixedDefaultSortkey;
5098 if ( $this->mDefaultSort
!== false ) {
5099 return $this->mDefaultSort
;
5100 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
5101 !$wgCategoryPrefixedDefaultSortkey )
5103 return $this->mTitle
->getText();
5105 return $this->mTitle
->getPrefixedText();
5110 * Accessor for $mDefaultSort
5111 * Unlike getDefaultSort(), will return false if none is set
5113 * @return string or false
5115 public function getCustomDefaultSort() {
5116 return $this->mDefaultSort
;
5120 * Try to guess the section anchor name based on a wikitext fragment
5121 * presumably extracted from a heading, for example "Header" from
5124 public function guessSectionNameFromWikiText( $text ) {
5125 # Strip out wikitext links(they break the anchor)
5126 $text = $this->stripSectionName( $text );
5127 $headline = Sanitizer
::decodeCharReferences( $text );
5129 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5130 $headline = trim( $headline );
5131 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5132 $replacearray = array(
5137 array_keys( $replacearray ),
5138 array_values( $replacearray ),
5143 * Strips a text string of wikitext for use in a section anchor
5145 * Accepts a text string and then removes all wikitext from the
5146 * string and leaves only the resultant text (i.e. the result of
5147 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5148 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5149 * to create valid section anchors by mimicing the output of the
5150 * parser when headings are parsed.
5152 * @param $text String: text string to be stripped of wikitext
5153 * for use in a Section anchor
5154 * @return Filtered text string
5156 public function stripSectionName( $text ) {
5157 # Strip internal link markup
5158 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5159 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5161 # Strip external link markup (FIXME: Not Tolerant to blank link text
5162 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5163 # on how many empty links there are on the page - need to figure that out.
5164 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5166 # Parse wikitext quotes (italics & bold)
5167 $text = $this->doQuotes( $text );
5170 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5174 function srvus( $text ) {
5175 return $this->testSrvus( $text, $this->mOutputType
);
5179 * strip/replaceVariables/unstrip for preprocessor regression testing
5181 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5182 $this->clearState();
5183 if ( !$title instanceof Title
) {
5184 $title = Title
::newFromText( $title );
5186 $this->mTitle
= $title;
5187 $this->mOptions
= $options;
5188 $this->setOutputType( $outputType );
5189 $text = $this->replaceVariables( $text );
5190 $text = $this->mStripState
->unstripBoth( $text );
5191 $text = Sanitizer
::removeHTMLtags( $text );
5195 function testPst( $text, $title, $options ) {
5197 if ( !$title instanceof Title
) {
5198 $title = Title
::newFromText( $title );
5200 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5203 function testPreprocess( $text, $title, $options ) {
5204 if ( !$title instanceof Title
) {
5205 $title = Title
::newFromText( $title );
5207 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5210 function markerSkipCallback( $s, $callback ) {
5213 while ( $i < strlen( $s ) ) {
5214 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5215 if ( $markerStart === false ) {
5216 $out .= call_user_func( $callback, substr( $s, $i ) );
5219 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5220 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5221 if ( $markerEnd === false ) {
5222 $out .= substr( $s, $markerStart );
5225 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5226 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5234 function serialiseHalfParsedText( $text ) {
5236 $data['text'] = $text;
5238 # First, find all strip markers, and store their
5240 $stripState = new StripState
;
5242 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5243 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5245 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5246 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5248 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5249 $replaceArray = $stripState->general
;
5250 $stripText = $this->mStripState
->general
->data
[$marker];
5251 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5252 $replaceArray = $stripState->nowiki
;
5253 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5255 throw new MWException( "Hanging strip marker: '$marker'." );
5258 $replaceArray->setPair( $marker, $stripText );
5261 $data['stripstate'] = $stripState;
5263 # Now, find all of our links, and store THEIR
5264 # data in an array! :)
5265 $links = array( 'internal' => array(), 'interwiki' => array() );
5269 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5270 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5273 if ( empty( $links['internal'][$ns] ) ) {
5274 $links['internal'][$ns] = array();
5277 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5278 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5279 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5285 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5286 $data = substr( $text, $start_pos );
5287 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5288 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5289 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5292 $data['linkholder'] = $links;
5299 * @param $data Array
5300 * @param $intPrefix String unique identifying prefix
5303 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5304 if ( !$intPrefix ) {
5305 $intPrefix = $this->getRandomString();
5308 # First, extract the strip state.
5309 $stripState = $data['stripstate'];
5310 $this->mStripState
->general
->merge( $stripState->general
);
5311 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5313 # Now, extract the text, and renumber links
5314 $text = $data['text'];
5315 $links = $data['linkholder'];
5318 foreach ( $links['internal'] as $ns => $nsLinks ) {
5319 foreach ( $nsLinks as $key => $entry ) {
5320 $newKey = $intPrefix . '-' . $key;
5321 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5323 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5328 foreach ( $links['interwiki'] as $key => $entry ) {
5329 $newKey = "$intPrefix-$key";
5330 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5332 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5335 # Should be good to go.
5341 * @todo document, briefly.
5345 var $general, $nowiki;
5347 function __construct() {
5348 $this->general
= new ReplacementArray
;
5349 $this->nowiki
= new ReplacementArray
;
5352 function unstripGeneral( $text ) {
5353 wfProfileIn( __METHOD__
);
5356 $text = $this->general
->replace( $text );
5357 } while ( $text !== $oldText );
5358 wfProfileOut( __METHOD__
);
5362 function unstripNoWiki( $text ) {
5363 wfProfileIn( __METHOD__
);
5366 $text = $this->nowiki
->replace( $text );
5367 } while ( $text !== $oldText );
5368 wfProfileOut( __METHOD__
);
5372 function unstripBoth( $text ) {
5373 wfProfileIn( __METHOD__
);
5376 $text = $this->general
->replace( $text );
5377 $text = $this->nowiki
->replace( $text );
5378 } while ( $text !== $oldText );
5379 wfProfileOut( __METHOD__
);
5385 * @todo document, briefly.
5388 class OnlyIncludeReplacer
{
5391 function replace( $matches ) {
5392 if ( substr( $matches[1], -1 ) === "\n" ) {
5393 $this->output
.= substr( $matches[1], 0, -1 );
5395 $this->output
.= $matches[1];