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
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
40 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.4';
58 # Flags for Parser::setFunctionHook
59 # Also available as global constants from Defines.php
60 const SFH_NO_HASH
= 1;
61 const SFH_OBJECT_ARGS
= 2;
63 # Constants needed for external link processing
64 # Everything except bracket, space, or control characters
65 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
66 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
67 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
69 # State constants for the definition list colon extraction
70 const COLON_STATE_TEXT
= 0;
71 const COLON_STATE_TAG
= 1;
72 const COLON_STATE_TAGSTART
= 2;
73 const COLON_STATE_CLOSETAG
= 3;
74 const COLON_STATE_TAGSLASH
= 4;
75 const COLON_STATE_COMMENT
= 5;
76 const COLON_STATE_COMMENTDASH
= 6;
77 const COLON_STATE_COMMENTDASHDASH
= 7;
79 # Flags for preprocessToDom
80 const PTD_FOR_INCLUSION
= 1;
82 # Allowed values for $this->mOutputType
83 # Parameter to startExternalParse().
84 const OT_HTML
= 1; # like parse()
85 const OT_WIKI
= 2; # like preSaveTransform()
86 const OT_PREPROCESS
= 3; # like preprocess()
88 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
90 # Marker Suffix needs to be accessible staticly.
91 const MARKER_SUFFIX
= "-QINU\x7f";
94 var $mTagHooks = array();
95 var $mTransparentTagHooks = array();
96 var $mFunctionHooks = array();
97 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
98 var $mFunctionTagHooks = array();
99 var $mStripList = array();
100 var $mDefaultStripList = array();
101 var $mVarCache = array();
102 var $mImageParams = array();
103 var $mImageParamsMagicArray = array();
104 var $mMarkerIndex = 0;
105 var $mFirstCall = true;
106 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
107 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
110 # Cleared with clearState():
111 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
112 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
113 var $mLinkHolders, $mLinkID;
114 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
115 var $mTplExpandCache; # empty-frame expansion cache
116 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
117 var $mExpensiveFunctionCount; # number of expensive parser function calls
118 var $mUser; # User object; only used when doing pre-save transform
121 # These are variables reset at least once per parse regardless of $clearState
127 var $mTitle; # Title context, used for self-link rendering and similar things
128 var $mOutputType; # Output type, one of the OT_xxx constants
129 var $ot; # Shortcut alias, see setOutputType()
130 var $mRevisionObject; # The revision object of the specified revision ID
131 var $mRevisionId; # ID to display in {{REVISIONID}} tags
132 var $mRevisionTimestamp; # The timestamp of the specified revision ID
133 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
134 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
141 function __construct( $conf = array() ) {
142 $this->mConf
= $conf;
143 $this->mUrlProtocols
= wfUrlProtocols();
144 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
145 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
146 if ( isset( $conf['preprocessorClass'] ) ) {
147 $this->mPreprocessorClass
= $conf['preprocessorClass'];
148 } elseif ( extension_loaded( 'domxml' ) ) {
149 # PECL extension that conflicts with the core DOM extension (bug 13770)
150 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
151 $this->mPreprocessorClass
= 'Preprocessor_Hash';
152 } elseif ( extension_loaded( 'dom' ) ) {
153 $this->mPreprocessorClass
= 'Preprocessor_DOM';
155 $this->mPreprocessorClass
= 'Preprocessor_Hash';
160 * Reduce memory usage to reduce the impact of circular references
162 function __destruct() {
163 if ( isset( $this->mLinkHolders
) ) {
164 $this->mLinkHolders
->__destruct();
166 foreach ( $this as $name => $value ) {
167 unset( $this->$name );
172 * Do various kinds of initialisation on the first call of the parser
174 function firstCallInit() {
175 if ( !$this->mFirstCall
) {
178 $this->mFirstCall
= false;
180 wfProfileIn( __METHOD__
);
182 CoreParserFunctions
::register( $this );
183 CoreTagHooks
::register( $this );
184 $this->initialiseVariables();
186 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
187 wfProfileOut( __METHOD__
);
195 function clearState() {
196 wfProfileIn( __METHOD__
);
197 if ( $this->mFirstCall
) {
198 $this->firstCallInit();
200 $this->mOutput
= new ParserOutput
;
201 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
202 $this->mAutonumber
= 0;
203 $this->mLastSection
= '';
204 $this->mDTopen
= false;
205 $this->mIncludeCount
= array();
206 $this->mStripState
= new StripState
;
207 $this->mArgStack
= false;
208 $this->mInPre
= false;
209 $this->mLinkHolders
= new LinkHolderArray( $this );
211 $this->mRevisionObject
= $this->mRevisionTimestamp
=
212 $this->mRevisionId
= $this->mRevisionUser
= null;
213 $this->mVarCache
= array();
217 * Prefix for temporary replacement strings for the multipass parser.
218 * \x07 should never appear in input as it's disallowed in XML.
219 * Using it at the front also gives us a little extra robustness
220 * since it shouldn't match when butted up against identifier-like
223 * Must not consist of all title characters, or else it will change
224 * the behaviour of <nowiki> in a link.
226 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
227 # Changed to \x7f to allow XML double-parsing -- TS
228 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
231 # Clear these on every parse, bug 4549
232 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
234 $this->mShowToc
= true;
235 $this->mForceTocPosition
= false;
236 $this->mIncludeSizes
= array(
240 $this->mPPNodeCount
= 0;
241 $this->mDefaultSort
= false;
242 $this->mHeadings
= array();
243 $this->mDoubleUnderscores
= array();
244 $this->mExpensiveFunctionCount
= 0;
247 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
248 $this->mPreprocessor
= null;
251 wfRunHooks( 'ParserClearState', array( &$this ) );
252 wfProfileOut( __METHOD__
);
256 * Convert wikitext to HTML
257 * Do not call this function recursively.
259 * @param $text String: text we want to parse
260 * @param $title A title object
261 * @param $options ParserOptions
262 * @param $linestart boolean
263 * @param $clearState boolean
264 * @param $revid Int: number to pass in {{REVISIONID}}
265 * @return ParserOutput a ParserOutput
267 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
269 * First pass--just handle <nowiki> sections, pass the rest off
270 * to internalParse() which does all the real work.
273 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
274 $fname = __METHOD__
.'-' . wfGetCaller();
275 wfProfileIn( __METHOD__
);
276 wfProfileIn( $fname );
278 $this->startExternalParse( $title, $options, self
::OT_HTML
, $clearState );
280 $oldRevisionId = $this->mRevisionId
;
281 $oldRevisionObject = $this->mRevisionObject
;
282 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
283 $oldRevisionUser = $this->mRevisionUser
;
284 if ( $revid !== null ) {
285 $this->mRevisionId
= $revid;
286 $this->mRevisionObject
= null;
287 $this->mRevisionTimestamp
= null;
288 $this->mRevisionUser
= null;
291 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
293 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
294 $text = $this->internalParse( $text );
296 $text = $this->mStripState
->unstripGeneral( $text );
298 # Clean up special characters, only run once, next-to-last before doBlockLevels
300 # french spaces, last one Guillemet-left
301 # only if there is something before the space
302 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
303 # french spaces, Guillemet-right
304 '/(\\302\\253) /' => '\\1 ',
305 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
307 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
309 $text = $this->doBlockLevels( $text, $linestart );
311 $this->replaceLinkHolders( $text );
314 * The page doesn't get language converted if
316 * b) Content isn't converted
317 * c) It's a conversion table
319 if ( !( $wgDisableLangConversion
320 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
321 ||
$this->mTitle
->isConversionTable() ) ) {
323 # The position of the convert() call should not be changed. it
324 # assumes that the links are all replaced and the only thing left
325 # is the <nowiki> mark.
327 $text = $wgContLang->convert( $text );
331 * A converted title will be provided in the output object if title and
332 * content conversion are enabled, the article text does not contain
333 * a conversion-suppressing double-underscore tag, and no
334 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
335 * automatic link conversion.
337 if ( !( $wgDisableLangConversion
338 ||
$wgDisableTitleConversion
339 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
340 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
341 ||
$this->mOutput
->getDisplayTitle() !== false ) )
343 $convruletitle = $wgContLang->getConvRuleTitle();
344 if ( $convruletitle ) {
345 $this->mOutput
->setTitleText( $convruletitle );
347 $titleText = $wgContLang->convertTitle( $title );
348 $this->mOutput
->setTitleText( $titleText );
352 $text = $this->mStripState
->unstripNoWiki( $text );
354 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
356 //!JF Move to its own function
358 $uniq_prefix = $this->mUniqPrefix
;
360 $elements = array_keys( $this->mTransparentTagHooks
);
361 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
363 foreach ( $matches as $marker => $data ) {
364 list( $element, $content, $params, $tag ) = $data;
365 $tagName = strtolower( $element );
366 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
367 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
371 $this->mStripState
->general
->setPair( $marker, $output );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 $text = Sanitizer
::normalizeCharReferences( $text );
377 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
378 $text = MWTidy
::tidy( $text );
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3<div\\5>\\6</div>\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 $max = $this->mOptions
->getMaxIncludeSize();
416 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
418 "NewPP limit report\n" .
419 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
420 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
421 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
423 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
424 $text .= "\n<!-- \n$limitReport-->\n";
426 $this->mOutput
->setText( $text );
428 $this->mRevisionId
= $oldRevisionId;
429 $this->mRevisionObject
= $oldRevisionObject;
430 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
431 $this->mRevisionUser
= $oldRevisionUser;
432 wfProfileOut( $fname );
433 wfProfileOut( __METHOD__
);
435 return $this->mOutput
;
439 * Recursive parser entry point that can be called from an extension tag
442 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
444 * @param $text String: text extension wants to have parsed
445 * @param $frame PPFrame: The frame to use for expanding any template variables
447 function recursiveTagParse( $text, $frame=false ) {
448 wfProfileIn( __METHOD__
);
449 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
450 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
451 $text = $this->internalParse( $text, false, $frame );
452 wfProfileOut( __METHOD__
);
457 * Expand templates and variables in the text, producing valid, static wikitext.
458 * Also removes comments.
460 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
461 wfProfileIn( __METHOD__
);
462 $this->startExternalParse( $title, $options, self
::OT_PREPROCESS
, true );
463 if ( $revid !== null ) {
464 $this->mRevisionId
= $revid;
466 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
467 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
468 $text = $this->replaceVariables( $text );
469 $text = $this->mStripState
->unstripBoth( $text );
470 wfProfileOut( __METHOD__
);
475 * Process the wikitext for the ?preload= feature. (bug 5210)
477 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
478 * comments, templates, arguments, tags hooks and parser functions are untouched.
480 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
481 # Parser (re)initialisation
482 $this->startExternalParse( $title, $options, self
::OT_PLAIN
, true );
484 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
485 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
486 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
490 * Get a random string
495 static private function getRandomString() {
496 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
500 * Set the current user.
501 * Should only be used when doing pre-save transform.
503 * @param $user Mixed: User object or null (to reset)
505 function setUser( $user ) {
506 $this->mUser
= $user;
510 * Accessor for mUniqPrefix.
514 public function uniqPrefix() {
515 if ( !isset( $this->mUniqPrefix
) ) {
516 # @todo Fixme: this is probably *horribly wrong*
517 # LanguageConverter seems to want $wgParser's uniqPrefix, however
518 # if this is called for a parser cache hit, the parser may not
519 # have ever been initialized in the first place.
520 # Not really sure what the heck is supposed to be going on here.
522 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
524 return $this->mUniqPrefix
;
528 * Set the context title
530 function setTitle( $t ) {
531 if ( !$t ||
$t instanceof FakeTitle
) {
532 $t = Title
::newFromText( 'NO TITLE' );
535 if ( strval( $t->getFragment() ) !== '' ) {
536 # Strip the fragment to avoid various odd effects
537 $this->mTitle
= clone $t;
538 $this->mTitle
->setFragment( '' );
545 * Accessor for the Title object
547 * @return Title object
549 function getTitle() {
550 return $this->mTitle
;
554 * Accessor/mutator for the Title object
556 * @param $x New Title object or null to just get the current one
557 * @return Title object
559 function Title( $x = null ) {
560 return wfSetVar( $this->mTitle
, $x );
564 * Set the output type
566 * @param $ot Integer: new value
568 function setOutputType( $ot ) {
569 $this->mOutputType
= $ot;
572 'html' => $ot == self
::OT_HTML
,
573 'wiki' => $ot == self
::OT_WIKI
,
574 'pre' => $ot == self
::OT_PREPROCESS
,
575 'plain' => $ot == self
::OT_PLAIN
,
580 * Accessor/mutator for the output type
582 * @param $x New value or null to just get the current one
585 function OutputType( $x = null ) {
586 return wfSetVar( $this->mOutputType
, $x );
590 * Get the ParserOutput object
592 * @return ParserOutput object
594 function getOutput() {
595 return $this->mOutput
;
599 * Get the ParserOptions object
601 * @return ParserOptions object
603 function getOptions() {
604 return $this->mOptions
;
608 * Accessor/mutator for the ParserOptions object
610 * @param $x New value or null to just get the current one
611 * @return Current ParserOptions object
613 function Options( $x = null ) {
614 return wfSetVar( $this->mOptions
, $x );
617 function nextLinkID() {
618 return $this->mLinkID++
;
624 function getFunctionLang() {
625 global $wgLang, $wgContLang;
627 $target = $this->mOptions
->getTargetLanguage();
628 if ( $target !== null ) {
631 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
636 * Get a User object either from $this->mUser, if set, or from the
637 * ParserOptions object otherwise
639 * @return User object
642 if ( !is_null( $this->mUser
) ) {
645 return $this->mOptions
->getUser();
649 * Get a preprocessor object
651 * @return Preprocessor instance
653 function getPreprocessor() {
654 if ( !isset( $this->mPreprocessor
) ) {
655 $class = $this->mPreprocessorClass
;
656 $this->mPreprocessor
= new $class( $this );
658 return $this->mPreprocessor
;
662 * Replaces all occurrences of HTML-style comments and the given tags
663 * in the text with a random marker and returns the next text. The output
664 * parameter $matches will be an associative array filled with data in
666 * 'UNIQ-xxxxx' => array(
669 * array( 'param' => 'x' ),
670 * '<element param="x">tag content</element>' ) )
672 * @param $elements list of element names. Comments are always extracted.
673 * @param $text Source text string.
674 * @param $matches Out parameter, Array: extracted tags
675 * @param $uniq_prefix
676 * @return String: stripped text
680 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
685 $taglist = implode( '|', $elements );
686 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
688 while ( $text != '' ) {
689 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
691 if ( count( $p ) < 5 ) {
694 if ( count( $p ) > 5 ) {
708 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
709 $stripped .= $marker;
711 if ( $close === '/>' ) {
712 # Empty element tag, <tag />
717 if ( $element === '!--' ) {
720 $end = "/(<\\/$element\\s*>)/i";
722 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
724 if ( count( $q ) < 3 ) {
725 # No end tag -- let it run out to the end of the text.
734 $matches[$marker] = array( $element,
736 Sanitizer
::decodeTagAttributes( $attributes ),
737 "<$element$attributes$close$content$tail" );
743 * Get a list of strippable XML-like elements
745 function getStripList() {
746 return $this->mStripList
;
750 * @deprecated use replaceVariables
752 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
757 * Restores pre, math, and other extensions removed by strip()
759 * always call unstripNoWiki() after this one
761 * @deprecated use $this->mStripState->unstrip()
763 function unstrip( $text, $state ) {
764 return $state->unstripGeneral( $text );
768 * Always call this after unstrip() to preserve the order
771 * @deprecated use $this->mStripState->unstrip()
773 function unstripNoWiki( $text, $state ) {
774 return $state->unstripNoWiki( $text );
778 * @deprecated use $this->mStripState->unstripBoth()
780 function unstripForHTML( $text ) {
781 return $this->mStripState
->unstripBoth( $text );
785 * Add an item to the strip state
786 * Returns the unique tag which must be inserted into the stripped text
787 * The tag will be replaced with the original text in unstrip()
791 function insertStripItem( $text ) {
792 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
793 $this->mMarkerIndex++
;
794 $this->mStripState
->general
->setPair( $rnd, $text );
799 * Interface with html tidy
800 * @deprecated Use MWTidy::tidy()
802 public static function tidy( $text ) {
803 wfDeprecated( __METHOD__
);
804 return MWTidy
::tidy( $text );
808 * parse the wiki syntax used to render tables
812 function doTableStuff( $text ) {
813 wfProfileIn( __METHOD__
);
815 $lines = StringUtils
::explode( "\n", $text );
817 $td_history = array(); # Is currently a td tag open?
818 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
819 $tr_history = array(); # Is currently a tr tag open?
820 $tr_attributes = array(); # history of tr attributes
821 $has_opened_tr = array(); # Did this table open a <tr> element?
822 $indent_level = 0; # indent level of the table
824 foreach ( $lines as $outLine ) {
825 $line = trim( $outLine );
827 if ( $line === '' ) { # empty line, go to next line
828 $out .= $outLine."\n";
832 $first_character = $line[0];
835 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
836 # First check if we are starting a new table
837 $indent_level = strlen( $matches[1] );
839 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
840 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
842 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
843 array_push( $td_history , false );
844 array_push( $last_tag_history , '' );
845 array_push( $tr_history , false );
846 array_push( $tr_attributes , '' );
847 array_push( $has_opened_tr , false );
848 } elseif ( count( $td_history ) == 0 ) {
849 # Don't do any of the following
850 $out .= $outLine."\n";
852 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
853 # We are ending a table
854 $line = '</table>' . substr( $line , 2 );
855 $last_tag = array_pop( $last_tag_history );
857 if ( !array_pop( $has_opened_tr ) ) {
858 $line = "<tr><td></td></tr>{$line}";
861 if ( array_pop( $tr_history ) ) {
862 $line = "</tr>{$line}";
865 if ( array_pop( $td_history ) ) {
866 $line = "</{$last_tag}>{$line}";
868 array_pop( $tr_attributes );
869 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
870 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
871 # Now we have a table row
872 $line = preg_replace( '#^\|-+#', '', $line );
874 # Whats after the tag is now only attributes
875 $attributes = $this->mStripState
->unstripBoth( $line );
876 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
877 array_pop( $tr_attributes );
878 array_push( $tr_attributes, $attributes );
881 $last_tag = array_pop( $last_tag_history );
882 array_pop( $has_opened_tr );
883 array_push( $has_opened_tr , true );
885 if ( array_pop( $tr_history ) ) {
889 if ( array_pop( $td_history ) ) {
890 $line = "</{$last_tag}>{$line}";
894 array_push( $tr_history , false );
895 array_push( $td_history , false );
896 array_push( $last_tag_history , '' );
897 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
898 # This might be cell elements, td, th or captions
899 if ( substr( $line , 0 , 2 ) === '|+' ) {
900 $first_character = '+';
901 $line = substr( $line , 1 );
904 $line = substr( $line , 1 );
906 if ( $first_character === '!' ) {
907 $line = str_replace( '!!' , '||' , $line );
910 # Split up multiple cells on the same line.
911 # FIXME : This can result in improper nesting of tags processed
912 # by earlier parser steps, but should avoid splitting up eg
913 # attribute values containing literal "||".
914 $cells = StringUtils
::explodeMarkup( '||' , $line );
918 # Loop through each table cell
919 foreach ( $cells as $cell ) {
921 if ( $first_character !== '+' ) {
922 $tr_after = array_pop( $tr_attributes );
923 if ( !array_pop( $tr_history ) ) {
924 $previous = "<tr{$tr_after}>\n";
926 array_push( $tr_history , true );
927 array_push( $tr_attributes , '' );
928 array_pop( $has_opened_tr );
929 array_push( $has_opened_tr , true );
932 $last_tag = array_pop( $last_tag_history );
934 if ( array_pop( $td_history ) ) {
935 $previous = "</{$last_tag}>\n{$previous}";
938 if ( $first_character === '|' ) {
940 } elseif ( $first_character === '!' ) {
942 } elseif ( $first_character === '+' ) {
943 $last_tag = 'caption';
948 array_push( $last_tag_history , $last_tag );
950 # A cell could contain both parameters and data
951 $cell_data = explode( '|' , $cell , 2 );
953 # Bug 553: Note that a '|' inside an invalid link should not
954 # be mistaken as delimiting cell parameters
955 if ( strpos( $cell_data[0], '[[' ) !== false ) {
956 $cell = "{$previous}<{$last_tag}>{$cell}";
957 } elseif ( count( $cell_data ) == 1 ) {
958 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
960 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
961 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
962 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
966 array_push( $td_history , true );
969 $out .= $outLine . "\n";
972 # Closing open td, tr && table
973 while ( count( $td_history ) > 0 ) {
974 if ( array_pop( $td_history ) ) {
977 if ( array_pop( $tr_history ) ) {
980 if ( !array_pop( $has_opened_tr ) ) {
981 $out .= "<tr><td></td></tr>\n" ;
984 $out .= "</table>\n";
987 # Remove trailing line-ending (b/c)
988 if ( substr( $out, -1 ) === "\n" ) {
989 $out = substr( $out, 0, -1 );
992 # special case: don't return empty table
993 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
997 wfProfileOut( __METHOD__
);
1003 * Helper function for parse() that transforms wiki markup into
1004 * HTML. Only called for $mOutputType == self::OT_HTML.
1008 function internalParse( $text, $isMain = true, $frame=false ) {
1009 wfProfileIn( __METHOD__
);
1013 # Hook to suspend the parser in this state
1014 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1015 wfProfileOut( __METHOD__
);
1019 # if $frame is provided, then use $frame for replacing any variables
1021 # use frame depth to infer how include/noinclude tags should be handled
1022 # depth=0 means this is the top-level document; otherwise it's an included document
1023 if ( !$frame->depth
) {
1026 $flag = Parser
::PTD_FOR_INCLUSION
;
1028 $dom = $this->preprocessToDom( $text, $flag );
1029 $text = $frame->expand( $dom );
1031 # if $frame is not provided, then use old-style replaceVariables
1032 $text = $this->replaceVariables( $text );
1035 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1036 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1038 # Tables need to come after variable replacement for things to work
1039 # properly; putting them before other transformations should keep
1040 # exciting things like link expansions from showing up in surprising
1042 $text = $this->doTableStuff( $text );
1044 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1046 $text = $this->doDoubleUnderscore( $text );
1048 $text = $this->doHeadings( $text );
1049 if ( $this->mOptions
->getUseDynamicDates() ) {
1050 $df = DateFormatter
::getInstance();
1051 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1053 $text = $this->replaceInternalLinks( $text );
1054 $text = $this->doAllQuotes( $text );
1055 $text = $this->replaceExternalLinks( $text );
1057 # replaceInternalLinks may sometimes leave behind
1058 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1059 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1061 $text = $this->doMagicLinks( $text );
1062 $text = $this->formatHeadings( $text, $origText, $isMain );
1064 wfProfileOut( __METHOD__
);
1069 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1070 * magic external links.
1075 function doMagicLinks( $text ) {
1076 wfProfileIn( __METHOD__
);
1077 $prots = $this->mUrlProtocols
;
1078 $urlChar = self
::EXT_LINK_URL_CLASS
;
1079 $text = preg_replace_callback(
1081 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1082 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1083 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1084 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1085 ISBN\s+(\b # m[5]: ISBN, capture number
1086 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1087 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1088 [0-9Xx] # check digit
1090 )!x', array( &$this, 'magicLinkCallback' ), $text );
1091 wfProfileOut( __METHOD__
);
1095 function magicLinkCallback( $m ) {
1096 if ( isset( $m[1] ) && $m[1] !== '' ) {
1099 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1102 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1103 # Free external link
1104 return $this->makeFreeExternalLink( $m[0] );
1105 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1107 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1110 $CssClass = 'mw-magiclink-rfc';
1112 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1114 $urlmsg = 'pubmedurl';
1115 $CssClass = 'mw-magiclink-pmid';
1118 throw new MWException( __METHOD__
.': unrecognised match type "' .
1119 substr( $m[0], 0, 20 ) . '"' );
1121 $url = wfMsgForContent( $urlmsg, $id );
1122 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1123 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1124 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1127 $num = strtr( $isbn, array(
1132 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1134 $titleObj->escapeLocalUrl() .
1135 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1142 * Make a free external link, given a user-supplied URL
1146 function makeFreeExternalLink( $url ) {
1148 wfProfileIn( __METHOD__
);
1150 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1153 # The characters '<' and '>' (which were escaped by
1154 # removeHTMLtags()) should not be included in
1155 # URLs, per RFC 2396.
1157 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1158 $trail = substr( $url, $m2[0][1] ) . $trail;
1159 $url = substr( $url, 0, $m2[0][1] );
1162 # Move trailing punctuation to $trail
1164 # If there is no left bracket, then consider right brackets fair game too
1165 if ( strpos( $url, '(' ) === false ) {
1169 $numSepChars = strspn( strrev( $url ), $sep );
1170 if ( $numSepChars ) {
1171 $trail = substr( $url, -$numSepChars ) . $trail;
1172 $url = substr( $url, 0, -$numSepChars );
1175 $url = Sanitizer
::cleanUrl( $url );
1177 # Is this an external image?
1178 $text = $this->maybeMakeExternalImage( $url );
1179 if ( $text === false ) {
1180 # Not an image, make a link
1181 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1182 $this->getExternalLinkAttribs( $url ) );
1183 # Register it in the output object...
1184 # Replace unnecessary URL escape codes with their equivalent characters
1185 $pasteurized = self
::replaceUnusualEscapes( $url );
1186 $this->mOutput
->addExternalLink( $pasteurized );
1188 wfProfileOut( __METHOD__
);
1189 return $text . $trail;
1194 * Parse headers and return html
1198 function doHeadings( $text ) {
1199 wfProfileIn( __METHOD__
);
1200 for ( $i = 6; $i >= 1; --$i ) {
1201 $h = str_repeat( '=', $i );
1202 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1203 "<h$i>\\1</h$i>", $text );
1205 wfProfileOut( __METHOD__
);
1210 * Replace single quotes with HTML markup
1212 * @return string the altered text
1214 function doAllQuotes( $text ) {
1215 wfProfileIn( __METHOD__
);
1217 $lines = StringUtils
::explode( "\n", $text );
1218 foreach ( $lines as $line ) {
1219 $outtext .= $this->doQuotes( $line ) . "\n";
1221 $outtext = substr( $outtext, 0,-1 );
1222 wfProfileOut( __METHOD__
);
1227 * Helper function for doAllQuotes()
1229 public function doQuotes( $text ) {
1230 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1231 if ( count( $arr ) == 1 ) {
1234 # First, do some preliminary work. This may shift some apostrophes from
1235 # being mark-up to being text. It also counts the number of occurrences
1236 # of bold and italics mark-ups.
1239 for ( $i = 0; $i < count( $arr ); $i++
) {
1240 if ( ( $i %
2 ) == 1 ) {
1241 # If there are ever four apostrophes, assume the first is supposed to
1242 # be text, and the remaining three constitute mark-up for bold text.
1243 if ( strlen( $arr[$i] ) == 4 ) {
1246 } elseif ( strlen( $arr[$i] ) > 5 ) {
1247 # If there are more than 5 apostrophes in a row, assume they're all
1248 # text except for the last 5.
1249 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1252 # Count the number of occurrences of bold and italics mark-ups.
1253 # We are not counting sequences of five apostrophes.
1254 if ( strlen( $arr[$i] ) == 2 ) {
1256 } elseif ( strlen( $arr[$i] ) == 3 ) {
1258 } elseif ( strlen( $arr[$i] ) == 5 ) {
1265 # If there is an odd number of both bold and italics, it is likely
1266 # that one of the bold ones was meant to be an apostrophe followed
1267 # by italics. Which one we cannot know for certain, but it is more
1268 # likely to be one that has a single-letter word before it.
1269 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1271 $firstsingleletterword = -1;
1272 $firstmultiletterword = -1;
1274 foreach ( $arr as $r ) {
1275 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1276 $x1 = substr( $arr[$i-1], -1 );
1277 $x2 = substr( $arr[$i-1], -2, 1 );
1278 if ( $x1 === ' ' ) {
1279 if ( $firstspace == -1 ) {
1282 } elseif ( $x2 === ' ') {
1283 if ( $firstsingleletterword == -1 ) {
1284 $firstsingleletterword = $i;
1287 if ( $firstmultiletterword == -1 ) {
1288 $firstmultiletterword = $i;
1295 # If there is a single-letter word, use it!
1296 if ( $firstsingleletterword > -1 ) {
1297 $arr[$firstsingleletterword] = "''";
1298 $arr[$firstsingleletterword-1] .= "'";
1299 } elseif ( $firstmultiletterword > -1 ) {
1300 # If not, but there's a multi-letter word, use that one.
1301 $arr[$firstmultiletterword] = "''";
1302 $arr[$firstmultiletterword-1] .= "'";
1303 } elseif ( $firstspace > -1 ) {
1304 # ... otherwise use the first one that has neither.
1305 # (notice that it is possible for all three to be -1 if, for example,
1306 # there is only one pentuple-apostrophe in the line)
1307 $arr[$firstspace] = "''";
1308 $arr[$firstspace-1] .= "'";
1312 # Now let's actually convert our apostrophic mush to HTML!
1317 foreach ( $arr as $r ) {
1318 if ( ( $i %
2 ) == 0 ) {
1319 if ( $state === 'both' ) {
1325 if ( strlen( $r ) == 2 ) {
1326 if ( $state === 'i' ) {
1327 $output .= '</i>'; $state = '';
1328 } elseif ( $state === 'bi' ) {
1329 $output .= '</i>'; $state = 'b';
1330 } elseif ( $state === 'ib' ) {
1331 $output .= '</b></i><b>'; $state = 'b';
1332 } elseif ( $state === 'both' ) {
1333 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1334 } else { # $state can be 'b' or ''
1335 $output .= '<i>'; $state .= 'i';
1337 } elseif ( strlen( $r ) == 3 ) {
1338 if ( $state === 'b' ) {
1339 $output .= '</b>'; $state = '';
1340 } elseif ( $state === 'bi' ) {
1341 $output .= '</i></b><i>'; $state = 'i';
1342 } elseif ( $state === 'ib' ) {
1343 $output .= '</b>'; $state = 'i';
1344 } elseif ( $state === 'both' ) {
1345 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1346 } else { # $state can be 'i' or ''
1347 $output .= '<b>'; $state .= 'b';
1349 } elseif ( strlen( $r ) == 5 ) {
1350 if ( $state === 'b' ) {
1351 $output .= '</b><i>'; $state = 'i';
1352 } elseif ( $state === 'i' ) {
1353 $output .= '</i><b>'; $state = 'b';
1354 } elseif ( $state === 'bi' ) {
1355 $output .= '</i></b>'; $state = '';
1356 } elseif ( $state === 'ib' ) {
1357 $output .= '</b></i>'; $state = '';
1358 } elseif ( $state === 'both' ) {
1359 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1360 } else { # ($state == '')
1361 $buffer = ''; $state = 'both';
1367 # Now close all remaining tags. Notice that the order is important.
1368 if ( $state === 'b' ||
$state === 'ib' ) {
1371 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1374 if ( $state === 'bi' ) {
1377 # There might be lonely ''''', so make sure we have a buffer
1378 if ( $state === 'both' && $buffer ) {
1379 $output .= '<b><i>'.$buffer.'</i></b>';
1386 * Replace external links (REL)
1388 * Note: this is all very hackish and the order of execution matters a lot.
1389 * Make sure to run maintenance/parserTests.php if you change this code.
1393 function replaceExternalLinks( $text ) {
1395 wfProfileIn( __METHOD__
);
1397 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1399 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1400 $s = array_shift( $bits );
1403 while ( $i<count( $bits ) ) {
1405 $protocol = $bits[$i++
];
1406 $text = $bits[$i++
];
1407 $trail = $bits[$i++
];
1409 # The characters '<' and '>' (which were escaped by
1410 # removeHTMLtags()) should not be included in
1411 # URLs, per RFC 2396.
1413 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1414 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1415 $url = substr( $url, 0, $m2[0][1] );
1418 # If the link text is an image URL, replace it with an <img> tag
1419 # This happened by accident in the original parser, but some people used it extensively
1420 $img = $this->maybeMakeExternalImage( $text );
1421 if ( $img !== false ) {
1427 # Set linktype for CSS - if URL==text, link is essentially free
1428 $linktype = ( $text === $url ) ?
'free' : 'text';
1430 # No link text, e.g. [http://domain.tld/some.link]
1431 if ( $text == '' ) {
1432 # Autonumber if allowed. See bug #5918
1433 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1434 $langObj = $this->getFunctionLang();
1435 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1436 $linktype = 'autonumber';
1438 # Otherwise just use the URL
1439 $text = htmlspecialchars( $url );
1443 # Have link text, e.g. [http://domain.tld/some.link text]s
1445 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1448 $text = $wgContLang->markNoConversion( $text );
1450 $url = Sanitizer
::cleanUrl( $url );
1452 # Use the encoded URL
1453 # This means that users can paste URLs directly into the text
1454 # Funny characters like ö aren't valid in URLs anyway
1455 # This was changed in August 2004
1456 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1457 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1459 # Register link in the output object.
1460 # Replace unnecessary URL escape codes with the referenced character
1461 # This prevents spammers from hiding links from the filters
1462 $pasteurized = self
::replaceUnusualEscapes( $url );
1463 $this->mOutput
->addExternalLink( $pasteurized );
1466 wfProfileOut( __METHOD__
);
1471 * Get an associative array of additional HTML attributes appropriate for a
1472 * particular external link. This currently may include rel => nofollow
1473 * (depending on configuration, namespace, and the URL's domain) and/or a
1474 * target attribute (depending on configuration).
1476 * @param $url String: optional URL, to extract the domain from for rel =>
1477 * nofollow if appropriate
1478 * @return Array: associative array of HTML attributes
1480 function getExternalLinkAttribs( $url = false ) {
1482 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1483 $ns = $this->mTitle
->getNamespace();
1484 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1485 $attribs['rel'] = 'nofollow';
1487 global $wgNoFollowDomainExceptions;
1488 if ( $wgNoFollowDomainExceptions ) {
1489 $bits = wfParseUrl( $url );
1490 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1491 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1492 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1493 unset( $attribs['rel'] );
1500 if ( $this->mOptions
->getExternalLinkTarget() ) {
1501 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1508 * Replace unusual URL escape codes with their equivalent characters
1510 * @param $url String
1513 * @todo This can merge genuinely required bits in the path or query string,
1514 * breaking legit URLs. A proper fix would treat the various parts of
1515 * the URL differently; as a workaround, just use the output for
1516 * statistical records, not for actual linking/output.
1518 static function replaceUnusualEscapes( $url ) {
1519 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1520 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1524 * Callback function used in replaceUnusualEscapes().
1525 * Replaces unusual URL escape codes with their equivalent character
1527 private static function replaceUnusualEscapesCallback( $matches ) {
1528 $char = urldecode( $matches[0] );
1529 $ord = ord( $char );
1530 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1531 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1532 # No, shouldn't be escaped
1535 # Yes, leave it escaped
1541 * make an image if it's allowed, either through the global
1542 * option, through the exception, or through the on-wiki whitelist
1545 function maybeMakeExternalImage( $url ) {
1546 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1547 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1548 $imagesexception = !empty( $imagesfrom );
1550 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1551 if ( $imagesexception && is_array( $imagesfrom ) ) {
1552 $imagematch = false;
1553 foreach ( $imagesfrom as $match ) {
1554 if ( strpos( $url, $match ) === 0 ) {
1559 } elseif ( $imagesexception ) {
1560 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1562 $imagematch = false;
1564 if ( $this->mOptions
->getAllowExternalImages()
1565 ||
( $imagesexception && $imagematch ) ) {
1566 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1568 $text = $sk->makeExternalImage( $url );
1571 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1572 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1573 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1574 foreach ( $whitelist as $entry ) {
1575 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1576 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1579 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1580 # Image matches a whitelist entry
1581 $text = $sk->makeExternalImage( $url );
1590 * Process [[ ]] wikilinks
1591 * @return String: processed text
1595 function replaceInternalLinks( $s ) {
1596 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1601 * Process [[ ]] wikilinks (RIL)
1602 * @return LinkHolderArray
1606 function replaceInternalLinks2( &$s ) {
1609 wfProfileIn( __METHOD__
);
1611 wfProfileIn( __METHOD__
.'-setup' );
1612 static $tc = FALSE, $e1, $e1_img;
1613 # the % is needed to support urlencoded titles as well
1615 $tc = Title
::legalChars() . '#%';
1616 # Match a link having the form [[namespace:link|alternate]]trail
1617 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1618 # Match cases where there is no "]]", which might still be images
1619 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1622 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1623 $holders = new LinkHolderArray( $this );
1625 # split the entire text string on occurences of [[
1626 $a = StringUtils
::explode( '[[', ' ' . $s );
1627 # get the first element (all text up to first [[), and remove the space we added
1630 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1631 $s = substr( $s, 1 );
1633 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1635 if ( $useLinkPrefixExtension ) {
1636 # Match the end of a line for a word that's not followed by whitespace,
1637 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1638 $e2 = wfMsgForContent( 'linkprefix' );
1641 if ( is_null( $this->mTitle
) ) {
1642 wfProfileOut( __METHOD__
.'-setup' );
1643 wfProfileOut( __METHOD__
);
1644 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1646 $nottalk = !$this->mTitle
->isTalkPage();
1648 if ( $useLinkPrefixExtension ) {
1650 if ( preg_match( $e2, $s, $m ) ) {
1651 $first_prefix = $m[2];
1653 $first_prefix = false;
1659 if ( $wgContLang->hasVariants() ) {
1660 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1662 $selflink = array( $this->mTitle
->getPrefixedText() );
1664 $useSubpages = $this->areSubpagesAllowed();
1665 wfProfileOut( __METHOD__
.'-setup' );
1667 # Loop for each link
1668 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1669 # Check for excessive memory usage
1670 if ( $holders->isBig() ) {
1672 # Do the existence check, replace the link holders and clear the array
1673 $holders->replace( $s );
1677 if ( $useLinkPrefixExtension ) {
1678 wfProfileIn( __METHOD__
.'-prefixhandling' );
1679 if ( preg_match( $e2, $s, $m ) ) {
1686 if ( $first_prefix ) {
1687 $prefix = $first_prefix;
1688 $first_prefix = false;
1690 wfProfileOut( __METHOD__
.'-prefixhandling' );
1693 $might_be_img = false;
1695 wfProfileIn( __METHOD__
."-e1" );
1696 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1698 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1699 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1700 # the real problem is with the $e1 regex
1703 # Still some problems for cases where the ] is meant to be outside punctuation,
1704 # and no image is in sight. See bug 2095.
1706 if ( $text !== '' &&
1707 substr( $m[3], 0, 1 ) === ']' &&
1708 strpos( $text, '[' ) !== false
1711 $text .= ']'; # so that replaceExternalLinks($text) works later
1712 $m[3] = substr( $m[3], 1 );
1714 # fix up urlencoded title texts
1715 if ( strpos( $m[1], '%' ) !== false ) {
1716 # Should anchors '#' also be rejected?
1717 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1720 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1721 $might_be_img = true;
1723 if ( strpos( $m[1], '%' ) !== false ) {
1724 $m[1] = rawurldecode( $m[1] );
1727 } else { # Invalid form; output directly
1728 $s .= $prefix . '[[' . $line ;
1729 wfProfileOut( __METHOD__
."-e1" );
1732 wfProfileOut( __METHOD__
."-e1" );
1733 wfProfileIn( __METHOD__
."-misc" );
1735 # Don't allow internal links to pages containing
1736 # PROTO: where PROTO is a valid URL protocol; these
1737 # should be external links.
1738 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1739 $s .= $prefix . '[[' . $line ;
1740 wfProfileOut( __METHOD__
."-misc" );
1744 # Make subpage if necessary
1745 if ( $useSubpages ) {
1746 $link = $this->maybeDoSubpageLink( $m[1], $text );
1751 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1753 # Strip off leading ':'
1754 $link = substr( $link, 1 );
1757 wfProfileOut( __METHOD__
."-misc" );
1758 wfProfileIn( __METHOD__
."-title" );
1759 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1760 if ( $nt === null ) {
1761 $s .= $prefix . '[[' . $line;
1762 wfProfileOut( __METHOD__
."-title" );
1766 $ns = $nt->getNamespace();
1767 $iw = $nt->getInterWiki();
1768 wfProfileOut( __METHOD__
."-title" );
1770 if ( $might_be_img ) { # if this is actually an invalid link
1771 wfProfileIn( __METHOD__
."-might_be_img" );
1772 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1775 # look at the next 'line' to see if we can close it there
1777 $next_line = $a->current();
1778 if ( $next_line === false ||
$next_line === null ) {
1781 $m = explode( ']]', $next_line, 3 );
1782 if ( count( $m ) == 3 ) {
1783 # the first ]] closes the inner link, the second the image
1785 $text .= "[[{$m[0]}]]{$m[1]}";
1788 } elseif ( count( $m ) == 2 ) {
1789 # if there's exactly one ]] that's fine, we'll keep looking
1790 $text .= "[[{$m[0]}]]{$m[1]}";
1792 # if $next_line is invalid too, we need look no further
1793 $text .= '[[' . $next_line;
1798 # we couldn't find the end of this imageLink, so output it raw
1799 # but don't ignore what might be perfectly normal links in the text we've examined
1800 $holders->merge( $this->replaceInternalLinks2( $text ) );
1801 $s .= "{$prefix}[[$link|$text";
1802 # note: no $trail, because without an end, there *is* no trail
1803 wfProfileOut( __METHOD__
."-might_be_img" );
1806 } else { # it's not an image, so output it raw
1807 $s .= "{$prefix}[[$link|$text";
1808 # note: no $trail, because without an end, there *is* no trail
1809 wfProfileOut( __METHOD__
."-might_be_img" );
1812 wfProfileOut( __METHOD__
."-might_be_img" );
1815 $wasblank = ( $text == '' );
1819 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1820 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1821 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1822 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1823 $text = $this->doQuotes( $text );
1826 # Link not escaped by : , create the various objects
1830 wfProfileIn( __METHOD__
."-interwiki" );
1831 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1832 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1833 $s = rtrim( $s . $prefix );
1834 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1835 wfProfileOut( __METHOD__
."-interwiki" );
1838 wfProfileOut( __METHOD__
."-interwiki" );
1840 if ( $ns == NS_FILE
) {
1841 wfProfileIn( __METHOD__
."-image" );
1842 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1844 # if no parameters were passed, $text
1845 # becomes something like "File:Foo.png",
1846 # which we don't want to pass on to the
1850 # recursively parse links inside the image caption
1851 # actually, this will parse them in any other parameters, too,
1852 # but it might be hard to fix that, and it doesn't matter ATM
1853 $text = $this->replaceExternalLinks( $text );
1854 $holders->merge( $this->replaceInternalLinks2( $text ) );
1856 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1857 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1859 $s .= $prefix . $trail;
1861 $this->mOutput
->addImage( $nt->getDBkey() );
1862 wfProfileOut( __METHOD__
."-image" );
1867 if ( $ns == NS_CATEGORY
) {
1868 wfProfileIn( __METHOD__
."-category" );
1869 $s = rtrim( $s . "\n" ); # bug 87
1872 $sortkey = $this->getDefaultSort();
1876 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1877 $sortkey = str_replace( "\n", '', $sortkey );
1878 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1879 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1882 * Strip the whitespace Category links produce, see bug 87
1883 * @todo We might want to use trim($tmp, "\n") here.
1885 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1887 wfProfileOut( __METHOD__
."-category" );
1892 # Self-link checking
1893 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1894 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1895 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1900 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1901 # FIXME: Should do batch file existence checks, see comment below
1902 if ( $ns == NS_MEDIA
) {
1903 wfProfileIn( __METHOD__
."-media" );
1904 # Give extensions a chance to select the file revision for us
1905 $skip = $time = false;
1906 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1908 $link = $sk->link( $nt );
1910 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1912 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1913 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1914 $this->mOutput
->addImage( $nt->getDBkey() );
1915 wfProfileOut( __METHOD__
."-media" );
1919 wfProfileIn( __METHOD__
."-always_known" );
1920 # Some titles, such as valid special pages or files in foreign repos, should
1921 # be shown as bluelinks even though they're not included in the page table
1923 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1924 # batch file existence checks for NS_FILE and NS_MEDIA
1925 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1926 $this->mOutput
->addLink( $nt );
1927 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1929 # Links will be added to the output link list after checking
1930 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1932 wfProfileOut( __METHOD__
."-always_known" );
1934 wfProfileOut( __METHOD__
);
1939 * Make a link placeholder. The text returned can be later resolved to a real link with
1940 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1941 * parsing of interwiki links, and secondly to allow all existence checks and
1942 * article length checks (for stub links) to be bundled into a single query.
1946 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1947 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1951 * Render a forced-blue link inline; protect against double expansion of
1952 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1953 * Since this little disaster has to split off the trail text to avoid
1954 * breaking URLs in the following text without breaking trails on the
1955 * wiki links, it's been made into a horrible function.
1958 * @param $text String
1959 * @param $query String
1960 * @param $trail String
1961 * @param $prefix String
1962 * @return String: HTML-wikitext mix oh yuck
1964 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1965 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1966 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1967 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1968 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1969 return $this->armorLinks( $link ) . $trail;
1973 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1974 * going to go through further parsing steps before inline URL expansion.
1976 * Not needed quite as much as it used to be since free links are a bit
1977 * more sensible these days. But bracketed links are still an issue.
1979 * @param $text String: more-or-less HTML
1980 * @return String: less-or-more HTML with NOPARSE bits
1982 function armorLinks( $text ) {
1983 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1984 "{$this->mUniqPrefix}NOPARSE$1", $text );
1988 * Return true if subpage links should be expanded on this page.
1991 function areSubpagesAllowed() {
1992 # Some namespaces don't allow subpages
1993 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1997 * Handle link to subpage if necessary
1999 * @param $target String: the source of the link
2000 * @param &$text String: the link text, modified as necessary
2001 * @return string the full name of the link
2004 function maybeDoSubpageLink( $target, &$text ) {
2005 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2009 * Used by doBlockLevels()
2012 function closeParagraph() {
2014 if ( $this->mLastSection
!= '' ) {
2015 $result = '</' . $this->mLastSection
. ">\n";
2017 $this->mInPre
= false;
2018 $this->mLastSection
= '';
2023 * getCommon() returns the length of the longest common substring
2024 * of both arguments, starting at the beginning of both.
2027 function getCommon( $st1, $st2 ) {
2028 $fl = strlen( $st1 );
2029 $shorter = strlen( $st2 );
2030 if ( $fl < $shorter ) {
2034 for ( $i = 0; $i < $shorter; ++
$i ) {
2035 if ( $st1{$i} != $st2{$i} ) {
2043 * These next three functions open, continue, and close the list
2044 * element appropriate to the prefix character passed into them.
2047 function openList( $char ) {
2048 $result = $this->closeParagraph();
2050 if ( '*' === $char ) {
2051 $result .= '<ul><li>';
2052 } elseif ( '#' === $char ) {
2053 $result .= '<ol><li>';
2054 } elseif ( ':' === $char ) {
2055 $result .= '<dl><dd>';
2056 } elseif ( ';' === $char ) {
2057 $result .= '<dl><dt>';
2058 $this->mDTopen
= true;
2060 $result = '<!-- ERR 1 -->';
2068 * @param $char String
2071 function nextItem( $char ) {
2072 if ( '*' === $char ||
'#' === $char ) {
2074 } elseif ( ':' === $char ||
';' === $char ) {
2076 if ( $this->mDTopen
) {
2079 if ( ';' === $char ) {
2080 $this->mDTopen
= true;
2081 return $close . '<dt>';
2083 $this->mDTopen
= false;
2084 return $close . '<dd>';
2087 return '<!-- ERR 2 -->';
2092 * @param $char String
2095 function closeList( $char ) {
2096 if ( '*' === $char ) {
2097 $text = '</li></ul>';
2098 } elseif ( '#' === $char ) {
2099 $text = '</li></ol>';
2100 } elseif ( ':' === $char ) {
2101 if ( $this->mDTopen
) {
2102 $this->mDTopen
= false;
2103 $text = '</dt></dl>';
2105 $text = '</dd></dl>';
2108 return '<!-- ERR 3 -->';
2115 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2117 * @param $text String
2118 * @param $linestart Boolean: whether or not this is at the start of a line.
2120 * @return string the lists rendered as HTML
2122 function doBlockLevels( $text, $linestart ) {
2123 wfProfileIn( __METHOD__
);
2125 # Parsing through the text line by line. The main thing
2126 # happening here is handling of block-level elements p, pre,
2127 # and making lists from lines starting with * # : etc.
2129 $textLines = StringUtils
::explode( "\n", $text );
2131 $lastPrefix = $output = '';
2132 $this->mDTopen
= $inBlockElem = false;
2134 $paragraphStack = false;
2136 foreach ( $textLines as $oLine ) {
2138 if ( !$linestart ) {
2148 $lastPrefixLength = strlen( $lastPrefix );
2149 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2150 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2151 # If not in a <pre> element, scan for and figure out what prefixes are there.
2152 if ( !$this->mInPre
) {
2153 # Multiple prefixes may abut each other for nested lists.
2154 $prefixLength = strspn( $oLine, '*#:;' );
2155 $prefix = substr( $oLine, 0, $prefixLength );
2158 # ; and : are both from definition-lists, so they're equivalent
2159 # for the purposes of determining whether or not we need to open/close
2161 $prefix2 = str_replace( ';', ':', $prefix );
2162 $t = substr( $oLine, $prefixLength );
2163 $this->mInPre
= (bool)$preOpenMatch;
2165 # Don't interpret any other prefixes in preformatted text
2167 $prefix = $prefix2 = '';
2172 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2173 # Same as the last item, so no need to deal with nesting or opening stuff
2174 $output .= $this->nextItem( substr( $prefix, -1 ) );
2175 $paragraphStack = false;
2177 if ( substr( $prefix, -1 ) === ';') {
2178 # The one nasty exception: definition lists work like this:
2179 # ; title : definition text
2180 # So we check for : in the remainder text to split up the
2181 # title and definition, without b0rking links.
2183 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2185 $output .= $term . $this->nextItem( ':' );
2188 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2189 # We need to open or close prefixes, or both.
2191 # Either open or close a level...
2192 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2193 $paragraphStack = false;
2195 # Close all the prefixes which aren't shared.
2196 while ( $commonPrefixLength < $lastPrefixLength ) {
2197 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2198 --$lastPrefixLength;
2201 # Continue the current prefix if appropriate.
2202 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2203 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2206 # Open prefixes where appropriate.
2207 while ( $prefixLength > $commonPrefixLength ) {
2208 $char = substr( $prefix, $commonPrefixLength, 1 );
2209 $output .= $this->openList( $char );
2211 if ( ';' === $char ) {
2212 # FIXME: This is dupe of code above
2213 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2215 $output .= $term . $this->nextItem( ':' );
2218 ++
$commonPrefixLength;
2220 $lastPrefix = $prefix2;
2223 # If we have no prefixes, go to paragraph mode.
2224 if ( 0 == $prefixLength ) {
2225 wfProfileIn( __METHOD__
."-paragraph" );
2226 # No prefix (not in list)--go to paragraph mode
2227 # XXX: use a stack for nestable elements like span, table and div
2228 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2229 $closematch = preg_match(
2230 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2231 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2232 if ( $openmatch or $closematch ) {
2233 $paragraphStack = false;
2234 #Â TODO bug 5718: paragraph closed
2235 $output .= $this->closeParagraph();
2236 if ( $preOpenMatch and !$preCloseMatch ) {
2237 $this->mInPre
= true;
2239 $inBlockElem = !$closematch;
2240 } elseif ( !$inBlockElem && !$this->mInPre
) {
2241 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2243 if ( $this->mLastSection
!== 'pre' ) {
2244 $paragraphStack = false;
2245 $output .= $this->closeParagraph().'<pre>';
2246 $this->mLastSection
= 'pre';
2248 $t = substr( $t, 1 );
2251 if ( trim( $t ) === '' ) {
2252 if ( $paragraphStack ) {
2253 $output .= $paragraphStack.'<br />';
2254 $paragraphStack = false;
2255 $this->mLastSection
= 'p';
2257 if ( $this->mLastSection
!== 'p' ) {
2258 $output .= $this->closeParagraph();
2259 $this->mLastSection
= '';
2260 $paragraphStack = '<p>';
2262 $paragraphStack = '</p><p>';
2266 if ( $paragraphStack ) {
2267 $output .= $paragraphStack;
2268 $paragraphStack = false;
2269 $this->mLastSection
= 'p';
2270 } elseif ( $this->mLastSection
!== 'p' ) {
2271 $output .= $this->closeParagraph().'<p>';
2272 $this->mLastSection
= 'p';
2277 wfProfileOut( __METHOD__
."-paragraph" );
2279 # somewhere above we forget to get out of pre block (bug 785)
2280 if ( $preCloseMatch && $this->mInPre
) {
2281 $this->mInPre
= false;
2283 if ( $paragraphStack === false ) {
2287 while ( $prefixLength ) {
2288 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2291 if ( $this->mLastSection
!= '' ) {
2292 $output .= '</' . $this->mLastSection
. '>';
2293 $this->mLastSection
= '';
2296 wfProfileOut( __METHOD__
);
2301 * Split up a string on ':', ignoring any occurences inside tags
2302 * to prevent illegal overlapping.
2304 * @param $str String: the string to split
2305 * @param &$before String: set to everything before the ':'
2306 * @param &$after String: set to everything after the ':'
2307 * return String: the position of the ':', or false if none found
2309 function findColonNoLinks( $str, &$before, &$after ) {
2310 wfProfileIn( __METHOD__
);
2312 $pos = strpos( $str, ':' );
2313 if ( $pos === false ) {
2315 wfProfileOut( __METHOD__
);
2319 $lt = strpos( $str, '<' );
2320 if ( $lt === false ||
$lt > $pos ) {
2321 # Easy; no tag nesting to worry about
2322 $before = substr( $str, 0, $pos );
2323 $after = substr( $str, $pos+
1 );
2324 wfProfileOut( __METHOD__
);
2328 # Ugly state machine to walk through avoiding tags.
2329 $state = self
::COLON_STATE_TEXT
;
2331 $len = strlen( $str );
2332 for( $i = 0; $i < $len; $i++
) {
2336 # (Using the number is a performance hack for common cases)
2337 case 0: # self::COLON_STATE_TEXT:
2340 # Could be either a <start> tag or an </end> tag
2341 $state = self
::COLON_STATE_TAGSTART
;
2344 if ( $stack == 0 ) {
2346 $before = substr( $str, 0, $i );
2347 $after = substr( $str, $i +
1 );
2348 wfProfileOut( __METHOD__
);
2351 # Embedded in a tag; don't break it.
2354 # Skip ahead looking for something interesting
2355 $colon = strpos( $str, ':', $i );
2356 if ( $colon === false ) {
2357 # Nothing else interesting
2358 wfProfileOut( __METHOD__
);
2361 $lt = strpos( $str, '<', $i );
2362 if ( $stack === 0 ) {
2363 if ( $lt === false ||
$colon < $lt ) {
2365 $before = substr( $str, 0, $colon );
2366 $after = substr( $str, $colon +
1 );
2367 wfProfileOut( __METHOD__
);
2371 if ( $lt === false ) {
2372 # Nothing else interesting to find; abort!
2373 # We're nested, but there's no close tags left. Abort!
2376 # Skip ahead to next tag start
2378 $state = self
::COLON_STATE_TAGSTART
;
2381 case 1: # self::COLON_STATE_TAG:
2386 $state = self
::COLON_STATE_TEXT
;
2389 # Slash may be followed by >?
2390 $state = self
::COLON_STATE_TAGSLASH
;
2396 case 2: # self::COLON_STATE_TAGSTART:
2399 $state = self
::COLON_STATE_CLOSETAG
;
2402 $state = self
::COLON_STATE_COMMENT
;
2405 # Illegal early close? This shouldn't happen D:
2406 $state = self
::COLON_STATE_TEXT
;
2409 $state = self
::COLON_STATE_TAG
;
2412 case 3: # self::COLON_STATE_CLOSETAG:
2417 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2418 wfProfileOut( __METHOD__
);
2421 $state = self
::COLON_STATE_TEXT
;
2424 case self
::COLON_STATE_TAGSLASH
:
2426 # Yes, a self-closed tag <blah/>
2427 $state = self
::COLON_STATE_TEXT
;
2429 # Probably we're jumping the gun, and this is an attribute
2430 $state = self
::COLON_STATE_TAG
;
2433 case 5: # self::COLON_STATE_COMMENT:
2435 $state = self
::COLON_STATE_COMMENTDASH
;
2438 case self
::COLON_STATE_COMMENTDASH
:
2440 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2442 $state = self
::COLON_STATE_COMMENT
;
2445 case self
::COLON_STATE_COMMENTDASHDASH
:
2447 $state = self
::COLON_STATE_TEXT
;
2449 $state = self
::COLON_STATE_COMMENT
;
2453 throw new MWException( "State machine error in " . __METHOD__
);
2457 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2458 wfProfileOut( __METHOD__
);
2461 wfProfileOut( __METHOD__
);
2466 * Return value of a magic variable (like PAGENAME)
2470 function getVariableValue( $index, $frame=false ) {
2471 global $wgContLang, $wgSitename, $wgServer;
2472 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2475 * Some of these require message or data lookups and can be
2476 * expensive to check many times.
2478 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2479 if ( isset( $this->mVarCache
[$index] ) ) {
2480 return $this->mVarCache
[$index];
2484 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2485 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2488 global $wgLocaltimezone;
2489 if ( isset( $wgLocaltimezone ) ) {
2490 $oldtz = date_default_timezone_get();
2491 date_default_timezone_set( $wgLocaltimezone );
2494 $localTimestamp = date( 'YmdHis', $ts );
2495 $localMonth = date( 'm', $ts );
2496 $localMonth1 = date( 'n', $ts );
2497 $localMonthName = date( 'n', $ts );
2498 $localDay = date( 'j', $ts );
2499 $localDay2 = date( 'd', $ts );
2500 $localDayOfWeek = date( 'w', $ts );
2501 $localWeek = date( 'W', $ts );
2502 $localYear = date( 'Y', $ts );
2503 $localHour = date( 'H', $ts );
2504 if ( isset( $wgLocaltimezone ) ) {
2505 date_default_timezone_set( $oldtz );
2509 case 'currentmonth':
2510 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2512 case 'currentmonth1':
2513 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2515 case 'currentmonthname':
2516 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2518 case 'currentmonthnamegen':
2519 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2521 case 'currentmonthabbrev':
2522 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2525 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2528 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2531 $value = $wgContLang->formatNum( $localMonth );
2534 $value = $wgContLang->formatNum( $localMonth1 );
2536 case 'localmonthname':
2537 $value = $wgContLang->getMonthName( $localMonthName );
2539 case 'localmonthnamegen':
2540 $value = $wgContLang->getMonthNameGen( $localMonthName );
2542 case 'localmonthabbrev':
2543 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2546 $value = $wgContLang->formatNum( $localDay );
2549 $value = $wgContLang->formatNum( $localDay2 );
2552 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2555 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2557 case 'fullpagename':
2558 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2560 case 'fullpagenamee':
2561 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2564 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2566 case 'subpagenamee':
2567 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2569 case 'basepagename':
2570 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2572 case 'basepagenamee':
2573 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2575 case 'talkpagename':
2576 if ( $this->mTitle
->canTalk() ) {
2577 $talkPage = $this->mTitle
->getTalkPage();
2578 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2583 case 'talkpagenamee':
2584 if ( $this->mTitle
->canTalk() ) {
2585 $talkPage = $this->mTitle
->getTalkPage();
2586 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2591 case 'subjectpagename':
2592 $subjPage = $this->mTitle
->getSubjectPage();
2593 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2595 case 'subjectpagenamee':
2596 $subjPage = $this->mTitle
->getSubjectPage();
2597 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2600 # Let the edit saving system know we should parse the page
2601 # *after* a revision ID has been assigned.
2602 $this->mOutput
->setFlag( 'vary-revision' );
2603 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2604 $value = $this->mRevisionId
;
2607 # Let the edit saving system know we should parse the page
2608 # *after* a revision ID has been assigned. This is for null edits.
2609 $this->mOutput
->setFlag( 'vary-revision' );
2610 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2611 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2613 case 'revisionday2':
2614 # Let the edit saving system know we should parse the page
2615 # *after* a revision ID has been assigned. This is for null edits.
2616 $this->mOutput
->setFlag( 'vary-revision' );
2617 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2618 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2620 case 'revisionmonth':
2621 # Let the edit saving system know we should parse the page
2622 # *after* a revision ID has been assigned. This is for null edits.
2623 $this->mOutput
->setFlag( 'vary-revision' );
2624 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2625 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2627 case 'revisionmonth1':
2628 # Let the edit saving system know we should parse the page
2629 # *after* a revision ID has been assigned. This is for null edits.
2630 $this->mOutput
->setFlag( 'vary-revision' );
2631 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2632 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2634 case 'revisionyear':
2635 # Let the edit saving system know we should parse the page
2636 # *after* a revision ID has been assigned. This is for null edits.
2637 $this->mOutput
->setFlag( 'vary-revision' );
2638 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2639 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2641 case 'revisiontimestamp':
2642 # Let the edit saving system know we should parse the page
2643 # *after* a revision ID has been assigned. This is for null edits.
2644 $this->mOutput
->setFlag( 'vary-revision' );
2645 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2646 $value = $this->getRevisionTimestamp();
2648 case 'revisionuser':
2649 # Let the edit saving system know we should parse the page
2650 # *after* a revision ID has been assigned. This is for null edits.
2651 $this->mOutput
->setFlag( 'vary-revision' );
2652 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2653 $value = $this->getRevisionUser();
2656 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2659 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2662 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2665 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2667 case 'subjectspace':
2668 $value = $this->mTitle
->getSubjectNsText();
2670 case 'subjectspacee':
2671 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2673 case 'currentdayname':
2674 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2677 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2680 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2683 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2686 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2687 # int to remove the padding
2688 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2691 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2693 case 'localdayname':
2694 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2697 $value = $wgContLang->formatNum( $localYear, true );
2700 $value = $wgContLang->time( $localTimestamp, false, false );
2703 $value = $wgContLang->formatNum( $localHour, true );
2706 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2707 # int to remove the padding
2708 $value = $wgContLang->formatNum( (int)$localWeek );
2711 $value = $wgContLang->formatNum( $localDayOfWeek );
2713 case 'numberofarticles':
2714 $value = $wgContLang->formatNum( SiteStats
::articles() );
2716 case 'numberoffiles':
2717 $value = $wgContLang->formatNum( SiteStats
::images() );
2719 case 'numberofusers':
2720 $value = $wgContLang->formatNum( SiteStats
::users() );
2722 case 'numberofactiveusers':
2723 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2725 case 'numberofpages':
2726 $value = $wgContLang->formatNum( SiteStats
::pages() );
2728 case 'numberofadmins':
2729 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2731 case 'numberofedits':
2732 $value = $wgContLang->formatNum( SiteStats
::edits() );
2734 case 'numberofviews':
2735 $value = $wgContLang->formatNum( SiteStats
::views() );
2737 case 'currenttimestamp':
2738 $value = wfTimestamp( TS_MW
, $ts );
2740 case 'localtimestamp':
2741 $value = $localTimestamp;
2743 case 'currentversion':
2744 $value = SpecialVersion
::getVersion();
2747 return $wgArticlePath;
2753 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2754 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2755 wfRestoreWarnings();
2756 return $serverName ?
$serverName : $wgServer;
2758 return $wgScriptPath;
2760 return $wgStylePath;
2761 case 'directionmark':
2762 return $wgContLang->getDirMark();
2763 case 'contentlanguage':
2764 global $wgLanguageCode;
2765 return $wgLanguageCode;
2768 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2776 $this->mVarCache
[$index] = $value;
2782 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2786 function initialiseVariables() {
2787 wfProfileIn( __METHOD__
);
2788 $variableIDs = MagicWord
::getVariableIDs();
2789 $substIDs = MagicWord
::getSubstIDs();
2791 $this->mVariables
= new MagicWordArray( $variableIDs );
2792 $this->mSubstWords
= new MagicWordArray( $substIDs );
2793 wfProfileOut( __METHOD__
);
2797 * Preprocess some wikitext and return the document tree.
2798 * This is the ghost of replace_variables().
2800 * @param $text String: The text to parse
2801 * @param $flags Integer: bitwise combination of:
2802 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2803 * included. Default is to assume a direct page view.
2805 * The generated DOM tree must depend only on the input text and the flags.
2806 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2808 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2809 * change in the DOM tree for a given text, must be passed through the section identifier
2810 * in the section edit link and thus back to extractSections().
2812 * The output of this function is currently only cached in process memory, but a persistent
2813 * cache may be implemented at a later date which takes further advantage of these strict
2814 * dependency requirements.
2818 function preprocessToDom( $text, $flags = 0 ) {
2819 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2824 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2826 public static function splitWhitespace( $s ) {
2827 $ltrimmed = ltrim( $s );
2828 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2829 $trimmed = rtrim( $ltrimmed );
2830 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2832 $w2 = substr( $ltrimmed, -$diff );
2836 return array( $w1, $trimmed, $w2 );
2840 * Replace magic variables, templates, and template arguments
2841 * with the appropriate text. Templates are substituted recursively,
2842 * taking care to avoid infinite loops.
2844 * Note that the substitution depends on value of $mOutputType:
2845 * self::OT_WIKI: only {{subst:}} templates
2846 * self::OT_PREPROCESS: templates but not extension tags
2847 * self::OT_HTML: all templates and extension tags
2849 * @param $text String: the text to transform
2850 * @param $frame PPFrame Object describing the arguments passed to the template.
2851 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2852 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2853 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2856 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2857 # Is there any text? Also, Prevent too big inclusions!
2858 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2861 wfProfileIn( __METHOD__
);
2863 if ( $frame === false ) {
2864 $frame = $this->getPreprocessor()->newFrame();
2865 } elseif ( !( $frame instanceof PPFrame
) ) {
2866 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2867 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2870 $dom = $this->preprocessToDom( $text );
2871 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2872 $text = $frame->expand( $dom, $flags );
2874 wfProfileOut( __METHOD__
);
2878 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2879 static function createAssocArgs( $args ) {
2880 $assocArgs = array();
2882 foreach ( $args as $arg ) {
2883 $eqpos = strpos( $arg, '=' );
2884 if ( $eqpos === false ) {
2885 $assocArgs[$index++
] = $arg;
2887 $name = trim( substr( $arg, 0, $eqpos ) );
2888 $value = trim( substr( $arg, $eqpos+
1 ) );
2889 if ( $value === false ) {
2892 if ( $name !== false ) {
2893 $assocArgs[$name] = $value;
2902 * Warn the user when a parser limitation is reached
2903 * Will warn at most once the user per limitation type
2905 * @param $limitationType String: should be one of:
2906 * 'expensive-parserfunction' (corresponding messages:
2907 * 'expensive-parserfunction-warning',
2908 * 'expensive-parserfunction-category')
2909 * 'post-expand-template-argument' (corresponding messages:
2910 * 'post-expand-template-argument-warning',
2911 * 'post-expand-template-argument-category')
2912 * 'post-expand-template-inclusion' (corresponding messages:
2913 * 'post-expand-template-inclusion-warning',
2914 * 'post-expand-template-inclusion-category')
2915 * @param $current Current value
2916 * @param $max Maximum allowed, when an explicit limit has been
2917 * exceeded, provide the values (optional)
2919 function limitationWarn( $limitationType, $current=null, $max=null) {
2920 # does no harm if $current and $max are present but are unnecessary for the message
2921 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2922 $this->mOutput
->addWarning( $warning );
2923 $this->addTrackingCategory( "$limitationType-category" );
2927 * Return the text of a template, after recursively
2928 * replacing any variables or templates within the template.
2930 * @param $piece Array: the parts of the template
2931 * $piece['title']: the title, i.e. the part before the |
2932 * $piece['parts']: the parameter array
2933 * $piece['lineStart']: whether the brace was at the start of a line
2934 * @param $frame PPFrame The current frame, contains template arguments
2935 * @return String: the text of the template
2938 function braceSubstitution( $piece, $frame ) {
2939 global $wgContLang, $wgNonincludableNamespaces;
2940 wfProfileIn( __METHOD__
);
2941 wfProfileIn( __METHOD__
.'-setup' );
2944 $found = false; # $text has been filled
2945 $nowiki = false; # wiki markup in $text should be escaped
2946 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2947 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2948 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2949 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2951 # Title object, where $text came from
2954 # $part1 is the bit before the first |, and must contain only title characters.
2955 # Various prefixes will be stripped from it later.
2956 $titleWithSpaces = $frame->expand( $piece['title'] );
2957 $part1 = trim( $titleWithSpaces );
2960 # Original title text preserved for various purposes
2961 $originalTitle = $part1;
2963 # $args is a list of argument nodes, starting from index 0, not including $part1
2964 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2965 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2966 wfProfileOut( __METHOD__
.'-setup' );
2969 wfProfileIn( __METHOD__
.'-modifiers' );
2972 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2974 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2975 # Decide whether to expand template or keep wikitext as-is.
2976 if ( $this->ot
['wiki'] ) {
2977 if ( $substMatch === false ) {
2978 $literal = true; # literal when in PST with no prefix
2980 $literal = false; # expand when in PST with subst: or safesubst:
2983 if ( $substMatch == 'subst' ) {
2984 $literal = true; # literal when not in PST with plain subst:
2986 $literal = false; # expand when not in PST with safesubst: or no prefix
2990 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2997 if ( !$found && $args->getLength() == 0 ) {
2998 $id = $this->mVariables
->matchStartToEnd( $part1 );
2999 if ( $id !== false ) {
3000 $text = $this->getVariableValue( $id, $frame );
3001 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3002 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3008 # MSG, MSGNW and RAW
3011 $mwMsgnw = MagicWord
::get( 'msgnw' );
3012 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3015 # Remove obsolete MSG:
3016 $mwMsg = MagicWord
::get( 'msg' );
3017 $mwMsg->matchStartAndRemove( $part1 );
3021 $mwRaw = MagicWord
::get( 'raw' );
3022 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3023 $forceRawInterwiki = true;
3026 wfProfileOut( __METHOD__
.'-modifiers' );
3030 wfProfileIn( __METHOD__
. '-pfunc' );
3032 $colonPos = strpos( $part1, ':' );
3033 if ( $colonPos !== false ) {
3034 # Case sensitive functions
3035 $function = substr( $part1, 0, $colonPos );
3036 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3037 $function = $this->mFunctionSynonyms
[1][$function];
3039 # Case insensitive functions
3040 $function = $wgContLang->lc( $function );
3041 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3042 $function = $this->mFunctionSynonyms
[0][$function];
3048 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3049 $initialArgs = array( &$this );
3050 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3051 if ( $flags & SFH_OBJECT_ARGS
) {
3052 # Add a frame parameter, and pass the arguments as an array
3053 $allArgs = $initialArgs;
3054 $allArgs[] = $frame;
3055 for ( $i = 0; $i < $args->getLength(); $i++
) {
3056 $funcArgs[] = $args->item( $i );
3058 $allArgs[] = $funcArgs;
3060 # Convert arguments to plain text
3061 for ( $i = 0; $i < $args->getLength(); $i++
) {
3062 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3064 $allArgs = array_merge( $initialArgs, $funcArgs );
3067 # Workaround for PHP bug 35229 and similar
3068 if ( !is_callable( $callback ) ) {
3069 wfProfileOut( __METHOD__
. '-pfunc' );
3070 wfProfileOut( __METHOD__
);
3071 throw new MWException( "Tag hook for $function is not callable\n" );
3073 $result = call_user_func_array( $callback, $allArgs );
3076 $preprocessFlags = 0;
3078 if ( is_array( $result ) ) {
3079 if ( isset( $result[0] ) ) {
3081 unset( $result[0] );
3084 # Extract flags into the local scope
3085 # This allows callers to set flags such as nowiki, found, etc.
3091 $text = $this->preprocessToDom( $text, $preprocessFlags );
3096 wfProfileOut( __METHOD__
. '-pfunc' );
3099 # Finish mangling title and then check for loops.
3100 # Set $title to a Title object and $titleText to the PDBK
3103 # Split the title into page and subpage
3105 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3106 if ( $subpage !== '' ) {
3107 $ns = $this->mTitle
->getNamespace();
3109 $title = Title
::newFromText( $part1, $ns );
3111 $titleText = $title->getPrefixedText();
3112 # Check for language variants if the template is not found
3113 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3114 $wgContLang->findVariantLink( $part1, $title, true );
3116 # Do recursion depth check
3117 $limit = $this->mOptions
->getMaxTemplateDepth();
3118 if ( $frame->depth
>= $limit ) {
3120 $text = '<span class="error">'
3121 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3127 # Load from database
3128 if ( !$found && $title ) {
3129 wfProfileIn( __METHOD__
. '-loadtpl' );
3130 if ( !$title->isExternal() ) {
3131 if ( $title->getNamespace() == NS_SPECIAL
3132 && $this->mOptions
->getAllowSpecialInclusion()
3133 && $this->ot
['html'] )
3135 $text = SpecialPage
::capturePath( $title );
3136 if ( is_string( $text ) ) {
3139 $this->disableCache();
3141 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3142 $found = false; # access denied
3143 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3145 list( $text, $title ) = $this->getTemplateDom( $title );
3146 if ( $text !== false ) {
3152 # If the title is valid but undisplayable, make a link to it
3153 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3154 $text = "[[:$titleText]]";
3157 } elseif ( $title->isTrans() ) {
3158 # Interwiki transclusion
3159 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3160 $text = $this->interwikiTransclude( $title, 'render' );
3163 $text = $this->interwikiTransclude( $title, 'raw' );
3164 # Preprocess it like a template
3165 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3171 # Do infinite loop check
3172 # This has to be done after redirect resolution to avoid infinite loops via redirects
3173 if ( !$frame->loopCheck( $title ) ) {
3175 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3176 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3178 wfProfileOut( __METHOD__
. '-loadtpl' );
3181 # If we haven't found text to substitute by now, we're done
3182 # Recover the source wikitext and return it
3184 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3185 wfProfileOut( __METHOD__
);
3186 return array( 'object' => $text );
3189 # Expand DOM-style return values in a child frame
3190 if ( $isChildObj ) {
3191 # Clean up argument array
3192 $newFrame = $frame->newChild( $args, $title );
3195 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3196 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3197 # Expansion is eligible for the empty-frame cache
3198 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3199 $text = $this->mTplExpandCache
[$titleText];
3201 $text = $newFrame->expand( $text );
3202 $this->mTplExpandCache
[$titleText] = $text;
3205 # Uncached expansion
3206 $text = $newFrame->expand( $text );
3209 if ( $isLocalObj && $nowiki ) {
3210 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3211 $isLocalObj = false;
3214 # Replace raw HTML by a placeholder
3215 # Add a blank line preceding, to prevent it from mucking up
3216 # immediately preceding headings
3218 $text = "\n\n" . $this->insertStripItem( $text );
3219 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3220 # Escape nowiki-style return values
3221 $text = wfEscapeWikiText( $text );
3222 } elseif ( is_string( $text )
3223 && !$piece['lineStart']
3224 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3226 # Bug 529: if the template begins with a table or block-level
3227 # element, it should be treated as beginning a new line.
3228 # This behaviour is somewhat controversial.
3229 $text = "\n" . $text;
3232 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3233 # Error, oversize inclusion
3234 if ( $titleText !== false ) {
3235 # Make a working, properly escaped link if possible (bug 23588)
3236 $text = "[[:$titleText]]";
3238 # This will probably not be a working link, but at least it may
3239 # provide some hint of where the problem is
3240 preg_replace( '/^:/', '', $originalTitle );
3241 $text = "[[:$originalTitle]]";
3243 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3244 $this->limitationWarn( 'post-expand-template-inclusion' );
3247 if ( $isLocalObj ) {
3248 $ret = array( 'object' => $text );
3250 $ret = array( 'text' => $text );
3253 wfProfileOut( __METHOD__
);
3258 * Get the semi-parsed DOM representation of a template with a given title,
3259 * and its redirect destination title. Cached.
3261 function getTemplateDom( $title ) {
3262 $cacheTitle = $title;
3263 $titleText = $title->getPrefixedDBkey();
3265 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3266 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3267 $title = Title
::makeTitle( $ns, $dbk );
3268 $titleText = $title->getPrefixedDBkey();
3270 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3271 return array( $this->mTplDomCache
[$titleText], $title );
3274 # Cache miss, go to the database
3275 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3277 if ( $text === false ) {
3278 $this->mTplDomCache
[$titleText] = false;
3279 return array( false, $title );
3282 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3283 $this->mTplDomCache
[ $titleText ] = $dom;
3285 if ( !$title->equals( $cacheTitle ) ) {
3286 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3287 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3290 return array( $dom, $title );
3294 * Fetch the unparsed text of a template and register a reference to it.
3296 function fetchTemplateAndTitle( $title ) {
3297 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3298 $stuff = call_user_func( $templateCb, $title, $this );
3299 $text = $stuff['text'];
3300 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3301 if ( isset( $stuff['deps'] ) ) {
3302 foreach ( $stuff['deps'] as $dep ) {
3303 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3306 return array( $text, $finalTitle );
3309 function fetchTemplate( $title ) {
3310 $rv = $this->fetchTemplateAndTitle( $title );
3315 * Static function to get a template
3316 * Can be overridden via ParserOptions::setTemplateCallback().
3318 static function statelessFetchTemplate( $title, $parser=false ) {
3319 $text = $skip = false;
3320 $finalTitle = $title;
3323 # Loop to fetch the article, with up to 1 redirect
3324 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3325 # Give extensions a chance to select the revision instead
3326 $id = false; # Assume current
3327 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3333 'page_id' => $title->getArticleID(),
3337 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3338 $rev_id = $rev ?
$rev->getId() : 0;
3339 # If there is no current revision, there is no page
3340 if ( $id === false && !$rev ) {
3341 $linkCache = LinkCache
::singleton();
3342 $linkCache->addBadLinkObj( $title );
3347 'page_id' => $title->getArticleID(),
3348 'rev_id' => $rev_id );
3351 $text = $rev->getText();
3352 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3354 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3355 if ( !$message->exists() ) {
3359 $text = $message->plain();
3363 if ( $text === false ) {
3367 $finalTitle = $title;
3368 $title = Title
::newFromRedirect( $text );
3372 'finalTitle' => $finalTitle,
3377 * Transclude an interwiki link.
3379 function interwikiTransclude( $title, $action ) {
3380 global $wgEnableScaryTranscluding;
3382 if ( !$wgEnableScaryTranscluding ) {
3383 return wfMsgForContent('scarytranscludedisabled');
3386 $url = $title->getFullUrl( "action=$action" );
3388 if ( strlen( $url ) > 255 ) {
3389 return wfMsgForContent( 'scarytranscludetoolong' );
3391 return $this->fetchScaryTemplateMaybeFromCache( $url );
3394 function fetchScaryTemplateMaybeFromCache( $url ) {
3395 global $wgTranscludeCacheExpiry;
3396 $dbr = wfGetDB( DB_SLAVE
);
3397 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3398 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3399 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3401 return $obj->tc_contents
;
3404 $text = Http
::get( $url );
3406 return wfMsgForContent( 'scarytranscludefailed', $url );
3409 $dbw = wfGetDB( DB_MASTER
);
3410 $dbw->replace( 'transcache', array('tc_url'), array(
3412 'tc_time' => $dbw->timestamp( time() ),
3413 'tc_contents' => $text)
3420 * Triple brace replacement -- used for template arguments
3423 function argSubstitution( $piece, $frame ) {
3424 wfProfileIn( __METHOD__
);
3427 $parts = $piece['parts'];
3428 $nameWithSpaces = $frame->expand( $piece['title'] );
3429 $argName = trim( $nameWithSpaces );
3431 $text = $frame->getArgument( $argName );
3432 if ( $text === false && $parts->getLength() > 0
3436 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3439 # No match in frame, use the supplied default
3440 $object = $parts->item( 0 )->getChildren();
3442 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3443 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3444 $this->limitationWarn( 'post-expand-template-argument' );
3447 if ( $text === false && $object === false ) {
3449 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3451 if ( $error !== false ) {
3454 if ( $object !== false ) {
3455 $ret = array( 'object' => $object );
3457 $ret = array( 'text' => $text );
3460 wfProfileOut( __METHOD__
);
3465 * Return the text to be used for a given extension tag.
3466 * This is the ghost of strip().
3468 * @param $params Associative array of parameters:
3469 * name PPNode for the tag name
3470 * attr PPNode for unparsed text where tag attributes are thought to be
3471 * attributes Optional associative array of parsed attributes
3472 * inner Contents of extension element
3473 * noClose Original text did not have a close tag
3474 * @param $frame PPFrame
3476 function extensionSubstitution( $params, $frame ) {
3477 $name = $frame->expand( $params['name'] );
3478 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3479 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3480 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3482 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3483 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3484 if ( $isFunctionTag ) {
3485 $markerType = 'none';
3487 $markerType = 'general';
3489 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3490 $name = strtolower( $name );
3491 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3492 if ( isset( $params['attributes'] ) ) {
3493 $attributes = $attributes +
$params['attributes'];
3496 if ( isset( $this->mTagHooks
[$name] ) ) {
3497 # Workaround for PHP bug 35229 and similar
3498 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3499 throw new MWException( "Tag hook for $name is not callable\n" );
3501 $output = call_user_func_array( $this->mTagHooks
[$name],
3502 array( $content, $attributes, $this, $frame ) );
3503 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3504 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3505 if ( !is_callable( $callback ) ) {
3506 throw new MWException( "Tag hook for $name is not callable\n" );
3509 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3511 $output = '<span class="error">Invalid tag extension name: ' .
3512 htmlspecialchars( $name ) . '</span>';
3515 if ( is_array( $output ) ) {
3516 # Extract flags to local scope (to override $markerType)
3518 $output = $flags[0];
3523 if ( is_null( $attrText ) ) {
3526 if ( isset( $params['attributes'] ) ) {
3527 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3528 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3529 htmlspecialchars( $attrValue ) . '"';
3532 if ( $content === null ) {
3533 $output = "<$name$attrText/>";
3535 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3536 $output = "<$name$attrText>$content$close";
3540 if ( $markerType === 'none' ) {
3542 } elseif ( $markerType === 'nowiki' ) {
3543 $this->mStripState
->nowiki
->setPair( $marker, $output );
3544 } elseif ( $markerType === 'general' ) {
3545 $this->mStripState
->general
->setPair( $marker, $output );
3547 throw new MWException( __METHOD__
.': invalid marker type' );
3553 * Increment an include size counter
3555 * @param $type String: the type of expansion
3556 * @param $size Integer: the size of the text
3557 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3559 function incrementIncludeSize( $type, $size ) {
3560 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3563 $this->mIncludeSizes
[$type] +
= $size;
3569 * Increment the expensive function count
3571 * @return Boolean: false if the limit has been exceeded
3573 function incrementExpensiveFunctionCount() {
3574 global $wgExpensiveParserFunctionLimit;
3575 $this->mExpensiveFunctionCount++
;
3576 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3583 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3584 * Fills $this->mDoubleUnderscores, returns the modified text
3586 function doDoubleUnderscore( $text ) {
3587 wfProfileIn( __METHOD__
);
3589 # The position of __TOC__ needs to be recorded
3590 $mw = MagicWord
::get( 'toc' );
3591 if ( $mw->match( $text ) ) {
3592 $this->mShowToc
= true;
3593 $this->mForceTocPosition
= true;
3595 # Set a placeholder. At the end we'll fill it in with the TOC.
3596 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3598 # Only keep the first one.
3599 $text = $mw->replace( '', $text );
3602 # Now match and remove the rest of them
3603 $mwa = MagicWord
::getDoubleUnderscoreArray();
3604 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3606 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3607 $this->mOutput
->mNoGallery
= true;
3609 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3610 $this->mShowToc
= false;
3612 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3613 $this->addTrackingCategory( 'hidden-category-category' );
3615 # (bug 8068) Allow control over whether robots index a page.
3617 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3618 # is not desirable, the last one on the page should win.
3619 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3620 $this->mOutput
->setIndexPolicy( 'noindex' );
3621 $this->addTrackingCategory( 'noindex-category' );
3623 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3624 $this->mOutput
->setIndexPolicy( 'index' );
3625 $this->addTrackingCategory( 'index-category' );
3628 # Cache all double underscores in the database
3629 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3630 $this->mOutput
->setProperty( $key, '' );
3633 wfProfileOut( __METHOD__
);
3638 * Add a tracking category, getting the title from a system message,
3639 * or print a debug message if the title is invalid.
3641 * @param $msg String: message key
3642 * @return Boolean: whether the addition was successful
3644 protected function addTrackingCategory( $msg ) {
3645 $cat = wfMsgForContent( $msg );
3647 # Allow tracking categories to be disabled by setting them to "-"
3648 if ( $cat === '-' ) {
3652 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3653 if ( $containerCategory ) {
3654 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3657 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3663 * This function accomplishes several tasks:
3664 * 1) Auto-number headings if that option is enabled
3665 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3666 * 3) Add a Table of contents on the top for users who have enabled the option
3667 * 4) Auto-anchor headings
3669 * It loops through all headlines, collects the necessary data, then splits up the
3670 * string and re-inserts the newly formatted headlines.
3672 * @param $text String
3673 * @param $origText String: original, untouched wikitext
3674 * @param $isMain Boolean
3677 function formatHeadings( $text, $origText, $isMain=true ) {
3678 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3680 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3682 # Inhibit editsection links if requested in the page
3683 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3686 $showEditLink = $this->mOptions
->getEditSection();
3688 if ( $showEditLink ) {
3689 $this->mOutput
->setEditSectionTokens( true );
3692 # Get all headlines for numbering them and adding funky stuff like [edit]
3693 # links - this is for later, but we need the number of headlines right now
3695 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3697 # if there are fewer than 4 headlines in the article, do not show TOC
3698 # unless it's been explicitly enabled.
3699 $enoughToc = $this->mShowToc
&&
3700 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3702 # Allow user to stipulate that a page should have a "new section"
3703 # link added via __NEWSECTIONLINK__
3704 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3705 $this->mOutput
->setNewSection( true );
3708 # Allow user to remove the "new section"
3709 # link via __NONEWSECTIONLINK__
3710 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3711 $this->mOutput
->hideNewSection( true );
3714 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3715 # override above conditions and always show TOC above first header
3716 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3717 $this->mShowToc
= true;
3721 # We need this to perform operations on the HTML
3722 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3728 # Ugh .. the TOC should have neat indentation levels which can be
3729 # passed to the skin functions. These are determined here
3733 $sublevelCount = array();
3734 $levelCount = array();
3739 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3740 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3741 $oldType = $this->mOutputType
;
3742 $this->setOutputType( self
::OT_WIKI
);
3743 $frame = $this->getPreprocessor()->newFrame();
3744 $root = $this->preprocessToDom( $origText );
3745 $node = $root->getFirstChild();
3750 foreach ( $matches[3] as $headline ) {
3751 $isTemplate = false;
3753 $sectionIndex = false;
3755 $markerMatches = array();
3756 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3757 $serial = $markerMatches[1];
3758 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3759 $isTemplate = ( $titleText != $baseTitleText );
3760 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3764 $prevlevel = $level;
3766 $level = $matches[1][$headlineCount];
3768 if ( $level > $prevlevel ) {
3769 # Increase TOC level
3771 $sublevelCount[$toclevel] = 0;
3772 if ( $toclevel<$wgMaxTocLevel ) {
3773 $prevtoclevel = $toclevel;
3774 $toc .= $sk->tocIndent();
3777 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3778 # Decrease TOC level, find level to jump to
3780 for ( $i = $toclevel; $i > 0; $i-- ) {
3781 if ( $levelCount[$i] == $level ) {
3782 # Found last matching level
3785 } elseif ( $levelCount[$i] < $level ) {
3786 # Found first matching level below current level
3794 if ( $toclevel<$wgMaxTocLevel ) {
3795 if ( $prevtoclevel < $wgMaxTocLevel ) {
3796 # Unindent only if the previous toc level was shown :p
3797 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3798 $prevtoclevel = $toclevel;
3800 $toc .= $sk->tocLineEnd();
3804 # No change in level, end TOC line
3805 if ( $toclevel<$wgMaxTocLevel ) {
3806 $toc .= $sk->tocLineEnd();
3810 $levelCount[$toclevel] = $level;
3812 # count number of headlines for each level
3813 @$sublevelCount[$toclevel]++
;
3815 for( $i = 1; $i <= $toclevel; $i++
) {
3816 if ( !empty( $sublevelCount[$i] ) ) {
3820 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3825 # The safe header is a version of the header text safe to use for links
3826 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3827 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3829 # Remove link placeholders by the link text.
3830 # <!--LINK number-->
3832 # link text with suffix
3833 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3835 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3836 $tocline = preg_replace(
3837 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3838 array( '', '<$1>' ),
3841 $tocline = trim( $tocline );
3843 # For the anchor, strip out HTML-y stuff period
3844 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3845 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3847 # Save headline for section edit hint before it's escaped
3848 $headlineHint = $safeHeadline;
3850 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3851 # For reverse compatibility, provide an id that's
3852 # HTML4-compatible, like we used to.
3854 # It may be worth noting, academically, that it's possible for
3855 # the legacy anchor to conflict with a non-legacy headline
3856 # anchor on the page. In this case likely the "correct" thing
3857 # would be to either drop the legacy anchors or make sure
3858 # they're numbered first. However, this would require people
3859 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3860 # manually, so let's not bother worrying about it.
3861 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3862 array( 'noninitial', 'legacy' ) );
3863 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3865 if ( $legacyHeadline == $safeHeadline ) {
3866 # No reason to have both (in fact, we can't)
3867 $legacyHeadline = false;
3870 $legacyHeadline = false;
3871 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3875 # HTML names must be case-insensitively unique (bug 10721).
3876 # This does not apply to Unicode characters per
3877 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3878 # FIXME: We may be changing them depending on the current locale.
3879 $arrayKey = strtolower( $safeHeadline );
3880 if ( $legacyHeadline === false ) {
3881 $legacyArrayKey = false;
3883 $legacyArrayKey = strtolower( $legacyHeadline );
3886 # count how many in assoc. array so we can track dupes in anchors
3887 if ( isset( $refers[$arrayKey] ) ) {
3888 $refers[$arrayKey]++
;
3890 $refers[$arrayKey] = 1;
3892 if ( isset( $refers[$legacyArrayKey] ) ) {
3893 $refers[$legacyArrayKey]++
;
3895 $refers[$legacyArrayKey] = 1;
3898 # Don't number the heading if it is the only one (looks silly)
3899 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3900 # the two are different if the line contains a link
3901 $headline = $numbering . ' ' . $headline;
3904 # Create the anchor for linking from the TOC to the section
3905 $anchor = $safeHeadline;
3906 $legacyAnchor = $legacyHeadline;
3907 if ( $refers[$arrayKey] > 1 ) {
3908 $anchor .= '_' . $refers[$arrayKey];
3910 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3911 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3913 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3914 $toc .= $sk->tocLine( $anchor, $tocline,
3915 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3918 # Add the section to the section tree
3919 # Find the DOM node for this header
3920 while ( $node && !$isTemplate ) {
3921 if ( $node->getName() === 'h' ) {
3922 $bits = $node->splitHeading();
3923 if ( $bits['i'] == $sectionIndex ) {
3927 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3928 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3929 $node = $node->getNextSibling();
3932 'toclevel' => $toclevel,
3935 'number' => $numbering,
3936 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3937 'fromtitle' => $titleText,
3938 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3939 'anchor' => $anchor,
3942 # give headline the correct <h#> tag
3943 if ( $showEditLink && $sectionIndex !== false ) {
3944 // Output edit section links as markers with styles that can be customized by skins
3945 if ( $isTemplate ) {
3946 # Put a T flag in the section identifier, to indicate to extractSections()
3947 # that sections inside <includeonly> should be counted.
3948 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3950 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3952 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3953 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3954 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3955 // so we don't have to worry about a user trying to input one of these markers directly.
3956 // We use a page and section attribute to stop the language converter from converting these important bits
3957 // of data, but put the headline hint inside a content block because the language converter is supposed to
3958 // be able to convert that piece of data.
3959 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
3960 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3961 if ( isset($editlinkArgs[2]) ) {
3962 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
3969 $head[$headlineCount] = $sk->makeHeadline( $level,
3970 $matches['attrib'][$headlineCount], $anchor, $headline,
3971 $editlink, $legacyAnchor );
3976 $this->setOutputType( $oldType );
3978 # Never ever show TOC if no headers
3979 if ( $numVisible < 1 ) {
3984 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3985 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3987 $toc = $sk->tocList( $toc );
3988 $this->mOutput
->setTOCHTML( $toc );
3992 $this->mOutput
->setSections( $tocraw );
3995 # split up and insert constructed headlines
3997 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4000 foreach ( $blocks as $block ) {
4001 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4002 # This is the [edit] link that appears for the top block of text when
4003 # section editing is enabled
4005 # Disabled because it broke block formatting
4006 # For example, a bullet point in the top line
4007 # $full .= $sk->editSectionLink(0);
4010 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4011 # Top anchor now in skin
4015 if ( !empty( $head[$i] ) ) {
4020 if ( $this->mForceTocPosition
) {
4021 return str_replace( '<!--MWTOC-->', $toc, $full );
4028 * Transform wiki markup when saving a page by doing \r\n -> \n
4029 * conversion, substitting signatures, {{subst:}} templates, etc.
4031 * @param $text String: the text to transform
4032 * @param $title Title: the Title object for the current article
4033 * @param $user User: the User object describing the current user
4034 * @param $options ParserOptions: parsing options
4035 * @param $clearState Boolean: whether to clear the parser state first
4036 * @return String: the altered wiki markup
4038 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4039 $this->startExternalParse( $title, $options, self
::OT_WIKI
, $clearState );
4040 $this->setUser( $user );
4045 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4046 if( $options->getPreSaveTransform() ) {
4047 $text = $this->pstPass2( $text, $user );
4049 $text = $this->mStripState
->unstripBoth( $text );
4051 $this->setUser( null ); #Reset
4057 * Pre-save transform helper function
4060 function pstPass2( $text, $user ) {
4061 global $wgContLang, $wgLocaltimezone;
4063 # Note: This is the timestamp saved as hardcoded wikitext to
4064 # the database, we use $wgContLang here in order to give
4065 # everyone the same signature and use the default one rather
4066 # than the one selected in each user's preferences.
4067 # (see also bug 12815)
4068 $ts = $this->mOptions
->getTimestamp();
4069 if ( isset( $wgLocaltimezone ) ) {
4070 $tz = $wgLocaltimezone;
4072 $tz = date_default_timezone_get();
4075 $unixts = wfTimestamp( TS_UNIX
, $ts );
4076 $oldtz = date_default_timezone_get();
4077 date_default_timezone_set( $tz );
4078 $ts = date( 'YmdHis', $unixts );
4079 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4081 # Allow translation of timezones through wiki. date() can return
4082 # whatever crap the system uses, localised or not, so we cannot
4083 # ship premade translations.
4084 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4085 $msg = wfMessage( $key )->inContentLanguage();
4086 if ( $msg->exists() ) {
4087 $tzMsg = $msg->text();
4090 date_default_timezone_set( $oldtz );
4092 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4094 # Variable replacement
4095 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4096 $text = $this->replaceVariables( $text );
4098 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4099 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4102 $sigText = $this->getUserSig( $user );
4103 $text = strtr( $text, array(
4105 '~~~~' => "$sigText $d",
4109 # Context links: [[|name]] and [[name (context)|]]
4110 global $wgLegalTitleChars;
4111 $tc = "[$wgLegalTitleChars]";
4112 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4114 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4115 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4116 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4117 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4119 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4120 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4121 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4122 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4124 $t = $this->mTitle
->getText();
4126 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4127 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4128 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4129 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4131 # if there's no context, don't bother duplicating the title
4132 $text = preg_replace( $p2, '[[\\1]]', $text );
4135 # Trim trailing whitespace
4136 $text = rtrim( $text );
4142 * Fetch the user's signature text, if any, and normalize to
4143 * validated, ready-to-insert wikitext.
4144 * If you have pre-fetched the nickname or the fancySig option, you can
4145 * specify them here to save a database query.
4146 * Do not reuse this parser instance after calling getUserSig(),
4147 * as it may have changed if it's the $wgParser.
4150 * @param $nickname String: nickname to use or false to use user's default nickname
4151 * @param $fancySig Boolean: whether the nicknname is the complete signature
4152 * or null to use default value
4155 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4156 global $wgMaxSigChars;
4158 $username = $user->getName();
4160 # If not given, retrieve from the user object.
4161 if ( $nickname === false )
4162 $nickname = $user->getOption( 'nickname' );
4164 if ( is_null( $fancySig ) ) {
4165 $fancySig = $user->getBoolOption( 'fancysig' );
4168 $nickname = $nickname == null ?
$username : $nickname;
4170 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4171 $nickname = $username;
4172 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4173 } elseif ( $fancySig !== false ) {
4174 # Sig. might contain markup; validate this
4175 if ( $this->validateSig( $nickname ) !== false ) {
4176 # Validated; clean up (if needed) and return it
4177 return $this->cleanSig( $nickname, true );
4179 # Failed to validate; fall back to the default
4180 $nickname = $username;
4181 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4185 # Make sure nickname doesnt get a sig in a sig
4186 $nickname = $this->cleanSigInSig( $nickname );
4188 # If we're still here, make it a link to the user page
4189 $userText = wfEscapeWikiText( $username );
4190 $nickText = wfEscapeWikiText( $nickname );
4191 if ( $user->isAnon() ) {
4192 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4194 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4199 * Check that the user's signature contains no bad XML
4201 * @param $text String
4202 * @return mixed An expanded string, or false if invalid.
4204 function validateSig( $text ) {
4205 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4209 * Clean up signature text
4211 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4212 * 2) Substitute all transclusions
4214 * @param $text String
4215 * @param $parsing Whether we're cleaning (preferences save) or parsing
4216 * @return String: signature text
4218 function cleanSig( $text, $parsing = false ) {
4221 $this->mOptions
= new ParserOptions
;
4222 $this->clearState();
4223 $this->setTitle( $wgTitle );
4224 $this->setOutputType
= self
::OT_PREPROCESS
;
4227 # Option to disable this feature
4228 if ( !$this->mOptions
->getCleanSignatures() ) {
4232 # FIXME: regex doesn't respect extension tags or nowiki
4233 # => Move this logic to braceSubstitution()
4234 $substWord = MagicWord
::get( 'subst' );
4235 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4236 $substText = '{{' . $substWord->getSynonym( 0 );
4238 $text = preg_replace( $substRegex, $substText, $text );
4239 $text = $this->cleanSigInSig( $text );
4240 $dom = $this->preprocessToDom( $text );
4241 $frame = $this->getPreprocessor()->newFrame();
4242 $text = $frame->expand( $dom );
4245 $text = $this->mStripState
->unstripBoth( $text );
4252 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4254 * @param $text String
4255 * @return String: signature text with /~{3,5}/ removed
4257 function cleanSigInSig( $text ) {
4258 $text = preg_replace( '/~{3,5}/', '', $text );
4263 * Set up some variables which are usually set up in parse()
4264 * so that an external function can call some class members with confidence
4266 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4267 $this->setTitle( $title );
4268 $this->mOptions
= $options;
4269 $this->setOutputType( $outputType );
4270 if ( $clearState ) {
4271 $this->clearState();
4276 * Wrapper for preprocess()
4278 * @param $text String: the text to preprocess
4279 * @param $options ParserOptions: options
4280 * @param $title Title object or null to use $wgTitle
4283 public function transformMsg( $text, $options, $title = null ) {
4284 static $executing = false;
4286 # Guard against infinite recursion
4292 wfProfileIn( __METHOD__
);
4298 # It's not uncommon having a null $wgTitle in scripts. See r80898
4299 # Create a ghost title in such case
4300 $title = Title
::newFromText( 'Dwimmerlaik' );
4302 $text = $this->preprocess( $text, $title, $options );
4305 wfProfileOut( __METHOD__
);
4310 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4311 * The callback should have the following form:
4312 * function myParserHook( $text, $params, $parser ) { ... }
4314 * Transform and return $text. Use $parser for any required context, e.g. use
4315 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4317 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4318 * @param $callback Mixed: the callback function (and object) to use for the tag
4319 * @return The old value of the mTagHooks array associated with the hook
4321 public function setHook( $tag, $callback ) {
4322 $tag = strtolower( $tag );
4323 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4324 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4325 $this->mTagHooks
[$tag] = $callback;
4326 if ( !in_array( $tag, $this->mStripList
) ) {
4327 $this->mStripList
[] = $tag;
4333 function setTransparentTagHook( $tag, $callback ) {
4334 $tag = strtolower( $tag );
4335 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4336 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4337 $this->mTransparentTagHooks
[$tag] = $callback;
4343 * Remove all tag hooks
4345 function clearTagHooks() {
4346 $this->mTagHooks
= array();
4347 $this->mStripList
= $this->mDefaultStripList
;
4351 * Create a function, e.g. {{sum:1|2|3}}
4352 * The callback function should have the form:
4353 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4355 * Or with SFH_OBJECT_ARGS:
4356 * function myParserFunction( $parser, $frame, $args ) { ... }
4358 * The callback may either return the text result of the function, or an array with the text
4359 * in element 0, and a number of flags in the other elements. The names of the flags are
4360 * specified in the keys. Valid flags are:
4361 * found The text returned is valid, stop processing the template. This
4363 * nowiki Wiki markup in the return value should be escaped
4364 * isHTML The returned text is HTML, armour it against wikitext transformation
4366 * @param $id String: The magic word ID
4367 * @param $callback Mixed: the callback function (and object) to use
4368 * @param $flags Integer: a combination of the following flags:
4369 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4371 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4372 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4373 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4374 * the arguments, and to control the way they are expanded.
4376 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4377 * arguments, for instance:
4378 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4380 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4381 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4382 * working if/when this is changed.
4384 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4387 * Please read the documentation in includes/parser/Preprocessor.php for more information
4388 * about the methods available in PPFrame and PPNode.
4390 * @return The old callback function for this name, if any
4392 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4395 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4396 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4398 # Add to function cache
4399 $mw = MagicWord
::get( $id );
4401 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4403 $synonyms = $mw->getSynonyms();
4404 $sensitive = intval( $mw->isCaseSensitive() );
4406 foreach ( $synonyms as $syn ) {
4408 if ( !$sensitive ) {
4409 $syn = $wgContLang->lc( $syn );
4412 if ( !( $flags & SFH_NO_HASH
) ) {
4415 # Remove trailing colon
4416 if ( substr( $syn, -1, 1 ) === ':' ) {
4417 $syn = substr( $syn, 0, -1 );
4419 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4425 * Get all registered function hook identifiers
4429 function getFunctionHooks() {
4430 return array_keys( $this->mFunctionHooks
);
4434 * Create a tag function, e.g. <test>some stuff</test>.
4435 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4436 * Unlike parser functions, their content is not preprocessed.
4438 function setFunctionTagHook( $tag, $callback, $flags ) {
4439 $tag = strtolower( $tag );
4440 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4441 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4442 $this->mFunctionTagHooks
[$tag] : null;
4443 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4445 if ( !in_array( $tag, $this->mStripList
) ) {
4446 $this->mStripList
[] = $tag;
4453 * FIXME: update documentation. makeLinkObj() is deprecated.
4454 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4455 * Placeholders created in Skin::makeLinkObj()
4456 * Returns an array of link CSS classes, indexed by PDBK.
4458 function replaceLinkHolders( &$text, $options = 0 ) {
4459 return $this->mLinkHolders
->replace( $text );
4463 * Replace <!--LINK--> link placeholders with plain text of links
4464 * (not HTML-formatted).
4466 * @param $text String
4469 function replaceLinkHoldersText( $text ) {
4470 return $this->mLinkHolders
->replaceText( $text );
4474 * Renders an image gallery from a text with one line per image.
4475 * text labels may be given by using |-style alternative text. E.g.
4476 * Image:one.jpg|The number "1"
4477 * Image:tree.jpg|A tree
4478 * given as text will return the HTML of a gallery with two images,
4479 * labeled 'The number "1"' and
4482 function renderImageGallery( $text, $params ) {
4483 $ig = new ImageGallery();
4484 $ig->setContextTitle( $this->mTitle
);
4485 $ig->setShowBytes( false );
4486 $ig->setShowFilename( false );
4487 $ig->setParser( $this );
4488 $ig->setHideBadImages();
4489 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4490 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4491 $ig->mRevisionId
= $this->mRevisionId
;
4493 if ( isset( $params['showfilename'] ) ) {
4494 $ig->setShowFilename( true );
4496 $ig->setShowFilename( false );
4498 if ( isset( $params['caption'] ) ) {
4499 $caption = $params['caption'];
4500 $caption = htmlspecialchars( $caption );
4501 $caption = $this->replaceInternalLinks( $caption );
4502 $ig->setCaptionHtml( $caption );
4504 if ( isset( $params['perrow'] ) ) {
4505 $ig->setPerRow( $params['perrow'] );
4507 if ( isset( $params['widths'] ) ) {
4508 $ig->setWidths( $params['widths'] );
4510 if ( isset( $params['heights'] ) ) {
4511 $ig->setHeights( $params['heights'] );
4514 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4516 $lines = StringUtils
::explode( "\n", $text );
4517 foreach ( $lines as $line ) {
4518 # match lines like these:
4519 # Image:someimage.jpg|This is some image
4521 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4523 if ( count( $matches ) == 0 ) {
4527 if ( strpos( $matches[0], '%' ) !== false ) {
4528 $matches[1] = rawurldecode( $matches[1] );
4530 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4532 if ( is_null( $nt ) ) {
4533 # Bogus title. Ignore these so we don't bomb out later.
4536 if ( isset( $matches[3] ) ) {
4537 $label = $matches[3];
4542 $html = $this->recursiveTagParse( trim( $label ) );
4544 $ig->add( $nt, $html );
4546 # Only add real images (bug #5586)
4547 if ( $nt->getNamespace() == NS_FILE
) {
4548 $this->mOutput
->addImage( $nt->getDBkey() );
4551 return $ig->toHTML();
4554 function getImageParams( $handler ) {
4556 $handlerClass = get_class( $handler );
4560 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4561 # Initialise static lists
4562 static $internalParamNames = array(
4563 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4564 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4565 'bottom', 'text-bottom' ),
4566 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4567 'upright', 'border', 'link', 'alt' ),
4569 static $internalParamMap;
4570 if ( !$internalParamMap ) {
4571 $internalParamMap = array();
4572 foreach ( $internalParamNames as $type => $names ) {
4573 foreach ( $names as $name ) {
4574 $magicName = str_replace( '-', '_', "img_$name" );
4575 $internalParamMap[$magicName] = array( $type, $name );
4580 # Add handler params
4581 $paramMap = $internalParamMap;
4583 $handlerParamMap = $handler->getParamMap();
4584 foreach ( $handlerParamMap as $magic => $paramName ) {
4585 $paramMap[$magic] = array( 'handler', $paramName );
4588 $this->mImageParams
[$handlerClass] = $paramMap;
4589 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4591 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4595 * Parse image options text and use it to make an image
4597 * @param $title Title
4598 * @param $options String
4599 * @param $holders LinkHolderArray
4601 function makeImage( $title, $options, $holders = false ) {
4602 # Check if the options text is of the form "options|alt text"
4604 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4605 # * left no resizing, just left align. label is used for alt= only
4606 # * right same, but right aligned
4607 # * none same, but not aligned
4608 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4609 # * center center the image
4610 # * frame Keep original image size, no magnify-button.
4611 # * framed Same as "frame"
4612 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4613 # * upright reduce width for upright images, rounded to full __0 px
4614 # * border draw a 1px border around the image
4615 # * alt Text for HTML alt attribute (defaults to empty)
4616 # * link Set the target of the image link. Can be external, interwiki, or local
4617 # vertical-align values (no % or length right now):
4627 $parts = StringUtils
::explode( "|", $options );
4628 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4630 # Give extensions a chance to select the file revision for us
4631 $skip = $time = $descQuery = false;
4632 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4635 return $sk->link( $title );
4639 $file = wfFindFile( $title, array( 'time' => $time ) );
4641 $handler = $file ?
$file->getHandler() : false;
4643 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4645 # Process the input parameters
4647 $params = array( 'frame' => array(), 'handler' => array(),
4648 'horizAlign' => array(), 'vertAlign' => array() );
4649 foreach ( $parts as $part ) {
4650 $part = trim( $part );
4651 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4653 if ( isset( $paramMap[$magicName] ) ) {
4654 list( $type, $paramName ) = $paramMap[$magicName];
4656 # Special case; width and height come in one variable together
4657 if ( $type === 'handler' && $paramName === 'width' ) {
4659 # (bug 13500) In both cases (width/height and width only),
4660 # permit trailing "px" for backward compatibility.
4661 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4662 $width = intval( $m[1] );
4663 $height = intval( $m[2] );
4664 if ( $handler->validateParam( 'width', $width ) ) {
4665 $params[$type]['width'] = $width;
4668 if ( $handler->validateParam( 'height', $height ) ) {
4669 $params[$type]['height'] = $height;
4672 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4673 $width = intval( $value );
4674 if ( $handler->validateParam( 'width', $width ) ) {
4675 $params[$type]['width'] = $width;
4678 } # else no validation -- bug 13436
4680 if ( $type === 'handler' ) {
4681 # Validate handler parameter
4682 $validated = $handler->validateParam( $paramName, $value );
4684 # Validate internal parameters
4685 switch( $paramName ) {
4688 # @todo Fixme: possibly check validity here for
4689 # manualthumb? downstream behavior seems odd with
4690 # missing manual thumbs.
4692 $value = $this->stripAltText( $value, $holders );
4695 $chars = self
::EXT_LINK_URL_CLASS
;
4696 $prots = $this->mUrlProtocols
;
4697 if ( $value === '' ) {
4698 $paramName = 'no-link';
4701 } elseif ( preg_match( "/^$prots/", $value ) ) {
4702 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4703 $paramName = 'link-url';
4704 $this->mOutput
->addExternalLink( $value );
4705 if ( $this->mOptions
->getExternalLinkTarget() ) {
4706 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4711 $linkTitle = Title
::newFromText( $value );
4713 $paramName = 'link-title';
4714 $value = $linkTitle;
4715 $this->mOutput
->addLink( $linkTitle );
4721 # Most other things appear to be empty or numeric...
4722 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4727 $params[$type][$paramName] = $value;
4731 if ( !$validated ) {
4736 # Process alignment parameters
4737 if ( $params['horizAlign'] ) {
4738 $params['frame']['align'] = key( $params['horizAlign'] );
4740 if ( $params['vertAlign'] ) {
4741 $params['frame']['valign'] = key( $params['vertAlign'] );
4744 $params['frame']['caption'] = $caption;
4746 # Will the image be presented in a frame, with the caption below?
4747 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4748 isset( $params['frame']['framed'] ) ||
4749 isset( $params['frame']['thumbnail'] ) ||
4750 isset( $params['frame']['manualthumb'] );
4752 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4753 # came to also set the caption, ordinary text after the image -- which
4754 # makes no sense, because that just repeats the text multiple times in
4755 # screen readers. It *also* came to set the title attribute.
4757 # Now that we have an alt attribute, we should not set the alt text to
4758 # equal the caption: that's worse than useless, it just repeats the
4759 # text. This is the framed/thumbnail case. If there's no caption, we
4760 # use the unnamed parameter for alt text as well, just for the time be-
4761 # ing, if the unnamed param is set and the alt param is not.
4763 # For the future, we need to figure out if we want to tweak this more,
4764 # e.g., introducing a title= parameter for the title; ignoring the un-
4765 # named parameter entirely for images without a caption; adding an ex-
4766 # plicit caption= parameter and preserving the old magic unnamed para-
4768 if ( $imageIsFramed ) { # Framed image
4769 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4770 # No caption or alt text, add the filename as the alt text so
4771 # that screen readers at least get some description of the image
4772 $params['frame']['alt'] = $title->getText();
4774 # Do not set $params['frame']['title'] because tooltips don't make sense
4776 } else { # Inline image
4777 if ( !isset( $params['frame']['alt'] ) ) {
4778 # No alt text, use the "caption" for the alt text
4779 if ( $caption !== '') {
4780 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4782 # No caption, fall back to using the filename for the
4784 $params['frame']['alt'] = $title->getText();
4787 # Use the "caption" for the tooltip text
4788 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4791 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4793 # Linker does the rest
4794 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4796 # Give the handler a chance to modify the parser object
4798 $handler->parserTransformHook( $this, $file );
4804 protected function stripAltText( $caption, $holders ) {
4805 # Strip bad stuff out of the title (tooltip). We can't just use
4806 # replaceLinkHoldersText() here, because if this function is called
4807 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4809 $tooltip = $holders->replaceText( $caption );
4811 $tooltip = $this->replaceLinkHoldersText( $caption );
4814 # make sure there are no placeholders in thumbnail attributes
4815 # that are later expanded to html- so expand them now and
4817 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4818 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4824 * Set a flag in the output object indicating that the content is dynamic and
4825 * shouldn't be cached.
4827 function disableCache() {
4828 wfDebug( "Parser output marked as uncacheable.\n" );
4829 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4830 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4834 * Callback from the Sanitizer for expanding items found in HTML attribute
4835 * values, so they can be safely tested and escaped.
4837 * @param $text String
4838 * @param $frame PPFrame
4842 function attributeStripCallback( &$text, $frame = false ) {
4843 $text = $this->replaceVariables( $text, $frame );
4844 $text = $this->mStripState
->unstripBoth( $text );
4851 function getTags() {
4852 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4856 * Break wikitext input into sections, and either pull or replace
4857 * some particular section's text.
4859 * External callers should use the getSection and replaceSection methods.
4861 * @param $text String: Page wikitext
4862 * @param $section String: a section identifier string of the form:
4863 * <flag1> - <flag2> - ... - <section number>
4865 * Currently the only recognised flag is "T", which means the target section number
4866 * was derived during a template inclusion parse, in other words this is a template
4867 * section edit link. If no flags are given, it was an ordinary section edit link.
4868 * This flag is required to avoid a section numbering mismatch when a section is
4869 * enclosed by <includeonly> (bug 6563).
4871 * The section number 0 pulls the text before the first heading; other numbers will
4872 * pull the given section along with its lower-level subsections. If the section is
4873 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4875 * @param $mode String: one of "get" or "replace"
4876 * @param $newText String: replacement text for section data.
4877 * @return String: for "get", the extracted section text.
4878 * for "replace", the whole page with the section replaced.
4880 private function extractSections( $text, $section, $mode, $newText='' ) {
4881 global $wgTitle; # not generally used but removes an ugly failure mode
4882 $this->startExternalParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4884 $frame = $this->getPreprocessor()->newFrame();
4886 # Process section extraction flags
4888 $sectionParts = explode( '-', $section );
4889 $sectionIndex = array_pop( $sectionParts );
4890 foreach ( $sectionParts as $part ) {
4891 if ( $part === 'T' ) {
4892 $flags |
= self
::PTD_FOR_INCLUSION
;
4895 # Preprocess the text
4896 $root = $this->preprocessToDom( $text, $flags );
4898 # <h> nodes indicate section breaks
4899 # They can only occur at the top level, so we can find them by iterating the root's children
4900 $node = $root->getFirstChild();
4902 # Find the target section
4903 if ( $sectionIndex == 0 ) {
4904 # Section zero doesn't nest, level=big
4905 $targetLevel = 1000;
4908 if ( $node->getName() === 'h' ) {
4909 $bits = $node->splitHeading();
4910 if ( $bits['i'] == $sectionIndex ) {
4911 $targetLevel = $bits['level'];
4915 if ( $mode === 'replace' ) {
4916 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4918 $node = $node->getNextSibling();
4924 if ( $mode === 'get' ) {
4931 # Find the end of the section, including nested sections
4933 if ( $node->getName() === 'h' ) {
4934 $bits = $node->splitHeading();
4935 $curLevel = $bits['level'];
4936 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4940 if ( $mode === 'get' ) {
4941 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4943 $node = $node->getNextSibling();
4946 # Write out the remainder (in replace mode only)
4947 if ( $mode === 'replace' ) {
4948 # Output the replacement text
4949 # Add two newlines on -- trailing whitespace in $newText is conventionally
4950 # stripped by the editor, so we need both newlines to restore the paragraph gap
4951 # Only add trailing whitespace if there is newText
4952 if ( $newText != "" ) {
4953 $outText .= $newText . "\n\n";
4957 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4958 $node = $node->getNextSibling();
4962 if ( is_string( $outText ) ) {
4963 # Re-insert stripped tags
4964 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4971 * This function returns the text of a section, specified by a number ($section).
4972 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4973 * the first section before any such heading (section 0).
4975 * If a section contains subsections, these are also returned.
4977 * @param $text String: text to look in
4978 * @param $section String: section identifier
4979 * @param $deftext String: default to return if section is not found
4980 * @return string text of the requested section
4982 public function getSection( $text, $section, $deftext='' ) {
4983 return $this->extractSections( $text, $section, "get", $deftext );
4987 * This function returns $oldtext after the content of the section
4988 * specified by $section has been replaced with $text.
4990 * @param $text String: former text of the article
4991 * @param $section Numeric: section identifier
4992 * @param $text String: replacing text
4993 * #return String: modified text
4995 public function replaceSection( $oldtext, $section, $text ) {
4996 return $this->extractSections( $oldtext, $section, "replace", $text );
5000 * Get the ID of the revision we are parsing
5002 * @return Mixed: integer or null
5004 function getRevisionId() {
5005 return $this->mRevisionId
;
5009 * Get the revision object for $this->mRevisionId
5011 * @return either a Revision object or null
5013 protected function getRevisionObject() {
5014 if ( !is_null( $this->mRevisionObject
) ) {
5015 return $this->mRevisionObject
;
5017 if ( is_null( $this->mRevisionId
) ) {
5021 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5022 return $this->mRevisionObject
;
5026 * Get the timestamp associated with the current revision, adjusted for
5027 * the default server-local timestamp
5029 function getRevisionTimestamp() {
5030 if ( is_null( $this->mRevisionTimestamp
) ) {
5031 wfProfileIn( __METHOD__
);
5033 $revObject = $this->getRevisionObject();
5034 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5036 if( $timestamp !== false ) {
5039 # The cryptic '' timezone parameter tells to use the site-default
5040 # timezone offset instead of the user settings.
5042 # Since this value will be saved into the parser cache, served
5043 # to other users, and potentially even used inside links and such,
5044 # it needs to be consistent for all visitors.
5045 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5048 wfProfileOut( __METHOD__
);
5050 return $this->mRevisionTimestamp
;
5054 * Get the name of the user that edited the last revision
5056 * @return String: user name
5058 function getRevisionUser() {
5059 if( is_null( $this->mRevisionUser
) ) {
5060 $revObject = $this->getRevisionObject();
5062 # if this template is subst: the revision id will be blank,
5063 # so just use the current user's name
5065 $this->mRevisionUser
= $revObject->getUserText();
5066 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5067 $this->mRevisionUser
= $this->getUser()->getName();
5070 return $this->mRevisionUser
;
5074 * Mutator for $mDefaultSort
5076 * @param $sort New value
5078 public function setDefaultSort( $sort ) {
5079 $this->mDefaultSort
= $sort;
5080 $this->mOutput
->setProperty( 'defaultsort', $sort );
5084 * Accessor for $mDefaultSort
5085 * Will use the empty string if none is set.
5087 * This value is treated as a prefix, so the
5088 * empty string is equivalent to sorting by
5093 public function getDefaultSort() {
5094 if ( $this->mDefaultSort
!== false ) {
5095 return $this->mDefaultSort
;
5102 * Accessor for $mDefaultSort
5103 * Unlike getDefaultSort(), will return false if none is set
5105 * @return string or false
5107 public function getCustomDefaultSort() {
5108 return $this->mDefaultSort
;
5112 * Try to guess the section anchor name based on a wikitext fragment
5113 * presumably extracted from a heading, for example "Header" from
5116 public function guessSectionNameFromWikiText( $text ) {
5117 # Strip out wikitext links(they break the anchor)
5118 $text = $this->stripSectionName( $text );
5119 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5120 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5124 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5125 * instead. For use in redirects, since IE6 interprets Redirect: headers
5126 * as something other than UTF-8 (apparently?), resulting in breakage.
5128 * @param $text String: The section name
5129 * @return string An anchor
5131 public function guessLegacySectionNameFromWikiText( $text ) {
5132 # Strip out wikitext links(they break the anchor)
5133 $text = $this->stripSectionName( $text );
5134 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5135 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5139 * Strips a text string of wikitext for use in a section anchor
5141 * Accepts a text string and then removes all wikitext from the
5142 * string and leaves only the resultant text (i.e. the result of
5143 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5144 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5145 * to create valid section anchors by mimicing the output of the
5146 * parser when headings are parsed.
5148 * @param $text String: text string to be stripped of wikitext
5149 * for use in a Section anchor
5150 * @return Filtered text string
5152 public function stripSectionName( $text ) {
5153 # Strip internal link markup
5154 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5155 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5157 # Strip external link markup (FIXME: Not Tolerant to blank link text
5158 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5159 # on how many empty links there are on the page - need to figure that out.
5160 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5162 # Parse wikitext quotes (italics & bold)
5163 $text = $this->doQuotes( $text );
5166 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5171 * strip/replaceVariables/unstrip for preprocessor regression testing
5173 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5174 if ( !$title instanceof Title
) {
5175 $title = Title
::newFromText( $title );
5177 $this->startExternalParse( $title, $options, $outputType, true );
5179 $text = $this->replaceVariables( $text );
5180 $text = $this->mStripState
->unstripBoth( $text );
5181 $text = Sanitizer
::removeHTMLtags( $text );
5185 function testPst( $text, $title, $options ) {
5187 if ( !$title instanceof Title
) {
5188 $title = Title
::newFromText( $title );
5190 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5193 function testPreprocess( $text, $title, $options ) {
5194 if ( !$title instanceof Title
) {
5195 $title = Title
::newFromText( $title );
5197 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5200 function markerSkipCallback( $s, $callback ) {
5203 while ( $i < strlen( $s ) ) {
5204 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5205 if ( $markerStart === false ) {
5206 $out .= call_user_func( $callback, substr( $s, $i ) );
5209 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5210 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5211 if ( $markerEnd === false ) {
5212 $out .= substr( $s, $markerStart );
5215 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5216 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5224 function serialiseHalfParsedText( $text ) {
5226 $data['text'] = $text;
5228 # First, find all strip markers, and store their
5230 $stripState = new StripState
;
5232 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5233 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5235 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5236 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5238 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5239 $replaceArray = $stripState->general
;
5240 $stripText = $this->mStripState
->general
->data
[$marker];
5241 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5242 $replaceArray = $stripState->nowiki
;
5243 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5245 throw new MWException( "Hanging strip marker: '$marker'." );
5248 $replaceArray->setPair( $marker, $stripText );
5251 $data['stripstate'] = $stripState;
5253 # Now, find all of our links, and store THEIR
5254 # data in an array! :)
5255 $links = array( 'internal' => array(), 'interwiki' => array() );
5259 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5260 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5263 if ( empty( $links['internal'][$ns] ) ) {
5264 $links['internal'][$ns] = array();
5267 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5268 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5269 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5275 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5276 $data = substr( $text, $start_pos );
5277 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5278 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5279 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5282 $data['linkholder'] = $links;
5289 * @param $data Array
5290 * @param $intPrefix String unique identifying prefix
5293 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5294 if ( !$intPrefix ) {
5295 $intPrefix = self
::getRandomString();
5298 # First, extract the strip state.
5299 $stripState = $data['stripstate'];
5300 $this->mStripState
->general
->merge( $stripState->general
);
5301 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5303 # Now, extract the text, and renumber links
5304 $text = $data['text'];
5305 $links = $data['linkholder'];
5308 foreach ( $links['internal'] as $ns => $nsLinks ) {
5309 foreach ( $nsLinks as $key => $entry ) {
5310 $newKey = $intPrefix . '-' . $key;
5311 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5313 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5318 foreach ( $links['interwiki'] as $key => $entry ) {
5319 $newKey = "$intPrefix-$key";
5320 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5322 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5325 # Should be good to go.
5331 * @todo document, briefly.
5335 var $general, $nowiki;
5337 function __construct() {
5338 $this->general
= new ReplacementArray
;
5339 $this->nowiki
= new ReplacementArray
;
5342 function unstripGeneral( $text ) {
5343 wfProfileIn( __METHOD__
);
5346 $text = $this->general
->replace( $text );
5347 } while ( $text !== $oldText );
5348 wfProfileOut( __METHOD__
);
5352 function unstripNoWiki( $text ) {
5353 wfProfileIn( __METHOD__
);
5356 $text = $this->nowiki
->replace( $text );
5357 } while ( $text !== $oldText );
5358 wfProfileOut( __METHOD__
);
5362 function unstripBoth( $text ) {
5363 wfProfileIn( __METHOD__
);
5366 $text = $this->general
->replace( $text );
5367 $text = $this->nowiki
->replace( $text );
5368 } while ( $text !== $oldText );
5369 wfProfileOut( __METHOD__
);
5375 * @todo document, briefly.
5378 class OnlyIncludeReplacer
{
5381 function replace( $matches ) {
5382 if ( substr( $matches[1], -1 ) === "\n" ) {
5383 $this->output
.= substr( $matches[1], 0, -1 );
5385 $this->output
.= $matches[1];