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->startParse( $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->startParse( $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->startParse( $title, $options, self
::OT_PLAIN
, true );
484 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
485 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
486 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
487 $text = $this->mStripState
->unstripBoth( $text );
492 * Get a random string
497 static private function getRandomString() {
498 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
502 * Set the current user.
503 * Should only be used when doing pre-save transform.
505 * @param $user Mixed: User object or null (to reset)
507 function setUser( $user ) {
508 $this->mUser
= $user;
512 * Accessor for mUniqPrefix.
516 public function uniqPrefix() {
517 if ( !isset( $this->mUniqPrefix
) ) {
518 # @todo Fixme: this is probably *horribly wrong*
519 # LanguageConverter seems to want $wgParser's uniqPrefix, however
520 # if this is called for a parser cache hit, the parser may not
521 # have ever been initialized in the first place.
522 # Not really sure what the heck is supposed to be going on here.
524 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
526 return $this->mUniqPrefix
;
530 * Set the context title
532 function setTitle( $t ) {
533 if ( !$t ||
$t instanceof FakeTitle
) {
534 $t = Title
::newFromText( 'NO TITLE' );
537 if ( strval( $t->getFragment() ) !== '' ) {
538 # Strip the fragment to avoid various odd effects
539 $this->mTitle
= clone $t;
540 $this->mTitle
->setFragment( '' );
547 * Accessor for the Title object
549 * @return Title object
551 function getTitle() {
552 return $this->mTitle
;
556 * Accessor/mutator for the Title object
558 * @param $x New Title object or null to just get the current one
559 * @return Title object
561 function Title( $x = null ) {
562 return wfSetVar( $this->mTitle
, $x );
566 * Set the output type
568 * @param $ot Integer: new value
570 function setOutputType( $ot ) {
571 $this->mOutputType
= $ot;
574 'html' => $ot == self
::OT_HTML
,
575 'wiki' => $ot == self
::OT_WIKI
,
576 'pre' => $ot == self
::OT_PREPROCESS
,
577 'plain' => $ot == self
::OT_PLAIN
,
582 * Accessor/mutator for the output type
584 * @param $x New value or null to just get the current one
587 function OutputType( $x = null ) {
588 return wfSetVar( $this->mOutputType
, $x );
592 * Get the ParserOutput object
594 * @return ParserOutput object
596 function getOutput() {
597 return $this->mOutput
;
601 * Get the ParserOptions object
603 * @return ParserOptions object
605 function getOptions() {
606 return $this->mOptions
;
610 * Accessor/mutator for the ParserOptions object
612 * @param $x New value or null to just get the current one
613 * @return Current ParserOptions object
615 function Options( $x = null ) {
616 return wfSetVar( $this->mOptions
, $x );
619 function nextLinkID() {
620 return $this->mLinkID++
;
626 function getFunctionLang() {
627 global $wgLang, $wgContLang;
629 $target = $this->mOptions
->getTargetLanguage();
630 if ( $target !== null ) {
633 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
638 * Get a User object either from $this->mUser, if set, or from the
639 * ParserOptions object otherwise
641 * @return User object
644 if ( !is_null( $this->mUser
) ) {
647 return $this->mOptions
->getUser();
651 * Get a preprocessor object
653 * @return Preprocessor instance
655 function getPreprocessor() {
656 if ( !isset( $this->mPreprocessor
) ) {
657 $class = $this->mPreprocessorClass
;
658 $this->mPreprocessor
= new $class( $this );
660 return $this->mPreprocessor
;
664 * Replaces all occurrences of HTML-style comments and the given tags
665 * in the text with a random marker and returns the next text. The output
666 * parameter $matches will be an associative array filled with data in
668 * 'UNIQ-xxxxx' => array(
671 * array( 'param' => 'x' ),
672 * '<element param="x">tag content</element>' ) )
674 * @param $elements list of element names. Comments are always extracted.
675 * @param $text Source text string.
676 * @param $matches Out parameter, Array: extracted tags
677 * @param $uniq_prefix
678 * @return String: stripped text
682 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
687 $taglist = implode( '|', $elements );
688 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
690 while ( $text != '' ) {
691 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
693 if ( count( $p ) < 5 ) {
696 if ( count( $p ) > 5 ) {
710 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
711 $stripped .= $marker;
713 if ( $close === '/>' ) {
714 # Empty element tag, <tag />
719 if ( $element === '!--' ) {
722 $end = "/(<\\/$element\\s*>)/i";
724 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
726 if ( count( $q ) < 3 ) {
727 # No end tag -- let it run out to the end of the text.
736 $matches[$marker] = array( $element,
738 Sanitizer
::decodeTagAttributes( $attributes ),
739 "<$element$attributes$close$content$tail" );
745 * Get a list of strippable XML-like elements
747 function getStripList() {
748 return $this->mStripList
;
752 * @deprecated use replaceVariables
754 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
759 * Restores pre, math, and other extensions removed by strip()
761 * always call unstripNoWiki() after this one
763 * @deprecated use $this->mStripState->unstrip()
765 function unstrip( $text, $state ) {
766 return $state->unstripGeneral( $text );
770 * Always call this after unstrip() to preserve the order
773 * @deprecated use $this->mStripState->unstrip()
775 function unstripNoWiki( $text, $state ) {
776 return $state->unstripNoWiki( $text );
780 * @deprecated use $this->mStripState->unstripBoth()
782 function unstripForHTML( $text ) {
783 return $this->mStripState
->unstripBoth( $text );
787 * Add an item to the strip state
788 * Returns the unique tag which must be inserted into the stripped text
789 * The tag will be replaced with the original text in unstrip()
793 function insertStripItem( $text ) {
794 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
795 $this->mMarkerIndex++
;
796 $this->mStripState
->general
->setPair( $rnd, $text );
801 * Interface with html tidy
802 * @deprecated Use MWTidy::tidy()
804 public static function tidy( $text ) {
805 wfDeprecated( __METHOD__
);
806 return MWTidy
::tidy( $text );
810 * parse the wiki syntax used to render tables
814 function doTableStuff( $text ) {
815 wfProfileIn( __METHOD__
);
817 $lines = StringUtils
::explode( "\n", $text );
819 $td_history = array(); # Is currently a td tag open?
820 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
821 $tr_history = array(); # Is currently a tr tag open?
822 $tr_attributes = array(); # history of tr attributes
823 $has_opened_tr = array(); # Did this table open a <tr> element?
824 $indent_level = 0; # indent level of the table
826 foreach ( $lines as $outLine ) {
827 $line = trim( $outLine );
829 if ( $line === '' ) { # empty line, go to next line
830 $out .= $outLine."\n";
834 $first_character = $line[0];
837 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
838 # First check if we are starting a new table
839 $indent_level = strlen( $matches[1] );
841 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
842 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
844 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
845 array_push( $td_history , false );
846 array_push( $last_tag_history , '' );
847 array_push( $tr_history , false );
848 array_push( $tr_attributes , '' );
849 array_push( $has_opened_tr , false );
850 } elseif ( count( $td_history ) == 0 ) {
851 # Don't do any of the following
852 $out .= $outLine."\n";
854 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
855 # We are ending a table
856 $line = '</table>' . substr( $line , 2 );
857 $last_tag = array_pop( $last_tag_history );
859 if ( !array_pop( $has_opened_tr ) ) {
860 $line = "<tr><td></td></tr>{$line}";
863 if ( array_pop( $tr_history ) ) {
864 $line = "</tr>{$line}";
867 if ( array_pop( $td_history ) ) {
868 $line = "</{$last_tag}>{$line}";
870 array_pop( $tr_attributes );
871 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
872 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
873 # Now we have a table row
874 $line = preg_replace( '#^\|-+#', '', $line );
876 # Whats after the tag is now only attributes
877 $attributes = $this->mStripState
->unstripBoth( $line );
878 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
879 array_pop( $tr_attributes );
880 array_push( $tr_attributes, $attributes );
883 $last_tag = array_pop( $last_tag_history );
884 array_pop( $has_opened_tr );
885 array_push( $has_opened_tr , true );
887 if ( array_pop( $tr_history ) ) {
891 if ( array_pop( $td_history ) ) {
892 $line = "</{$last_tag}>{$line}";
896 array_push( $tr_history , false );
897 array_push( $td_history , false );
898 array_push( $last_tag_history , '' );
899 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
900 # This might be cell elements, td, th or captions
901 if ( substr( $line , 0 , 2 ) === '|+' ) {
902 $first_character = '+';
903 $line = substr( $line , 1 );
906 $line = substr( $line , 1 );
908 if ( $first_character === '!' ) {
909 $line = str_replace( '!!' , '||' , $line );
912 # Split up multiple cells on the same line.
913 # FIXME : This can result in improper nesting of tags processed
914 # by earlier parser steps, but should avoid splitting up eg
915 # attribute values containing literal "||".
916 $cells = StringUtils
::explodeMarkup( '||' , $line );
920 # Loop through each table cell
921 foreach ( $cells as $cell ) {
923 if ( $first_character !== '+' ) {
924 $tr_after = array_pop( $tr_attributes );
925 if ( !array_pop( $tr_history ) ) {
926 $previous = "<tr{$tr_after}>\n";
928 array_push( $tr_history , true );
929 array_push( $tr_attributes , '' );
930 array_pop( $has_opened_tr );
931 array_push( $has_opened_tr , true );
934 $last_tag = array_pop( $last_tag_history );
936 if ( array_pop( $td_history ) ) {
937 $previous = "</{$last_tag}>\n{$previous}";
940 if ( $first_character === '|' ) {
942 } elseif ( $first_character === '!' ) {
944 } elseif ( $first_character === '+' ) {
945 $last_tag = 'caption';
950 array_push( $last_tag_history , $last_tag );
952 # A cell could contain both parameters and data
953 $cell_data = explode( '|' , $cell , 2 );
955 # Bug 553: Note that a '|' inside an invalid link should not
956 # be mistaken as delimiting cell parameters
957 if ( strpos( $cell_data[0], '[[' ) !== false ) {
958 $cell = "{$previous}<{$last_tag}>{$cell}";
959 } elseif ( count( $cell_data ) == 1 ) {
960 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
962 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
963 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
964 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
968 array_push( $td_history , true );
971 $out .= $outLine . "\n";
974 # Closing open td, tr && table
975 while ( count( $td_history ) > 0 ) {
976 if ( array_pop( $td_history ) ) {
979 if ( array_pop( $tr_history ) ) {
982 if ( !array_pop( $has_opened_tr ) ) {
983 $out .= "<tr><td></td></tr>\n" ;
986 $out .= "</table>\n";
989 # Remove trailing line-ending (b/c)
990 if ( substr( $out, -1 ) === "\n" ) {
991 $out = substr( $out, 0, -1 );
994 # special case: don't return empty table
995 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
999 wfProfileOut( __METHOD__
);
1005 * Helper function for parse() that transforms wiki markup into
1006 * HTML. Only called for $mOutputType == self::OT_HTML.
1010 function internalParse( $text, $isMain = true, $frame=false ) {
1011 wfProfileIn( __METHOD__
);
1015 # Hook to suspend the parser in this state
1016 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1017 wfProfileOut( __METHOD__
);
1021 # if $frame is provided, then use $frame for replacing any variables
1023 # use frame depth to infer how include/noinclude tags should be handled
1024 # depth=0 means this is the top-level document; otherwise it's an included document
1025 if ( !$frame->depth
) {
1028 $flag = Parser
::PTD_FOR_INCLUSION
;
1030 $dom = $this->preprocessToDom( $text, $flag );
1031 $text = $frame->expand( $dom );
1033 # if $frame is not provided, then use old-style replaceVariables
1034 $text = $this->replaceVariables( $text );
1037 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1038 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1040 # Tables need to come after variable replacement for things to work
1041 # properly; putting them before other transformations should keep
1042 # exciting things like link expansions from showing up in surprising
1044 $text = $this->doTableStuff( $text );
1046 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1048 $text = $this->doDoubleUnderscore( $text );
1050 $text = $this->doHeadings( $text );
1051 if ( $this->mOptions
->getUseDynamicDates() ) {
1052 $df = DateFormatter
::getInstance();
1053 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1055 $text = $this->replaceInternalLinks( $text );
1056 $text = $this->doAllQuotes( $text );
1057 $text = $this->replaceExternalLinks( $text );
1059 # replaceInternalLinks may sometimes leave behind
1060 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1061 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1063 $text = $this->doMagicLinks( $text );
1064 $text = $this->formatHeadings( $text, $origText, $isMain );
1066 wfProfileOut( __METHOD__
);
1071 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1072 * magic external links.
1077 function doMagicLinks( $text ) {
1078 wfProfileIn( __METHOD__
);
1079 $prots = $this->mUrlProtocols
;
1080 $urlChar = self
::EXT_LINK_URL_CLASS
;
1081 $text = preg_replace_callback(
1083 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1084 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1085 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1086 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1087 ISBN\s+(\b # m[5]: ISBN, capture number
1088 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1089 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1090 [0-9Xx] # check digit
1092 )!x', array( &$this, 'magicLinkCallback' ), $text );
1093 wfProfileOut( __METHOD__
);
1097 function magicLinkCallback( $m ) {
1098 if ( isset( $m[1] ) && $m[1] !== '' ) {
1101 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1104 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1105 # Free external link
1106 return $this->makeFreeExternalLink( $m[0] );
1107 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1109 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1112 $CssClass = 'mw-magiclink-rfc';
1114 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1116 $urlmsg = 'pubmedurl';
1117 $CssClass = 'mw-magiclink-pmid';
1120 throw new MWException( __METHOD__
.': unrecognised match type "' .
1121 substr( $m[0], 0, 20 ) . '"' );
1123 $url = wfMsgForContent( $urlmsg, $id );
1124 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1125 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1126 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1129 $num = strtr( $isbn, array(
1134 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1136 $titleObj->escapeLocalUrl() .
1137 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1144 * Make a free external link, given a user-supplied URL
1148 function makeFreeExternalLink( $url ) {
1150 wfProfileIn( __METHOD__
);
1152 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1155 # The characters '<' and '>' (which were escaped by
1156 # removeHTMLtags()) should not be included in
1157 # URLs, per RFC 2396.
1159 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1160 $trail = substr( $url, $m2[0][1] ) . $trail;
1161 $url = substr( $url, 0, $m2[0][1] );
1164 # Move trailing punctuation to $trail
1166 # If there is no left bracket, then consider right brackets fair game too
1167 if ( strpos( $url, '(' ) === false ) {
1171 $numSepChars = strspn( strrev( $url ), $sep );
1172 if ( $numSepChars ) {
1173 $trail = substr( $url, -$numSepChars ) . $trail;
1174 $url = substr( $url, 0, -$numSepChars );
1177 $url = Sanitizer
::cleanUrl( $url );
1179 # Is this an external image?
1180 $text = $this->maybeMakeExternalImage( $url );
1181 if ( $text === false ) {
1182 # Not an image, make a link
1183 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1184 $this->getExternalLinkAttribs( $url ) );
1185 # Register it in the output object...
1186 # Replace unnecessary URL escape codes with their equivalent characters
1187 $pasteurized = self
::replaceUnusualEscapes( $url );
1188 $this->mOutput
->addExternalLink( $pasteurized );
1190 wfProfileOut( __METHOD__
);
1191 return $text . $trail;
1196 * Parse headers and return html
1200 function doHeadings( $text ) {
1201 wfProfileIn( __METHOD__
);
1202 for ( $i = 6; $i >= 1; --$i ) {
1203 $h = str_repeat( '=', $i );
1204 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1205 "<h$i>\\1</h$i>", $text );
1207 wfProfileOut( __METHOD__
);
1212 * Replace single quotes with HTML markup
1214 * @return string the altered text
1216 function doAllQuotes( $text ) {
1217 wfProfileIn( __METHOD__
);
1219 $lines = StringUtils
::explode( "\n", $text );
1220 foreach ( $lines as $line ) {
1221 $outtext .= $this->doQuotes( $line ) . "\n";
1223 $outtext = substr( $outtext, 0,-1 );
1224 wfProfileOut( __METHOD__
);
1229 * Helper function for doAllQuotes()
1231 public function doQuotes( $text ) {
1232 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1233 if ( count( $arr ) == 1 ) {
1236 # First, do some preliminary work. This may shift some apostrophes from
1237 # being mark-up to being text. It also counts the number of occurrences
1238 # of bold and italics mark-ups.
1241 for ( $i = 0; $i < count( $arr ); $i++
) {
1242 if ( ( $i %
2 ) == 1 ) {
1243 # If there are ever four apostrophes, assume the first is supposed to
1244 # be text, and the remaining three constitute mark-up for bold text.
1245 if ( strlen( $arr[$i] ) == 4 ) {
1248 } elseif ( strlen( $arr[$i] ) > 5 ) {
1249 # If there are more than 5 apostrophes in a row, assume they're all
1250 # text except for the last 5.
1251 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1254 # Count the number of occurrences of bold and italics mark-ups.
1255 # We are not counting sequences of five apostrophes.
1256 if ( strlen( $arr[$i] ) == 2 ) {
1258 } elseif ( strlen( $arr[$i] ) == 3 ) {
1260 } elseif ( strlen( $arr[$i] ) == 5 ) {
1267 # If there is an odd number of both bold and italics, it is likely
1268 # that one of the bold ones was meant to be an apostrophe followed
1269 # by italics. Which one we cannot know for certain, but it is more
1270 # likely to be one that has a single-letter word before it.
1271 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1273 $firstsingleletterword = -1;
1274 $firstmultiletterword = -1;
1276 foreach ( $arr as $r ) {
1277 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1278 $x1 = substr( $arr[$i-1], -1 );
1279 $x2 = substr( $arr[$i-1], -2, 1 );
1280 if ( $x1 === ' ' ) {
1281 if ( $firstspace == -1 ) {
1284 } elseif ( $x2 === ' ') {
1285 if ( $firstsingleletterword == -1 ) {
1286 $firstsingleletterword = $i;
1289 if ( $firstmultiletterword == -1 ) {
1290 $firstmultiletterword = $i;
1297 # If there is a single-letter word, use it!
1298 if ( $firstsingleletterword > -1 ) {
1299 $arr[$firstsingleletterword] = "''";
1300 $arr[$firstsingleletterword-1] .= "'";
1301 } elseif ( $firstmultiletterword > -1 ) {
1302 # If not, but there's a multi-letter word, use that one.
1303 $arr[$firstmultiletterword] = "''";
1304 $arr[$firstmultiletterword-1] .= "'";
1305 } elseif ( $firstspace > -1 ) {
1306 # ... otherwise use the first one that has neither.
1307 # (notice that it is possible for all three to be -1 if, for example,
1308 # there is only one pentuple-apostrophe in the line)
1309 $arr[$firstspace] = "''";
1310 $arr[$firstspace-1] .= "'";
1314 # Now let's actually convert our apostrophic mush to HTML!
1319 foreach ( $arr as $r ) {
1320 if ( ( $i %
2 ) == 0 ) {
1321 if ( $state === 'both' ) {
1327 if ( strlen( $r ) == 2 ) {
1328 if ( $state === 'i' ) {
1329 $output .= '</i>'; $state = '';
1330 } elseif ( $state === 'bi' ) {
1331 $output .= '</i>'; $state = 'b';
1332 } elseif ( $state === 'ib' ) {
1333 $output .= '</b></i><b>'; $state = 'b';
1334 } elseif ( $state === 'both' ) {
1335 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1336 } else { # $state can be 'b' or ''
1337 $output .= '<i>'; $state .= 'i';
1339 } elseif ( strlen( $r ) == 3 ) {
1340 if ( $state === 'b' ) {
1341 $output .= '</b>'; $state = '';
1342 } elseif ( $state === 'bi' ) {
1343 $output .= '</i></b><i>'; $state = 'i';
1344 } elseif ( $state === 'ib' ) {
1345 $output .= '</b>'; $state = 'i';
1346 } elseif ( $state === 'both' ) {
1347 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1348 } else { # $state can be 'i' or ''
1349 $output .= '<b>'; $state .= 'b';
1351 } elseif ( strlen( $r ) == 5 ) {
1352 if ( $state === 'b' ) {
1353 $output .= '</b><i>'; $state = 'i';
1354 } elseif ( $state === 'i' ) {
1355 $output .= '</i><b>'; $state = 'b';
1356 } elseif ( $state === 'bi' ) {
1357 $output .= '</i></b>'; $state = '';
1358 } elseif ( $state === 'ib' ) {
1359 $output .= '</b></i>'; $state = '';
1360 } elseif ( $state === 'both' ) {
1361 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1362 } else { # ($state == '')
1363 $buffer = ''; $state = 'both';
1369 # Now close all remaining tags. Notice that the order is important.
1370 if ( $state === 'b' ||
$state === 'ib' ) {
1373 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1376 if ( $state === 'bi' ) {
1379 # There might be lonely ''''', so make sure we have a buffer
1380 if ( $state === 'both' && $buffer ) {
1381 $output .= '<b><i>'.$buffer.'</i></b>';
1388 * Replace external links (REL)
1390 * Note: this is all very hackish and the order of execution matters a lot.
1391 * Make sure to run maintenance/parserTests.php if you change this code.
1395 function replaceExternalLinks( $text ) {
1397 wfProfileIn( __METHOD__
);
1399 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1401 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1402 $s = array_shift( $bits );
1405 while ( $i<count( $bits ) ) {
1407 $protocol = $bits[$i++
];
1408 $text = $bits[$i++
];
1409 $trail = $bits[$i++
];
1411 # The characters '<' and '>' (which were escaped by
1412 # removeHTMLtags()) should not be included in
1413 # URLs, per RFC 2396.
1415 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1416 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1417 $url = substr( $url, 0, $m2[0][1] );
1420 # If the link text is an image URL, replace it with an <img> tag
1421 # This happened by accident in the original parser, but some people used it extensively
1422 $img = $this->maybeMakeExternalImage( $text );
1423 if ( $img !== false ) {
1429 # Set linktype for CSS - if URL==text, link is essentially free
1430 $linktype = ( $text === $url ) ?
'free' : 'text';
1432 # No link text, e.g. [http://domain.tld/some.link]
1433 if ( $text == '' ) {
1434 # Autonumber if allowed. See bug #5918
1435 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1436 $langObj = $this->getFunctionLang();
1437 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1438 $linktype = 'autonumber';
1440 # Otherwise just use the URL
1441 $text = htmlspecialchars( $url );
1445 # Have link text, e.g. [http://domain.tld/some.link text]s
1447 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1450 $text = $wgContLang->markNoConversion( $text );
1452 $url = Sanitizer
::cleanUrl( $url );
1454 # Use the encoded URL
1455 # This means that users can paste URLs directly into the text
1456 # Funny characters like ö aren't valid in URLs anyway
1457 # This was changed in August 2004
1458 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1459 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1461 # Register link in the output object.
1462 # Replace unnecessary URL escape codes with the referenced character
1463 # This prevents spammers from hiding links from the filters
1464 $pasteurized = self
::replaceUnusualEscapes( $url );
1465 $this->mOutput
->addExternalLink( $pasteurized );
1468 wfProfileOut( __METHOD__
);
1473 * Get an associative array of additional HTML attributes appropriate for a
1474 * particular external link. This currently may include rel => nofollow
1475 * (depending on configuration, namespace, and the URL's domain) and/or a
1476 * target attribute (depending on configuration).
1478 * @param $url String: optional URL, to extract the domain from for rel =>
1479 * nofollow if appropriate
1480 * @return Array: associative array of HTML attributes
1482 function getExternalLinkAttribs( $url = false ) {
1484 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1485 $ns = $this->mTitle
->getNamespace();
1486 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1487 $attribs['rel'] = 'nofollow';
1489 global $wgNoFollowDomainExceptions;
1490 if ( $wgNoFollowDomainExceptions ) {
1491 $bits = wfParseUrl( $url );
1492 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1493 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1494 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1495 unset( $attribs['rel'] );
1502 if ( $this->mOptions
->getExternalLinkTarget() ) {
1503 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1510 * Replace unusual URL escape codes with their equivalent characters
1512 * @param $url String
1515 * @todo This can merge genuinely required bits in the path or query string,
1516 * breaking legit URLs. A proper fix would treat the various parts of
1517 * the URL differently; as a workaround, just use the output for
1518 * statistical records, not for actual linking/output.
1520 static function replaceUnusualEscapes( $url ) {
1521 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1522 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1526 * Callback function used in replaceUnusualEscapes().
1527 * Replaces unusual URL escape codes with their equivalent character
1529 private static function replaceUnusualEscapesCallback( $matches ) {
1530 $char = urldecode( $matches[0] );
1531 $ord = ord( $char );
1532 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1533 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1534 # No, shouldn't be escaped
1537 # Yes, leave it escaped
1543 * make an image if it's allowed, either through the global
1544 * option, through the exception, or through the on-wiki whitelist
1547 function maybeMakeExternalImage( $url ) {
1548 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1549 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1550 $imagesexception = !empty( $imagesfrom );
1552 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1553 if ( $imagesexception && is_array( $imagesfrom ) ) {
1554 $imagematch = false;
1555 foreach ( $imagesfrom as $match ) {
1556 if ( strpos( $url, $match ) === 0 ) {
1561 } elseif ( $imagesexception ) {
1562 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1564 $imagematch = false;
1566 if ( $this->mOptions
->getAllowExternalImages()
1567 ||
( $imagesexception && $imagematch ) ) {
1568 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1570 $text = $sk->makeExternalImage( $url );
1573 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1574 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1575 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1576 foreach ( $whitelist as $entry ) {
1577 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1578 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1581 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1582 # Image matches a whitelist entry
1583 $text = $sk->makeExternalImage( $url );
1592 * Process [[ ]] wikilinks
1593 * @return String: processed text
1597 function replaceInternalLinks( $s ) {
1598 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1603 * Process [[ ]] wikilinks (RIL)
1604 * @return LinkHolderArray
1608 function replaceInternalLinks2( &$s ) {
1611 wfProfileIn( __METHOD__
);
1613 wfProfileIn( __METHOD__
.'-setup' );
1614 static $tc = FALSE, $e1, $e1_img;
1615 # the % is needed to support urlencoded titles as well
1617 $tc = Title
::legalChars() . '#%';
1618 # Match a link having the form [[namespace:link|alternate]]trail
1619 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1620 # Match cases where there is no "]]", which might still be images
1621 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1624 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1625 $holders = new LinkHolderArray( $this );
1627 # split the entire text string on occurences of [[
1628 $a = StringUtils
::explode( '[[', ' ' . $s );
1629 # get the first element (all text up to first [[), and remove the space we added
1632 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1633 $s = substr( $s, 1 );
1635 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1637 if ( $useLinkPrefixExtension ) {
1638 # Match the end of a line for a word that's not followed by whitespace,
1639 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1640 $e2 = wfMsgForContent( 'linkprefix' );
1643 if ( is_null( $this->mTitle
) ) {
1644 wfProfileOut( __METHOD__
.'-setup' );
1645 wfProfileOut( __METHOD__
);
1646 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1648 $nottalk = !$this->mTitle
->isTalkPage();
1650 if ( $useLinkPrefixExtension ) {
1652 if ( preg_match( $e2, $s, $m ) ) {
1653 $first_prefix = $m[2];
1655 $first_prefix = false;
1661 if ( $wgContLang->hasVariants() ) {
1662 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1664 $selflink = array( $this->mTitle
->getPrefixedText() );
1666 $useSubpages = $this->areSubpagesAllowed();
1667 wfProfileOut( __METHOD__
.'-setup' );
1669 # Loop for each link
1670 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1671 # Check for excessive memory usage
1672 if ( $holders->isBig() ) {
1674 # Do the existence check, replace the link holders and clear the array
1675 $holders->replace( $s );
1679 if ( $useLinkPrefixExtension ) {
1680 wfProfileIn( __METHOD__
.'-prefixhandling' );
1681 if ( preg_match( $e2, $s, $m ) ) {
1688 if ( $first_prefix ) {
1689 $prefix = $first_prefix;
1690 $first_prefix = false;
1692 wfProfileOut( __METHOD__
.'-prefixhandling' );
1695 $might_be_img = false;
1697 wfProfileIn( __METHOD__
."-e1" );
1698 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1700 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1701 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1702 # the real problem is with the $e1 regex
1705 # Still some problems for cases where the ] is meant to be outside punctuation,
1706 # and no image is in sight. See bug 2095.
1708 if ( $text !== '' &&
1709 substr( $m[3], 0, 1 ) === ']' &&
1710 strpos( $text, '[' ) !== false
1713 $text .= ']'; # so that replaceExternalLinks($text) works later
1714 $m[3] = substr( $m[3], 1 );
1716 # fix up urlencoded title texts
1717 if ( strpos( $m[1], '%' ) !== false ) {
1718 # Should anchors '#' also be rejected?
1719 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1722 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1723 $might_be_img = true;
1725 if ( strpos( $m[1], '%' ) !== false ) {
1726 $m[1] = rawurldecode( $m[1] );
1729 } else { # Invalid form; output directly
1730 $s .= $prefix . '[[' . $line ;
1731 wfProfileOut( __METHOD__
."-e1" );
1734 wfProfileOut( __METHOD__
."-e1" );
1735 wfProfileIn( __METHOD__
."-misc" );
1737 # Don't allow internal links to pages containing
1738 # PROTO: where PROTO is a valid URL protocol; these
1739 # should be external links.
1740 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1741 $s .= $prefix . '[[' . $line ;
1742 wfProfileOut( __METHOD__
."-misc" );
1746 # Make subpage if necessary
1747 if ( $useSubpages ) {
1748 $link = $this->maybeDoSubpageLink( $m[1], $text );
1753 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1755 # Strip off leading ':'
1756 $link = substr( $link, 1 );
1759 wfProfileOut( __METHOD__
."-misc" );
1760 wfProfileIn( __METHOD__
."-title" );
1761 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1762 if ( $nt === null ) {
1763 $s .= $prefix . '[[' . $line;
1764 wfProfileOut( __METHOD__
."-title" );
1768 $ns = $nt->getNamespace();
1769 $iw = $nt->getInterWiki();
1770 wfProfileOut( __METHOD__
."-title" );
1772 if ( $might_be_img ) { # if this is actually an invalid link
1773 wfProfileIn( __METHOD__
."-might_be_img" );
1774 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1777 # look at the next 'line' to see if we can close it there
1779 $next_line = $a->current();
1780 if ( $next_line === false ||
$next_line === null ) {
1783 $m = explode( ']]', $next_line, 3 );
1784 if ( count( $m ) == 3 ) {
1785 # the first ]] closes the inner link, the second the image
1787 $text .= "[[{$m[0]}]]{$m[1]}";
1790 } elseif ( count( $m ) == 2 ) {
1791 # if there's exactly one ]] that's fine, we'll keep looking
1792 $text .= "[[{$m[0]}]]{$m[1]}";
1794 # if $next_line is invalid too, we need look no further
1795 $text .= '[[' . $next_line;
1800 # we couldn't find the end of this imageLink, so output it raw
1801 # but don't ignore what might be perfectly normal links in the text we've examined
1802 $holders->merge( $this->replaceInternalLinks2( $text ) );
1803 $s .= "{$prefix}[[$link|$text";
1804 # note: no $trail, because without an end, there *is* no trail
1805 wfProfileOut( __METHOD__
."-might_be_img" );
1808 } else { # it's not an image, so output it raw
1809 $s .= "{$prefix}[[$link|$text";
1810 # note: no $trail, because without an end, there *is* no trail
1811 wfProfileOut( __METHOD__
."-might_be_img" );
1814 wfProfileOut( __METHOD__
."-might_be_img" );
1817 $wasblank = ( $text == '' );
1821 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1822 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1823 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1824 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1825 $text = $this->doQuotes( $text );
1828 # Link not escaped by : , create the various objects
1832 wfProfileIn( __METHOD__
."-interwiki" );
1833 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1834 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1835 $s = rtrim( $s . $prefix );
1836 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1837 wfProfileOut( __METHOD__
."-interwiki" );
1840 wfProfileOut( __METHOD__
."-interwiki" );
1842 if ( $ns == NS_FILE
) {
1843 wfProfileIn( __METHOD__
."-image" );
1844 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1846 # if no parameters were passed, $text
1847 # becomes something like "File:Foo.png",
1848 # which we don't want to pass on to the
1852 # recursively parse links inside the image caption
1853 # actually, this will parse them in any other parameters, too,
1854 # but it might be hard to fix that, and it doesn't matter ATM
1855 $text = $this->replaceExternalLinks( $text );
1856 $holders->merge( $this->replaceInternalLinks2( $text ) );
1858 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1859 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1861 $s .= $prefix . $trail;
1863 $this->mOutput
->addImage( $nt->getDBkey() );
1864 wfProfileOut( __METHOD__
."-image" );
1869 if ( $ns == NS_CATEGORY
) {
1870 wfProfileIn( __METHOD__
."-category" );
1871 $s = rtrim( $s . "\n" ); # bug 87
1874 $sortkey = $this->getDefaultSort();
1878 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1879 $sortkey = str_replace( "\n", '', $sortkey );
1880 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1881 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1884 * Strip the whitespace Category links produce, see bug 87
1885 * @todo We might want to use trim($tmp, "\n") here.
1887 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1889 wfProfileOut( __METHOD__
."-category" );
1894 # Self-link checking
1895 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1896 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1897 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1902 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1903 # FIXME: Should do batch file existence checks, see comment below
1904 if ( $ns == NS_MEDIA
) {
1905 wfProfileIn( __METHOD__
."-media" );
1906 # Give extensions a chance to select the file revision for us
1907 $skip = $time = false;
1908 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1910 $link = $sk->link( $nt );
1912 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1914 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1915 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1916 $this->mOutput
->addImage( $nt->getDBkey() );
1917 wfProfileOut( __METHOD__
."-media" );
1921 wfProfileIn( __METHOD__
."-always_known" );
1922 # Some titles, such as valid special pages or files in foreign repos, should
1923 # be shown as bluelinks even though they're not included in the page table
1925 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1926 # batch file existence checks for NS_FILE and NS_MEDIA
1927 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1928 $this->mOutput
->addLink( $nt );
1929 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1931 # Links will be added to the output link list after checking
1932 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1934 wfProfileOut( __METHOD__
."-always_known" );
1936 wfProfileOut( __METHOD__
);
1941 * Make a link placeholder. The text returned can be later resolved to a real link with
1942 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1943 * parsing of interwiki links, and secondly to allow all existence checks and
1944 * article length checks (for stub links) to be bundled into a single query.
1948 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1949 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1953 * Render a forced-blue link inline; protect against double expansion of
1954 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1955 * Since this little disaster has to split off the trail text to avoid
1956 * breaking URLs in the following text without breaking trails on the
1957 * wiki links, it's been made into a horrible function.
1960 * @param $text String
1961 * @param $query String
1962 * @param $trail String
1963 * @param $prefix String
1964 * @return String: HTML-wikitext mix oh yuck
1966 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1967 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1968 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1969 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1970 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1971 return $this->armorLinks( $link ) . $trail;
1975 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1976 * going to go through further parsing steps before inline URL expansion.
1978 * Not needed quite as much as it used to be since free links are a bit
1979 * more sensible these days. But bracketed links are still an issue.
1981 * @param $text String: more-or-less HTML
1982 * @return String: less-or-more HTML with NOPARSE bits
1984 function armorLinks( $text ) {
1985 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1986 "{$this->mUniqPrefix}NOPARSE$1", $text );
1990 * Return true if subpage links should be expanded on this page.
1993 function areSubpagesAllowed() {
1994 # Some namespaces don't allow subpages
1995 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1999 * Handle link to subpage if necessary
2001 * @param $target String: the source of the link
2002 * @param &$text String: the link text, modified as necessary
2003 * @return string the full name of the link
2006 function maybeDoSubpageLink( $target, &$text ) {
2007 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2011 * Used by doBlockLevels()
2014 function closeParagraph() {
2016 if ( $this->mLastSection
!= '' ) {
2017 $result = '</' . $this->mLastSection
. ">\n";
2019 $this->mInPre
= false;
2020 $this->mLastSection
= '';
2025 * getCommon() returns the length of the longest common substring
2026 * of both arguments, starting at the beginning of both.
2029 function getCommon( $st1, $st2 ) {
2030 $fl = strlen( $st1 );
2031 $shorter = strlen( $st2 );
2032 if ( $fl < $shorter ) {
2036 for ( $i = 0; $i < $shorter; ++
$i ) {
2037 if ( $st1{$i} != $st2{$i} ) {
2045 * These next three functions open, continue, and close the list
2046 * element appropriate to the prefix character passed into them.
2049 function openList( $char ) {
2050 $result = $this->closeParagraph();
2052 if ( '*' === $char ) {
2053 $result .= '<ul><li>';
2054 } elseif ( '#' === $char ) {
2055 $result .= '<ol><li>';
2056 } elseif ( ':' === $char ) {
2057 $result .= '<dl><dd>';
2058 } elseif ( ';' === $char ) {
2059 $result .= '<dl><dt>';
2060 $this->mDTopen
= true;
2062 $result = '<!-- ERR 1 -->';
2070 * @param $char String
2073 function nextItem( $char ) {
2074 if ( '*' === $char ||
'#' === $char ) {
2076 } elseif ( ':' === $char ||
';' === $char ) {
2078 if ( $this->mDTopen
) {
2081 if ( ';' === $char ) {
2082 $this->mDTopen
= true;
2083 return $close . '<dt>';
2085 $this->mDTopen
= false;
2086 return $close . '<dd>';
2089 return '<!-- ERR 2 -->';
2094 * @param $char String
2097 function closeList( $char ) {
2098 if ( '*' === $char ) {
2099 $text = '</li></ul>';
2100 } elseif ( '#' === $char ) {
2101 $text = '</li></ol>';
2102 } elseif ( ':' === $char ) {
2103 if ( $this->mDTopen
) {
2104 $this->mDTopen
= false;
2105 $text = '</dt></dl>';
2107 $text = '</dd></dl>';
2110 return '<!-- ERR 3 -->';
2117 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2119 * @param $text String
2120 * @param $linestart Boolean: whether or not this is at the start of a line.
2122 * @return string the lists rendered as HTML
2124 function doBlockLevels( $text, $linestart ) {
2125 wfProfileIn( __METHOD__
);
2127 # Parsing through the text line by line. The main thing
2128 # happening here is handling of block-level elements p, pre,
2129 # and making lists from lines starting with * # : etc.
2131 $textLines = StringUtils
::explode( "\n", $text );
2133 $lastPrefix = $output = '';
2134 $this->mDTopen
= $inBlockElem = false;
2136 $paragraphStack = false;
2138 foreach ( $textLines as $oLine ) {
2140 if ( !$linestart ) {
2150 $lastPrefixLength = strlen( $lastPrefix );
2151 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2152 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2153 # If not in a <pre> element, scan for and figure out what prefixes are there.
2154 if ( !$this->mInPre
) {
2155 # Multiple prefixes may abut each other for nested lists.
2156 $prefixLength = strspn( $oLine, '*#:;' );
2157 $prefix = substr( $oLine, 0, $prefixLength );
2160 # ; and : are both from definition-lists, so they're equivalent
2161 # for the purposes of determining whether or not we need to open/close
2163 $prefix2 = str_replace( ';', ':', $prefix );
2164 $t = substr( $oLine, $prefixLength );
2165 $this->mInPre
= (bool)$preOpenMatch;
2167 # Don't interpret any other prefixes in preformatted text
2169 $prefix = $prefix2 = '';
2174 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2175 # Same as the last item, so no need to deal with nesting or opening stuff
2176 $output .= $this->nextItem( substr( $prefix, -1 ) );
2177 $paragraphStack = false;
2179 if ( substr( $prefix, -1 ) === ';') {
2180 # The one nasty exception: definition lists work like this:
2181 # ; title : definition text
2182 # So we check for : in the remainder text to split up the
2183 # title and definition, without b0rking links.
2185 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2187 $output .= $term . $this->nextItem( ':' );
2190 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2191 # We need to open or close prefixes, or both.
2193 # Either open or close a level...
2194 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2195 $paragraphStack = false;
2197 # Close all the prefixes which aren't shared.
2198 while ( $commonPrefixLength < $lastPrefixLength ) {
2199 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2200 --$lastPrefixLength;
2203 # Continue the current prefix if appropriate.
2204 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2205 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2208 # Open prefixes where appropriate.
2209 while ( $prefixLength > $commonPrefixLength ) {
2210 $char = substr( $prefix, $commonPrefixLength, 1 );
2211 $output .= $this->openList( $char );
2213 if ( ';' === $char ) {
2214 # FIXME: This is dupe of code above
2215 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2217 $output .= $term . $this->nextItem( ':' );
2220 ++
$commonPrefixLength;
2222 $lastPrefix = $prefix2;
2225 # If we have no prefixes, go to paragraph mode.
2226 if ( 0 == $prefixLength ) {
2227 wfProfileIn( __METHOD__
."-paragraph" );
2228 # No prefix (not in list)--go to paragraph mode
2229 # XXX: use a stack for nestable elements like span, table and div
2230 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2231 $closematch = preg_match(
2232 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2233 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2234 if ( $openmatch or $closematch ) {
2235 $paragraphStack = false;
2236 #Â TODO bug 5718: paragraph closed
2237 $output .= $this->closeParagraph();
2238 if ( $preOpenMatch and !$preCloseMatch ) {
2239 $this->mInPre
= true;
2241 $inBlockElem = !$closematch;
2242 } elseif ( !$inBlockElem && !$this->mInPre
) {
2243 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2245 if ( $this->mLastSection
!== 'pre' ) {
2246 $paragraphStack = false;
2247 $output .= $this->closeParagraph().'<pre>';
2248 $this->mLastSection
= 'pre';
2250 $t = substr( $t, 1 );
2253 if ( trim( $t ) === '' ) {
2254 if ( $paragraphStack ) {
2255 $output .= $paragraphStack.'<br />';
2256 $paragraphStack = false;
2257 $this->mLastSection
= 'p';
2259 if ( $this->mLastSection
!== 'p' ) {
2260 $output .= $this->closeParagraph();
2261 $this->mLastSection
= '';
2262 $paragraphStack = '<p>';
2264 $paragraphStack = '</p><p>';
2268 if ( $paragraphStack ) {
2269 $output .= $paragraphStack;
2270 $paragraphStack = false;
2271 $this->mLastSection
= 'p';
2272 } elseif ( $this->mLastSection
!== 'p' ) {
2273 $output .= $this->closeParagraph().'<p>';
2274 $this->mLastSection
= 'p';
2279 wfProfileOut( __METHOD__
."-paragraph" );
2281 # somewhere above we forget to get out of pre block (bug 785)
2282 if ( $preCloseMatch && $this->mInPre
) {
2283 $this->mInPre
= false;
2285 if ( $paragraphStack === false ) {
2289 while ( $prefixLength ) {
2290 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2293 if ( $this->mLastSection
!= '' ) {
2294 $output .= '</' . $this->mLastSection
. '>';
2295 $this->mLastSection
= '';
2298 wfProfileOut( __METHOD__
);
2303 * Split up a string on ':', ignoring any occurences inside tags
2304 * to prevent illegal overlapping.
2306 * @param $str String: the string to split
2307 * @param &$before String: set to everything before the ':'
2308 * @param &$after String: set to everything after the ':'
2309 * return String: the position of the ':', or false if none found
2311 function findColonNoLinks( $str, &$before, &$after ) {
2312 wfProfileIn( __METHOD__
);
2314 $pos = strpos( $str, ':' );
2315 if ( $pos === false ) {
2317 wfProfileOut( __METHOD__
);
2321 $lt = strpos( $str, '<' );
2322 if ( $lt === false ||
$lt > $pos ) {
2323 # Easy; no tag nesting to worry about
2324 $before = substr( $str, 0, $pos );
2325 $after = substr( $str, $pos+
1 );
2326 wfProfileOut( __METHOD__
);
2330 # Ugly state machine to walk through avoiding tags.
2331 $state = self
::COLON_STATE_TEXT
;
2333 $len = strlen( $str );
2334 for( $i = 0; $i < $len; $i++
) {
2338 # (Using the number is a performance hack for common cases)
2339 case 0: # self::COLON_STATE_TEXT:
2342 # Could be either a <start> tag or an </end> tag
2343 $state = self
::COLON_STATE_TAGSTART
;
2346 if ( $stack == 0 ) {
2348 $before = substr( $str, 0, $i );
2349 $after = substr( $str, $i +
1 );
2350 wfProfileOut( __METHOD__
);
2353 # Embedded in a tag; don't break it.
2356 # Skip ahead looking for something interesting
2357 $colon = strpos( $str, ':', $i );
2358 if ( $colon === false ) {
2359 # Nothing else interesting
2360 wfProfileOut( __METHOD__
);
2363 $lt = strpos( $str, '<', $i );
2364 if ( $stack === 0 ) {
2365 if ( $lt === false ||
$colon < $lt ) {
2367 $before = substr( $str, 0, $colon );
2368 $after = substr( $str, $colon +
1 );
2369 wfProfileOut( __METHOD__
);
2373 if ( $lt === false ) {
2374 # Nothing else interesting to find; abort!
2375 # We're nested, but there's no close tags left. Abort!
2378 # Skip ahead to next tag start
2380 $state = self
::COLON_STATE_TAGSTART
;
2383 case 1: # self::COLON_STATE_TAG:
2388 $state = self
::COLON_STATE_TEXT
;
2391 # Slash may be followed by >?
2392 $state = self
::COLON_STATE_TAGSLASH
;
2398 case 2: # self::COLON_STATE_TAGSTART:
2401 $state = self
::COLON_STATE_CLOSETAG
;
2404 $state = self
::COLON_STATE_COMMENT
;
2407 # Illegal early close? This shouldn't happen D:
2408 $state = self
::COLON_STATE_TEXT
;
2411 $state = self
::COLON_STATE_TAG
;
2414 case 3: # self::COLON_STATE_CLOSETAG:
2419 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2420 wfProfileOut( __METHOD__
);
2423 $state = self
::COLON_STATE_TEXT
;
2426 case self
::COLON_STATE_TAGSLASH
:
2428 # Yes, a self-closed tag <blah/>
2429 $state = self
::COLON_STATE_TEXT
;
2431 # Probably we're jumping the gun, and this is an attribute
2432 $state = self
::COLON_STATE_TAG
;
2435 case 5: # self::COLON_STATE_COMMENT:
2437 $state = self
::COLON_STATE_COMMENTDASH
;
2440 case self
::COLON_STATE_COMMENTDASH
:
2442 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2444 $state = self
::COLON_STATE_COMMENT
;
2447 case self
::COLON_STATE_COMMENTDASHDASH
:
2449 $state = self
::COLON_STATE_TEXT
;
2451 $state = self
::COLON_STATE_COMMENT
;
2455 throw new MWException( "State machine error in " . __METHOD__
);
2459 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2460 wfProfileOut( __METHOD__
);
2463 wfProfileOut( __METHOD__
);
2468 * Return value of a magic variable (like PAGENAME)
2472 function getVariableValue( $index, $frame=false ) {
2473 global $wgContLang, $wgSitename, $wgServer;
2474 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2477 * Some of these require message or data lookups and can be
2478 * expensive to check many times.
2480 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2481 if ( isset( $this->mVarCache
[$index] ) ) {
2482 return $this->mVarCache
[$index];
2486 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2487 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2490 global $wgLocaltimezone;
2491 if ( isset( $wgLocaltimezone ) ) {
2492 $oldtz = date_default_timezone_get();
2493 date_default_timezone_set( $wgLocaltimezone );
2496 $localTimestamp = date( 'YmdHis', $ts );
2497 $localMonth = date( 'm', $ts );
2498 $localMonth1 = date( 'n', $ts );
2499 $localMonthName = date( 'n', $ts );
2500 $localDay = date( 'j', $ts );
2501 $localDay2 = date( 'd', $ts );
2502 $localDayOfWeek = date( 'w', $ts );
2503 $localWeek = date( 'W', $ts );
2504 $localYear = date( 'Y', $ts );
2505 $localHour = date( 'H', $ts );
2506 if ( isset( $wgLocaltimezone ) ) {
2507 date_default_timezone_set( $oldtz );
2511 case 'currentmonth':
2512 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2514 case 'currentmonth1':
2515 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2517 case 'currentmonthname':
2518 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2520 case 'currentmonthnamegen':
2521 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2523 case 'currentmonthabbrev':
2524 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2527 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2530 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2533 $value = $wgContLang->formatNum( $localMonth );
2536 $value = $wgContLang->formatNum( $localMonth1 );
2538 case 'localmonthname':
2539 $value = $wgContLang->getMonthName( $localMonthName );
2541 case 'localmonthnamegen':
2542 $value = $wgContLang->getMonthNameGen( $localMonthName );
2544 case 'localmonthabbrev':
2545 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2548 $value = $wgContLang->formatNum( $localDay );
2551 $value = $wgContLang->formatNum( $localDay2 );
2554 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2557 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2559 case 'fullpagename':
2560 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2562 case 'fullpagenamee':
2563 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2566 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2568 case 'subpagenamee':
2569 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2571 case 'basepagename':
2572 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2574 case 'basepagenamee':
2575 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2577 case 'talkpagename':
2578 if ( $this->mTitle
->canTalk() ) {
2579 $talkPage = $this->mTitle
->getTalkPage();
2580 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2585 case 'talkpagenamee':
2586 if ( $this->mTitle
->canTalk() ) {
2587 $talkPage = $this->mTitle
->getTalkPage();
2588 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2593 case 'subjectpagename':
2594 $subjPage = $this->mTitle
->getSubjectPage();
2595 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2597 case 'subjectpagenamee':
2598 $subjPage = $this->mTitle
->getSubjectPage();
2599 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2602 # Let the edit saving system know we should parse the page
2603 # *after* a revision ID has been assigned.
2604 $this->mOutput
->setFlag( 'vary-revision' );
2605 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2606 $value = $this->mRevisionId
;
2609 # Let the edit saving system know we should parse the page
2610 # *after* a revision ID has been assigned. This is for null edits.
2611 $this->mOutput
->setFlag( 'vary-revision' );
2612 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2613 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2615 case 'revisionday2':
2616 # Let the edit saving system know we should parse the page
2617 # *after* a revision ID has been assigned. This is for null edits.
2618 $this->mOutput
->setFlag( 'vary-revision' );
2619 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2620 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2622 case 'revisionmonth':
2623 # Let the edit saving system know we should parse the page
2624 # *after* a revision ID has been assigned. This is for null edits.
2625 $this->mOutput
->setFlag( 'vary-revision' );
2626 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2627 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2629 case 'revisionmonth1':
2630 # Let the edit saving system know we should parse the page
2631 # *after* a revision ID has been assigned. This is for null edits.
2632 $this->mOutput
->setFlag( 'vary-revision' );
2633 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2634 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2636 case 'revisionyear':
2637 # Let the edit saving system know we should parse the page
2638 # *after* a revision ID has been assigned. This is for null edits.
2639 $this->mOutput
->setFlag( 'vary-revision' );
2640 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2641 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2643 case 'revisiontimestamp':
2644 # Let the edit saving system know we should parse the page
2645 # *after* a revision ID has been assigned. This is for null edits.
2646 $this->mOutput
->setFlag( 'vary-revision' );
2647 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2648 $value = $this->getRevisionTimestamp();
2650 case 'revisionuser':
2651 # Let the edit saving system know we should parse the page
2652 # *after* a revision ID has been assigned. This is for null edits.
2653 $this->mOutput
->setFlag( 'vary-revision' );
2654 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2655 $value = $this->getRevisionUser();
2658 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2661 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2664 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2667 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2669 case 'subjectspace':
2670 $value = $this->mTitle
->getSubjectNsText();
2672 case 'subjectspacee':
2673 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2675 case 'currentdayname':
2676 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2679 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2682 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2685 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2688 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2689 # int to remove the padding
2690 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2693 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2695 case 'localdayname':
2696 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2699 $value = $wgContLang->formatNum( $localYear, true );
2702 $value = $wgContLang->time( $localTimestamp, false, false );
2705 $value = $wgContLang->formatNum( $localHour, true );
2708 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2709 # int to remove the padding
2710 $value = $wgContLang->formatNum( (int)$localWeek );
2713 $value = $wgContLang->formatNum( $localDayOfWeek );
2715 case 'numberofarticles':
2716 $value = $wgContLang->formatNum( SiteStats
::articles() );
2718 case 'numberoffiles':
2719 $value = $wgContLang->formatNum( SiteStats
::images() );
2721 case 'numberofusers':
2722 $value = $wgContLang->formatNum( SiteStats
::users() );
2724 case 'numberofactiveusers':
2725 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2727 case 'numberofpages':
2728 $value = $wgContLang->formatNum( SiteStats
::pages() );
2730 case 'numberofadmins':
2731 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2733 case 'numberofedits':
2734 $value = $wgContLang->formatNum( SiteStats
::edits() );
2736 case 'numberofviews':
2737 $value = $wgContLang->formatNum( SiteStats
::views() );
2739 case 'currenttimestamp':
2740 $value = wfTimestamp( TS_MW
, $ts );
2742 case 'localtimestamp':
2743 $value = $localTimestamp;
2745 case 'currentversion':
2746 $value = SpecialVersion
::getVersion();
2749 return $wgArticlePath;
2755 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2756 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2757 wfRestoreWarnings();
2758 return $serverName ?
$serverName : $wgServer;
2760 return $wgScriptPath;
2762 return $wgStylePath;
2763 case 'directionmark':
2764 return $wgContLang->getDirMark();
2765 case 'contentlanguage':
2766 global $wgLanguageCode;
2767 return $wgLanguageCode;
2770 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2778 $this->mVarCache
[$index] = $value;
2784 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2788 function initialiseVariables() {
2789 wfProfileIn( __METHOD__
);
2790 $variableIDs = MagicWord
::getVariableIDs();
2791 $substIDs = MagicWord
::getSubstIDs();
2793 $this->mVariables
= new MagicWordArray( $variableIDs );
2794 $this->mSubstWords
= new MagicWordArray( $substIDs );
2795 wfProfileOut( __METHOD__
);
2799 * Preprocess some wikitext and return the document tree.
2800 * This is the ghost of replace_variables().
2802 * @param $text String: The text to parse
2803 * @param $flags Integer: bitwise combination of:
2804 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2805 * included. Default is to assume a direct page view.
2807 * The generated DOM tree must depend only on the input text and the flags.
2808 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2810 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2811 * change in the DOM tree for a given text, must be passed through the section identifier
2812 * in the section edit link and thus back to extractSections().
2814 * The output of this function is currently only cached in process memory, but a persistent
2815 * cache may be implemented at a later date which takes further advantage of these strict
2816 * dependency requirements.
2820 function preprocessToDom( $text, $flags = 0 ) {
2821 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2826 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2828 public static function splitWhitespace( $s ) {
2829 $ltrimmed = ltrim( $s );
2830 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2831 $trimmed = rtrim( $ltrimmed );
2832 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2834 $w2 = substr( $ltrimmed, -$diff );
2838 return array( $w1, $trimmed, $w2 );
2842 * Replace magic variables, templates, and template arguments
2843 * with the appropriate text. Templates are substituted recursively,
2844 * taking care to avoid infinite loops.
2846 * Note that the substitution depends on value of $mOutputType:
2847 * self::OT_WIKI: only {{subst:}} templates
2848 * self::OT_PREPROCESS: templates but not extension tags
2849 * self::OT_HTML: all templates and extension tags
2851 * @param $text String: the text to transform
2852 * @param $frame PPFrame Object describing the arguments passed to the template.
2853 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2854 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2855 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2858 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2859 # Is there any text? Also, Prevent too big inclusions!
2860 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2863 wfProfileIn( __METHOD__
);
2865 if ( $frame === false ) {
2866 $frame = $this->getPreprocessor()->newFrame();
2867 } elseif ( !( $frame instanceof PPFrame
) ) {
2868 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2869 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2872 $dom = $this->preprocessToDom( $text );
2873 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2874 $text = $frame->expand( $dom, $flags );
2876 wfProfileOut( __METHOD__
);
2880 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2881 static function createAssocArgs( $args ) {
2882 $assocArgs = array();
2884 foreach ( $args as $arg ) {
2885 $eqpos = strpos( $arg, '=' );
2886 if ( $eqpos === false ) {
2887 $assocArgs[$index++
] = $arg;
2889 $name = trim( substr( $arg, 0, $eqpos ) );
2890 $value = trim( substr( $arg, $eqpos+
1 ) );
2891 if ( $value === false ) {
2894 if ( $name !== false ) {
2895 $assocArgs[$name] = $value;
2904 * Warn the user when a parser limitation is reached
2905 * Will warn at most once the user per limitation type
2907 * @param $limitationType String: should be one of:
2908 * 'expensive-parserfunction' (corresponding messages:
2909 * 'expensive-parserfunction-warning',
2910 * 'expensive-parserfunction-category')
2911 * 'post-expand-template-argument' (corresponding messages:
2912 * 'post-expand-template-argument-warning',
2913 * 'post-expand-template-argument-category')
2914 * 'post-expand-template-inclusion' (corresponding messages:
2915 * 'post-expand-template-inclusion-warning',
2916 * 'post-expand-template-inclusion-category')
2917 * @param $current Current value
2918 * @param $max Maximum allowed, when an explicit limit has been
2919 * exceeded, provide the values (optional)
2921 function limitationWarn( $limitationType, $current=null, $max=null) {
2922 # does no harm if $current and $max are present but are unnecessary for the message
2923 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2924 $this->mOutput
->addWarning( $warning );
2925 $this->addTrackingCategory( "$limitationType-category" );
2929 * Return the text of a template, after recursively
2930 * replacing any variables or templates within the template.
2932 * @param $piece Array: the parts of the template
2933 * $piece['title']: the title, i.e. the part before the |
2934 * $piece['parts']: the parameter array
2935 * $piece['lineStart']: whether the brace was at the start of a line
2936 * @param $frame PPFrame The current frame, contains template arguments
2937 * @return String: the text of the template
2940 function braceSubstitution( $piece, $frame ) {
2941 global $wgContLang, $wgNonincludableNamespaces;
2942 wfProfileIn( __METHOD__
);
2943 wfProfileIn( __METHOD__
.'-setup' );
2946 $found = false; # $text has been filled
2947 $nowiki = false; # wiki markup in $text should be escaped
2948 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2949 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2950 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2951 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2953 # Title object, where $text came from
2956 # $part1 is the bit before the first |, and must contain only title characters.
2957 # Various prefixes will be stripped from it later.
2958 $titleWithSpaces = $frame->expand( $piece['title'] );
2959 $part1 = trim( $titleWithSpaces );
2962 # Original title text preserved for various purposes
2963 $originalTitle = $part1;
2965 # $args is a list of argument nodes, starting from index 0, not including $part1
2966 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2967 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2968 wfProfileOut( __METHOD__
.'-setup' );
2971 wfProfileIn( __METHOD__
.'-modifiers' );
2974 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2976 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2977 # Decide whether to expand template or keep wikitext as-is.
2978 if ( $this->ot
['wiki'] ) {
2979 if ( $substMatch === false ) {
2980 $literal = true; # literal when in PST with no prefix
2982 $literal = false; # expand when in PST with subst: or safesubst:
2985 if ( $substMatch == 'subst' ) {
2986 $literal = true; # literal when not in PST with plain subst:
2988 $literal = false; # expand when not in PST with safesubst: or no prefix
2992 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2999 if ( !$found && $args->getLength() == 0 ) {
3000 $id = $this->mVariables
->matchStartToEnd( $part1 );
3001 if ( $id !== false ) {
3002 $text = $this->getVariableValue( $id, $frame );
3003 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3004 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3010 # MSG, MSGNW and RAW
3013 $mwMsgnw = MagicWord
::get( 'msgnw' );
3014 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3017 # Remove obsolete MSG:
3018 $mwMsg = MagicWord
::get( 'msg' );
3019 $mwMsg->matchStartAndRemove( $part1 );
3023 $mwRaw = MagicWord
::get( 'raw' );
3024 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3025 $forceRawInterwiki = true;
3028 wfProfileOut( __METHOD__
.'-modifiers' );
3032 wfProfileIn( __METHOD__
. '-pfunc' );
3034 $colonPos = strpos( $part1, ':' );
3035 if ( $colonPos !== false ) {
3036 # Case sensitive functions
3037 $function = substr( $part1, 0, $colonPos );
3038 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3039 $function = $this->mFunctionSynonyms
[1][$function];
3041 # Case insensitive functions
3042 $function = $wgContLang->lc( $function );
3043 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3044 $function = $this->mFunctionSynonyms
[0][$function];
3050 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3051 $initialArgs = array( &$this );
3052 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3053 if ( $flags & SFH_OBJECT_ARGS
) {
3054 # Add a frame parameter, and pass the arguments as an array
3055 $allArgs = $initialArgs;
3056 $allArgs[] = $frame;
3057 for ( $i = 0; $i < $args->getLength(); $i++
) {
3058 $funcArgs[] = $args->item( $i );
3060 $allArgs[] = $funcArgs;
3062 # Convert arguments to plain text
3063 for ( $i = 0; $i < $args->getLength(); $i++
) {
3064 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3066 $allArgs = array_merge( $initialArgs, $funcArgs );
3069 # Workaround for PHP bug 35229 and similar
3070 if ( !is_callable( $callback ) ) {
3071 wfProfileOut( __METHOD__
. '-pfunc' );
3072 wfProfileOut( __METHOD__
);
3073 throw new MWException( "Tag hook for $function is not callable\n" );
3075 $result = call_user_func_array( $callback, $allArgs );
3078 $preprocessFlags = 0;
3080 if ( is_array( $result ) ) {
3081 if ( isset( $result[0] ) ) {
3083 unset( $result[0] );
3086 # Extract flags into the local scope
3087 # This allows callers to set flags such as nowiki, found, etc.
3093 $text = $this->preprocessToDom( $text, $preprocessFlags );
3098 wfProfileOut( __METHOD__
. '-pfunc' );
3101 # Finish mangling title and then check for loops.
3102 # Set $title to a Title object and $titleText to the PDBK
3105 # Split the title into page and subpage
3107 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3108 if ( $subpage !== '' ) {
3109 $ns = $this->mTitle
->getNamespace();
3111 $title = Title
::newFromText( $part1, $ns );
3113 $titleText = $title->getPrefixedText();
3114 # Check for language variants if the template is not found
3115 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3116 $wgContLang->findVariantLink( $part1, $title, true );
3118 # Do recursion depth check
3119 $limit = $this->mOptions
->getMaxTemplateDepth();
3120 if ( $frame->depth
>= $limit ) {
3122 $text = '<span class="error">'
3123 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3129 # Load from database
3130 if ( !$found && $title ) {
3131 wfProfileIn( __METHOD__
. '-loadtpl' );
3132 if ( !$title->isExternal() ) {
3133 if ( $title->getNamespace() == NS_SPECIAL
3134 && $this->mOptions
->getAllowSpecialInclusion()
3135 && $this->ot
['html'] )
3137 $text = SpecialPage
::capturePath( $title );
3138 if ( is_string( $text ) ) {
3141 $this->disableCache();
3143 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3144 $found = false; # access denied
3145 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3147 list( $text, $title ) = $this->getTemplateDom( $title );
3148 if ( $text !== false ) {
3154 # If the title is valid but undisplayable, make a link to it
3155 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3156 $text = "[[:$titleText]]";
3159 } elseif ( $title->isTrans() ) {
3160 # Interwiki transclusion
3161 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3162 $text = $this->interwikiTransclude( $title, 'render' );
3165 $text = $this->interwikiTransclude( $title, 'raw' );
3166 # Preprocess it like a template
3167 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3173 # Do infinite loop check
3174 # This has to be done after redirect resolution to avoid infinite loops via redirects
3175 if ( !$frame->loopCheck( $title ) ) {
3177 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3178 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3180 wfProfileOut( __METHOD__
. '-loadtpl' );
3183 # If we haven't found text to substitute by now, we're done
3184 # Recover the source wikitext and return it
3186 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3187 wfProfileOut( __METHOD__
);
3188 return array( 'object' => $text );
3191 # Expand DOM-style return values in a child frame
3192 if ( $isChildObj ) {
3193 # Clean up argument array
3194 $newFrame = $frame->newChild( $args, $title );
3197 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3198 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3199 # Expansion is eligible for the empty-frame cache
3200 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3201 $text = $this->mTplExpandCache
[$titleText];
3203 $text = $newFrame->expand( $text );
3204 $this->mTplExpandCache
[$titleText] = $text;
3207 # Uncached expansion
3208 $text = $newFrame->expand( $text );
3211 if ( $isLocalObj && $nowiki ) {
3212 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3213 $isLocalObj = false;
3216 # Replace raw HTML by a placeholder
3217 # Add a blank line preceding, to prevent it from mucking up
3218 # immediately preceding headings
3220 $text = "\n\n" . $this->insertStripItem( $text );
3221 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3222 # Escape nowiki-style return values
3223 $text = wfEscapeWikiText( $text );
3224 } elseif ( is_string( $text )
3225 && !$piece['lineStart']
3226 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3228 # Bug 529: if the template begins with a table or block-level
3229 # element, it should be treated as beginning a new line.
3230 # This behaviour is somewhat controversial.
3231 $text = "\n" . $text;
3234 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3235 # Error, oversize inclusion
3236 if ( $titleText !== false ) {
3237 # Make a working, properly escaped link if possible (bug 23588)
3238 $text = "[[:$titleText]]";
3240 # This will probably not be a working link, but at least it may
3241 # provide some hint of where the problem is
3242 preg_replace( '/^:/', '', $originalTitle );
3243 $text = "[[:$originalTitle]]";
3245 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3246 $this->limitationWarn( 'post-expand-template-inclusion' );
3249 if ( $isLocalObj ) {
3250 $ret = array( 'object' => $text );
3252 $ret = array( 'text' => $text );
3255 wfProfileOut( __METHOD__
);
3260 * Get the semi-parsed DOM representation of a template with a given title,
3261 * and its redirect destination title. Cached.
3263 function getTemplateDom( $title ) {
3264 $cacheTitle = $title;
3265 $titleText = $title->getPrefixedDBkey();
3267 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3268 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3269 $title = Title
::makeTitle( $ns, $dbk );
3270 $titleText = $title->getPrefixedDBkey();
3272 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3273 return array( $this->mTplDomCache
[$titleText], $title );
3276 # Cache miss, go to the database
3277 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3279 if ( $text === false ) {
3280 $this->mTplDomCache
[$titleText] = false;
3281 return array( false, $title );
3284 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3285 $this->mTplDomCache
[ $titleText ] = $dom;
3287 if ( !$title->equals( $cacheTitle ) ) {
3288 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3289 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3292 return array( $dom, $title );
3296 * Fetch the unparsed text of a template and register a reference to it.
3298 function fetchTemplateAndTitle( $title ) {
3299 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3300 $stuff = call_user_func( $templateCb, $title, $this );
3301 $text = $stuff['text'];
3302 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3303 if ( isset( $stuff['deps'] ) ) {
3304 foreach ( $stuff['deps'] as $dep ) {
3305 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3308 return array( $text, $finalTitle );
3311 function fetchTemplate( $title ) {
3312 $rv = $this->fetchTemplateAndTitle( $title );
3317 * Static function to get a template
3318 * Can be overridden via ParserOptions::setTemplateCallback().
3320 static function statelessFetchTemplate( $title, $parser=false ) {
3321 $text = $skip = false;
3322 $finalTitle = $title;
3325 # Loop to fetch the article, with up to 1 redirect
3326 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3327 # Give extensions a chance to select the revision instead
3328 $id = false; # Assume current
3329 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3335 'page_id' => $title->getArticleID(),
3339 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3340 $rev_id = $rev ?
$rev->getId() : 0;
3341 # If there is no current revision, there is no page
3342 if ( $id === false && !$rev ) {
3343 $linkCache = LinkCache
::singleton();
3344 $linkCache->addBadLinkObj( $title );
3349 'page_id' => $title->getArticleID(),
3350 'rev_id' => $rev_id );
3353 $text = $rev->getText();
3354 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3356 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3357 if ( !$message->exists() ) {
3361 $text = $message->plain();
3365 if ( $text === false ) {
3369 $finalTitle = $title;
3370 $title = Title
::newFromRedirect( $text );
3374 'finalTitle' => $finalTitle,
3379 * Transclude an interwiki link.
3381 function interwikiTransclude( $title, $action ) {
3382 global $wgEnableScaryTranscluding;
3384 if ( !$wgEnableScaryTranscluding ) {
3385 return wfMsgForContent('scarytranscludedisabled');
3388 $url = $title->getFullUrl( "action=$action" );
3390 if ( strlen( $url ) > 255 ) {
3391 return wfMsgForContent( 'scarytranscludetoolong' );
3393 return $this->fetchScaryTemplateMaybeFromCache( $url );
3396 function fetchScaryTemplateMaybeFromCache( $url ) {
3397 global $wgTranscludeCacheExpiry;
3398 $dbr = wfGetDB( DB_SLAVE
);
3399 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3400 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3401 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3403 return $obj->tc_contents
;
3406 $text = Http
::get( $url );
3408 return wfMsgForContent( 'scarytranscludefailed', $url );
3411 $dbw = wfGetDB( DB_MASTER
);
3412 $dbw->replace( 'transcache', array('tc_url'), array(
3414 'tc_time' => $dbw->timestamp( time() ),
3415 'tc_contents' => $text)
3422 * Triple brace replacement -- used for template arguments
3425 function argSubstitution( $piece, $frame ) {
3426 wfProfileIn( __METHOD__
);
3429 $parts = $piece['parts'];
3430 $nameWithSpaces = $frame->expand( $piece['title'] );
3431 $argName = trim( $nameWithSpaces );
3433 $text = $frame->getArgument( $argName );
3434 if ( $text === false && $parts->getLength() > 0
3438 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3441 # No match in frame, use the supplied default
3442 $object = $parts->item( 0 )->getChildren();
3444 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3445 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3446 $this->limitationWarn( 'post-expand-template-argument' );
3449 if ( $text === false && $object === false ) {
3451 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3453 if ( $error !== false ) {
3456 if ( $object !== false ) {
3457 $ret = array( 'object' => $object );
3459 $ret = array( 'text' => $text );
3462 wfProfileOut( __METHOD__
);
3467 * Return the text to be used for a given extension tag.
3468 * This is the ghost of strip().
3470 * @param $params Associative array of parameters:
3471 * name PPNode for the tag name
3472 * attr PPNode for unparsed text where tag attributes are thought to be
3473 * attributes Optional associative array of parsed attributes
3474 * inner Contents of extension element
3475 * noClose Original text did not have a close tag
3476 * @param $frame PPFrame
3478 function extensionSubstitution( $params, $frame ) {
3479 $name = $frame->expand( $params['name'] );
3480 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3481 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3482 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3484 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3485 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3486 if ( $isFunctionTag ) {
3487 $markerType = 'none';
3489 $markerType = 'general';
3491 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3492 $name = strtolower( $name );
3493 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3494 if ( isset( $params['attributes'] ) ) {
3495 $attributes = $attributes +
$params['attributes'];
3498 if ( isset( $this->mTagHooks
[$name] ) ) {
3499 # Workaround for PHP bug 35229 and similar
3500 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3501 throw new MWException( "Tag hook for $name is not callable\n" );
3503 $output = call_user_func_array( $this->mTagHooks
[$name],
3504 array( $content, $attributes, $this, $frame ) );
3505 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3506 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3507 if ( !is_callable( $callback ) ) {
3508 throw new MWException( "Tag hook for $name is not callable\n" );
3511 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3513 $output = '<span class="error">Invalid tag extension name: ' .
3514 htmlspecialchars( $name ) . '</span>';
3517 if ( is_array( $output ) ) {
3518 # Extract flags to local scope (to override $markerType)
3520 $output = $flags[0];
3525 if ( is_null( $attrText ) ) {
3528 if ( isset( $params['attributes'] ) ) {
3529 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3530 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3531 htmlspecialchars( $attrValue ) . '"';
3534 if ( $content === null ) {
3535 $output = "<$name$attrText/>";
3537 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3538 $output = "<$name$attrText>$content$close";
3542 if ( $markerType === 'none' ) {
3544 } elseif ( $markerType === 'nowiki' ) {
3545 $this->mStripState
->nowiki
->setPair( $marker, $output );
3546 } elseif ( $markerType === 'general' ) {
3547 $this->mStripState
->general
->setPair( $marker, $output );
3549 throw new MWException( __METHOD__
.': invalid marker type' );
3555 * Increment an include size counter
3557 * @param $type String: the type of expansion
3558 * @param $size Integer: the size of the text
3559 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3561 function incrementIncludeSize( $type, $size ) {
3562 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3565 $this->mIncludeSizes
[$type] +
= $size;
3571 * Increment the expensive function count
3573 * @return Boolean: false if the limit has been exceeded
3575 function incrementExpensiveFunctionCount() {
3576 global $wgExpensiveParserFunctionLimit;
3577 $this->mExpensiveFunctionCount++
;
3578 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3585 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3586 * Fills $this->mDoubleUnderscores, returns the modified text
3588 function doDoubleUnderscore( $text ) {
3589 wfProfileIn( __METHOD__
);
3591 # The position of __TOC__ needs to be recorded
3592 $mw = MagicWord
::get( 'toc' );
3593 if ( $mw->match( $text ) ) {
3594 $this->mShowToc
= true;
3595 $this->mForceTocPosition
= true;
3597 # Set a placeholder. At the end we'll fill it in with the TOC.
3598 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3600 # Only keep the first one.
3601 $text = $mw->replace( '', $text );
3604 # Now match and remove the rest of them
3605 $mwa = MagicWord
::getDoubleUnderscoreArray();
3606 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3608 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3609 $this->mOutput
->mNoGallery
= true;
3611 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3612 $this->mShowToc
= false;
3614 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3615 $this->addTrackingCategory( 'hidden-category-category' );
3617 # (bug 8068) Allow control over whether robots index a page.
3619 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3620 # is not desirable, the last one on the page should win.
3621 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3622 $this->mOutput
->setIndexPolicy( 'noindex' );
3623 $this->addTrackingCategory( 'noindex-category' );
3625 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3626 $this->mOutput
->setIndexPolicy( 'index' );
3627 $this->addTrackingCategory( 'index-category' );
3630 # Cache all double underscores in the database
3631 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3632 $this->mOutput
->setProperty( $key, '' );
3635 wfProfileOut( __METHOD__
);
3640 * Add a tracking category, getting the title from a system message,
3641 * or print a debug message if the title is invalid.
3643 * @param $msg String: message key
3644 * @return Boolean: whether the addition was successful
3646 protected function addTrackingCategory( $msg ) {
3647 $cat = wfMsgForContent( $msg );
3649 # Allow tracking categories to be disabled by setting them to "-"
3650 if ( $cat === '-' ) {
3654 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3655 if ( $containerCategory ) {
3656 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3659 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3665 * This function accomplishes several tasks:
3666 * 1) Auto-number headings if that option is enabled
3667 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3668 * 3) Add a Table of contents on the top for users who have enabled the option
3669 * 4) Auto-anchor headings
3671 * It loops through all headlines, collects the necessary data, then splits up the
3672 * string and re-inserts the newly formatted headlines.
3674 * @param $text String
3675 * @param $origText String: original, untouched wikitext
3676 * @param $isMain Boolean
3679 function formatHeadings( $text, $origText, $isMain=true ) {
3680 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3682 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3684 # Inhibit editsection links if requested in the page
3685 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3688 $showEditLink = $this->mOptions
->getEditSection();
3690 if ( $showEditLink ) {
3691 $this->mOutput
->setEditSectionTokens( true );
3694 # Get all headlines for numbering them and adding funky stuff like [edit]
3695 # links - this is for later, but we need the number of headlines right now
3697 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3699 # if there are fewer than 4 headlines in the article, do not show TOC
3700 # unless it's been explicitly enabled.
3701 $enoughToc = $this->mShowToc
&&
3702 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3704 # Allow user to stipulate that a page should have a "new section"
3705 # link added via __NEWSECTIONLINK__
3706 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3707 $this->mOutput
->setNewSection( true );
3710 # Allow user to remove the "new section"
3711 # link via __NONEWSECTIONLINK__
3712 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3713 $this->mOutput
->hideNewSection( true );
3716 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3717 # override above conditions and always show TOC above first header
3718 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3719 $this->mShowToc
= true;
3723 # We need this to perform operations on the HTML
3724 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3730 # Ugh .. the TOC should have neat indentation levels which can be
3731 # passed to the skin functions. These are determined here
3735 $sublevelCount = array();
3736 $levelCount = array();
3741 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3742 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3743 $oldType = $this->mOutputType
;
3744 $this->setOutputType( self
::OT_WIKI
);
3745 $frame = $this->getPreprocessor()->newFrame();
3746 $root = $this->preprocessToDom( $origText );
3747 $node = $root->getFirstChild();
3752 foreach ( $matches[3] as $headline ) {
3753 $isTemplate = false;
3755 $sectionIndex = false;
3757 $markerMatches = array();
3758 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3759 $serial = $markerMatches[1];
3760 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3761 $isTemplate = ( $titleText != $baseTitleText );
3762 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3766 $prevlevel = $level;
3768 $level = $matches[1][$headlineCount];
3770 if ( $level > $prevlevel ) {
3771 # Increase TOC level
3773 $sublevelCount[$toclevel] = 0;
3774 if ( $toclevel<$wgMaxTocLevel ) {
3775 $prevtoclevel = $toclevel;
3776 $toc .= $sk->tocIndent();
3779 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3780 # Decrease TOC level, find level to jump to
3782 for ( $i = $toclevel; $i > 0; $i-- ) {
3783 if ( $levelCount[$i] == $level ) {
3784 # Found last matching level
3787 } elseif ( $levelCount[$i] < $level ) {
3788 # Found first matching level below current level
3796 if ( $toclevel<$wgMaxTocLevel ) {
3797 if ( $prevtoclevel < $wgMaxTocLevel ) {
3798 # Unindent only if the previous toc level was shown :p
3799 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3800 $prevtoclevel = $toclevel;
3802 $toc .= $sk->tocLineEnd();
3806 # No change in level, end TOC line
3807 if ( $toclevel<$wgMaxTocLevel ) {
3808 $toc .= $sk->tocLineEnd();
3812 $levelCount[$toclevel] = $level;
3814 # count number of headlines for each level
3815 @$sublevelCount[$toclevel]++
;
3817 for( $i = 1; $i <= $toclevel; $i++
) {
3818 if ( !empty( $sublevelCount[$i] ) ) {
3822 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3827 # The safe header is a version of the header text safe to use for links
3828 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3829 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3831 # Remove link placeholders by the link text.
3832 # <!--LINK number-->
3834 # link text with suffix
3835 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3837 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3838 $tocline = preg_replace(
3839 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3840 array( '', '<$1>' ),
3843 $tocline = trim( $tocline );
3845 # For the anchor, strip out HTML-y stuff period
3846 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3847 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3849 # Save headline for section edit hint before it's escaped
3850 $headlineHint = $safeHeadline;
3852 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3853 # For reverse compatibility, provide an id that's
3854 # HTML4-compatible, like we used to.
3856 # It may be worth noting, academically, that it's possible for
3857 # the legacy anchor to conflict with a non-legacy headline
3858 # anchor on the page. In this case likely the "correct" thing
3859 # would be to either drop the legacy anchors or make sure
3860 # they're numbered first. However, this would require people
3861 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3862 # manually, so let's not bother worrying about it.
3863 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3864 array( 'noninitial', 'legacy' ) );
3865 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3867 if ( $legacyHeadline == $safeHeadline ) {
3868 # No reason to have both (in fact, we can't)
3869 $legacyHeadline = false;
3872 $legacyHeadline = false;
3873 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3877 # HTML names must be case-insensitively unique (bug 10721).
3878 # This does not apply to Unicode characters per
3879 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3880 # FIXME: We may be changing them depending on the current locale.
3881 $arrayKey = strtolower( $safeHeadline );
3882 if ( $legacyHeadline === false ) {
3883 $legacyArrayKey = false;
3885 $legacyArrayKey = strtolower( $legacyHeadline );
3888 # count how many in assoc. array so we can track dupes in anchors
3889 if ( isset( $refers[$arrayKey] ) ) {
3890 $refers[$arrayKey]++
;
3892 $refers[$arrayKey] = 1;
3894 if ( isset( $refers[$legacyArrayKey] ) ) {
3895 $refers[$legacyArrayKey]++
;
3897 $refers[$legacyArrayKey] = 1;
3900 # Don't number the heading if it is the only one (looks silly)
3901 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3902 # the two are different if the line contains a link
3903 $headline = $numbering . ' ' . $headline;
3906 # Create the anchor for linking from the TOC to the section
3907 $anchor = $safeHeadline;
3908 $legacyAnchor = $legacyHeadline;
3909 if ( $refers[$arrayKey] > 1 ) {
3910 $anchor .= '_' . $refers[$arrayKey];
3912 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3913 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3915 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3916 $toc .= $sk->tocLine( $anchor, $tocline,
3917 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3920 # Add the section to the section tree
3921 # Find the DOM node for this header
3922 while ( $node && !$isTemplate ) {
3923 if ( $node->getName() === 'h' ) {
3924 $bits = $node->splitHeading();
3925 if ( $bits['i'] == $sectionIndex ) {
3929 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3930 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3931 $node = $node->getNextSibling();
3934 'toclevel' => $toclevel,
3937 'number' => $numbering,
3938 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3939 'fromtitle' => $titleText,
3940 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3941 'anchor' => $anchor,
3944 # give headline the correct <h#> tag
3945 if ( $showEditLink && $sectionIndex !== false ) {
3946 // Output edit section links as markers with styles that can be customized by skins
3947 if ( $isTemplate ) {
3948 # Put a T flag in the section identifier, to indicate to extractSections()
3949 # that sections inside <includeonly> should be counted.
3950 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3952 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3954 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3955 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3956 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3957 // so we don't have to worry about a user trying to input one of these markers directly.
3958 // We use a page and section attribute to stop the language converter from converting these important bits
3959 // of data, but put the headline hint inside a content block because the language converter is supposed to
3960 // be able to convert that piece of data.
3961 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
3962 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3963 if ( isset($editlinkArgs[2]) ) {
3964 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
3971 $head[$headlineCount] = $sk->makeHeadline( $level,
3972 $matches['attrib'][$headlineCount], $anchor, $headline,
3973 $editlink, $legacyAnchor );
3978 $this->setOutputType( $oldType );
3980 # Never ever show TOC if no headers
3981 if ( $numVisible < 1 ) {
3986 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3987 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3989 $toc = $sk->tocList( $toc );
3990 $this->mOutput
->setTOCHTML( $toc );
3994 $this->mOutput
->setSections( $tocraw );
3997 # split up and insert constructed headlines
3999 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4002 foreach ( $blocks as $block ) {
4003 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4004 # This is the [edit] link that appears for the top block of text when
4005 # section editing is enabled
4007 # Disabled because it broke block formatting
4008 # For example, a bullet point in the top line
4009 # $full .= $sk->editSectionLink(0);
4012 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4013 # Top anchor now in skin
4017 if ( !empty( $head[$i] ) ) {
4022 if ( $this->mForceTocPosition
) {
4023 return str_replace( '<!--MWTOC-->', $toc, $full );
4030 * Transform wiki markup when saving a page by doing \r\n -> \n
4031 * conversion, substitting signatures, {{subst:}} templates, etc.
4033 * @param $text String: the text to transform
4034 * @param $title Title: the Title object for the current article
4035 * @param $user User: the User object describing the current user
4036 * @param $options ParserOptions: parsing options
4037 * @param $clearState Boolean: whether to clear the parser state first
4038 * @return String: the altered wiki markup
4040 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4041 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4042 $this->setUser( $user );
4047 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4048 if( $options->getPreSaveTransform() ) {
4049 $text = $this->pstPass2( $text, $user );
4051 $text = $this->mStripState
->unstripBoth( $text );
4053 $this->setUser( null ); #Reset
4059 * Pre-save transform helper function
4062 function pstPass2( $text, $user ) {
4063 global $wgContLang, $wgLocaltimezone;
4065 # Note: This is the timestamp saved as hardcoded wikitext to
4066 # the database, we use $wgContLang here in order to give
4067 # everyone the same signature and use the default one rather
4068 # than the one selected in each user's preferences.
4069 # (see also bug 12815)
4070 $ts = $this->mOptions
->getTimestamp();
4071 if ( isset( $wgLocaltimezone ) ) {
4072 $tz = $wgLocaltimezone;
4074 $tz = date_default_timezone_get();
4077 $unixts = wfTimestamp( TS_UNIX
, $ts );
4078 $oldtz = date_default_timezone_get();
4079 date_default_timezone_set( $tz );
4080 $ts = date( 'YmdHis', $unixts );
4081 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4083 # Allow translation of timezones through wiki. date() can return
4084 # whatever crap the system uses, localised or not, so we cannot
4085 # ship premade translations.
4086 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4087 $msg = wfMessage( $key )->inContentLanguage();
4088 if ( $msg->exists() ) {
4089 $tzMsg = $msg->text();
4092 date_default_timezone_set( $oldtz );
4094 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4096 # Variable replacement
4097 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4098 $text = $this->replaceVariables( $text );
4100 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4101 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4104 $sigText = $this->getUserSig( $user );
4105 $text = strtr( $text, array(
4107 '~~~~' => "$sigText $d",
4111 # Context links: [[|name]] and [[name (context)|]]
4112 global $wgLegalTitleChars;
4113 $tc = "[$wgLegalTitleChars]";
4114 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4116 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4117 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4118 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4119 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4121 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4122 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4123 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4124 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4126 $t = $this->mTitle
->getText();
4128 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4129 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4130 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4131 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4133 # if there's no context, don't bother duplicating the title
4134 $text = preg_replace( $p2, '[[\\1]]', $text );
4137 # Trim trailing whitespace
4138 $text = rtrim( $text );
4144 * Fetch the user's signature text, if any, and normalize to
4145 * validated, ready-to-insert wikitext.
4146 * If you have pre-fetched the nickname or the fancySig option, you can
4147 * specify them here to save a database query.
4148 * Do not reuse this parser instance after calling getUserSig(),
4149 * as it may have changed if it's the $wgParser.
4152 * @param $nickname String: nickname to use or false to use user's default nickname
4153 * @param $fancySig Boolean: whether the nicknname is the complete signature
4154 * or null to use default value
4157 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4158 global $wgMaxSigChars;
4160 $username = $user->getName();
4162 # If not given, retrieve from the user object.
4163 if ( $nickname === false )
4164 $nickname = $user->getOption( 'nickname' );
4166 if ( is_null( $fancySig ) ) {
4167 $fancySig = $user->getBoolOption( 'fancysig' );
4170 $nickname = $nickname == null ?
$username : $nickname;
4172 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4173 $nickname = $username;
4174 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4175 } elseif ( $fancySig !== false ) {
4176 # Sig. might contain markup; validate this
4177 if ( $this->validateSig( $nickname ) !== false ) {
4178 # Validated; clean up (if needed) and return it
4179 return $this->cleanSig( $nickname, true );
4181 # Failed to validate; fall back to the default
4182 $nickname = $username;
4183 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4187 # Make sure nickname doesnt get a sig in a sig
4188 $nickname = $this->cleanSigInSig( $nickname );
4190 # If we're still here, make it a link to the user page
4191 $userText = wfEscapeWikiText( $username );
4192 $nickText = wfEscapeWikiText( $nickname );
4193 if ( $user->isAnon() ) {
4194 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4196 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4201 * Check that the user's signature contains no bad XML
4203 * @param $text String
4204 * @return mixed An expanded string, or false if invalid.
4206 function validateSig( $text ) {
4207 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4211 * Clean up signature text
4213 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4214 * 2) Substitute all transclusions
4216 * @param $text String
4217 * @param $parsing Whether we're cleaning (preferences save) or parsing
4218 * @return String: signature text
4220 function cleanSig( $text, $parsing = false ) {
4223 $this->mOptions
= new ParserOptions
;
4224 $this->clearState();
4225 $this->setTitle( $wgTitle );
4226 $this->setOutputType
= self
::OT_PREPROCESS
;
4229 # Option to disable this feature
4230 if ( !$this->mOptions
->getCleanSignatures() ) {
4234 # FIXME: regex doesn't respect extension tags or nowiki
4235 # => Move this logic to braceSubstitution()
4236 $substWord = MagicWord
::get( 'subst' );
4237 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4238 $substText = '{{' . $substWord->getSynonym( 0 );
4240 $text = preg_replace( $substRegex, $substText, $text );
4241 $text = $this->cleanSigInSig( $text );
4242 $dom = $this->preprocessToDom( $text );
4243 $frame = $this->getPreprocessor()->newFrame();
4244 $text = $frame->expand( $dom );
4247 $text = $this->mStripState
->unstripBoth( $text );
4254 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4256 * @param $text String
4257 * @return String: signature text with /~{3,5}/ removed
4259 function cleanSigInSig( $text ) {
4260 $text = preg_replace( '/~{3,5}/', '', $text );
4265 * Set up some variables which are usually set up in parse()
4266 * so that an external function can call some class members with confidence
4268 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4269 $this->startParse( $title, $options, $outputType, $clearState );
4272 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4273 $this->setTitle( $title );
4274 $this->mOptions
= $options;
4275 $this->setOutputType( $outputType );
4276 if ( $clearState ) {
4277 $this->clearState();
4282 * Wrapper for preprocess()
4284 * @param $text String: the text to preprocess
4285 * @param $options ParserOptions: options
4286 * @param $title Title object or null to use $wgTitle
4289 public function transformMsg( $text, $options, $title = null ) {
4290 static $executing = false;
4292 # Guard against infinite recursion
4298 wfProfileIn( __METHOD__
);
4304 # It's not uncommon having a null $wgTitle in scripts. See r80898
4305 # Create a ghost title in such case
4306 $title = Title
::newFromText( 'Dwimmerlaik' );
4308 $text = $this->preprocess( $text, $title, $options );
4311 wfProfileOut( __METHOD__
);
4316 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4317 * The callback should have the following form:
4318 * function myParserHook( $text, $params, $parser ) { ... }
4320 * Transform and return $text. Use $parser for any required context, e.g. use
4321 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4323 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4324 * @param $callback Mixed: the callback function (and object) to use for the tag
4325 * @return The old value of the mTagHooks array associated with the hook
4327 public function setHook( $tag, $callback ) {
4328 $tag = strtolower( $tag );
4329 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4330 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4331 $this->mTagHooks
[$tag] = $callback;
4332 if ( !in_array( $tag, $this->mStripList
) ) {
4333 $this->mStripList
[] = $tag;
4339 function setTransparentTagHook( $tag, $callback ) {
4340 $tag = strtolower( $tag );
4341 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4342 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4343 $this->mTransparentTagHooks
[$tag] = $callback;
4349 * Remove all tag hooks
4351 function clearTagHooks() {
4352 $this->mTagHooks
= array();
4353 $this->mStripList
= $this->mDefaultStripList
;
4357 * Create a function, e.g. {{sum:1|2|3}}
4358 * The callback function should have the form:
4359 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4361 * Or with SFH_OBJECT_ARGS:
4362 * function myParserFunction( $parser, $frame, $args ) { ... }
4364 * The callback may either return the text result of the function, or an array with the text
4365 * in element 0, and a number of flags in the other elements. The names of the flags are
4366 * specified in the keys. Valid flags are:
4367 * found The text returned is valid, stop processing the template. This
4369 * nowiki Wiki markup in the return value should be escaped
4370 * isHTML The returned text is HTML, armour it against wikitext transformation
4372 * @param $id String: The magic word ID
4373 * @param $callback Mixed: the callback function (and object) to use
4374 * @param $flags Integer: a combination of the following flags:
4375 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4377 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4378 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4379 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4380 * the arguments, and to control the way they are expanded.
4382 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4383 * arguments, for instance:
4384 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4386 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4387 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4388 * working if/when this is changed.
4390 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4393 * Please read the documentation in includes/parser/Preprocessor.php for more information
4394 * about the methods available in PPFrame and PPNode.
4396 * @return The old callback function for this name, if any
4398 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4401 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4402 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4404 # Add to function cache
4405 $mw = MagicWord
::get( $id );
4407 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4409 $synonyms = $mw->getSynonyms();
4410 $sensitive = intval( $mw->isCaseSensitive() );
4412 foreach ( $synonyms as $syn ) {
4414 if ( !$sensitive ) {
4415 $syn = $wgContLang->lc( $syn );
4418 if ( !( $flags & SFH_NO_HASH
) ) {
4421 # Remove trailing colon
4422 if ( substr( $syn, -1, 1 ) === ':' ) {
4423 $syn = substr( $syn, 0, -1 );
4425 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4431 * Get all registered function hook identifiers
4435 function getFunctionHooks() {
4436 return array_keys( $this->mFunctionHooks
);
4440 * Create a tag function, e.g. <test>some stuff</test>.
4441 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4442 * Unlike parser functions, their content is not preprocessed.
4444 function setFunctionTagHook( $tag, $callback, $flags ) {
4445 $tag = strtolower( $tag );
4446 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4447 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4448 $this->mFunctionTagHooks
[$tag] : null;
4449 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4451 if ( !in_array( $tag, $this->mStripList
) ) {
4452 $this->mStripList
[] = $tag;
4459 * FIXME: update documentation. makeLinkObj() is deprecated.
4460 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4461 * Placeholders created in Skin::makeLinkObj()
4462 * Returns an array of link CSS classes, indexed by PDBK.
4464 function replaceLinkHolders( &$text, $options = 0 ) {
4465 return $this->mLinkHolders
->replace( $text );
4469 * Replace <!--LINK--> link placeholders with plain text of links
4470 * (not HTML-formatted).
4472 * @param $text String
4475 function replaceLinkHoldersText( $text ) {
4476 return $this->mLinkHolders
->replaceText( $text );
4480 * Renders an image gallery from a text with one line per image.
4481 * text labels may be given by using |-style alternative text. E.g.
4482 * Image:one.jpg|The number "1"
4483 * Image:tree.jpg|A tree
4484 * given as text will return the HTML of a gallery with two images,
4485 * labeled 'The number "1"' and
4488 function renderImageGallery( $text, $params ) {
4489 $ig = new ImageGallery();
4490 $ig->setContextTitle( $this->mTitle
);
4491 $ig->setShowBytes( false );
4492 $ig->setShowFilename( false );
4493 $ig->setParser( $this );
4494 $ig->setHideBadImages();
4495 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4496 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4497 $ig->mRevisionId
= $this->mRevisionId
;
4499 if ( isset( $params['showfilename'] ) ) {
4500 $ig->setShowFilename( true );
4502 $ig->setShowFilename( false );
4504 if ( isset( $params['caption'] ) ) {
4505 $caption = $params['caption'];
4506 $caption = htmlspecialchars( $caption );
4507 $caption = $this->replaceInternalLinks( $caption );
4508 $ig->setCaptionHtml( $caption );
4510 if ( isset( $params['perrow'] ) ) {
4511 $ig->setPerRow( $params['perrow'] );
4513 if ( isset( $params['widths'] ) ) {
4514 $ig->setWidths( $params['widths'] );
4516 if ( isset( $params['heights'] ) ) {
4517 $ig->setHeights( $params['heights'] );
4520 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4522 $lines = StringUtils
::explode( "\n", $text );
4523 foreach ( $lines as $line ) {
4524 # match lines like these:
4525 # Image:someimage.jpg|This is some image
4527 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4529 if ( count( $matches ) == 0 ) {
4533 if ( strpos( $matches[0], '%' ) !== false ) {
4534 $matches[1] = rawurldecode( $matches[1] );
4536 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4538 if ( is_null( $nt ) ) {
4539 # Bogus title. Ignore these so we don't bomb out later.
4542 if ( isset( $matches[3] ) ) {
4543 $label = $matches[3];
4548 $html = $this->recursiveTagParse( trim( $label ) );
4550 $ig->add( $nt, $html );
4552 # Only add real images (bug #5586)
4553 if ( $nt->getNamespace() == NS_FILE
) {
4554 $this->mOutput
->addImage( $nt->getDBkey() );
4557 return $ig->toHTML();
4560 function getImageParams( $handler ) {
4562 $handlerClass = get_class( $handler );
4566 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4567 # Initialise static lists
4568 static $internalParamNames = array(
4569 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4570 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4571 'bottom', 'text-bottom' ),
4572 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4573 'upright', 'border', 'link', 'alt' ),
4575 static $internalParamMap;
4576 if ( !$internalParamMap ) {
4577 $internalParamMap = array();
4578 foreach ( $internalParamNames as $type => $names ) {
4579 foreach ( $names as $name ) {
4580 $magicName = str_replace( '-', '_', "img_$name" );
4581 $internalParamMap[$magicName] = array( $type, $name );
4586 # Add handler params
4587 $paramMap = $internalParamMap;
4589 $handlerParamMap = $handler->getParamMap();
4590 foreach ( $handlerParamMap as $magic => $paramName ) {
4591 $paramMap[$magic] = array( 'handler', $paramName );
4594 $this->mImageParams
[$handlerClass] = $paramMap;
4595 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4597 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4601 * Parse image options text and use it to make an image
4603 * @param $title Title
4604 * @param $options String
4605 * @param $holders LinkHolderArray
4607 function makeImage( $title, $options, $holders = false ) {
4608 # Check if the options text is of the form "options|alt text"
4610 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4611 # * left no resizing, just left align. label is used for alt= only
4612 # * right same, but right aligned
4613 # * none same, but not aligned
4614 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4615 # * center center the image
4616 # * frame Keep original image size, no magnify-button.
4617 # * framed Same as "frame"
4618 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4619 # * upright reduce width for upright images, rounded to full __0 px
4620 # * border draw a 1px border around the image
4621 # * alt Text for HTML alt attribute (defaults to empty)
4622 # * link Set the target of the image link. Can be external, interwiki, or local
4623 # vertical-align values (no % or length right now):
4633 $parts = StringUtils
::explode( "|", $options );
4634 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4636 # Give extensions a chance to select the file revision for us
4637 $skip = $time = $descQuery = false;
4638 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4641 return $sk->link( $title );
4645 $file = wfFindFile( $title, array( 'time' => $time ) );
4647 $handler = $file ?
$file->getHandler() : false;
4649 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4651 # Process the input parameters
4653 $params = array( 'frame' => array(), 'handler' => array(),
4654 'horizAlign' => array(), 'vertAlign' => array() );
4655 foreach ( $parts as $part ) {
4656 $part = trim( $part );
4657 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4659 if ( isset( $paramMap[$magicName] ) ) {
4660 list( $type, $paramName ) = $paramMap[$magicName];
4662 # Special case; width and height come in one variable together
4663 if ( $type === 'handler' && $paramName === 'width' ) {
4665 # (bug 13500) In both cases (width/height and width only),
4666 # permit trailing "px" for backward compatibility.
4667 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4668 $width = intval( $m[1] );
4669 $height = intval( $m[2] );
4670 if ( $handler->validateParam( 'width', $width ) ) {
4671 $params[$type]['width'] = $width;
4674 if ( $handler->validateParam( 'height', $height ) ) {
4675 $params[$type]['height'] = $height;
4678 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4679 $width = intval( $value );
4680 if ( $handler->validateParam( 'width', $width ) ) {
4681 $params[$type]['width'] = $width;
4684 } # else no validation -- bug 13436
4686 if ( $type === 'handler' ) {
4687 # Validate handler parameter
4688 $validated = $handler->validateParam( $paramName, $value );
4690 # Validate internal parameters
4691 switch( $paramName ) {
4694 # @todo Fixme: possibly check validity here for
4695 # manualthumb? downstream behavior seems odd with
4696 # missing manual thumbs.
4698 $value = $this->stripAltText( $value, $holders );
4701 $chars = self
::EXT_LINK_URL_CLASS
;
4702 $prots = $this->mUrlProtocols
;
4703 if ( $value === '' ) {
4704 $paramName = 'no-link';
4707 } elseif ( preg_match( "/^$prots/", $value ) ) {
4708 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4709 $paramName = 'link-url';
4710 $this->mOutput
->addExternalLink( $value );
4711 if ( $this->mOptions
->getExternalLinkTarget() ) {
4712 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4717 $linkTitle = Title
::newFromText( $value );
4719 $paramName = 'link-title';
4720 $value = $linkTitle;
4721 $this->mOutput
->addLink( $linkTitle );
4727 # Most other things appear to be empty or numeric...
4728 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4733 $params[$type][$paramName] = $value;
4737 if ( !$validated ) {
4742 # Process alignment parameters
4743 if ( $params['horizAlign'] ) {
4744 $params['frame']['align'] = key( $params['horizAlign'] );
4746 if ( $params['vertAlign'] ) {
4747 $params['frame']['valign'] = key( $params['vertAlign'] );
4750 $params['frame']['caption'] = $caption;
4752 # Will the image be presented in a frame, with the caption below?
4753 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4754 isset( $params['frame']['framed'] ) ||
4755 isset( $params['frame']['thumbnail'] ) ||
4756 isset( $params['frame']['manualthumb'] );
4758 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4759 # came to also set the caption, ordinary text after the image -- which
4760 # makes no sense, because that just repeats the text multiple times in
4761 # screen readers. It *also* came to set the title attribute.
4763 # Now that we have an alt attribute, we should not set the alt text to
4764 # equal the caption: that's worse than useless, it just repeats the
4765 # text. This is the framed/thumbnail case. If there's no caption, we
4766 # use the unnamed parameter for alt text as well, just for the time be-
4767 # ing, if the unnamed param is set and the alt param is not.
4769 # For the future, we need to figure out if we want to tweak this more,
4770 # e.g., introducing a title= parameter for the title; ignoring the un-
4771 # named parameter entirely for images without a caption; adding an ex-
4772 # plicit caption= parameter and preserving the old magic unnamed para-
4774 if ( $imageIsFramed ) { # Framed image
4775 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4776 # No caption or alt text, add the filename as the alt text so
4777 # that screen readers at least get some description of the image
4778 $params['frame']['alt'] = $title->getText();
4780 # Do not set $params['frame']['title'] because tooltips don't make sense
4782 } else { # Inline image
4783 if ( !isset( $params['frame']['alt'] ) ) {
4784 # No alt text, use the "caption" for the alt text
4785 if ( $caption !== '') {
4786 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4788 # No caption, fall back to using the filename for the
4790 $params['frame']['alt'] = $title->getText();
4793 # Use the "caption" for the tooltip text
4794 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4797 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4799 # Linker does the rest
4800 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4802 # Give the handler a chance to modify the parser object
4804 $handler->parserTransformHook( $this, $file );
4810 protected function stripAltText( $caption, $holders ) {
4811 # Strip bad stuff out of the title (tooltip). We can't just use
4812 # replaceLinkHoldersText() here, because if this function is called
4813 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4815 $tooltip = $holders->replaceText( $caption );
4817 $tooltip = $this->replaceLinkHoldersText( $caption );
4820 # make sure there are no placeholders in thumbnail attributes
4821 # that are later expanded to html- so expand them now and
4823 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4824 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4830 * Set a flag in the output object indicating that the content is dynamic and
4831 * shouldn't be cached.
4833 function disableCache() {
4834 wfDebug( "Parser output marked as uncacheable.\n" );
4835 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4836 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4840 * Callback from the Sanitizer for expanding items found in HTML attribute
4841 * values, so they can be safely tested and escaped.
4843 * @param $text String
4844 * @param $frame PPFrame
4848 function attributeStripCallback( &$text, $frame = false ) {
4849 $text = $this->replaceVariables( $text, $frame );
4850 $text = $this->mStripState
->unstripBoth( $text );
4857 function getTags() {
4858 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4862 * Break wikitext input into sections, and either pull or replace
4863 * some particular section's text.
4865 * External callers should use the getSection and replaceSection methods.
4867 * @param $text String: Page wikitext
4868 * @param $section String: a section identifier string of the form:
4869 * <flag1> - <flag2> - ... - <section number>
4871 * Currently the only recognised flag is "T", which means the target section number
4872 * was derived during a template inclusion parse, in other words this is a template
4873 * section edit link. If no flags are given, it was an ordinary section edit link.
4874 * This flag is required to avoid a section numbering mismatch when a section is
4875 * enclosed by <includeonly> (bug 6563).
4877 * The section number 0 pulls the text before the first heading; other numbers will
4878 * pull the given section along with its lower-level subsections. If the section is
4879 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4881 * @param $mode String: one of "get" or "replace"
4882 * @param $newText String: replacement text for section data.
4883 * @return String: for "get", the extracted section text.
4884 * for "replace", the whole page with the section replaced.
4886 private function extractSections( $text, $section, $mode, $newText='' ) {
4887 global $wgTitle; # not generally used but removes an ugly failure mode
4888 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4890 $frame = $this->getPreprocessor()->newFrame();
4892 # Process section extraction flags
4894 $sectionParts = explode( '-', $section );
4895 $sectionIndex = array_pop( $sectionParts );
4896 foreach ( $sectionParts as $part ) {
4897 if ( $part === 'T' ) {
4898 $flags |
= self
::PTD_FOR_INCLUSION
;
4901 # Preprocess the text
4902 $root = $this->preprocessToDom( $text, $flags );
4904 # <h> nodes indicate section breaks
4905 # They can only occur at the top level, so we can find them by iterating the root's children
4906 $node = $root->getFirstChild();
4908 # Find the target section
4909 if ( $sectionIndex == 0 ) {
4910 # Section zero doesn't nest, level=big
4911 $targetLevel = 1000;
4914 if ( $node->getName() === 'h' ) {
4915 $bits = $node->splitHeading();
4916 if ( $bits['i'] == $sectionIndex ) {
4917 $targetLevel = $bits['level'];
4921 if ( $mode === 'replace' ) {
4922 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4924 $node = $node->getNextSibling();
4930 if ( $mode === 'get' ) {
4937 # Find the end of the section, including nested sections
4939 if ( $node->getName() === 'h' ) {
4940 $bits = $node->splitHeading();
4941 $curLevel = $bits['level'];
4942 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4946 if ( $mode === 'get' ) {
4947 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4949 $node = $node->getNextSibling();
4952 # Write out the remainder (in replace mode only)
4953 if ( $mode === 'replace' ) {
4954 # Output the replacement text
4955 # Add two newlines on -- trailing whitespace in $newText is conventionally
4956 # stripped by the editor, so we need both newlines to restore the paragraph gap
4957 # Only add trailing whitespace if there is newText
4958 if ( $newText != "" ) {
4959 $outText .= $newText . "\n\n";
4963 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4964 $node = $node->getNextSibling();
4968 if ( is_string( $outText ) ) {
4969 # Re-insert stripped tags
4970 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4977 * This function returns the text of a section, specified by a number ($section).
4978 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4979 * the first section before any such heading (section 0).
4981 * If a section contains subsections, these are also returned.
4983 * @param $text String: text to look in
4984 * @param $section String: section identifier
4985 * @param $deftext String: default to return if section is not found
4986 * @return string text of the requested section
4988 public function getSection( $text, $section, $deftext='' ) {
4989 return $this->extractSections( $text, $section, "get", $deftext );
4993 * This function returns $oldtext after the content of the section
4994 * specified by $section has been replaced with $text.
4996 * @param $text String: former text of the article
4997 * @param $section Numeric: section identifier
4998 * @param $text String: replacing text
4999 * #return String: modified text
5001 public function replaceSection( $oldtext, $section, $text ) {
5002 return $this->extractSections( $oldtext, $section, "replace", $text );
5006 * Get the ID of the revision we are parsing
5008 * @return Mixed: integer or null
5010 function getRevisionId() {
5011 return $this->mRevisionId
;
5015 * Get the revision object for $this->mRevisionId
5017 * @return either a Revision object or null
5019 protected function getRevisionObject() {
5020 if ( !is_null( $this->mRevisionObject
) ) {
5021 return $this->mRevisionObject
;
5023 if ( is_null( $this->mRevisionId
) ) {
5027 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5028 return $this->mRevisionObject
;
5032 * Get the timestamp associated with the current revision, adjusted for
5033 * the default server-local timestamp
5035 function getRevisionTimestamp() {
5036 if ( is_null( $this->mRevisionTimestamp
) ) {
5037 wfProfileIn( __METHOD__
);
5039 $revObject = $this->getRevisionObject();
5040 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5042 if( $timestamp !== false ) {
5045 # The cryptic '' timezone parameter tells to use the site-default
5046 # timezone offset instead of the user settings.
5048 # Since this value will be saved into the parser cache, served
5049 # to other users, and potentially even used inside links and such,
5050 # it needs to be consistent for all visitors.
5051 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5054 wfProfileOut( __METHOD__
);
5056 return $this->mRevisionTimestamp
;
5060 * Get the name of the user that edited the last revision
5062 * @return String: user name
5064 function getRevisionUser() {
5065 if( is_null( $this->mRevisionUser
) ) {
5066 $revObject = $this->getRevisionObject();
5068 # if this template is subst: the revision id will be blank,
5069 # so just use the current user's name
5071 $this->mRevisionUser
= $revObject->getUserText();
5072 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5073 $this->mRevisionUser
= $this->getUser()->getName();
5076 return $this->mRevisionUser
;
5080 * Mutator for $mDefaultSort
5082 * @param $sort New value
5084 public function setDefaultSort( $sort ) {
5085 $this->mDefaultSort
= $sort;
5086 $this->mOutput
->setProperty( 'defaultsort', $sort );
5090 * Accessor for $mDefaultSort
5091 * Will use the empty string if none is set.
5093 * This value is treated as a prefix, so the
5094 * empty string is equivalent to sorting by
5099 public function getDefaultSort() {
5100 if ( $this->mDefaultSort
!== false ) {
5101 return $this->mDefaultSort
;
5108 * Accessor for $mDefaultSort
5109 * Unlike getDefaultSort(), will return false if none is set
5111 * @return string or false
5113 public function getCustomDefaultSort() {
5114 return $this->mDefaultSort
;
5118 * Try to guess the section anchor name based on a wikitext fragment
5119 * presumably extracted from a heading, for example "Header" from
5122 public function guessSectionNameFromWikiText( $text ) {
5123 # Strip out wikitext links(they break the anchor)
5124 $text = $this->stripSectionName( $text );
5125 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5126 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5130 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5131 * instead. For use in redirects, since IE6 interprets Redirect: headers
5132 * as something other than UTF-8 (apparently?), resulting in breakage.
5134 * @param $text String: The section name
5135 * @return string An anchor
5137 public function guessLegacySectionNameFromWikiText( $text ) {
5138 # Strip out wikitext links(they break the anchor)
5139 $text = $this->stripSectionName( $text );
5140 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5141 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5145 * Strips a text string of wikitext for use in a section anchor
5147 * Accepts a text string and then removes all wikitext from the
5148 * string and leaves only the resultant text (i.e. the result of
5149 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5150 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5151 * to create valid section anchors by mimicing the output of the
5152 * parser when headings are parsed.
5154 * @param $text String: text string to be stripped of wikitext
5155 * for use in a Section anchor
5156 * @return Filtered text string
5158 public function stripSectionName( $text ) {
5159 # Strip internal link markup
5160 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5161 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5163 # Strip external link markup (FIXME: Not Tolerant to blank link text
5164 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5165 # on how many empty links there are on the page - need to figure that out.
5166 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5168 # Parse wikitext quotes (italics & bold)
5169 $text = $this->doQuotes( $text );
5172 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5177 * strip/replaceVariables/unstrip for preprocessor regression testing
5179 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5180 if ( !$title instanceof Title
) {
5181 $title = Title
::newFromText( $title );
5183 $this->startParse( $title, $options, $outputType, true );
5185 $text = $this->replaceVariables( $text );
5186 $text = $this->mStripState
->unstripBoth( $text );
5187 $text = Sanitizer
::removeHTMLtags( $text );
5191 function testPst( $text, $title, $options ) {
5193 if ( !$title instanceof Title
) {
5194 $title = Title
::newFromText( $title );
5196 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5199 function testPreprocess( $text, $title, $options ) {
5200 if ( !$title instanceof Title
) {
5201 $title = Title
::newFromText( $title );
5203 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5206 function markerSkipCallback( $s, $callback ) {
5209 while ( $i < strlen( $s ) ) {
5210 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5211 if ( $markerStart === false ) {
5212 $out .= call_user_func( $callback, substr( $s, $i ) );
5215 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5216 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5217 if ( $markerEnd === false ) {
5218 $out .= substr( $s, $markerStart );
5221 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5222 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5230 function serialiseHalfParsedText( $text ) {
5232 $data['text'] = $text;
5234 # First, find all strip markers, and store their
5236 $stripState = new StripState
;
5238 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5239 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5241 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5242 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5244 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5245 $replaceArray = $stripState->general
;
5246 $stripText = $this->mStripState
->general
->data
[$marker];
5247 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5248 $replaceArray = $stripState->nowiki
;
5249 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5251 throw new MWException( "Hanging strip marker: '$marker'." );
5254 $replaceArray->setPair( $marker, $stripText );
5257 $data['stripstate'] = $stripState;
5259 # Now, find all of our links, and store THEIR
5260 # data in an array! :)
5261 $links = array( 'internal' => array(), 'interwiki' => array() );
5265 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5266 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5269 if ( empty( $links['internal'][$ns] ) ) {
5270 $links['internal'][$ns] = array();
5273 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5274 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5275 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5281 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5282 $data = substr( $text, $start_pos );
5283 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5284 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5285 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5288 $data['linkholder'] = $links;
5295 * @param $data Array
5296 * @param $intPrefix String unique identifying prefix
5299 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5300 if ( !$intPrefix ) {
5301 $intPrefix = self
::getRandomString();
5304 # First, extract the strip state.
5305 $stripState = $data['stripstate'];
5306 $this->mStripState
->general
->merge( $stripState->general
);
5307 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5309 # Now, extract the text, and renumber links
5310 $text = $data['text'];
5311 $links = $data['linkholder'];
5314 foreach ( $links['internal'] as $ns => $nsLinks ) {
5315 foreach ( $nsLinks as $key => $entry ) {
5316 $newKey = $intPrefix . '-' . $key;
5317 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5319 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5324 foreach ( $links['interwiki'] as $key => $entry ) {
5325 $newKey = "$intPrefix-$key";
5326 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5328 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5331 # Should be good to go.
5337 * @todo document, briefly.
5341 var $general, $nowiki;
5343 function __construct() {
5344 $this->general
= new ReplacementArray
;
5345 $this->nowiki
= new ReplacementArray
;
5348 function unstripGeneral( $text ) {
5349 wfProfileIn( __METHOD__
);
5352 $text = $this->general
->replace( $text );
5353 } while ( $text !== $oldText );
5354 wfProfileOut( __METHOD__
);
5358 function unstripNoWiki( $text ) {
5359 wfProfileIn( __METHOD__
);
5362 $text = $this->nowiki
->replace( $text );
5363 } while ( $text !== $oldText );
5364 wfProfileOut( __METHOD__
);
5368 function unstripBoth( $text ) {
5369 wfProfileIn( __METHOD__
);
5372 $text = $this->general
->replace( $text );
5373 $text = $this->nowiki
->replace( $text );
5374 } while ( $text !== $oldText );
5375 wfProfileOut( __METHOD__
);
5381 * @todo document, briefly.
5384 class OnlyIncludeReplacer
{
5387 function replace( $matches ) {
5388 if ( substr( $matches[1], -1 ) === "\n" ) {
5389 $this->output
.= substr( $matches[1], 0, -1 );
5391 $this->output
.= $matches[1];