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
106 var $mUser; # User object; only used when doing pre-save transform
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions; # ParserOptions object
111 var $mTitle; # Title context, used for self-link rendering and similar things
112 var $mOutputType; # Output type, one of the OT_xxx constants
113 var $ot; # Shortcut alias, see setOutputType()
114 var $mRevisionObject; # The revision object of the specified revision ID
115 var $mRevisionId; # ID to display in {{REVISIONID}} tags
116 var $mRevisionTimestamp; # The timestamp of the specified revision ID
117 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
118 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionTagHooks
= array();
131 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
132 $this->mDefaultStripList
= $this->mStripList
= array();
133 $this->mUrlProtocols
= wfUrlProtocols();
134 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
135 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
136 $this->mVarCache
= array();
137 if ( isset( $conf['preprocessorClass'] ) ) {
138 $this->mPreprocessorClass
= $conf['preprocessorClass'];
139 } elseif ( extension_loaded( 'domxml' ) ) {
140 # PECL extension that conflicts with the core DOM extension (bug 13770)
141 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
142 $this->mPreprocessorClass
= 'Preprocessor_Hash';
143 } elseif ( extension_loaded( 'dom' ) ) {
144 $this->mPreprocessorClass
= 'Preprocessor_DOM';
146 $this->mPreprocessorClass
= 'Preprocessor_Hash';
148 $this->mMarkerIndex
= 0;
149 $this->mFirstCall
= true;
153 * Reduce memory usage to reduce the impact of circular references
155 function __destruct() {
156 if ( isset( $this->mLinkHolders
) ) {
157 $this->mLinkHolders
->__destruct();
159 foreach ( $this as $name => $value ) {
160 unset( $this->$name );
165 * Do various kinds of initialisation on the first call of the parser
167 function firstCallInit() {
168 if ( !$this->mFirstCall
) {
171 $this->mFirstCall
= false;
173 wfProfileIn( __METHOD__
);
175 CoreParserFunctions
::register( $this );
176 CoreTagHooks
::register( $this );
177 $this->initialiseVariables();
179 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
180 wfProfileOut( __METHOD__
);
188 function clearState() {
189 wfProfileIn( __METHOD__
);
190 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= new StripState
;
199 $this->mArgStack
= false;
200 $this->mInPre
= false;
201 $this->mLinkHolders
= new LinkHolderArray( $this );
203 $this->mRevisionObject
= $this->mRevisionTimestamp
=
204 $this->mRevisionId
= $this->mRevisionUser
= null;
205 $this->mVarCache
= array();
209 * Prefix for temporary replacement strings for the multipass parser.
210 * \x07 should never appear in input as it's disallowed in XML.
211 * Using it at the front also gives us a little extra robustness
212 * since it shouldn't match when butted up against identifier-like
215 * Must not consist of all title characters, or else it will change
216 * the behaviour of <nowiki> in a link.
218 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
219 # Changed to \x7f to allow XML double-parsing -- TS
220 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
226 $this->mShowToc
= true;
227 $this->mForceTocPosition
= false;
228 $this->mIncludeSizes
= array(
232 $this->mPPNodeCount
= 0;
233 $this->mDefaultSort
= false;
234 $this->mHeadings
= array();
235 $this->mDoubleUnderscores
= array();
236 $this->mExpensiveFunctionCount
= 0;
239 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
240 $this->mPreprocessor
= null;
243 wfRunHooks( 'ParserClearState', array( &$this ) );
244 wfProfileOut( __METHOD__
);
248 * Convert wikitext to HTML
249 * Do not call this function recursively.
251 * @param $text String: text we want to parse
252 * @param $title A title object
253 * @param $options ParserOptions
254 * @param $linestart boolean
255 * @param $clearState boolean
256 * @param $revid Int: number to pass in {{REVISIONID}}
257 * @return ParserOutput a ParserOutput
259 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
261 * First pass--just handle <nowiki> sections, pass the rest off
262 * to internalParse() which does all the real work.
265 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
266 $fname = __METHOD__
.'-' . wfGetCaller();
267 wfProfileIn( __METHOD__
);
268 wfProfileIn( $fname );
274 $options->resetUsage();
275 $this->mOptions
= $options;
276 $this->setTitle( $title ); # Page title has to be set for the pre-processor
278 $oldRevisionId = $this->mRevisionId
;
279 $oldRevisionObject = $this->mRevisionObject
;
280 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
281 $oldRevisionUser = $this->mRevisionUser
;
282 if ( $revid !== null ) {
283 $this->mRevisionId
= $revid;
284 $this->mRevisionObject
= null;
285 $this->mRevisionTimestamp
= null;
286 $this->mRevisionUser
= null;
288 $this->setOutputType( self
::OT_HTML
);
289 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
291 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
292 $text = $this->internalParse( $text );
294 $text = $this->mStripState
->unstripGeneral( $text );
296 # Clean up special characters, only run once, next-to-last before doBlockLevels
298 # french spaces, last one Guillemet-left
299 # only if there is something before the space
300 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
301 # french spaces, Guillemet-right
302 '/(\\302\\253) /' => '\\1 ',
303 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
305 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
307 $text = $this->doBlockLevels( $text, $linestart );
309 $this->replaceLinkHolders( $text );
312 * The page doesn't get language converted if
314 * b) Content isn't converted
315 * c) It's a conversion table
317 if ( !( $wgDisableLangConversion
318 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
319 ||
$this->mTitle
->isConversionTable() ) ) {
321 # The position of the convert() call should not be changed. it
322 # assumes that the links are all replaced and the only thing left
323 # is the <nowiki> mark.
325 $text = $wgContLang->convert( $text );
329 * A page get its title converted except:
330 * a) Language conversion is globally disabled
331 * b) Title convert is globally disabled
332 * c) The page is a redirect page
333 * d) User request with a "linkconvert" set to "no"
334 * e) A "nocontentconvert" magic word has been set
335 * f) A "notitleconvert" magic word has been set
336 * g) User sets "noconvertlink" in his/her preference
338 * Note that if a user tries to set a title in a conversion
339 * rule but content conversion was not done, then the parser
340 * won't pick it up. This is probably expected behavior.
342 if ( !( $wgDisableLangConversion
343 ||
$wgDisableTitleConversion
344 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
345 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
346 ||
$this->mOutput
->getDisplayTitle() !== false ) )
348 $convruletitle = $wgContLang->getConvRuleTitle();
349 if ( $convruletitle ) {
350 $this->mOutput
->setTitleText( $convruletitle );
352 $titleText = $wgContLang->convertTitle( $title );
353 $this->mOutput
->setTitleText( $titleText );
357 $text = $this->mStripState
->unstripNoWiki( $text );
359 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
361 //!JF Move to its own function
363 $uniq_prefix = $this->mUniqPrefix
;
365 $elements = array_keys( $this->mTransparentTagHooks
);
366 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
368 foreach ( $matches as $marker => $data ) {
369 list( $element, $content, $params, $tag ) = $data;
370 $tagName = strtolower( $element );
371 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
372 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
376 $this->mStripState
->general
->setPair( $marker, $output );
378 $text = $this->mStripState
->unstripGeneral( $text );
380 $text = Sanitizer
::normalizeCharReferences( $text );
382 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
383 $text = MWTidy
::tidy( $text );
385 # attempt to sanitize at least some nesting problems
386 # (bug #2702 and quite a few others)
388 # ''Something [http://www.cool.com cool''] -->
389 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
390 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
391 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
392 # fix up an anchor inside another anchor, only
393 # at least for a single single nested link (bug 3695)
394 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
395 '\\1\\2</a>\\3</a>\\1\\4</a>',
396 # fix div inside inline elements- doBlockLevels won't wrap a line which
397 # contains a div, so fix it up here; replace
398 # div with escaped text
399 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
400 '\\1\\3<div\\5>\\6</div>\\8\\9',
401 # remove empty italic or bold tag pairs, some
402 # introduced by rules above
403 '/<([bi])><\/\\1>/' => '',
406 $text = preg_replace(
407 array_keys( $tidyregs ),
408 array_values( $tidyregs ),
411 global $wgExpensiveParserFunctionLimit;
412 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
413 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
416 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
418 # Information on include size limits, for the benefit of users who try to skirt them
419 if ( $this->mOptions
->getEnableLimitReport() ) {
420 $max = $this->mOptions
->getMaxIncludeSize();
421 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
423 "NewPP limit report\n" .
424 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
425 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
426 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
428 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
429 $text .= "\n<!-- \n$limitReport-->\n";
431 $this->mOutput
->setText( $text );
433 $this->mRevisionId
= $oldRevisionId;
434 $this->mRevisionObject
= $oldRevisionObject;
435 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
436 $this->mRevisionUser
= $oldRevisionUser;
437 wfProfileOut( $fname );
438 wfProfileOut( __METHOD__
);
440 return $this->mOutput
;
444 * Recursive parser entry point that can be called from an extension tag
447 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
449 * @param $text String: text extension wants to have parsed
450 * @param $frame PPFrame: The frame to use for expanding any template variables
452 function recursiveTagParse( $text, $frame=false ) {
453 wfProfileIn( __METHOD__
);
454 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
455 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
456 $text = $this->internalParse( $text, false, $frame );
457 wfProfileOut( __METHOD__
);
462 * Expand templates and variables in the text, producing valid, static wikitext.
463 * Also removes comments.
465 function preprocess( $text, $title, $options, $revid = null ) {
466 wfProfileIn( __METHOD__
);
468 $this->setOutputType( self
::OT_PREPROCESS
);
469 $options->resetUsage();
470 $this->mOptions
= $options;
471 $this->setTitle( $title );
472 if ( $revid !== null ) {
473 $this->mRevisionId
= $revid;
475 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
476 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
477 $text = $this->replaceVariables( $text );
478 $text = $this->mStripState
->unstripBoth( $text );
479 wfProfileOut( __METHOD__
);
484 * Process the wikitext for the ?preload= feature. (bug 5210)
486 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
487 * comments, templates, arguments, tags hooks and parser functions are untouched.
489 public function getPreloadText( $text, $title, $options ) {
490 # Parser (re)initialisation
492 $this->setOutputType( self
::OT_PLAIN
);
493 $options->resetUsage();
494 $this->mOptions
= $options;
495 $this->setTitle( $title );
497 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
498 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
499 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
503 * Get a random string
508 static private function getRandomString() {
509 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
513 * Set the current user.
514 * Should only be used when doing pre-save transform.
516 * @param $user Mixed: User object or null (to reset)
518 function setUser( $user ) {
519 $this->mUser
= $user;
523 * Accessor for mUniqPrefix.
527 public function uniqPrefix() {
528 if ( !isset( $this->mUniqPrefix
) ) {
529 # @todo Fixme: this is probably *horribly wrong*
530 # LanguageConverter seems to want $wgParser's uniqPrefix, however
531 # if this is called for a parser cache hit, the parser may not
532 # have ever been initialized in the first place.
533 # Not really sure what the heck is supposed to be going on here.
535 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
537 return $this->mUniqPrefix
;
541 * Set the context title
543 function setTitle( $t ) {
544 if ( !$t ||
$t instanceof FakeTitle
) {
545 $t = Title
::newFromText( 'NO TITLE' );
548 if ( strval( $t->getFragment() ) !== '' ) {
549 # Strip the fragment to avoid various odd effects
550 $this->mTitle
= clone $t;
551 $this->mTitle
->setFragment( '' );
558 * Accessor for the Title object
560 * @return Title object
562 function getTitle() {
563 return $this->mTitle
;
567 * Accessor/mutator for the Title object
569 * @param $x New Title object or null to just get the current one
570 * @return Title object
572 function Title( $x = null ) {
573 return wfSetVar( $this->mTitle
, $x );
577 * Set the output type
579 * @param $ot Integer: new value
581 function setOutputType( $ot ) {
582 $this->mOutputType
= $ot;
585 'html' => $ot == self
::OT_HTML
,
586 'wiki' => $ot == self
::OT_WIKI
,
587 'pre' => $ot == self
::OT_PREPROCESS
,
588 'plain' => $ot == self
::OT_PLAIN
,
593 * Accessor/mutator for the output type
595 * @param $x New value or null to just get the current one
598 function OutputType( $x = null ) {
599 return wfSetVar( $this->mOutputType
, $x );
603 * Get the ParserOutput object
605 * @return ParserOutput object
607 function getOutput() {
608 return $this->mOutput
;
612 * Get the ParserOptions object
614 * @return ParserOptions object
616 function getOptions() {
617 return $this->mOptions
;
621 * Accessor/mutator for the ParserOptions object
623 * @param $x New value or null to just get the current one
624 * @return Current ParserOptions object
626 function Options( $x = null ) {
627 return wfSetVar( $this->mOptions
, $x );
630 function nextLinkID() {
631 return $this->mLinkID++
;
634 function getFunctionLang() {
635 global $wgLang, $wgContLang;
637 $target = $this->mOptions
->getTargetLanguage();
638 if ( $target !== null ) {
641 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
646 * Get a User object either from $this->mUser, if set, or from the
647 * ParserOptions object otherwise
649 * @return User object
652 if( !is_null( $this->mUser
) )
654 return $this->mOptions
->getUser();
658 * Get a preprocessor object
660 * @return Preprocessor instance
662 function getPreprocessor() {
663 if ( !isset( $this->mPreprocessor
) ) {
664 $class = $this->mPreprocessorClass
;
665 $this->mPreprocessor
= new $class( $this );
667 return $this->mPreprocessor
;
671 * Replaces all occurrences of HTML-style comments and the given tags
672 * in the text with a random marker and returns the next text. The output
673 * parameter $matches will be an associative array filled with data in
675 * 'UNIQ-xxxxx' => array(
678 * array( 'param' => 'x' ),
679 * '<element param="x">tag content</element>' ) )
681 * @param $elements list of element names. Comments are always extracted.
682 * @param $text Source text string.
683 * @param $matches Out parameter, Array: extracted tags
684 * @param $uniq_prefix
685 * @return String: stripped text
689 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
694 $taglist = implode( '|', $elements );
695 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
697 while ( $text != '' ) {
698 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
700 if ( count( $p ) < 5 ) {
703 if ( count( $p ) > 5 ) {
717 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
718 $stripped .= $marker;
720 if ( $close === '/>' ) {
721 # Empty element tag, <tag />
726 if ( $element === '!--' ) {
729 $end = "/(<\\/$element\\s*>)/i";
731 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
733 if ( count( $q ) < 3 ) {
734 # No end tag -- let it run out to the end of the text.
743 $matches[$marker] = array( $element,
745 Sanitizer
::decodeTagAttributes( $attributes ),
746 "<$element$attributes$close$content$tail" );
752 * Get a list of strippable XML-like elements
754 function getStripList() {
755 return $this->mStripList
;
759 * @deprecated use replaceVariables
761 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
766 * Restores pre, math, and other extensions removed by strip()
768 * always call unstripNoWiki() after this one
770 * @deprecated use $this->mStripState->unstrip()
772 function unstrip( $text, $state ) {
773 return $state->unstripGeneral( $text );
777 * Always call this after unstrip() to preserve the order
780 * @deprecated use $this->mStripState->unstrip()
782 function unstripNoWiki( $text, $state ) {
783 return $state->unstripNoWiki( $text );
787 * @deprecated use $this->mStripState->unstripBoth()
789 function unstripForHTML( $text ) {
790 return $this->mStripState
->unstripBoth( $text );
794 * Add an item to the strip state
795 * Returns the unique tag which must be inserted into the stripped text
796 * The tag will be replaced with the original text in unstrip()
800 function insertStripItem( $text ) {
801 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
802 $this->mMarkerIndex++
;
803 $this->mStripState
->general
->setPair( $rnd, $text );
808 * Interface with html tidy
809 * @deprecated Use MWTidy::tidy()
811 public static function tidy( $text ) {
812 wfDeprecated( __METHOD__
);
813 return MWTidy
::tidy( $text );
817 * parse the wiki syntax used to render tables
821 function doTableStuff( $text ) {
822 wfProfileIn( __METHOD__
);
824 $lines = StringUtils
::explode( "\n", $text );
826 $td_history = array(); # Is currently a td tag open?
827 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
828 $tr_history = array(); # Is currently a tr tag open?
829 $tr_attributes = array(); # history of tr attributes
830 $has_opened_tr = array(); # Did this table open a <tr> element?
831 $indent_level = 0; # indent level of the table
833 foreach ( $lines as $outLine ) {
834 $line = trim( $outLine );
836 if ( $line === '' ) { # empty line, go to next line
837 $out .= $outLine."\n";
841 $first_character = $line[0];
844 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
845 # First check if we are starting a new table
846 $indent_level = strlen( $matches[1] );
848 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
849 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
851 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
852 array_push( $td_history , false );
853 array_push( $last_tag_history , '' );
854 array_push( $tr_history , false );
855 array_push( $tr_attributes , '' );
856 array_push( $has_opened_tr , false );
857 } elseif ( count( $td_history ) == 0 ) {
858 # Don't do any of the following
859 $out .= $outLine."\n";
861 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
862 # We are ending a table
863 $line = '</table>' . substr( $line , 2 );
864 $last_tag = array_pop( $last_tag_history );
866 if ( !array_pop( $has_opened_tr ) ) {
867 $line = "<tr><td></td></tr>{$line}";
870 if ( array_pop( $tr_history ) ) {
871 $line = "</tr>{$line}";
874 if ( array_pop( $td_history ) ) {
875 $line = "</{$last_tag}>{$line}";
877 array_pop( $tr_attributes );
878 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
879 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
880 # Now we have a table row
881 $line = preg_replace( '#^\|-+#', '', $line );
883 # Whats after the tag is now only attributes
884 $attributes = $this->mStripState
->unstripBoth( $line );
885 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
886 array_pop( $tr_attributes );
887 array_push( $tr_attributes, $attributes );
890 $last_tag = array_pop( $last_tag_history );
891 array_pop( $has_opened_tr );
892 array_push( $has_opened_tr , true );
894 if ( array_pop( $tr_history ) ) {
898 if ( array_pop( $td_history ) ) {
899 $line = "</{$last_tag}>{$line}";
903 array_push( $tr_history , false );
904 array_push( $td_history , false );
905 array_push( $last_tag_history , '' );
906 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
907 # This might be cell elements, td, th or captions
908 if ( substr( $line , 0 , 2 ) === '|+' ) {
909 $first_character = '+';
910 $line = substr( $line , 1 );
913 $line = substr( $line , 1 );
915 if ( $first_character === '!' ) {
916 $line = str_replace( '!!' , '||' , $line );
919 # Split up multiple cells on the same line.
920 # FIXME : This can result in improper nesting of tags processed
921 # by earlier parser steps, but should avoid splitting up eg
922 # attribute values containing literal "||".
923 $cells = StringUtils
::explodeMarkup( '||' , $line );
927 # Loop through each table cell
928 foreach ( $cells as $cell ) {
930 if ( $first_character !== '+' ) {
931 $tr_after = array_pop( $tr_attributes );
932 if ( !array_pop( $tr_history ) ) {
933 $previous = "<tr{$tr_after}>\n";
935 array_push( $tr_history , true );
936 array_push( $tr_attributes , '' );
937 array_pop( $has_opened_tr );
938 array_push( $has_opened_tr , true );
941 $last_tag = array_pop( $last_tag_history );
943 if ( array_pop( $td_history ) ) {
944 $previous = "</{$last_tag}>\n{$previous}";
947 if ( $first_character === '|' ) {
949 } elseif ( $first_character === '!' ) {
951 } elseif ( $first_character === '+' ) {
952 $last_tag = 'caption';
957 array_push( $last_tag_history , $last_tag );
959 # A cell could contain both parameters and data
960 $cell_data = explode( '|' , $cell , 2 );
962 # Bug 553: Note that a '|' inside an invalid link should not
963 # be mistaken as delimiting cell parameters
964 if ( strpos( $cell_data[0], '[[' ) !== false ) {
965 $cell = "{$previous}<{$last_tag}>{$cell}";
966 } elseif ( count( $cell_data ) == 1 ) {
967 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
969 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
970 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
971 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
975 array_push( $td_history , true );
978 $out .= $outLine . "\n";
981 # Closing open td, tr && table
982 while ( count( $td_history ) > 0 ) {
983 if ( array_pop( $td_history ) ) {
986 if ( array_pop( $tr_history ) ) {
989 if ( !array_pop( $has_opened_tr ) ) {
990 $out .= "<tr><td></td></tr>\n" ;
993 $out .= "</table>\n";
996 # Remove trailing line-ending (b/c)
997 if ( substr( $out, -1 ) === "\n" ) {
998 $out = substr( $out, 0, -1 );
1001 # special case: don't return empty table
1002 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1006 wfProfileOut( __METHOD__
);
1012 * Helper function for parse() that transforms wiki markup into
1013 * HTML. Only called for $mOutputType == self::OT_HTML.
1017 function internalParse( $text, $isMain = true, $frame=false ) {
1018 wfProfileIn( __METHOD__
);
1022 # Hook to suspend the parser in this state
1023 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1024 wfProfileOut( __METHOD__
);
1028 # if $frame is provided, then use $frame for replacing any variables
1030 # use frame depth to infer how include/noinclude tags should be handled
1031 # depth=0 means this is the top-level document; otherwise it's an included document
1032 if ( !$frame->depth
) {
1035 $flag = Parser
::PTD_FOR_INCLUSION
;
1037 $dom = $this->preprocessToDom( $text, $flag );
1038 $text = $frame->expand( $dom );
1040 # if $frame is not provided, then use old-style replaceVariables
1041 $text = $this->replaceVariables( $text );
1044 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1045 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1047 # Tables need to come after variable replacement for things to work
1048 # properly; putting them before other transformations should keep
1049 # exciting things like link expansions from showing up in surprising
1051 $text = $this->doTableStuff( $text );
1053 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1055 $text = $this->doDoubleUnderscore( $text );
1057 $text = $this->doHeadings( $text );
1058 if ( $this->mOptions
->getUseDynamicDates() ) {
1059 $df = DateFormatter
::getInstance();
1060 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1062 $text = $this->replaceInternalLinks( $text );
1063 $text = $this->doAllQuotes( $text );
1064 $text = $this->replaceExternalLinks( $text );
1066 # replaceInternalLinks may sometimes leave behind
1067 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1068 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1070 $text = $this->doMagicLinks( $text );
1071 $text = $this->formatHeadings( $text, $origText, $isMain );
1073 wfProfileOut( __METHOD__
);
1078 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1079 * magic external links.
1084 function doMagicLinks( $text ) {
1085 wfProfileIn( __METHOD__
);
1086 $prots = $this->mUrlProtocols
;
1087 $urlChar = self
::EXT_LINK_URL_CLASS
;
1088 $text = preg_replace_callback(
1090 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1091 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1092 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1093 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1094 ISBN\s+(\b # m[5]: ISBN, capture number
1095 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1096 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1097 [0-9Xx] # check digit
1099 )!x', array( &$this, 'magicLinkCallback' ), $text );
1100 wfProfileOut( __METHOD__
);
1104 function magicLinkCallback( $m ) {
1105 if ( isset( $m[1] ) && $m[1] !== '' ) {
1108 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1111 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1112 # Free external link
1113 return $this->makeFreeExternalLink( $m[0] );
1114 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1116 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1119 $CssClass = 'mw-magiclink-rfc';
1121 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1123 $urlmsg = 'pubmedurl';
1124 $CssClass = 'mw-magiclink-pmid';
1127 throw new MWException( __METHOD__
.': unrecognised match type "' .
1128 substr( $m[0], 0, 20 ) . '"' );
1130 $url = wfMsgForContent( $urlmsg, $id);
1131 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1132 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1133 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1134 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1137 $num = strtr( $isbn, array(
1142 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1144 $titleObj->escapeLocalUrl() .
1145 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1152 * Make a free external link, given a user-supplied URL
1156 function makeFreeExternalLink( $url ) {
1158 wfProfileIn( __METHOD__
);
1160 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1163 # The characters '<' and '>' (which were escaped by
1164 # removeHTMLtags()) should not be included in
1165 # URLs, per RFC 2396.
1167 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1168 $trail = substr( $url, $m2[0][1] ) . $trail;
1169 $url = substr( $url, 0, $m2[0][1] );
1172 # Move trailing punctuation to $trail
1174 # If there is no left bracket, then consider right brackets fair game too
1175 if ( strpos( $url, '(' ) === false ) {
1179 $numSepChars = strspn( strrev( $url ), $sep );
1180 if ( $numSepChars ) {
1181 $trail = substr( $url, -$numSepChars ) . $trail;
1182 $url = substr( $url, 0, -$numSepChars );
1185 $url = Sanitizer
::cleanUrl( $url );
1187 # Is this an external image?
1188 $text = $this->maybeMakeExternalImage( $url );
1189 if ( $text === false ) {
1190 # Not an image, make a link
1191 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1192 $this->getExternalLinkAttribs( $url ) );
1193 # Register it in the output object...
1194 # Replace unnecessary URL escape codes with their equivalent characters
1195 $pasteurized = self
::replaceUnusualEscapes( $url );
1196 $this->mOutput
->addExternalLink( $pasteurized );
1198 wfProfileOut( __METHOD__
);
1199 return $text . $trail;
1204 * Parse headers and return html
1208 function doHeadings( $text ) {
1209 wfProfileIn( __METHOD__
);
1210 for ( $i = 6; $i >= 1; --$i ) {
1211 $h = str_repeat( '=', $i );
1212 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1213 "<h$i>\\1</h$i>", $text );
1215 wfProfileOut( __METHOD__
);
1220 * Replace single quotes with HTML markup
1222 * @return string the altered text
1224 function doAllQuotes( $text ) {
1225 wfProfileIn( __METHOD__
);
1227 $lines = StringUtils
::explode( "\n", $text );
1228 foreach ( $lines as $line ) {
1229 $outtext .= $this->doQuotes( $line ) . "\n";
1231 $outtext = substr( $outtext, 0,-1 );
1232 wfProfileOut( __METHOD__
);
1237 * Helper function for doAllQuotes()
1239 public function doQuotes( $text ) {
1240 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1241 if ( count( $arr ) == 1 ) {
1244 # First, do some preliminary work. This may shift some apostrophes from
1245 # being mark-up to being text. It also counts the number of occurrences
1246 # of bold and italics mark-ups.
1249 for ( $i = 0; $i < count( $arr ); $i++
) {
1250 if ( ( $i %
2 ) == 1 ) {
1251 # If there are ever four apostrophes, assume the first is supposed to
1252 # be text, and the remaining three constitute mark-up for bold text.
1253 if ( strlen( $arr[$i] ) == 4 ) {
1256 } elseif ( strlen( $arr[$i] ) > 5 ) {
1257 # If there are more than 5 apostrophes in a row, assume they're all
1258 # text except for the last 5.
1259 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1262 # Count the number of occurrences of bold and italics mark-ups.
1263 # We are not counting sequences of five apostrophes.
1264 if ( strlen( $arr[$i] ) == 2 ) {
1266 } elseif ( strlen( $arr[$i] ) == 3 ) {
1268 } elseif ( strlen( $arr[$i] ) == 5 ) {
1275 # If there is an odd number of both bold and italics, it is likely
1276 # that one of the bold ones was meant to be an apostrophe followed
1277 # by italics. Which one we cannot know for certain, but it is more
1278 # likely to be one that has a single-letter word before it.
1279 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1281 $firstsingleletterword = -1;
1282 $firstmultiletterword = -1;
1284 foreach ( $arr as $r ) {
1285 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1286 $x1 = substr( $arr[$i-1], -1 );
1287 $x2 = substr( $arr[$i-1], -2, 1 );
1288 if ( $x1 === ' ' ) {
1289 if ( $firstspace == -1 ) {
1292 } elseif ( $x2 === ' ') {
1293 if ( $firstsingleletterword == -1 ) {
1294 $firstsingleletterword = $i;
1297 if ( $firstmultiletterword == -1 ) {
1298 $firstmultiletterword = $i;
1305 # If there is a single-letter word, use it!
1306 if ( $firstsingleletterword > -1 ) {
1307 $arr[$firstsingleletterword] = "''";
1308 $arr[$firstsingleletterword-1] .= "'";
1309 } elseif ( $firstmultiletterword > -1 ) {
1310 # If not, but there's a multi-letter word, use that one.
1311 $arr[$firstmultiletterword] = "''";
1312 $arr[$firstmultiletterword-1] .= "'";
1313 } elseif ( $firstspace > -1 ) {
1314 # ... otherwise use the first one that has neither.
1315 # (notice that it is possible for all three to be -1 if, for example,
1316 # there is only one pentuple-apostrophe in the line)
1317 $arr[$firstspace] = "''";
1318 $arr[$firstspace-1] .= "'";
1322 # Now let's actually convert our apostrophic mush to HTML!
1327 foreach ( $arr as $r ) {
1328 if ( ( $i %
2 ) == 0 ) {
1329 if ( $state === 'both' ) {
1335 if ( strlen( $r ) == 2 ) {
1336 if ( $state === 'i' ) {
1337 $output .= '</i>'; $state = '';
1338 } elseif ( $state === 'bi' ) {
1339 $output .= '</i>'; $state = 'b';
1340 } elseif ( $state === 'ib' ) {
1341 $output .= '</b></i><b>'; $state = 'b';
1342 } elseif ( $state === 'both' ) {
1343 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1344 } else { # $state can be 'b' or ''
1345 $output .= '<i>'; $state .= 'i';
1347 } elseif ( strlen( $r ) == 3 ) {
1348 if ( $state === 'b' ) {
1349 $output .= '</b>'; $state = '';
1350 } elseif ( $state === 'bi' ) {
1351 $output .= '</i></b><i>'; $state = 'i';
1352 } elseif ( $state === 'ib' ) {
1353 $output .= '</b>'; $state = 'i';
1354 } elseif ( $state === 'both' ) {
1355 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1356 } else { # $state can be 'i' or ''
1357 $output .= '<b>'; $state .= 'b';
1359 } elseif ( strlen( $r ) == 5 ) {
1360 if ( $state === 'b' ) {
1361 $output .= '</b><i>'; $state = 'i';
1362 } elseif ( $state === 'i' ) {
1363 $output .= '</i><b>'; $state = 'b';
1364 } elseif ( $state === 'bi' ) {
1365 $output .= '</i></b>'; $state = '';
1366 } elseif ( $state === 'ib' ) {
1367 $output .= '</b></i>'; $state = '';
1368 } elseif ( $state === 'both' ) {
1369 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1370 } else { # ($state == '')
1371 $buffer = ''; $state = 'both';
1377 # Now close all remaining tags. Notice that the order is important.
1378 if ( $state === 'b' ||
$state === 'ib' ) {
1381 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1384 if ( $state === 'bi' ) {
1387 # There might be lonely ''''', so make sure we have a buffer
1388 if ( $state === 'both' && $buffer ) {
1389 $output .= '<b><i>'.$buffer.'</i></b>';
1396 * Replace external links (REL)
1398 * Note: this is all very hackish and the order of execution matters a lot.
1399 * Make sure to run maintenance/parserTests.php if you change this code.
1403 function replaceExternalLinks( $text ) {
1405 wfProfileIn( __METHOD__
);
1407 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1409 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1410 $s = array_shift( $bits );
1413 while ( $i<count( $bits ) ) {
1415 $protocol = $bits[$i++
];
1416 $text = $bits[$i++
];
1417 $trail = $bits[$i++
];
1419 # The characters '<' and '>' (which were escaped by
1420 # removeHTMLtags()) should not be included in
1421 # URLs, per RFC 2396.
1423 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1424 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1425 $url = substr( $url, 0, $m2[0][1] );
1428 # If the link text is an image URL, replace it with an <img> tag
1429 # This happened by accident in the original parser, but some people used it extensively
1430 $img = $this->maybeMakeExternalImage( $text );
1431 if ( $img !== false ) {
1437 # Set linktype for CSS - if URL==text, link is essentially free
1438 $linktype = ( $text === $url ) ?
'free' : 'text';
1440 # No link text, e.g. [http://domain.tld/some.link]
1441 if ( $text == '' ) {
1442 # Autonumber if allowed. See bug #5918
1443 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1444 $langObj = $this->getFunctionLang();
1445 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1446 $linktype = 'autonumber';
1448 # Otherwise just use the URL
1449 $text = htmlspecialchars( $url );
1453 # Have link text, e.g. [http://domain.tld/some.link text]s
1455 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1458 $text = $wgContLang->markNoConversion( $text );
1460 $url = Sanitizer
::cleanUrl( $url );
1462 # Use the encoded URL
1463 # This means that users can paste URLs directly into the text
1464 # Funny characters like ö aren't valid in URLs anyway
1465 # This was changed in August 2004
1466 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1467 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1469 # Register link in the output object.
1470 # Replace unnecessary URL escape codes with the referenced character
1471 # This prevents spammers from hiding links from the filters
1472 $pasteurized = self
::replaceUnusualEscapes( $url );
1473 $this->mOutput
->addExternalLink( $pasteurized );
1476 wfProfileOut( __METHOD__
);
1481 * Get an associative array of additional HTML attributes appropriate for a
1482 * particular external link. This currently may include rel => nofollow
1483 * (depending on configuration, namespace, and the URL's domain) and/or a
1484 * target attribute (depending on configuration).
1486 * @param $url String: optional URL, to extract the domain from for rel =>
1487 * nofollow if appropriate
1488 * @return Array: associative array of HTML attributes
1490 function getExternalLinkAttribs( $url = false ) {
1492 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1493 $ns = $this->mTitle
->getNamespace();
1494 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1495 $attribs['rel'] = 'nofollow';
1497 global $wgNoFollowDomainExceptions;
1498 if ( $wgNoFollowDomainExceptions ) {
1499 $bits = wfParseUrl( $url );
1500 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1501 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1502 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1503 unset( $attribs['rel'] );
1510 if ( $this->mOptions
->getExternalLinkTarget() ) {
1511 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1518 * Replace unusual URL escape codes with their equivalent characters
1520 * @param $url String
1523 * @todo This can merge genuinely required bits in the path or query string,
1524 * breaking legit URLs. A proper fix would treat the various parts of
1525 * the URL differently; as a workaround, just use the output for
1526 * statistical records, not for actual linking/output.
1528 static function replaceUnusualEscapes( $url ) {
1529 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1530 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1534 * Callback function used in replaceUnusualEscapes().
1535 * Replaces unusual URL escape codes with their equivalent character
1537 private static function replaceUnusualEscapesCallback( $matches ) {
1538 $char = urldecode( $matches[0] );
1539 $ord = ord( $char );
1540 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1541 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1542 # No, shouldn't be escaped
1545 # Yes, leave it escaped
1551 * make an image if it's allowed, either through the global
1552 * option, through the exception, or through the on-wiki whitelist
1555 function maybeMakeExternalImage( $url ) {
1556 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1557 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1558 $imagesexception = !empty( $imagesfrom );
1560 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1561 if ( $imagesexception && is_array( $imagesfrom ) ) {
1562 $imagematch = false;
1563 foreach ( $imagesfrom as $match ) {
1564 if ( strpos( $url, $match ) === 0 ) {
1569 } elseif ( $imagesexception ) {
1570 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1572 $imagematch = false;
1574 if ( $this->mOptions
->getAllowExternalImages()
1575 ||
( $imagesexception && $imagematch ) ) {
1576 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1578 $text = $sk->makeExternalImage( $url );
1581 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1582 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1583 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1584 foreach ( $whitelist as $entry ) {
1585 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1586 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1589 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1590 # Image matches a whitelist entry
1591 $text = $sk->makeExternalImage( $url );
1600 * Process [[ ]] wikilinks
1601 * @return String: processed text
1605 function replaceInternalLinks( $s ) {
1606 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1611 * Process [[ ]] wikilinks (RIL)
1612 * @return LinkHolderArray
1616 function replaceInternalLinks2( &$s ) {
1619 wfProfileIn( __METHOD__
);
1621 wfProfileIn( __METHOD__
.'-setup' );
1622 static $tc = FALSE, $e1, $e1_img;
1623 # the % is needed to support urlencoded titles as well
1625 $tc = Title
::legalChars() . '#%';
1626 # Match a link having the form [[namespace:link|alternate]]trail
1627 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1628 # Match cases where there is no "]]", which might still be images
1629 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1632 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1633 $holders = new LinkHolderArray( $this );
1635 # split the entire text string on occurences of [[
1636 $a = StringUtils
::explode( '[[', ' ' . $s );
1637 # get the first element (all text up to first [[), and remove the space we added
1640 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1641 $s = substr( $s, 1 );
1643 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1645 if ( $useLinkPrefixExtension ) {
1646 # Match the end of a line for a word that's not followed by whitespace,
1647 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1648 $e2 = wfMsgForContent( 'linkprefix' );
1651 if ( is_null( $this->mTitle
) ) {
1652 wfProfileOut( __METHOD__
.'-setup' );
1653 wfProfileOut( __METHOD__
);
1654 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1656 $nottalk = !$this->mTitle
->isTalkPage();
1658 if ( $useLinkPrefixExtension ) {
1660 if ( preg_match( $e2, $s, $m ) ) {
1661 $first_prefix = $m[2];
1663 $first_prefix = false;
1669 if ( $wgContLang->hasVariants() ) {
1670 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1672 $selflink = array( $this->mTitle
->getPrefixedText() );
1674 $useSubpages = $this->areSubpagesAllowed();
1675 wfProfileOut( __METHOD__
.'-setup' );
1677 # Loop for each link
1678 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1679 # Check for excessive memory usage
1680 if ( $holders->isBig() ) {
1682 # Do the existence check, replace the link holders and clear the array
1683 $holders->replace( $s );
1687 if ( $useLinkPrefixExtension ) {
1688 wfProfileIn( __METHOD__
.'-prefixhandling' );
1689 if ( preg_match( $e2, $s, $m ) ) {
1696 if ( $first_prefix ) {
1697 $prefix = $first_prefix;
1698 $first_prefix = false;
1700 wfProfileOut( __METHOD__
.'-prefixhandling' );
1703 $might_be_img = false;
1705 wfProfileIn( __METHOD__
."-e1" );
1706 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1708 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1709 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1710 # the real problem is with the $e1 regex
1713 # Still some problems for cases where the ] is meant to be outside punctuation,
1714 # and no image is in sight. See bug 2095.
1716 if ( $text !== '' &&
1717 substr( $m[3], 0, 1 ) === ']' &&
1718 strpos( $text, '[' ) !== false
1721 $text .= ']'; # so that replaceExternalLinks($text) works later
1722 $m[3] = substr( $m[3], 1 );
1724 # fix up urlencoded title texts
1725 if ( strpos( $m[1], '%' ) !== false ) {
1726 # Should anchors '#' also be rejected?
1727 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1730 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1731 $might_be_img = true;
1733 if ( strpos( $m[1], '%' ) !== false ) {
1734 $m[1] = urldecode( $m[1] );
1737 } else { # Invalid form; output directly
1738 $s .= $prefix . '[[' . $line ;
1739 wfProfileOut( __METHOD__
."-e1" );
1742 wfProfileOut( __METHOD__
."-e1" );
1743 wfProfileIn( __METHOD__
."-misc" );
1745 # Don't allow internal links to pages containing
1746 # PROTO: where PROTO is a valid URL protocol; these
1747 # should be external links.
1748 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1749 $s .= $prefix . '[[' . $line ;
1750 wfProfileOut( __METHOD__
."-misc" );
1754 # Make subpage if necessary
1755 if ( $useSubpages ) {
1756 $link = $this->maybeDoSubpageLink( $m[1], $text );
1761 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1763 # Strip off leading ':'
1764 $link = substr( $link, 1 );
1767 wfProfileOut( __METHOD__
."-misc" );
1768 wfProfileIn( __METHOD__
."-title" );
1769 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1770 if ( $nt === null ) {
1771 $s .= $prefix . '[[' . $line;
1772 wfProfileOut( __METHOD__
."-title" );
1776 $ns = $nt->getNamespace();
1777 $iw = $nt->getInterWiki();
1778 wfProfileOut( __METHOD__
."-title" );
1780 if ( $might_be_img ) { # if this is actually an invalid link
1781 wfProfileIn( __METHOD__
."-might_be_img" );
1782 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1785 # look at the next 'line' to see if we can close it there
1787 $next_line = $a->current();
1788 if ( $next_line === false ||
$next_line === null ) {
1791 $m = explode( ']]', $next_line, 3 );
1792 if ( count( $m ) == 3 ) {
1793 # the first ]] closes the inner link, the second the image
1795 $text .= "[[{$m[0]}]]{$m[1]}";
1798 } elseif ( count( $m ) == 2 ) {
1799 # if there's exactly one ]] that's fine, we'll keep looking
1800 $text .= "[[{$m[0]}]]{$m[1]}";
1802 # if $next_line is invalid too, we need look no further
1803 $text .= '[[' . $next_line;
1808 # we couldn't find the end of this imageLink, so output it raw
1809 # but don't ignore what might be perfectly normal links in the text we've examined
1810 $holders->merge( $this->replaceInternalLinks2( $text ) );
1811 $s .= "{$prefix}[[$link|$text";
1812 # note: no $trail, because without an end, there *is* no trail
1813 wfProfileOut( __METHOD__
."-might_be_img" );
1816 } else { # it's not an image, so output it raw
1817 $s .= "{$prefix}[[$link|$text";
1818 # note: no $trail, because without an end, there *is* no trail
1819 wfProfileOut( __METHOD__
."-might_be_img" );
1822 wfProfileOut( __METHOD__
."-might_be_img" );
1825 $wasblank = ( $text == '' );
1829 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1830 # [[Lista d''e paise d''o munno]] -> <a href="">Lista d''e paise d''o munno</a>
1831 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1832 $text = $this->doQuotes($text);
1835 # Link not escaped by : , create the various objects
1839 wfProfileIn( __METHOD__
."-interwiki" );
1840 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1841 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1842 $s = rtrim( $s . $prefix );
1843 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1844 wfProfileOut( __METHOD__
."-interwiki" );
1847 wfProfileOut( __METHOD__
."-interwiki" );
1849 if ( $ns == NS_FILE
) {
1850 wfProfileIn( __METHOD__
."-image" );
1851 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1853 # if no parameters were passed, $text
1854 # becomes something like "File:Foo.png",
1855 # which we don't want to pass on to the
1859 # recursively parse links inside the image caption
1860 # actually, this will parse them in any other parameters, too,
1861 # but it might be hard to fix that, and it doesn't matter ATM
1862 $text = $this->replaceExternalLinks( $text );
1863 $holders->merge( $this->replaceInternalLinks2( $text ) );
1865 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1866 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1868 $s .= $prefix . $trail;
1870 $this->mOutput
->addImage( $nt->getDBkey() );
1871 wfProfileOut( __METHOD__
."-image" );
1876 if ( $ns == NS_CATEGORY
) {
1877 wfProfileIn( __METHOD__
."-category" );
1878 $s = preg_replace( "/(\s*\n)+\s*$/D", '', $s ); # bug 87
1881 $sortkey = $this->getDefaultSort();
1885 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1886 $sortkey = str_replace( "\n", '', $sortkey );
1887 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1888 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1891 * Strip the whitespace Category links produce, see bug 87
1892 * @todo We might want to use trim($tmp, "\n") here.
1894 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1896 wfProfileOut( __METHOD__
."-category" );
1901 # Self-link checking
1902 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1903 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1904 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1909 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1910 # FIXME: Should do batch file existence checks, see comment below
1911 if ( $ns == NS_MEDIA
) {
1912 wfProfileIn( __METHOD__
."-media" );
1913 # Give extensions a chance to select the file revision for us
1914 $skip = $time = false;
1915 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1917 $link = $sk->link( $nt );
1919 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1921 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1922 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1923 $this->mOutput
->addImage( $nt->getDBkey() );
1924 wfProfileOut( __METHOD__
."-media" );
1928 wfProfileIn( __METHOD__
."-always_known" );
1929 # Some titles, such as valid special pages or files in foreign repos, should
1930 # be shown as bluelinks even though they're not included in the page table
1932 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1933 # batch file existence checks for NS_FILE and NS_MEDIA
1934 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1935 $this->mOutput
->addLink( $nt );
1936 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1938 # Links will be added to the output link list after checking
1939 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1941 wfProfileOut( __METHOD__
."-always_known" );
1943 wfProfileOut( __METHOD__
);
1948 * Make a link placeholder. The text returned can be later resolved to a real link with
1949 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1950 * parsing of interwiki links, and secondly to allow all existence checks and
1951 * article length checks (for stub links) to be bundled into a single query.
1955 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1956 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1960 * Render a forced-blue link inline; protect against double expansion of
1961 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1962 * Since this little disaster has to split off the trail text to avoid
1963 * breaking URLs in the following text without breaking trails on the
1964 * wiki links, it's been made into a horrible function.
1967 * @param $text String
1968 * @param $query String
1969 * @param $trail String
1970 * @param $prefix String
1971 * @return String: HTML-wikitext mix oh yuck
1973 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1974 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1975 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1976 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1977 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1978 return $this->armorLinks( $link ) . $trail;
1982 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1983 * going to go through further parsing steps before inline URL expansion.
1985 * Not needed quite as much as it used to be since free links are a bit
1986 * more sensible these days. But bracketed links are still an issue.
1988 * @param $text String: more-or-less HTML
1989 * @return String: less-or-more HTML with NOPARSE bits
1991 function armorLinks( $text ) {
1992 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1993 "{$this->mUniqPrefix}NOPARSE$1", $text );
1997 * Return true if subpage links should be expanded on this page.
2000 function areSubpagesAllowed() {
2001 # Some namespaces don't allow subpages
2002 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2006 * Handle link to subpage if necessary
2008 * @param $target String: the source of the link
2009 * @param &$text String: the link text, modified as necessary
2010 * @return string the full name of the link
2013 function maybeDoSubpageLink( $target, &$text ) {
2014 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2018 * Used by doBlockLevels()
2021 function closeParagraph() {
2023 if ( $this->mLastSection
!= '' ) {
2024 $result = '</' . $this->mLastSection
. ">\n";
2026 $this->mInPre
= false;
2027 $this->mLastSection
= '';
2032 * getCommon() returns the length of the longest common substring
2033 * of both arguments, starting at the beginning of both.
2036 function getCommon( $st1, $st2 ) {
2037 $fl = strlen( $st1 );
2038 $shorter = strlen( $st2 );
2039 if ( $fl < $shorter ) {
2043 for ( $i = 0; $i < $shorter; ++
$i ) {
2044 if ( $st1{$i} != $st2{$i} ) {
2052 * These next three functions open, continue, and close the list
2053 * element appropriate to the prefix character passed into them.
2056 function openList( $char ) {
2057 $result = $this->closeParagraph();
2059 if ( '*' === $char ) {
2060 $result .= '<ul><li>';
2061 } elseif ( '#' === $char ) {
2062 $result .= '<ol><li>';
2063 } elseif ( ':' === $char ) {
2064 $result .= '<dl><dd>';
2065 } elseif ( ';' === $char ) {
2066 $result .= '<dl><dt>';
2067 $this->mDTopen
= true;
2069 $result = '<!-- ERR 1 -->';
2077 * @param $char String
2080 function nextItem( $char ) {
2081 if ( '*' === $char ||
'#' === $char ) {
2083 } elseif ( ':' === $char ||
';' === $char ) {
2085 if ( $this->mDTopen
) {
2088 if ( ';' === $char ) {
2089 $this->mDTopen
= true;
2090 return $close . '<dt>';
2092 $this->mDTopen
= false;
2093 return $close . '<dd>';
2096 return '<!-- ERR 2 -->';
2101 * @param $char String
2104 function closeList( $char ) {
2105 if ( '*' === $char ) {
2106 $text = '</li></ul>';
2107 } elseif ( '#' === $char ) {
2108 $text = '</li></ol>';
2109 } elseif ( ':' === $char ) {
2110 if ( $this->mDTopen
) {
2111 $this->mDTopen
= false;
2112 $text = '</dt></dl>';
2114 $text = '</dd></dl>';
2117 return '<!-- ERR 3 -->';
2124 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2126 * @param $text String
2127 * @param $linestart Boolean: whether or not this is at the start of a line.
2129 * @return string the lists rendered as HTML
2131 function doBlockLevels( $text, $linestart ) {
2132 wfProfileIn( __METHOD__
);
2134 # Parsing through the text line by line. The main thing
2135 # happening here is handling of block-level elements p, pre,
2136 # and making lists from lines starting with * # : etc.
2138 $textLines = StringUtils
::explode( "\n", $text );
2140 $lastPrefix = $output = '';
2141 $this->mDTopen
= $inBlockElem = false;
2143 $paragraphStack = false;
2145 foreach ( $textLines as $oLine ) {
2147 if ( !$linestart ) {
2157 $lastPrefixLength = strlen( $lastPrefix );
2158 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2159 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2160 # If not in a <pre> element, scan for and figure out what prefixes are there.
2161 if ( !$this->mInPre
) {
2162 # Multiple prefixes may abut each other for nested lists.
2163 $prefixLength = strspn( $oLine, '*#:;' );
2164 $prefix = substr( $oLine, 0, $prefixLength );
2167 # ; and : are both from definition-lists, so they're equivalent
2168 # for the purposes of determining whether or not we need to open/close
2170 $prefix2 = str_replace( ';', ':', $prefix );
2171 $t = substr( $oLine, $prefixLength );
2172 $this->mInPre
= (bool)$preOpenMatch;
2174 # Don't interpret any other prefixes in preformatted text
2176 $prefix = $prefix2 = '';
2181 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2182 # Same as the last item, so no need to deal with nesting or opening stuff
2183 $output .= $this->nextItem( substr( $prefix, -1 ) );
2184 $paragraphStack = false;
2186 if ( substr( $prefix, -1 ) === ';') {
2187 # The one nasty exception: definition lists work like this:
2188 # ; title : definition text
2189 # So we check for : in the remainder text to split up the
2190 # title and definition, without b0rking links.
2192 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2194 $output .= $term . $this->nextItem( ':' );
2197 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2198 # We need to open or close prefixes, or both.
2200 # Either open or close a level...
2201 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2202 $paragraphStack = false;
2204 # Close all the prefixes which aren't shared.
2205 while ( $commonPrefixLength < $lastPrefixLength ) {
2206 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2207 --$lastPrefixLength;
2210 # Continue the current prefix if appropriate.
2211 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2212 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2215 # Open prefixes where appropriate.
2216 while ( $prefixLength > $commonPrefixLength ) {
2217 $char = substr( $prefix, $commonPrefixLength, 1 );
2218 $output .= $this->openList( $char );
2220 if ( ';' === $char ) {
2221 # FIXME: This is dupe of code above
2222 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2224 $output .= $term . $this->nextItem( ':' );
2227 ++
$commonPrefixLength;
2229 $lastPrefix = $prefix2;
2232 # If we have no prefixes, go to paragraph mode.
2233 if ( 0 == $prefixLength ) {
2234 wfProfileIn( __METHOD__
."-paragraph" );
2235 # No prefix (not in list)--go to paragraph mode
2236 # XXX: use a stack for nestable elements like span, table and div
2237 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2238 $closematch = preg_match(
2239 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2240 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2241 if ( $openmatch or $closematch ) {
2242 $paragraphStack = false;
2243 #Â TODO bug 5718: paragraph closed
2244 $output .= $this->closeParagraph();
2245 if ( $preOpenMatch and !$preCloseMatch ) {
2246 $this->mInPre
= true;
2248 $inBlockElem = !$closematch;
2249 } elseif ( !$inBlockElem && !$this->mInPre
) {
2250 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2252 if ( $this->mLastSection
!== 'pre' ) {
2253 $paragraphStack = false;
2254 $output .= $this->closeParagraph().'<pre>';
2255 $this->mLastSection
= 'pre';
2257 $t = substr( $t, 1 );
2260 if ( trim( $t ) === '' ) {
2261 if ( $paragraphStack ) {
2262 $output .= $paragraphStack.'<br />';
2263 $paragraphStack = false;
2264 $this->mLastSection
= 'p';
2266 if ( $this->mLastSection
!== 'p' ) {
2267 $output .= $this->closeParagraph();
2268 $this->mLastSection
= '';
2269 $paragraphStack = '<p>';
2271 $paragraphStack = '</p><p>';
2275 if ( $paragraphStack ) {
2276 $output .= $paragraphStack;
2277 $paragraphStack = false;
2278 $this->mLastSection
= 'p';
2279 } elseif ( $this->mLastSection
!== 'p' ) {
2280 $output .= $this->closeParagraph().'<p>';
2281 $this->mLastSection
= 'p';
2286 wfProfileOut( __METHOD__
."-paragraph" );
2288 # somewhere above we forget to get out of pre block (bug 785)
2289 if ( $preCloseMatch && $this->mInPre
) {
2290 $this->mInPre
= false;
2292 if ( $paragraphStack === false ) {
2296 while ( $prefixLength ) {
2297 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2300 if ( $this->mLastSection
!= '' ) {
2301 $output .= '</' . $this->mLastSection
. '>';
2302 $this->mLastSection
= '';
2305 wfProfileOut( __METHOD__
);
2310 * Split up a string on ':', ignoring any occurences inside tags
2311 * to prevent illegal overlapping.
2313 * @param $str String: the string to split
2314 * @param &$before String: set to everything before the ':'
2315 * @param &$after String: set to everything after the ':'
2316 * return String: the position of the ':', or false if none found
2318 function findColonNoLinks( $str, &$before, &$after ) {
2319 wfProfileIn( __METHOD__
);
2321 $pos = strpos( $str, ':' );
2322 if ( $pos === false ) {
2324 wfProfileOut( __METHOD__
);
2328 $lt = strpos( $str, '<' );
2329 if ( $lt === false ||
$lt > $pos ) {
2330 # Easy; no tag nesting to worry about
2331 $before = substr( $str, 0, $pos );
2332 $after = substr( $str, $pos+
1 );
2333 wfProfileOut( __METHOD__
);
2337 # Ugly state machine to walk through avoiding tags.
2338 $state = self
::COLON_STATE_TEXT
;
2340 $len = strlen( $str );
2341 for( $i = 0; $i < $len; $i++
) {
2345 # (Using the number is a performance hack for common cases)
2346 case 0: # self::COLON_STATE_TEXT:
2349 # Could be either a <start> tag or an </end> tag
2350 $state = self
::COLON_STATE_TAGSTART
;
2353 if ( $stack == 0 ) {
2355 $before = substr( $str, 0, $i );
2356 $after = substr( $str, $i +
1 );
2357 wfProfileOut( __METHOD__
);
2360 # Embedded in a tag; don't break it.
2363 # Skip ahead looking for something interesting
2364 $colon = strpos( $str, ':', $i );
2365 if ( $colon === false ) {
2366 # Nothing else interesting
2367 wfProfileOut( __METHOD__
);
2370 $lt = strpos( $str, '<', $i );
2371 if ( $stack === 0 ) {
2372 if ( $lt === false ||
$colon < $lt ) {
2374 $before = substr( $str, 0, $colon );
2375 $after = substr( $str, $colon +
1 );
2376 wfProfileOut( __METHOD__
);
2380 if ( $lt === false ) {
2381 # Nothing else interesting to find; abort!
2382 # We're nested, but there's no close tags left. Abort!
2385 # Skip ahead to next tag start
2387 $state = self
::COLON_STATE_TAGSTART
;
2390 case 1: # self::COLON_STATE_TAG:
2395 $state = self
::COLON_STATE_TEXT
;
2398 # Slash may be followed by >?
2399 $state = self
::COLON_STATE_TAGSLASH
;
2405 case 2: # self::COLON_STATE_TAGSTART:
2408 $state = self
::COLON_STATE_CLOSETAG
;
2411 $state = self
::COLON_STATE_COMMENT
;
2414 # Illegal early close? This shouldn't happen D:
2415 $state = self
::COLON_STATE_TEXT
;
2418 $state = self
::COLON_STATE_TAG
;
2421 case 3: # self::COLON_STATE_CLOSETAG:
2426 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2427 wfProfileOut( __METHOD__
);
2430 $state = self
::COLON_STATE_TEXT
;
2433 case self
::COLON_STATE_TAGSLASH
:
2435 # Yes, a self-closed tag <blah/>
2436 $state = self
::COLON_STATE_TEXT
;
2438 # Probably we're jumping the gun, and this is an attribute
2439 $state = self
::COLON_STATE_TAG
;
2442 case 5: # self::COLON_STATE_COMMENT:
2444 $state = self
::COLON_STATE_COMMENTDASH
;
2447 case self
::COLON_STATE_COMMENTDASH
:
2449 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2451 $state = self
::COLON_STATE_COMMENT
;
2454 case self
::COLON_STATE_COMMENTDASHDASH
:
2456 $state = self
::COLON_STATE_TEXT
;
2458 $state = self
::COLON_STATE_COMMENT
;
2462 throw new MWException( "State machine error in " . __METHOD__
);
2466 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2469 wfProfileOut( __METHOD__
);
2474 * Return value of a magic variable (like PAGENAME)
2478 function getVariableValue( $index, $frame=false ) {
2479 global $wgContLang, $wgSitename, $wgServer;
2480 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2483 * Some of these require message or data lookups and can be
2484 * expensive to check many times.
2486 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2487 if ( isset( $this->mVarCache
[$index] ) ) {
2488 return $this->mVarCache
[$index];
2492 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2493 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2496 global $wgLocaltimezone;
2497 if ( isset( $wgLocaltimezone ) ) {
2498 $oldtz = date_default_timezone_get();
2499 date_default_timezone_set( $wgLocaltimezone );
2502 $localTimestamp = date( 'YmdHis', $ts );
2503 $localMonth = date( 'm', $ts );
2504 $localMonth1 = date( 'n', $ts );
2505 $localMonthName = date( 'n', $ts );
2506 $localDay = date( 'j', $ts );
2507 $localDay2 = date( 'd', $ts );
2508 $localDayOfWeek = date( 'w', $ts );
2509 $localWeek = date( 'W', $ts );
2510 $localYear = date( 'Y', $ts );
2511 $localHour = date( 'H', $ts );
2512 if ( isset( $wgLocaltimezone ) ) {
2513 date_default_timezone_set( $oldtz );
2517 case 'currentmonth':
2518 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2520 case 'currentmonth1':
2521 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2523 case 'currentmonthname':
2524 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2526 case 'currentmonthnamegen':
2527 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2529 case 'currentmonthabbrev':
2530 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2533 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2536 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2539 $value = $wgContLang->formatNum( $localMonth );
2542 $value = $wgContLang->formatNum( $localMonth1 );
2544 case 'localmonthname':
2545 $value = $wgContLang->getMonthName( $localMonthName );
2547 case 'localmonthnamegen':
2548 $value = $wgContLang->getMonthNameGen( $localMonthName );
2550 case 'localmonthabbrev':
2551 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2554 $value = $wgContLang->formatNum( $localDay );
2557 $value = $wgContLang->formatNum( $localDay2 );
2560 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2563 $value = $this->mTitle
->getPartialURL();
2565 case 'fullpagename':
2566 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2568 case 'fullpagenamee':
2569 $value = $this->mTitle
->getPrefixedURL();
2572 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2574 case 'subpagenamee':
2575 $value = $this->mTitle
->getSubpageUrlForm();
2577 case 'basepagename':
2578 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2580 case 'basepagenamee':
2581 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2583 case 'talkpagename':
2584 if ( $this->mTitle
->canTalk() ) {
2585 $talkPage = $this->mTitle
->getTalkPage();
2586 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2591 case 'talkpagenamee':
2592 if ( $this->mTitle
->canTalk() ) {
2593 $talkPage = $this->mTitle
->getTalkPage();
2594 $value = $talkPage->getPrefixedUrl();
2599 case 'subjectpagename':
2600 $subjPage = $this->mTitle
->getSubjectPage();
2601 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2603 case 'subjectpagenamee':
2604 $subjPage = $this->mTitle
->getSubjectPage();
2605 $value = $subjPage->getPrefixedUrl();
2608 # Let the edit saving system know we should parse the page
2609 # *after* a revision ID has been assigned.
2610 $this->mOutput
->setFlag( 'vary-revision' );
2611 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2612 $value = $this->mRevisionId
;
2615 # Let the edit saving system know we should parse the page
2616 # *after* a revision ID has been assigned. This is for null edits.
2617 $this->mOutput
->setFlag( 'vary-revision' );
2618 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2619 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2621 case 'revisionday2':
2622 # Let the edit saving system know we should parse the page
2623 # *after* a revision ID has been assigned. This is for null edits.
2624 $this->mOutput
->setFlag( 'vary-revision' );
2625 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2626 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2628 case 'revisionmonth':
2629 # Let the edit saving system know we should parse the page
2630 # *after* a revision ID has been assigned. This is for null edits.
2631 $this->mOutput
->setFlag( 'vary-revision' );
2632 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2633 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2635 case 'revisionmonth1':
2636 # Let the edit saving system know we should parse the page
2637 # *after* a revision ID has been assigned. This is for null edits.
2638 $this->mOutput
->setFlag( 'vary-revision' );
2639 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2640 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2642 case 'revisionyear':
2643 # Let the edit saving system know we should parse the page
2644 # *after* a revision ID has been assigned. This is for null edits.
2645 $this->mOutput
->setFlag( 'vary-revision' );
2646 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2647 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2649 case 'revisiontimestamp':
2650 # Let the edit saving system know we should parse the page
2651 # *after* a revision ID has been assigned. This is for null edits.
2652 $this->mOutput
->setFlag( 'vary-revision' );
2653 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2654 $value = $this->getRevisionTimestamp();
2656 case 'revisionuser':
2657 # Let the edit saving system know we should parse the page
2658 # *after* a revision ID has been assigned. This is for null edits.
2659 $this->mOutput
->setFlag( 'vary-revision' );
2660 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2661 $value = $this->getRevisionUser();
2664 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2667 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2670 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2673 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2675 case 'subjectspace':
2676 $value = $this->mTitle
->getSubjectNsText();
2678 case 'subjectspacee':
2679 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2681 case 'currentdayname':
2682 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2685 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2688 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2691 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2694 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2695 # int to remove the padding
2696 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2699 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2701 case 'localdayname':
2702 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2705 $value = $wgContLang->formatNum( $localYear, true );
2708 $value = $wgContLang->time( $localTimestamp, false, false );
2711 $value = $wgContLang->formatNum( $localHour, true );
2714 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2715 # int to remove the padding
2716 $value = $wgContLang->formatNum( (int)$localWeek );
2719 $value = $wgContLang->formatNum( $localDayOfWeek );
2721 case 'numberofarticles':
2722 $value = $wgContLang->formatNum( SiteStats
::articles() );
2724 case 'numberoffiles':
2725 $value = $wgContLang->formatNum( SiteStats
::images() );
2727 case 'numberofusers':
2728 $value = $wgContLang->formatNum( SiteStats
::users() );
2730 case 'numberofactiveusers':
2731 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2733 case 'numberofpages':
2734 $value = $wgContLang->formatNum( SiteStats
::pages() );
2736 case 'numberofadmins':
2737 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2739 case 'numberofedits':
2740 $value = $wgContLang->formatNum( SiteStats
::edits() );
2742 case 'numberofviews':
2743 $value = $wgContLang->formatNum( SiteStats
::views() );
2745 case 'currenttimestamp':
2746 $value = wfTimestamp( TS_MW
, $ts );
2748 case 'localtimestamp':
2749 $value = $localTimestamp;
2751 case 'currentversion':
2752 $value = SpecialVersion
::getVersion();
2755 return $wgArticlePath;
2761 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2762 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2763 wfRestoreWarnings();
2764 return $serverName ?
$serverName : $wgServer;
2766 return $wgScriptPath;
2768 return $wgStylePath;
2769 case 'directionmark':
2770 return $wgContLang->getDirMark();
2771 case 'contentlanguage':
2772 global $wgLanguageCode;
2773 return $wgLanguageCode;
2776 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2784 $this->mVarCache
[$index] = $value;
2790 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2794 function initialiseVariables() {
2795 wfProfileIn( __METHOD__
);
2796 $variableIDs = MagicWord
::getVariableIDs();
2797 $substIDs = MagicWord
::getSubstIDs();
2799 $this->mVariables
= new MagicWordArray( $variableIDs );
2800 $this->mSubstWords
= new MagicWordArray( $substIDs );
2801 wfProfileOut( __METHOD__
);
2805 * Preprocess some wikitext and return the document tree.
2806 * This is the ghost of replace_variables().
2808 * @param $text String: The text to parse
2809 * @param $flags Integer: bitwise combination of:
2810 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2811 * included. Default is to assume a direct page view.
2813 * The generated DOM tree must depend only on the input text and the flags.
2814 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2816 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2817 * change in the DOM tree for a given text, must be passed through the section identifier
2818 * in the section edit link and thus back to extractSections().
2820 * The output of this function is currently only cached in process memory, but a persistent
2821 * cache may be implemented at a later date which takes further advantage of these strict
2822 * dependency requirements.
2826 function preprocessToDom( $text, $flags = 0 ) {
2827 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2832 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2834 public static function splitWhitespace( $s ) {
2835 $ltrimmed = ltrim( $s );
2836 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2837 $trimmed = rtrim( $ltrimmed );
2838 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2840 $w2 = substr( $ltrimmed, -$diff );
2844 return array( $w1, $trimmed, $w2 );
2848 * Replace magic variables, templates, and template arguments
2849 * with the appropriate text. Templates are substituted recursively,
2850 * taking care to avoid infinite loops.
2852 * Note that the substitution depends on value of $mOutputType:
2853 * self::OT_WIKI: only {{subst:}} templates
2854 * self::OT_PREPROCESS: templates but not extension tags
2855 * self::OT_HTML: all templates and extension tags
2857 * @param $text String: the text to transform
2858 * @param $frame PPFrame Object describing the arguments passed to the template.
2859 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2860 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2861 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2864 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2865 # Is there any text? Also, Prevent too big inclusions!
2866 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2869 wfProfileIn( __METHOD__
);
2871 if ( $frame === false ) {
2872 $frame = $this->getPreprocessor()->newFrame();
2873 } elseif ( !( $frame instanceof PPFrame
) ) {
2874 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2875 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2878 $dom = $this->preprocessToDom( $text );
2879 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2880 $text = $frame->expand( $dom, $flags );
2882 wfProfileOut( __METHOD__
);
2886 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2887 static function createAssocArgs( $args ) {
2888 $assocArgs = array();
2890 foreach ( $args as $arg ) {
2891 $eqpos = strpos( $arg, '=' );
2892 if ( $eqpos === false ) {
2893 $assocArgs[$index++
] = $arg;
2895 $name = trim( substr( $arg, 0, $eqpos ) );
2896 $value = trim( substr( $arg, $eqpos+
1 ) );
2897 if ( $value === false ) {
2900 if ( $name !== false ) {
2901 $assocArgs[$name] = $value;
2910 * Warn the user when a parser limitation is reached
2911 * Will warn at most once the user per limitation type
2913 * @param $limitationType String: should be one of:
2914 * 'expensive-parserfunction' (corresponding messages:
2915 * 'expensive-parserfunction-warning',
2916 * 'expensive-parserfunction-category')
2917 * 'post-expand-template-argument' (corresponding messages:
2918 * 'post-expand-template-argument-warning',
2919 * 'post-expand-template-argument-category')
2920 * 'post-expand-template-inclusion' (corresponding messages:
2921 * 'post-expand-template-inclusion-warning',
2922 * 'post-expand-template-inclusion-category')
2923 * @param $current Current value
2924 * @param $max Maximum allowed, when an explicit limit has been
2925 * exceeded, provide the values (optional)
2927 function limitationWarn( $limitationType, $current=null, $max=null) {
2928 # does no harm if $current and $max are present but are unnecessary for the message
2929 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2930 $this->mOutput
->addWarning( $warning );
2931 $this->addTrackingCategory( "$limitationType-category" );
2935 * Return the text of a template, after recursively
2936 * replacing any variables or templates within the template.
2938 * @param $piece Array: the parts of the template
2939 * $piece['title']: the title, i.e. the part before the |
2940 * $piece['parts']: the parameter array
2941 * $piece['lineStart']: whether the brace was at the start of a line
2942 * @param $frame PPFrame The current frame, contains template arguments
2943 * @return String: the text of the template
2946 function braceSubstitution( $piece, $frame ) {
2947 global $wgContLang, $wgNonincludableNamespaces;
2948 wfProfileIn( __METHOD__
);
2949 wfProfileIn( __METHOD__
.'-setup' );
2952 $found = false; # $text has been filled
2953 $nowiki = false; # wiki markup in $text should be escaped
2954 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2955 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2956 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2957 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2959 # Title object, where $text came from
2962 # $part1 is the bit before the first |, and must contain only title characters.
2963 # Various prefixes will be stripped from it later.
2964 $titleWithSpaces = $frame->expand( $piece['title'] );
2965 $part1 = trim( $titleWithSpaces );
2968 # Original title text preserved for various purposes
2969 $originalTitle = $part1;
2971 # $args is a list of argument nodes, starting from index 0, not including $part1
2972 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2973 wfProfileOut( __METHOD__
.'-setup' );
2976 wfProfileIn( __METHOD__
.'-modifiers' );
2979 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2981 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2982 # Decide whether to expand template or keep wikitext as-is.
2983 if ( $this->ot
['wiki'] ) {
2984 if ( $substMatch === false ) {
2985 $literal = true; # literal when in PST with no prefix
2987 $literal = false; # expand when in PST with subst: or safesubst:
2990 if ( $substMatch == 'subst' ) {
2991 $literal = true; # literal when not in PST with plain subst:
2993 $literal = false; # expand when not in PST with safesubst: or no prefix
2997 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3004 if ( !$found && $args->getLength() == 0 ) {
3005 $id = $this->mVariables
->matchStartToEnd( $part1 );
3006 if ( $id !== false ) {
3007 $text = $this->getVariableValue( $id, $frame );
3008 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3009 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3015 # MSG, MSGNW and RAW
3018 $mwMsgnw = MagicWord
::get( 'msgnw' );
3019 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3022 # Remove obsolete MSG:
3023 $mwMsg = MagicWord
::get( 'msg' );
3024 $mwMsg->matchStartAndRemove( $part1 );
3028 $mwRaw = MagicWord
::get( 'raw' );
3029 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3030 $forceRawInterwiki = true;
3033 wfProfileOut( __METHOD__
.'-modifiers' );
3037 wfProfileIn( __METHOD__
. '-pfunc' );
3039 $colonPos = strpos( $part1, ':' );
3040 if ( $colonPos !== false ) {
3041 # Case sensitive functions
3042 $function = substr( $part1, 0, $colonPos );
3043 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3044 $function = $this->mFunctionSynonyms
[1][$function];
3046 # Case insensitive functions
3047 $function = $wgContLang->lc( $function );
3048 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3049 $function = $this->mFunctionSynonyms
[0][$function];
3055 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3056 $initialArgs = array( &$this );
3057 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3058 if ( $flags & SFH_OBJECT_ARGS
) {
3059 # Add a frame parameter, and pass the arguments as an array
3060 $allArgs = $initialArgs;
3061 $allArgs[] = $frame;
3062 for ( $i = 0; $i < $args->getLength(); $i++
) {
3063 $funcArgs[] = $args->item( $i );
3065 $allArgs[] = $funcArgs;
3067 # Convert arguments to plain text
3068 for ( $i = 0; $i < $args->getLength(); $i++
) {
3069 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3071 $allArgs = array_merge( $initialArgs, $funcArgs );
3074 # Workaround for PHP bug 35229 and similar
3075 if ( !is_callable( $callback ) ) {
3076 wfProfileOut( __METHOD__
. '-pfunc' );
3077 wfProfileOut( __METHOD__
);
3078 throw new MWException( "Tag hook for $function is not callable\n" );
3080 $result = call_user_func_array( $callback, $allArgs );
3083 $preprocessFlags = 0;
3085 if ( is_array( $result ) ) {
3086 if ( isset( $result[0] ) ) {
3088 unset( $result[0] );
3091 # Extract flags into the local scope
3092 # This allows callers to set flags such as nowiki, found, etc.
3098 $text = $this->preprocessToDom( $text, $preprocessFlags );
3103 wfProfileOut( __METHOD__
. '-pfunc' );
3106 # Finish mangling title and then check for loops.
3107 # Set $title to a Title object and $titleText to the PDBK
3110 # Split the title into page and subpage
3112 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3113 if ( $subpage !== '' ) {
3114 $ns = $this->mTitle
->getNamespace();
3116 $title = Title
::newFromText( $part1, $ns );
3118 $titleText = $title->getPrefixedText();
3119 # Check for language variants if the template is not found
3120 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3121 $wgContLang->findVariantLink( $part1, $title, true );
3123 # Do recursion depth check
3124 $limit = $this->mOptions
->getMaxTemplateDepth();
3125 if ( $frame->depth
>= $limit ) {
3127 $text = '<span class="error">'
3128 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3134 # Load from database
3135 if ( !$found && $title ) {
3136 wfProfileIn( __METHOD__
. '-loadtpl' );
3137 if ( !$title->isExternal() ) {
3138 if ( $title->getNamespace() == NS_SPECIAL
3139 && $this->mOptions
->getAllowSpecialInclusion()
3140 && $this->ot
['html'] )
3142 $text = SpecialPage
::capturePath( $title );
3143 if ( is_string( $text ) ) {
3146 $this->disableCache();
3148 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3149 $found = false; # access denied
3150 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3152 list( $text, $title ) = $this->getTemplateDom( $title );
3153 if ( $text !== false ) {
3159 # If the title is valid but undisplayable, make a link to it
3160 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3161 $text = "[[:$titleText]]";
3164 } elseif ( $title->isTrans() ) {
3165 # Interwiki transclusion
3166 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3167 $text = $this->interwikiTransclude( $title, 'render' );
3170 $text = $this->interwikiTransclude( $title, 'raw' );
3171 # Preprocess it like a template
3172 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3178 # Do infinite loop check
3179 # This has to be done after redirect resolution to avoid infinite loops via redirects
3180 if ( !$frame->loopCheck( $title ) ) {
3182 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3183 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3185 wfProfileOut( __METHOD__
. '-loadtpl' );
3188 # If we haven't found text to substitute by now, we're done
3189 # Recover the source wikitext and return it
3191 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3192 wfProfileOut( __METHOD__
);
3193 return array( 'object' => $text );
3196 # Expand DOM-style return values in a child frame
3197 if ( $isChildObj ) {
3198 # Clean up argument array
3199 $newFrame = $frame->newChild( $args, $title );
3202 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3203 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3204 # Expansion is eligible for the empty-frame cache
3205 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3206 $text = $this->mTplExpandCache
[$titleText];
3208 $text = $newFrame->expand( $text );
3209 $this->mTplExpandCache
[$titleText] = $text;
3212 # Uncached expansion
3213 $text = $newFrame->expand( $text );
3216 if ( $isLocalObj && $nowiki ) {
3217 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3218 $isLocalObj = false;
3221 # Replace raw HTML by a placeholder
3222 # Add a blank line preceding, to prevent it from mucking up
3223 # immediately preceding headings
3225 $text = "\n\n" . $this->insertStripItem( $text );
3226 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3227 # Escape nowiki-style return values
3228 $text = wfEscapeWikiText( $text );
3229 } elseif ( is_string( $text )
3230 && !$piece['lineStart']
3231 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3233 # Bug 529: if the template begins with a table or block-level
3234 # element, it should be treated as beginning a new line.
3235 # This behaviour is somewhat controversial.
3236 $text = "\n" . $text;
3239 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3240 # Error, oversize inclusion
3241 if ( $titleText !== false ) {
3242 # Make a working, properly escaped link if possible (bug 23588)
3243 $text = "[[:$titleText]]";
3245 # This will probably not be a working link, but at least it may
3246 # provide some hint of where the problem is
3247 preg_replace( '/^:/', '', $originalTitle );
3248 $text = "[[:$originalTitle]]";
3250 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3251 $this->limitationWarn( 'post-expand-template-inclusion' );
3254 if ( $isLocalObj ) {
3255 $ret = array( 'object' => $text );
3257 $ret = array( 'text' => $text );
3260 wfProfileOut( __METHOD__
);
3265 * Get the semi-parsed DOM representation of a template with a given title,
3266 * and its redirect destination title. Cached.
3268 function getTemplateDom( $title ) {
3269 $cacheTitle = $title;
3270 $titleText = $title->getPrefixedDBkey();
3272 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3273 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3274 $title = Title
::makeTitle( $ns, $dbk );
3275 $titleText = $title->getPrefixedDBkey();
3277 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3278 return array( $this->mTplDomCache
[$titleText], $title );
3281 # Cache miss, go to the database
3282 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3284 if ( $text === false ) {
3285 $this->mTplDomCache
[$titleText] = false;
3286 return array( false, $title );
3289 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3290 $this->mTplDomCache
[ $titleText ] = $dom;
3292 if ( !$title->equals( $cacheTitle ) ) {
3293 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3294 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3297 return array( $dom, $title );
3301 * Fetch the unparsed text of a template and register a reference to it.
3303 function fetchTemplateAndTitle( $title ) {
3304 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3305 $stuff = call_user_func( $templateCb, $title, $this );
3306 $text = $stuff['text'];
3307 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3308 if ( isset( $stuff['deps'] ) ) {
3309 foreach ( $stuff['deps'] as $dep ) {
3310 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3313 return array( $text, $finalTitle );
3316 function fetchTemplate( $title ) {
3317 $rv = $this->fetchTemplateAndTitle( $title );
3322 * Static function to get a template
3323 * Can be overridden via ParserOptions::setTemplateCallback().
3325 static function statelessFetchTemplate( $title, $parser=false ) {
3326 $text = $skip = false;
3327 $finalTitle = $title;
3330 # Loop to fetch the article, with up to 1 redirect
3331 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3332 # Give extensions a chance to select the revision instead
3333 $id = false; # Assume current
3334 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3340 'page_id' => $title->getArticleID(),
3344 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3345 $rev_id = $rev ?
$rev->getId() : 0;
3346 # If there is no current revision, there is no page
3347 if ( $id === false && !$rev ) {
3348 $linkCache = LinkCache
::singleton();
3349 $linkCache->addBadLinkObj( $title );
3354 'page_id' => $title->getArticleID(),
3355 'rev_id' => $rev_id );
3358 $text = $rev->getText();
3359 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3361 $message = $wgContLang->lcfirst( $title->getText() );
3362 $text = wfMsgForContentNoTrans( $message );
3363 if ( wfEmptyMsg( $message, $text ) ) {
3370 if ( $text === false ) {
3374 $finalTitle = $title;
3375 $title = Title
::newFromRedirect( $text );
3379 'finalTitle' => $finalTitle,
3384 * Transclude an interwiki link.
3386 function interwikiTransclude( $title, $action ) {
3387 global $wgEnableScaryTranscluding;
3389 if ( !$wgEnableScaryTranscluding ) {
3390 return wfMsgForContent('scarytranscludedisabled');
3393 $url = $title->getFullUrl( "action=$action" );
3395 if ( strlen( $url ) > 255 ) {
3396 return wfMsgForContent( 'scarytranscludetoolong' );
3398 return $this->fetchScaryTemplateMaybeFromCache( $url );
3401 function fetchScaryTemplateMaybeFromCache( $url ) {
3402 global $wgTranscludeCacheExpiry;
3403 $dbr = wfGetDB( DB_SLAVE
);
3404 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3405 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3406 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3408 return $obj->tc_contents
;
3411 $text = Http
::get( $url );
3413 return wfMsgForContent( 'scarytranscludefailed', $url );
3416 $dbw = wfGetDB( DB_MASTER
);
3417 $dbw->replace( 'transcache', array('tc_url'), array(
3419 'tc_time' => $dbw->timestamp( time() ),
3420 'tc_contents' => $text)
3427 * Triple brace replacement -- used for template arguments
3430 function argSubstitution( $piece, $frame ) {
3431 wfProfileIn( __METHOD__
);
3434 $parts = $piece['parts'];
3435 $nameWithSpaces = $frame->expand( $piece['title'] );
3436 $argName = trim( $nameWithSpaces );
3438 $text = $frame->getArgument( $argName );
3439 if ( $text === false && $parts->getLength() > 0
3443 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3446 # No match in frame, use the supplied default
3447 $object = $parts->item( 0 )->getChildren();
3449 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3450 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3451 $this->limitationWarn( 'post-expand-template-argument' );
3454 if ( $text === false && $object === false ) {
3456 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3458 if ( $error !== false ) {
3461 if ( $object !== false ) {
3462 $ret = array( 'object' => $object );
3464 $ret = array( 'text' => $text );
3467 wfProfileOut( __METHOD__
);
3472 * Return the text to be used for a given extension tag.
3473 * This is the ghost of strip().
3475 * @param $params Associative array of parameters:
3476 * name PPNode for the tag name
3477 * attr PPNode for unparsed text where tag attributes are thought to be
3478 * attributes Optional associative array of parsed attributes
3479 * inner Contents of extension element
3480 * noClose Original text did not have a close tag
3481 * @param $frame PPFrame
3483 function extensionSubstitution( $params, $frame ) {
3484 $name = $frame->expand( $params['name'] );
3485 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3486 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3487 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3489 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3490 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3491 if ( $isFunctionTag ) {
3492 $markerType = 'none';
3494 $markerType = 'general';
3496 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3497 $name = strtolower( $name );
3498 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3499 if ( isset( $params['attributes'] ) ) {
3500 $attributes = $attributes +
$params['attributes'];
3503 if ( isset( $this->mTagHooks
[$name] ) ) {
3504 # Workaround for PHP bug 35229 and similar
3505 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3506 throw new MWException( "Tag hook for $name is not callable\n" );
3508 $output = call_user_func_array( $this->mTagHooks
[$name],
3509 array( $content, $attributes, $this, $frame ) );
3510 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3511 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3512 if ( !is_callable( $callback ) ) {
3513 throw new MWException( "Tag hook for $name is not callable\n" );
3516 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3518 $output = '<span class="error">Invalid tag extension name: ' .
3519 htmlspecialchars( $name ) . '</span>';
3522 if ( is_array( $output ) ) {
3523 # Extract flags to local scope (to override $markerType)
3525 $output = $flags[0];
3530 if ( is_null( $attrText ) ) {
3533 if ( isset( $params['attributes'] ) ) {
3534 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3535 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3536 htmlspecialchars( $attrValue ) . '"';
3539 if ( $content === null ) {
3540 $output = "<$name$attrText/>";
3542 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3543 $output = "<$name$attrText>$content$close";
3547 if ( $markerType === 'none' ) {
3549 } elseif ( $markerType === 'nowiki' ) {
3550 $this->mStripState
->nowiki
->setPair( $marker, $output );
3551 } elseif ( $markerType === 'general' ) {
3552 $this->mStripState
->general
->setPair( $marker, $output );
3554 throw new MWException( __METHOD__
.': invalid marker type' );
3560 * Increment an include size counter
3562 * @param $type String: the type of expansion
3563 * @param $size Integer: the size of the text
3564 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3566 function incrementIncludeSize( $type, $size ) {
3567 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3570 $this->mIncludeSizes
[$type] +
= $size;
3576 * Increment the expensive function count
3578 * @return Boolean: false if the limit has been exceeded
3580 function incrementExpensiveFunctionCount() {
3581 global $wgExpensiveParserFunctionLimit;
3582 $this->mExpensiveFunctionCount++
;
3583 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3590 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3591 * Fills $this->mDoubleUnderscores, returns the modified text
3593 function doDoubleUnderscore( $text ) {
3594 wfProfileIn( __METHOD__
);
3596 # The position of __TOC__ needs to be recorded
3597 $mw = MagicWord
::get( 'toc' );
3598 if ( $mw->match( $text ) ) {
3599 $this->mShowToc
= true;
3600 $this->mForceTocPosition
= true;
3602 # Set a placeholder. At the end we'll fill it in with the TOC.
3603 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3605 # Only keep the first one.
3606 $text = $mw->replace( '', $text );
3609 # Now match and remove the rest of them
3610 $mwa = MagicWord
::getDoubleUnderscoreArray();
3611 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3613 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3614 $this->mOutput
->mNoGallery
= true;
3616 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3617 $this->mShowToc
= false;
3619 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3620 $this->addTrackingCategory( 'hidden-category-category' );
3622 # (bug 8068) Allow control over whether robots index a page.
3624 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3625 # is not desirable, the last one on the page should win.
3626 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3627 $this->mOutput
->setIndexPolicy( 'noindex' );
3628 $this->addTrackingCategory( 'noindex-category' );
3630 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3631 $this->mOutput
->setIndexPolicy( 'index' );
3632 $this->addTrackingCategory( 'index-category' );
3635 # Cache all double underscores in the database
3636 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3637 $this->mOutput
->setProperty( $key, '' );
3640 wfProfileOut( __METHOD__
);
3645 * Add a tracking category, getting the title from a system message,
3646 * or print a debug message if the title is invalid.
3648 * @param $msg String: message key
3649 * @return Boolean: whether the addition was successful
3651 protected function addTrackingCategory( $msg ) {
3652 $cat = wfMsgForContent( $msg );
3654 # Allow tracking categories to be disabled by setting them to "-"
3655 if ( $cat === '-' ) {
3659 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3660 if ( $containerCategory ) {
3661 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3664 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3670 * This function accomplishes several tasks:
3671 * 1) Auto-number headings if that option is enabled
3672 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3673 * 3) Add a Table of contents on the top for users who have enabled the option
3674 * 4) Auto-anchor headings
3676 * It loops through all headlines, collects the necessary data, then splits up the
3677 * string and re-inserts the newly formatted headlines.
3679 * @param $text String
3680 * @param $origText String: original, untouched wikitext
3681 * @param $isMain Boolean
3684 function formatHeadings( $text, $origText, $isMain=true ) {
3685 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3687 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3689 # Inhibit editsection links if requested in the page
3690 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3693 $showEditLink = $this->mOptions
->getEditSection();
3696 # Get all headlines for numbering them and adding funky stuff like [edit]
3697 # links - this is for later, but we need the number of headlines right now
3699 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3701 # if there are fewer than 4 headlines in the article, do not show TOC
3702 # unless it's been explicitly enabled.
3703 $enoughToc = $this->mShowToc
&&
3704 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3706 # Allow user to stipulate that a page should have a "new section"
3707 # link added via __NEWSECTIONLINK__
3708 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3709 $this->mOutput
->setNewSection( true );
3712 # Allow user to remove the "new section"
3713 # link via __NONEWSECTIONLINK__
3714 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3715 $this->mOutput
->hideNewSection( true );
3718 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3719 # override above conditions and always show TOC above first header
3720 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3721 $this->mShowToc
= true;
3725 # We need this to perform operations on the HTML
3726 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3732 # Ugh .. the TOC should have neat indentation levels which can be
3733 # passed to the skin functions. These are determined here
3737 $sublevelCount = array();
3738 $levelCount = array();
3743 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3744 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3745 $oldType = $this->mOutputType
;
3746 $this->setOutputType( self
::OT_WIKI
);
3747 $frame = $this->getPreprocessor()->newFrame();
3748 $root = $this->preprocessToDom( $origText );
3749 $node = $root->getFirstChild();
3754 foreach ( $matches[3] as $headline ) {
3755 $isTemplate = false;
3757 $sectionIndex = false;
3759 $markerMatches = array();
3760 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3761 $serial = $markerMatches[1];
3762 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3763 $isTemplate = ( $titleText != $baseTitleText );
3764 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3768 $prevlevel = $level;
3770 $level = $matches[1][$headlineCount];
3772 if ( $level > $prevlevel ) {
3773 # Increase TOC level
3775 $sublevelCount[$toclevel] = 0;
3776 if ( $toclevel<$wgMaxTocLevel ) {
3777 $prevtoclevel = $toclevel;
3778 $toc .= $sk->tocIndent();
3781 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3782 # Decrease TOC level, find level to jump to
3784 for ( $i = $toclevel; $i > 0; $i-- ) {
3785 if ( $levelCount[$i] == $level ) {
3786 # Found last matching level
3789 } elseif ( $levelCount[$i] < $level ) {
3790 # Found first matching level below current level
3798 if ( $toclevel<$wgMaxTocLevel ) {
3799 if ( $prevtoclevel < $wgMaxTocLevel ) {
3800 # Unindent only if the previous toc level was shown :p
3801 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3802 $prevtoclevel = $toclevel;
3804 $toc .= $sk->tocLineEnd();
3808 # No change in level, end TOC line
3809 if ( $toclevel<$wgMaxTocLevel ) {
3810 $toc .= $sk->tocLineEnd();
3814 $levelCount[$toclevel] = $level;
3816 # count number of headlines for each level
3817 @$sublevelCount[$toclevel]++
;
3819 for( $i = 1; $i <= $toclevel; $i++
) {
3820 if ( !empty( $sublevelCount[$i] ) ) {
3824 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3829 # The safe header is a version of the header text safe to use for links
3830 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3831 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3833 # Remove link placeholders by the link text.
3834 # <!--LINK number-->
3836 # link text with suffix
3837 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3839 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3840 $tocline = preg_replace(
3841 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3842 array( '', '<$1>' ),
3845 $tocline = trim( $tocline );
3847 # For the anchor, strip out HTML-y stuff period
3848 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3849 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3851 # Save headline for section edit hint before it's escaped
3852 $headlineHint = $safeHeadline;
3854 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3855 # For reverse compatibility, provide an id that's
3856 # HTML4-compatible, like we used to.
3858 # It may be worth noting, academically, that it's possible for
3859 # the legacy anchor to conflict with a non-legacy headline
3860 # anchor on the page. In this case likely the "correct" thing
3861 # would be to either drop the legacy anchors or make sure
3862 # they're numbered first. However, this would require people
3863 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3864 # manually, so let's not bother worrying about it.
3865 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3866 array( 'noninitial', 'legacy' ) );
3867 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3869 if ( $legacyHeadline == $safeHeadline ) {
3870 # No reason to have both (in fact, we can't)
3871 $legacyHeadline = false;
3874 $legacyHeadline = false;
3875 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3879 # HTML names must be case-insensitively unique (bug 10721).
3880 # This does not apply to Unicode characters per
3881 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3882 # FIXME: We may be changing them depending on the current locale.
3883 $arrayKey = strtolower( $safeHeadline );
3884 if ( $legacyHeadline === false ) {
3885 $legacyArrayKey = false;
3887 $legacyArrayKey = strtolower( $legacyHeadline );
3890 # count how many in assoc. array so we can track dupes in anchors
3891 if ( isset( $refers[$arrayKey] ) ) {
3892 $refers[$arrayKey]++
;
3894 $refers[$arrayKey] = 1;
3896 if ( isset( $refers[$legacyArrayKey] ) ) {
3897 $refers[$legacyArrayKey]++
;
3899 $refers[$legacyArrayKey] = 1;
3902 # Don't number the heading if it is the only one (looks silly)
3903 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3904 # the two are different if the line contains a link
3905 $headline = $numbering . ' ' . $headline;
3908 # Create the anchor for linking from the TOC to the section
3909 $anchor = $safeHeadline;
3910 $legacyAnchor = $legacyHeadline;
3911 if ( $refers[$arrayKey] > 1 ) {
3912 $anchor .= '_' . $refers[$arrayKey];
3914 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3915 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3917 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3918 $toc .= $sk->tocLine( $anchor, $tocline,
3919 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3922 # Add the section to the section tree
3923 # Find the DOM node for this header
3924 while ( $node && !$isTemplate ) {
3925 if ( $node->getName() === 'h' ) {
3926 $bits = $node->splitHeading();
3927 if ( $bits['i'] == $sectionIndex ) {
3931 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3932 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3933 $node = $node->getNextSibling();
3936 'toclevel' => $toclevel,
3939 'number' => $numbering,
3940 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3941 'fromtitle' => $titleText,
3942 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3943 'anchor' => $anchor,
3946 # give headline the correct <h#> tag
3947 if ( $showEditLink && $sectionIndex !== false ) {
3948 if ( $isTemplate ) {
3949 # Put a T flag in the section identifier, to indicate to extractSections()
3950 # that sections inside <includeonly> should be counted.
3951 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex", null, $this->mOptions
->getUserLang() );
3953 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint, $this->mOptions
->getUserLang() );
3958 $head[$headlineCount] = $sk->makeHeadline( $level,
3959 $matches['attrib'][$headlineCount], $anchor, $headline,
3960 $editlink, $legacyAnchor );
3965 $this->setOutputType( $oldType );
3967 # Never ever show TOC if no headers
3968 if ( $numVisible < 1 ) {
3973 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3974 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3976 $toc = $sk->tocList( $toc );
3977 $this->mOutput
->setTOCHTML( $toc );
3981 $this->mOutput
->setSections( $tocraw );
3984 # split up and insert constructed headlines
3986 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3989 foreach ( $blocks as $block ) {
3990 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3991 # This is the [edit] link that appears for the top block of text when
3992 # section editing is enabled
3994 # Disabled because it broke block formatting
3995 # For example, a bullet point in the top line
3996 # $full .= $sk->editSectionLink(0);
3999 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4000 # Top anchor now in skin
4004 if ( !empty( $head[$i] ) ) {
4009 if ( $this->mForceTocPosition
) {
4010 return str_replace( '<!--MWTOC-->', $toc, $full );
4017 * Transform wiki markup when saving a page by doing \r\n -> \n
4018 * conversion, substitting signatures, {{subst:}} templates, etc.
4020 * @param $text String: the text to transform
4021 * @param $title Title: the Title object for the current article
4022 * @param $user User: the User object describing the current user
4023 * @param $options ParserOptions: parsing options
4024 * @param $clearState Boolean: whether to clear the parser state first
4025 * @return String: the altered wiki markup
4027 public function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4028 $options->resetUsage();
4029 $this->mOptions
= $options;
4030 $this->setTitle( $title );
4031 $this->setUser( $user );
4032 $this->setOutputType( self
::OT_WIKI
);
4034 if ( $clearState ) {
4035 $this->clearState();
4041 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4042 $text = $this->pstPass2( $text, $user );
4043 $text = $this->mStripState
->unstripBoth( $text );
4045 $this->setUser( null ); #Reset
4051 * Pre-save transform helper function
4054 function pstPass2( $text, $user ) {
4055 global $wgContLang, $wgLocaltimezone;
4057 # Note: This is the timestamp saved as hardcoded wikitext to
4058 # the database, we use $wgContLang here in order to give
4059 # everyone the same signature and use the default one rather
4060 # than the one selected in each user's preferences.
4061 # (see also bug 12815)
4062 $ts = $this->mOptions
->getTimestamp();
4063 if ( isset( $wgLocaltimezone ) ) {
4064 $tz = $wgLocaltimezone;
4066 $tz = date_default_timezone_get();
4069 $unixts = wfTimestamp( TS_UNIX
, $ts );
4070 $oldtz = date_default_timezone_get();
4071 date_default_timezone_set( $tz );
4072 $ts = date( 'YmdHis', $unixts );
4073 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4075 # Allow translation of timezones through wiki. date() can return
4076 # whatever crap the system uses, localised or not, so we cannot
4077 # ship premade translations.
4078 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4079 $value = wfMsgForContent( $key );
4080 if ( !wfEmptyMsg( $key, $value ) ) {
4084 date_default_timezone_set( $oldtz );
4086 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4088 # Variable replacement
4089 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4090 $text = $this->replaceVariables( $text );
4093 $sigText = $this->getUserSig( $user );
4094 $text = strtr( $text, array(
4096 '~~~~' => "$sigText $d",
4100 # Context links: [[|name]] and [[name (context)|]]
4101 global $wgLegalTitleChars;
4102 $tc = "[$wgLegalTitleChars]";
4103 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4105 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4106 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4107 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4108 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4110 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4111 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4112 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4113 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4115 $t = $this->mTitle
->getText();
4117 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4118 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4119 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4120 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4122 # if there's no context, don't bother duplicating the title
4123 $text = preg_replace( $p2, '[[\\1]]', $text );
4126 # Trim trailing whitespace
4127 $text = rtrim( $text );
4133 * Fetch the user's signature text, if any, and normalize to
4134 * validated, ready-to-insert wikitext.
4135 * If you have pre-fetched the nickname or the fancySig option, you can
4136 * specify them here to save a database query.
4139 * @param $nickname String: nickname to use or false to use user's default nickname
4140 * @param $fancySig Boolean: whether the nicknname is the complete signature
4141 * or null to use default value
4144 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4145 global $wgMaxSigChars;
4147 $username = $user->getName();
4149 # If not given, retrieve from the user object.
4150 if ( $nickname === false )
4151 $nickname = $user->getOption( 'nickname' );
4153 if ( is_null( $fancySig ) ) {
4154 $fancySig = $user->getBoolOption( 'fancysig' );
4157 $nickname = $nickname == null ?
$username : $nickname;
4159 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4160 $nickname = $username;
4161 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4162 } elseif ( $fancySig !== false ) {
4163 # Sig. might contain markup; validate this
4164 if ( $this->validateSig( $nickname ) !== false ) {
4165 # Validated; clean up (if needed) and return it
4166 return $this->cleanSig( $nickname, true );
4168 # Failed to validate; fall back to the default
4169 $nickname = $username;
4170 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4174 # Make sure nickname doesnt get a sig in a sig
4175 $nickname = $this->cleanSigInSig( $nickname );
4177 # If we're still here, make it a link to the user page
4178 $userText = wfEscapeWikiText( $username );
4179 $nickText = wfEscapeWikiText( $nickname );
4180 if ( $user->isAnon() ) {
4181 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4183 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4188 * Check that the user's signature contains no bad XML
4190 * @param $text String
4191 * @return mixed An expanded string, or false if invalid.
4193 function validateSig( $text ) {
4194 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4198 * Clean up signature text
4200 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4201 * 2) Substitute all transclusions
4203 * @param $text String
4204 * @param $parsing Whether we're cleaning (preferences save) or parsing
4205 * @return String: signature text
4207 function cleanSig( $text, $parsing = false ) {
4210 $this->clearState();
4211 $this->setTitle( $wgTitle );
4212 $this->mOptions
= new ParserOptions
;
4213 $this->setOutputType
= self
::OT_PREPROCESS
;
4216 # Option to disable this feature
4217 if ( !$this->mOptions
->getCleanSignatures() ) {
4221 # FIXME: regex doesn't respect extension tags or nowiki
4222 # => Move this logic to braceSubstitution()
4223 $substWord = MagicWord
::get( 'subst' );
4224 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4225 $substText = '{{' . $substWord->getSynonym( 0 );
4227 $text = preg_replace( $substRegex, $substText, $text );
4228 $text = $this->cleanSigInSig( $text );
4229 $dom = $this->preprocessToDom( $text );
4230 $frame = $this->getPreprocessor()->newFrame();
4231 $text = $frame->expand( $dom );
4234 $text = $this->mStripState
->unstripBoth( $text );
4241 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4243 * @param $text String
4244 * @return String: signature text with /~{3,5}/ removed
4246 function cleanSigInSig( $text ) {
4247 $text = preg_replace( '/~{3,5}/', '', $text );
4252 * Set up some variables which are usually set up in parse()
4253 * so that an external function can call some class members with confidence
4255 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4256 $this->setTitle( $title );
4257 $options->resetUsage();
4258 $this->mOptions
= $options;
4259 $this->setOutputType( $outputType );
4260 if ( $clearState ) {
4261 $this->clearState();
4266 * Wrapper for preprocess()
4268 * @param $text String: the text to preprocess
4269 * @param $options ParserOptions: options
4272 public function transformMsg( $text, $options ) {
4274 static $executing = false;
4276 # Guard against infinite recursion
4282 wfProfileIn( __METHOD__
);
4283 $text = $this->preprocess( $text, $wgTitle, $options );
4286 wfProfileOut( __METHOD__
);
4291 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4292 * The callback should have the following form:
4293 * function myParserHook( $text, $params, $parser ) { ... }
4295 * Transform and return $text. Use $parser for any required context, e.g. use
4296 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4298 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4299 * @param $callback Mixed: the callback function (and object) to use for the tag
4300 * @return The old value of the mTagHooks array associated with the hook
4302 public function setHook( $tag, $callback ) {
4303 $tag = strtolower( $tag );
4304 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4305 $this->mTagHooks
[$tag] = $callback;
4306 if ( !in_array( $tag, $this->mStripList
) ) {
4307 $this->mStripList
[] = $tag;
4313 function setTransparentTagHook( $tag, $callback ) {
4314 $tag = strtolower( $tag );
4315 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4316 $this->mTransparentTagHooks
[$tag] = $callback;
4322 * Remove all tag hooks
4324 function clearTagHooks() {
4325 $this->mTagHooks
= array();
4326 $this->mStripList
= $this->mDefaultStripList
;
4330 * Create a function, e.g. {{sum:1|2|3}}
4331 * The callback function should have the form:
4332 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4334 * Or with SFH_OBJECT_ARGS:
4335 * function myParserFunction( $parser, $frame, $args ) { ... }
4337 * The callback may either return the text result of the function, or an array with the text
4338 * in element 0, and a number of flags in the other elements. The names of the flags are
4339 * specified in the keys. Valid flags are:
4340 * found The text returned is valid, stop processing the template. This
4342 * nowiki Wiki markup in the return value should be escaped
4343 * isHTML The returned text is HTML, armour it against wikitext transformation
4345 * @param $id String: The magic word ID
4346 * @param $callback Mixed: the callback function (and object) to use
4347 * @param $flags Integer: a combination of the following flags:
4348 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4350 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4351 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4352 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4353 * the arguments, and to control the way they are expanded.
4355 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4356 * arguments, for instance:
4357 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4359 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4360 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4361 * working if/when this is changed.
4363 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4366 * Please read the documentation in includes/parser/Preprocessor.php for more information
4367 * about the methods available in PPFrame and PPNode.
4369 * @return The old callback function for this name, if any
4371 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4374 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4375 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4377 # Add to function cache
4378 $mw = MagicWord
::get( $id );
4380 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4382 $synonyms = $mw->getSynonyms();
4383 $sensitive = intval( $mw->isCaseSensitive() );
4385 foreach ( $synonyms as $syn ) {
4387 if ( !$sensitive ) {
4388 $syn = $wgContLang->lc( $syn );
4391 if ( !( $flags & SFH_NO_HASH
) ) {
4394 # Remove trailing colon
4395 if ( substr( $syn, -1, 1 ) === ':' ) {
4396 $syn = substr( $syn, 0, -1 );
4398 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4404 * Get all registered function hook identifiers
4408 function getFunctionHooks() {
4409 return array_keys( $this->mFunctionHooks
);
4413 * Create a tag function, e.g. <test>some stuff</test>.
4414 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4415 * Unlike parser functions, their content is not preprocessed.
4417 function setFunctionTagHook( $tag, $callback, $flags ) {
4418 $tag = strtolower( $tag );
4419 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4420 $this->mFunctionTagHooks
[$tag] : null;
4421 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4423 if ( !in_array( $tag, $this->mStripList
) ) {
4424 $this->mStripList
[] = $tag;
4431 * FIXME: update documentation. makeLinkObj() is deprecated.
4432 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4433 * Placeholders created in Skin::makeLinkObj()
4434 * Returns an array of link CSS classes, indexed by PDBK.
4436 function replaceLinkHolders( &$text, $options = 0 ) {
4437 return $this->mLinkHolders
->replace( $text );
4441 * Replace <!--LINK--> link placeholders with plain text of links
4442 * (not HTML-formatted).
4444 * @param $text String
4447 function replaceLinkHoldersText( $text ) {
4448 return $this->mLinkHolders
->replaceText( $text );
4452 * Renders an image gallery from a text with one line per image.
4453 * text labels may be given by using |-style alternative text. E.g.
4454 * Image:one.jpg|The number "1"
4455 * Image:tree.jpg|A tree
4456 * given as text will return the HTML of a gallery with two images,
4457 * labeled 'The number "1"' and
4460 function renderImageGallery( $text, $params ) {
4461 $ig = new ImageGallery();
4462 $ig->setContextTitle( $this->mTitle
);
4463 $ig->setShowBytes( false );
4464 $ig->setShowFilename( false );
4465 $ig->setParser( $this );
4466 $ig->setHideBadImages();
4467 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4468 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4469 $ig->mRevisionId
= $this->mRevisionId
;
4471 if ( isset( $params['showfilename'] ) ) {
4472 $ig->setShowFilename( true );
4474 $ig->setShowFilename( false );
4476 if ( isset( $params['caption'] ) ) {
4477 $caption = $params['caption'];
4478 $caption = htmlspecialchars( $caption );
4479 $caption = $this->replaceInternalLinks( $caption );
4480 $ig->setCaptionHtml( $caption );
4482 if ( isset( $params['perrow'] ) ) {
4483 $ig->setPerRow( $params['perrow'] );
4485 if ( isset( $params['widths'] ) ) {
4486 $ig->setWidths( $params['widths'] );
4488 if ( isset( $params['heights'] ) ) {
4489 $ig->setHeights( $params['heights'] );
4492 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4494 $lines = StringUtils
::explode( "\n", $text );
4495 foreach ( $lines as $line ) {
4496 # match lines like these:
4497 # Image:someimage.jpg|This is some image
4499 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4501 if ( count( $matches ) == 0 ) {
4505 if ( strpos( $matches[0], '%' ) !== false ) {
4506 $matches[1] = urldecode( $matches[1] );
4508 $tp = Title
::newFromText( $matches[1] );
4510 if ( is_null( $nt ) ) {
4511 # Bogus title. Ignore these so we don't bomb out later.
4514 if ( isset( $matches[3] ) ) {
4515 $label = $matches[3];
4520 $html = $this->recursiveTagParse( trim( $label ) );
4522 $ig->add( $nt, $html );
4524 # Only add real images (bug #5586)
4525 if ( $nt->getNamespace() == NS_FILE
) {
4526 $this->mOutput
->addImage( $nt->getDBkey() );
4529 return $ig->toHTML();
4532 function getImageParams( $handler ) {
4534 $handlerClass = get_class( $handler );
4538 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4539 # Initialise static lists
4540 static $internalParamNames = array(
4541 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4542 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4543 'bottom', 'text-bottom' ),
4544 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4545 'upright', 'border', 'link', 'alt' ),
4547 static $internalParamMap;
4548 if ( !$internalParamMap ) {
4549 $internalParamMap = array();
4550 foreach ( $internalParamNames as $type => $names ) {
4551 foreach ( $names as $name ) {
4552 $magicName = str_replace( '-', '_', "img_$name" );
4553 $internalParamMap[$magicName] = array( $type, $name );
4558 # Add handler params
4559 $paramMap = $internalParamMap;
4561 $handlerParamMap = $handler->getParamMap();
4562 foreach ( $handlerParamMap as $magic => $paramName ) {
4563 $paramMap[$magic] = array( 'handler', $paramName );
4566 $this->mImageParams
[$handlerClass] = $paramMap;
4567 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4569 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4573 * Parse image options text and use it to make an image
4575 * @param $title Title
4576 * @param $options String
4577 * @param $holders LinkHolderArray
4579 function makeImage( $title, $options, $holders = false ) {
4580 # Check if the options text is of the form "options|alt text"
4582 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4583 # * left no resizing, just left align. label is used for alt= only
4584 # * right same, but right aligned
4585 # * none same, but not aligned
4586 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4587 # * center center the image
4588 # * frame Keep original image size, no magnify-button.
4589 # * framed Same as "frame"
4590 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4591 # * upright reduce width for upright images, rounded to full __0 px
4592 # * border draw a 1px border around the image
4593 # * alt Text for HTML alt attribute (defaults to empty)
4594 # * link Set the target of the image link. Can be external, interwiki, or local
4595 # vertical-align values (no % or length right now):
4605 $parts = StringUtils
::explode( "|", $options );
4606 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4608 # Give extensions a chance to select the file revision for us
4609 $skip = $time = $descQuery = false;
4610 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4613 return $sk->link( $title );
4617 $file = wfFindFile( $title, array( 'time' => $time ) );
4619 $handler = $file ?
$file->getHandler() : false;
4621 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4623 # Process the input parameters
4625 $params = array( 'frame' => array(), 'handler' => array(),
4626 'horizAlign' => array(), 'vertAlign' => array() );
4627 foreach ( $parts as $part ) {
4628 $part = trim( $part );
4629 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4631 if ( isset( $paramMap[$magicName] ) ) {
4632 list( $type, $paramName ) = $paramMap[$magicName];
4634 # Special case; width and height come in one variable together
4635 if ( $type === 'handler' && $paramName === 'width' ) {
4637 # (bug 13500) In both cases (width/height and width only),
4638 # permit trailing "px" for backward compatibility.
4639 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4640 $width = intval( $m[1] );
4641 $height = intval( $m[2] );
4642 if ( $handler->validateParam( 'width', $width ) ) {
4643 $params[$type]['width'] = $width;
4646 if ( $handler->validateParam( 'height', $height ) ) {
4647 $params[$type]['height'] = $height;
4650 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4651 $width = intval( $value );
4652 if ( $handler->validateParam( 'width', $width ) ) {
4653 $params[$type]['width'] = $width;
4656 } # else no validation -- bug 13436
4658 if ( $type === 'handler' ) {
4659 # Validate handler parameter
4660 $validated = $handler->validateParam( $paramName, $value );
4662 # Validate internal parameters
4663 switch( $paramName ) {
4666 # @todo Fixme: possibly check validity here for
4667 # manualthumb? downstream behavior seems odd with
4668 # missing manual thumbs.
4670 $value = $this->stripAltText( $value, $holders );
4673 $chars = self
::EXT_LINK_URL_CLASS
;
4674 $prots = $this->mUrlProtocols
;
4675 if ( $value === '' ) {
4676 $paramName = 'no-link';
4679 } elseif ( preg_match( "/^$prots/", $value ) ) {
4680 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4681 $paramName = 'link-url';
4682 $this->mOutput
->addExternalLink( $value );
4683 if ( $this->mOptions
->getExternalLinkTarget() ) {
4684 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4689 $linkTitle = Title
::newFromText( $value );
4691 $paramName = 'link-title';
4692 $value = $linkTitle;
4693 $this->mOutput
->addLink( $linkTitle );
4699 # Most other things appear to be empty or numeric...
4700 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4705 $params[$type][$paramName] = $value;
4709 if ( !$validated ) {
4714 # Process alignment parameters
4715 if ( $params['horizAlign'] ) {
4716 $params['frame']['align'] = key( $params['horizAlign'] );
4718 if ( $params['vertAlign'] ) {
4719 $params['frame']['valign'] = key( $params['vertAlign'] );
4722 $params['frame']['caption'] = $caption;
4724 # Will the image be presented in a frame, with the caption below?
4725 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4726 isset( $params['frame']['framed'] ) ||
4727 isset( $params['frame']['thumbnail'] ) ||
4728 isset( $params['frame']['manualthumb'] );
4730 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4731 # came to also set the caption, ordinary text after the image -- which
4732 # makes no sense, because that just repeats the text multiple times in
4733 # screen readers. It *also* came to set the title attribute.
4735 # Now that we have an alt attribute, we should not set the alt text to
4736 # equal the caption: that's worse than useless, it just repeats the
4737 # text. This is the framed/thumbnail case. If there's no caption, we
4738 # use the unnamed parameter for alt text as well, just for the time be-
4739 # ing, if the unnamed param is set and the alt param is not.
4741 # For the future, we need to figure out if we want to tweak this more,
4742 # e.g., introducing a title= parameter for the title; ignoring the un-
4743 # named parameter entirely for images without a caption; adding an ex-
4744 # plicit caption= parameter and preserving the old magic unnamed para-
4746 if ( $imageIsFramed ) { # Framed image
4747 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4748 # No caption or alt text, add the filename as the alt text so
4749 # that screen readers at least get some description of the image
4750 $params['frame']['alt'] = $title->getText();
4752 # Do not set $params['frame']['title'] because tooltips don't make sense
4754 } else { # Inline image
4755 if ( !isset( $params['frame']['alt'] ) ) {
4756 # No alt text, use the "caption" for the alt text
4757 if ( $caption !== '') {
4758 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4760 # No caption, fall back to using the filename for the
4762 $params['frame']['alt'] = $title->getText();
4765 # Use the "caption" for the tooltip text
4766 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4769 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4771 # Linker does the rest
4772 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4774 # Give the handler a chance to modify the parser object
4776 $handler->parserTransformHook( $this, $file );
4782 protected function stripAltText( $caption, $holders ) {
4783 # Strip bad stuff out of the title (tooltip). We can't just use
4784 # replaceLinkHoldersText() here, because if this function is called
4785 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4787 $tooltip = $holders->replaceText( $caption );
4789 $tooltip = $this->replaceLinkHoldersText( $caption );
4792 # make sure there are no placeholders in thumbnail attributes
4793 # that are later expanded to html- so expand them now and
4795 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4796 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4802 * Set a flag in the output object indicating that the content is dynamic and
4803 * shouldn't be cached.
4805 function disableCache() {
4806 wfDebug( "Parser output marked as uncacheable.\n" );
4807 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4808 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4812 * Callback from the Sanitizer for expanding items found in HTML attribute
4813 * values, so they can be safely tested and escaped.
4815 * @param $text String
4816 * @param $frame PPFrame
4820 function attributeStripCallback( &$text, $frame = false ) {
4821 $text = $this->replaceVariables( $text, $frame );
4822 $text = $this->mStripState
->unstripBoth( $text );
4829 function getTags() {
4830 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4834 * Break wikitext input into sections, and either pull or replace
4835 * some particular section's text.
4837 * External callers should use the getSection and replaceSection methods.
4839 * @param $text String: Page wikitext
4840 * @param $section String: a section identifier string of the form:
4841 * <flag1> - <flag2> - ... - <section number>
4843 * Currently the only recognised flag is "T", which means the target section number
4844 * was derived during a template inclusion parse, in other words this is a template
4845 * section edit link. If no flags are given, it was an ordinary section edit link.
4846 * This flag is required to avoid a section numbering mismatch when a section is
4847 * enclosed by <includeonly> (bug 6563).
4849 * The section number 0 pulls the text before the first heading; other numbers will
4850 * pull the given section along with its lower-level subsections. If the section is
4851 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4853 * @param $mode String: one of "get" or "replace"
4854 * @param $newText String: replacement text for section data.
4855 * @return String: for "get", the extracted section text.
4856 * for "replace", the whole page with the section replaced.
4858 private function extractSections( $text, $section, $mode, $newText='' ) {
4860 $this->clearState();
4861 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4862 $this->mOptions
= new ParserOptions
;
4863 $this->setOutputType( self
::OT_PLAIN
);
4865 $frame = $this->getPreprocessor()->newFrame();
4867 # Process section extraction flags
4869 $sectionParts = explode( '-', $section );
4870 $sectionIndex = array_pop( $sectionParts );
4871 foreach ( $sectionParts as $part ) {
4872 if ( $part === 'T' ) {
4873 $flags |
= self
::PTD_FOR_INCLUSION
;
4876 # Preprocess the text
4877 $root = $this->preprocessToDom( $text, $flags );
4879 # <h> nodes indicate section breaks
4880 # They can only occur at the top level, so we can find them by iterating the root's children
4881 $node = $root->getFirstChild();
4883 # Find the target section
4884 if ( $sectionIndex == 0 ) {
4885 # Section zero doesn't nest, level=big
4886 $targetLevel = 1000;
4889 if ( $node->getName() === 'h' ) {
4890 $bits = $node->splitHeading();
4891 if ( $bits['i'] == $sectionIndex ) {
4892 $targetLevel = $bits['level'];
4896 if ( $mode === 'replace' ) {
4897 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4899 $node = $node->getNextSibling();
4905 if ( $mode === 'get' ) {
4912 # Find the end of the section, including nested sections
4914 if ( $node->getName() === 'h' ) {
4915 $bits = $node->splitHeading();
4916 $curLevel = $bits['level'];
4917 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4921 if ( $mode === 'get' ) {
4922 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4924 $node = $node->getNextSibling();
4927 # Write out the remainder (in replace mode only)
4928 if ( $mode === 'replace' ) {
4929 # Output the replacement text
4930 # Add two newlines on -- trailing whitespace in $newText is conventionally
4931 # stripped by the editor, so we need both newlines to restore the paragraph gap
4932 # Only add trailing whitespace if there is newText
4933 if ( $newText != "" ) {
4934 $outText .= $newText . "\n\n";
4938 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4939 $node = $node->getNextSibling();
4943 if ( is_string( $outText ) ) {
4944 # Re-insert stripped tags
4945 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4952 * This function returns the text of a section, specified by a number ($section).
4953 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4954 * the first section before any such heading (section 0).
4956 * If a section contains subsections, these are also returned.
4958 * @param $text String: text to look in
4959 * @param $section String: section identifier
4960 * @param $deftext String: default to return if section is not found
4961 * @return string text of the requested section
4963 public function getSection( $text, $section, $deftext='' ) {
4964 return $this->extractSections( $text, $section, "get", $deftext );
4967 public function replaceSection( $oldtext, $section, $text ) {
4968 return $this->extractSections( $oldtext, $section, "replace", $text );
4972 * Get the ID of the revision we are parsing
4974 * @return Mixed: integer or null
4976 function getRevisionId() {
4977 return $this->mRevisionId
;
4981 * Get the revision object for $this->mRevisionId
4983 * @return either a Revision object or null
4985 protected function getRevisionObject() {
4986 if ( !is_null( $this->mRevisionObject
) )
4987 return $this->mRevisionObject
;
4988 if ( is_null( $this->mRevisionId
) )
4991 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
4992 return $this->mRevisionObject
;
4996 * Get the timestamp associated with the current revision, adjusted for
4997 * the default server-local timestamp
4999 function getRevisionTimestamp() {
5000 if ( is_null( $this->mRevisionTimestamp
) ) {
5001 wfProfileIn( __METHOD__
);
5003 $revObject = $this->getRevisionObject();
5004 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5006 if( $timestamp !== false ) {
5009 # The cryptic '' timezone parameter tells to use the site-default
5010 # timezone offset instead of the user settings.
5012 # Since this value will be saved into the parser cache, served
5013 # to other users, and potentially even used inside links and such,
5014 # it needs to be consistent for all visitors.
5015 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5018 wfProfileOut( __METHOD__
);
5020 return $this->mRevisionTimestamp
;
5024 * Get the name of the user that edited the last revision
5026 * @return String: user name
5028 function getRevisionUser() {
5029 if( is_null( $this->mRevisionUser
) ) {
5030 $revObject = $this->getRevisionObject();
5032 # if this template is subst: the revision id will be blank,
5033 # so just use the current user's name
5035 $this->mRevisionUser
= $revObject->getUserText();
5036 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5037 $this->mRevisionUser
= $this->getUser()->getName();
5040 return $this->mRevisionUser
;
5044 * Mutator for $mDefaultSort
5046 * @param $sort New value
5048 public function setDefaultSort( $sort ) {
5049 $this->mDefaultSort
= $sort;
5050 $this->mOutput
->setProperty( 'defaultsort', $sort );
5054 * Accessor for $mDefaultSort
5055 * Will use the title/prefixed title if none is set
5059 public function getDefaultSort() {
5060 if ( $this->mDefaultSort
!== false ) {
5061 return $this->mDefaultSort
;
5063 return $this->mTitle
->getCategorySortkey();
5068 * Accessor for $mDefaultSort
5069 * Unlike getDefaultSort(), will return false if none is set
5071 * @return string or false
5073 public function getCustomDefaultSort() {
5074 return $this->mDefaultSort
;
5078 * Try to guess the section anchor name based on a wikitext fragment
5079 * presumably extracted from a heading, for example "Header" from
5082 public function guessSectionNameFromWikiText( $text ) {
5083 # Strip out wikitext links(they break the anchor)
5084 $text = $this->stripSectionName( $text );
5085 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5086 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5090 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5091 * instead. For use in redirects, since IE6 interprets Redirect: headers
5092 * as something other than UTF-8 (apparently?), resulting in breakage.
5094 * @param $text String: The section name
5095 * @return string An anchor
5097 public function guessLegacySectionNameFromWikiText( $text ) {
5098 # Strip out wikitext links(they break the anchor)
5099 $text = $this->stripSectionName( $text );
5100 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5101 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5105 * Strips a text string of wikitext for use in a section anchor
5107 * Accepts a text string and then removes all wikitext from the
5108 * string and leaves only the resultant text (i.e. the result of
5109 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5110 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5111 * to create valid section anchors by mimicing the output of the
5112 * parser when headings are parsed.
5114 * @param $text String: text string to be stripped of wikitext
5115 * for use in a Section anchor
5116 * @return Filtered text string
5118 public function stripSectionName( $text ) {
5119 # Strip internal link markup
5120 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5121 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5123 # Strip external link markup (FIXME: Not Tolerant to blank link text
5124 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5125 # on how many empty links there are on the page - need to figure that out.
5126 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5128 # Parse wikitext quotes (italics & bold)
5129 $text = $this->doQuotes( $text );
5132 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5137 * strip/replaceVariables/unstrip for preprocessor regression testing
5139 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5140 $this->clearState();
5141 if ( !$title instanceof Title
) {
5142 $title = Title
::newFromText( $title );
5144 $this->mTitle
= $title;
5145 $options->resetUsage();
5146 $this->mOptions
= $options;
5147 $this->setOutputType( $outputType );
5148 $text = $this->replaceVariables( $text );
5149 $text = $this->mStripState
->unstripBoth( $text );
5150 $text = Sanitizer
::removeHTMLtags( $text );
5154 function testPst( $text, $title, $options ) {
5156 if ( !$title instanceof Title
) {
5157 $title = Title
::newFromText( $title );
5159 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5162 function testPreprocess( $text, $title, $options ) {
5163 if ( !$title instanceof Title
) {
5164 $title = Title
::newFromText( $title );
5166 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5169 function markerSkipCallback( $s, $callback ) {
5172 while ( $i < strlen( $s ) ) {
5173 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5174 if ( $markerStart === false ) {
5175 $out .= call_user_func( $callback, substr( $s, $i ) );
5178 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5179 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5180 if ( $markerEnd === false ) {
5181 $out .= substr( $s, $markerStart );
5184 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5185 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5193 function serialiseHalfParsedText( $text ) {
5195 $data['text'] = $text;
5197 # First, find all strip markers, and store their
5199 $stripState = new StripState
;
5201 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5202 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5204 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5205 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5207 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5208 $replaceArray = $stripState->general
;
5209 $stripText = $this->mStripState
->general
->data
[$marker];
5210 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5211 $replaceArray = $stripState->nowiki
;
5212 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5214 throw new MWException( "Hanging strip marker: '$marker'." );
5217 $replaceArray->setPair( $marker, $stripText );
5220 $data['stripstate'] = $stripState;
5222 # Now, find all of our links, and store THEIR
5223 # data in an array! :)
5224 $links = array( 'internal' => array(), 'interwiki' => array() );
5228 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5229 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5232 if ( empty( $links['internal'][$ns] ) ) {
5233 $links['internal'][$ns] = array();
5236 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5237 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5238 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5244 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5245 $data = substr( $text, $start_pos );
5246 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5247 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5248 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5251 $data['linkholder'] = $links;
5258 * @param $data Array
5259 * @param $intPrefix String unique identifying prefix
5262 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5263 if ( !$intPrefix ) {
5264 $intPrefix = self
::getRandomString();
5267 # First, extract the strip state.
5268 $stripState = $data['stripstate'];
5269 $this->mStripState
->general
->merge( $stripState->general
);
5270 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5272 # Now, extract the text, and renumber links
5273 $text = $data['text'];
5274 $links = $data['linkholder'];
5277 foreach ( $links['internal'] as $ns => $nsLinks ) {
5278 foreach ( $nsLinks as $key => $entry ) {
5279 $newKey = $intPrefix . '-' . $key;
5280 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5282 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5287 foreach ( $links['interwiki'] as $key => $entry ) {
5288 $newKey = "$intPrefix-$key";
5289 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5291 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5294 # Should be good to go.
5300 * @todo document, briefly.
5304 var $general, $nowiki;
5306 function __construct() {
5307 $this->general
= new ReplacementArray
;
5308 $this->nowiki
= new ReplacementArray
;
5311 function unstripGeneral( $text ) {
5312 wfProfileIn( __METHOD__
);
5315 $text = $this->general
->replace( $text );
5316 } while ( $text !== $oldText );
5317 wfProfileOut( __METHOD__
);
5321 function unstripNoWiki( $text ) {
5322 wfProfileIn( __METHOD__
);
5325 $text = $this->nowiki
->replace( $text );
5326 } while ( $text !== $oldText );
5327 wfProfileOut( __METHOD__
);
5331 function unstripBoth( $text ) {
5332 wfProfileIn( __METHOD__
);
5335 $text = $this->general
->replace( $text );
5336 $text = $this->nowiki
->replace( $text );
5337 } while ( $text !== $oldText );
5338 wfProfileOut( __METHOD__
);
5344 * @todo document, briefly.
5347 class OnlyIncludeReplacer
{
5350 function replace( $matches ) {
5351 if ( substr( $matches[1], -1 ) === "\n" ) {
5352 $this->output
.= substr( $matches[1], 0, -1 );
5354 $this->output
.= $matches[1];