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 * $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.5';
59 * Update this version number when the output of serialiseHalfParsedText()
60 * changes in an incompatible way
62 const HALF_PARSED_VERSION
= 2;
64 # Flags for Parser::setFunctionHook
65 # Also available as global constants from Defines.php
66 const SFH_NO_HASH
= 1;
67 const SFH_OBJECT_ARGS
= 2;
69 # Constants needed for external link processing
70 # Everything except bracket, space, or control characters
71 const EXT_LINK_URL_CLASS
= '(?:[^\]\[<>"\\x00-\\x20\\x7F]|(?:\[\]))';
72 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
73 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
75 # State constants for the definition list colon extraction
76 const COLON_STATE_TEXT
= 0;
77 const COLON_STATE_TAG
= 1;
78 const COLON_STATE_TAGSTART
= 2;
79 const COLON_STATE_CLOSETAG
= 3;
80 const COLON_STATE_TAGSLASH
= 4;
81 const COLON_STATE_COMMENT
= 5;
82 const COLON_STATE_COMMENTDASH
= 6;
83 const COLON_STATE_COMMENTDASHDASH
= 7;
85 # Flags for preprocessToDom
86 const PTD_FOR_INCLUSION
= 1;
88 # Allowed values for $this->mOutputType
89 # Parameter to startExternalParse().
90 const OT_HTML
= 1; # like parse()
91 const OT_WIKI
= 2; # like preSaveTransform()
92 const OT_PREPROCESS
= 3; # like preprocess()
94 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
96 # Marker Suffix needs to be accessible staticly.
97 const MARKER_SUFFIX
= "-QINU\x7f";
100 var $mTagHooks = array();
101 var $mTransparentTagHooks = array();
102 var $mFunctionHooks = array();
103 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
104 var $mFunctionTagHooks = array();
105 var $mStripList = array();
106 var $mDefaultStripList = array();
107 var $mVarCache = array();
108 var $mImageParams = array();
109 var $mImageParamsMagicArray = array();
110 var $mMarkerIndex = 0;
111 var $mFirstCall = true;
112 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
113 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
115 # Cleared with clearState():
120 var $mAutonumber, $mDTopen;
127 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
128 var $mLinkHolders, $mLinkID;
129 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
130 var $mTplExpandCache; # empty-frame expansion cache
131 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
132 var $mExpensiveFunctionCount; # number of expensive parser function calls
137 var $mUser; # User object; only used when doing pre-save transform
140 # These are variables reset at least once per parse regardless of $clearState
150 var $mTitle; # Title context, used for self-link rendering and similar things
151 var $mOutputType; # Output type, one of the OT_xxx constants
152 var $ot; # Shortcut alias, see setOutputType()
153 var $mRevisionObject; # The revision object of the specified revision ID
154 var $mRevisionId; # ID to display in {{REVISIONID}} tags
155 var $mRevisionTimestamp; # The timestamp of the specified revision ID
156 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
157 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
162 public function __construct( $conf = array() ) {
163 $this->mConf
= $conf;
164 $this->mUrlProtocols
= wfUrlProtocols();
165 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
166 '(?:[^\]\[<>"\x00-\x20\x7F]|\[\])+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
167 if ( isset( $conf['preprocessorClass'] ) ) {
168 $this->mPreprocessorClass
= $conf['preprocessorClass'];
169 } elseif ( extension_loaded( 'domxml' ) ) {
170 # PECL extension that conflicts with the core DOM extension (bug 13770)
171 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
172 $this->mPreprocessorClass
= 'Preprocessor_Hash';
173 } elseif ( extension_loaded( 'dom' ) ) {
174 $this->mPreprocessorClass
= 'Preprocessor_DOM';
176 $this->mPreprocessorClass
= 'Preprocessor_Hash';
181 * Reduce memory usage to reduce the impact of circular references
183 function __destruct() {
184 if ( isset( $this->mLinkHolders
) ) {
185 $this->mLinkHolders
->__destruct();
187 foreach ( $this as $name => $value ) {
188 unset( $this->$name );
193 * Do various kinds of initialisation on the first call of the parser
195 function firstCallInit() {
196 if ( !$this->mFirstCall
) {
199 $this->mFirstCall
= false;
201 wfProfileIn( __METHOD__
);
203 CoreParserFunctions
::register( $this );
204 CoreTagHooks
::register( $this );
205 $this->initialiseVariables();
207 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
208 wfProfileOut( __METHOD__
);
216 function clearState() {
217 wfProfileIn( __METHOD__
);
218 if ( $this->mFirstCall
) {
219 $this->firstCallInit();
221 $this->mOutput
= new ParserOutput
;
222 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
223 $this->mAutonumber
= 0;
224 $this->mLastSection
= '';
225 $this->mDTopen
= false;
226 $this->mIncludeCount
= array();
227 $this->mArgStack
= false;
228 $this->mInPre
= false;
229 $this->mLinkHolders
= new LinkHolderArray( $this );
231 $this->mRevisionObject
= $this->mRevisionTimestamp
=
232 $this->mRevisionId
= $this->mRevisionUser
= null;
233 $this->mVarCache
= array();
237 * Prefix for temporary replacement strings for the multipass parser.
238 * \x07 should never appear in input as it's disallowed in XML.
239 * Using it at the front also gives us a little extra robustness
240 * since it shouldn't match when butted up against identifier-like
243 * Must not consist of all title characters, or else it will change
244 * the behaviour of <nowiki> in a link.
246 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
247 # Changed to \x7f to allow XML double-parsing -- TS
248 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
249 $this->mStripState
= new StripState( $this->mUniqPrefix
);
252 # Clear these on every parse, bug 4549
253 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
255 $this->mShowToc
= true;
256 $this->mForceTocPosition
= false;
257 $this->mIncludeSizes
= array(
261 $this->mPPNodeCount
= 0;
262 $this->mDefaultSort
= false;
263 $this->mHeadings
= array();
264 $this->mDoubleUnderscores
= array();
265 $this->mExpensiveFunctionCount
= 0;
268 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
269 $this->mPreprocessor
= null;
272 wfRunHooks( 'ParserClearState', array( &$this ) );
273 wfProfileOut( __METHOD__
);
277 * Convert wikitext to HTML
278 * Do not call this function recursively.
280 * @param $text String: text we want to parse
281 * @param $title A title object
282 * @param $options ParserOptions
283 * @param $linestart boolean
284 * @param $clearState boolean
285 * @param $revid Int: number to pass in {{REVISIONID}}
286 * @return ParserOutput a ParserOutput
288 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
290 * First pass--just handle <nowiki> sections, pass the rest off
291 * to internalParse() which does all the real work.
294 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
295 $fname = __METHOD__
.'-' . wfGetCaller();
296 wfProfileIn( __METHOD__
);
297 wfProfileIn( $fname );
299 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
301 $oldRevisionId = $this->mRevisionId
;
302 $oldRevisionObject = $this->mRevisionObject
;
303 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
304 $oldRevisionUser = $this->mRevisionUser
;
305 if ( $revid !== null ) {
306 $this->mRevisionId
= $revid;
307 $this->mRevisionObject
= null;
308 $this->mRevisionTimestamp
= null;
309 $this->mRevisionUser
= null;
312 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
314 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
315 $text = $this->internalParse( $text );
317 $text = $this->mStripState
->unstripGeneral( $text );
319 # Clean up special characters, only run once, next-to-last before doBlockLevels
321 # french spaces, last one Guillemet-left
322 # only if there is something before the space
323 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
324 # french spaces, Guillemet-right
325 '/(\\302\\253) /' => '\\1 ',
326 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
328 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
330 $text = $this->doBlockLevels( $text, $linestart );
332 $this->replaceLinkHolders( $text );
335 * The page doesn't get language converted if
337 * b) Content isn't converted
338 * c) It's a conversion table
340 if ( !( $wgDisableLangConversion
341 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
342 ||
$this->mTitle
->isConversionTable() ) ) {
344 # The position of the convert() call should not be changed. it
345 # assumes that the links are all replaced and the only thing left
346 # is the <nowiki> mark.
348 $text = $wgContLang->convert( $text );
352 * A converted title will be provided in the output object if title and
353 * content conversion are enabled, the article text does not contain
354 * a conversion-suppressing double-underscore tag, and no
355 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
356 * automatic link conversion.
358 if ( !( $wgDisableLangConversion
359 ||
$wgDisableTitleConversion
360 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
361 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
362 ||
$this->mOutput
->getDisplayTitle() !== false ) )
364 $convruletitle = $wgContLang->getConvRuleTitle();
365 if ( $convruletitle ) {
366 $this->mOutput
->setTitleText( $convruletitle );
368 $titleText = $wgContLang->convertTitle( $title );
369 $this->mOutput
->setTitleText( $titleText );
373 $text = $this->mStripState
->unstripNoWiki( $text );
375 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
377 $text = $this->replaceTransparentTags( $text );
378 $text = $this->mStripState
->unstripGeneral( $text );
380 $text = Sanitizer
::normalizeCharReferences( $text );
382 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
383 $text = MWTidy
::tidy( $text );
385 # attempt to sanitize at least some nesting problems
386 # (bug #2702 and quite a few others)
388 # ''Something [http://www.cool.com cool''] -->
389 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
390 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
391 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
392 # fix up an anchor inside another anchor, only
393 # at least for a single single nested link (bug 3695)
394 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
395 '\\1\\2</a>\\3</a>\\1\\4</a>',
396 # fix div inside inline elements- doBlockLevels won't wrap a line which
397 # contains a div, so fix it up here; replace
398 # div with escaped text
399 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
400 '\\1\\3<div\\5>\\6</div>\\8\\9',
401 # remove empty italic or bold tag pairs, some
402 # introduced by rules above
403 '/<([bi])><\/\\1>/' => '',
406 $text = preg_replace(
407 array_keys( $tidyregs ),
408 array_values( $tidyregs ),
411 global $wgExpensiveParserFunctionLimit;
412 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
413 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
416 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
418 # Information on include size limits, for the benefit of users who try to skirt them
419 if ( $this->mOptions
->getEnableLimitReport() ) {
420 $max = $this->mOptions
->getMaxIncludeSize();
421 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
423 "NewPP limit report\n" .
424 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
425 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
426 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
428 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
429 $text .= "\n<!-- \n$limitReport-->\n";
431 $this->mOutput
->setText( $text );
433 $this->mRevisionId
= $oldRevisionId;
434 $this->mRevisionObject
= $oldRevisionObject;
435 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
436 $this->mRevisionUser
= $oldRevisionUser;
437 wfProfileOut( $fname );
438 wfProfileOut( __METHOD__
);
440 return $this->mOutput
;
444 * Recursive parser entry point that can be called from an extension tag
447 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
449 * @param $text String: text extension wants to have parsed
450 * @param $frame PPFrame: The frame to use for expanding any template variables
452 function recursiveTagParse( $text, $frame=false ) {
453 wfProfileIn( __METHOD__
);
454 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
455 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
456 $text = $this->internalParse( $text, false, $frame );
457 wfProfileOut( __METHOD__
);
462 * Expand templates and variables in the text, producing valid, static wikitext.
463 * Also removes comments.
465 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
466 wfProfileIn( __METHOD__
);
467 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
468 if ( $revid !== null ) {
469 $this->mRevisionId
= $revid;
471 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
472 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
473 $text = $this->replaceVariables( $text );
474 $text = $this->mStripState
->unstripBoth( $text );
475 wfProfileOut( __METHOD__
);
480 * Process the wikitext for the ?preload= feature. (bug 5210)
482 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
483 * comments, templates, arguments, tags hooks and parser functions are untouched.
485 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
486 # Parser (re)initialisation
487 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
489 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
490 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
491 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
492 $text = $this->mStripState
->unstripBoth( $text );
497 * Get a random string
501 static public function getRandomString() {
502 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
506 * Set the current user.
507 * Should only be used when doing pre-save transform.
509 * @param $user Mixed: User object or null (to reset)
511 function setUser( $user ) {
512 $this->mUser
= $user;
516 * Accessor for mUniqPrefix.
520 public function uniqPrefix() {
521 if ( !isset( $this->mUniqPrefix
) ) {
522 # @todo Fixme: this is probably *horribly wrong*
523 # LanguageConverter seems to want $wgParser's uniqPrefix, however
524 # if this is called for a parser cache hit, the parser may not
525 # have ever been initialized in the first place.
526 # Not really sure what the heck is supposed to be going on here.
528 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
530 return $this->mUniqPrefix
;
534 * Set the context title
536 function setTitle( $t ) {
537 if ( !$t ||
$t instanceof FakeTitle
) {
538 $t = Title
::newFromText( 'NO TITLE' );
541 if ( strval( $t->getFragment() ) !== '' ) {
542 # Strip the fragment to avoid various odd effects
543 $this->mTitle
= clone $t;
544 $this->mTitle
->setFragment( '' );
551 * Accessor for the Title object
553 * @return Title object
555 function getTitle() {
556 return $this->mTitle
;
560 * Accessor/mutator for the Title object
562 * @param $x New Title object or null to just get the current one
563 * @return Title object
565 function Title( $x = null ) {
566 return wfSetVar( $this->mTitle
, $x );
570 * Set the output type
572 * @param $ot Integer: new value
574 function setOutputType( $ot ) {
575 $this->mOutputType
= $ot;
578 'html' => $ot == self
::OT_HTML
,
579 'wiki' => $ot == self
::OT_WIKI
,
580 'pre' => $ot == self
::OT_PREPROCESS
,
581 'plain' => $ot == self
::OT_PLAIN
,
586 * Accessor/mutator for the output type
588 * @param $x New value or null to just get the current one
591 function OutputType( $x = null ) {
592 return wfSetVar( $this->mOutputType
, $x );
596 * Get the ParserOutput object
598 * @return ParserOutput object
600 function getOutput() {
601 return $this->mOutput
;
605 * Get the ParserOptions object
607 * @return ParserOptions object
609 function getOptions() {
610 return $this->mOptions
;
614 * Accessor/mutator for the ParserOptions object
616 * @param $x New value or null to just get the current one
617 * @return Current ParserOptions object
619 function Options( $x = null ) {
620 return wfSetVar( $this->mOptions
, $x );
623 function nextLinkID() {
624 return $this->mLinkID++
;
627 function setLinkID( $id ) {
628 $this->mLinkID
= $id;
634 function getFunctionLang() {
635 global $wgLang, $wgContLang;
637 $target = $this->mOptions
->getTargetLanguage();
638 if ( $target !== null ) {
641 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
646 * Get a User object either from $this->mUser, if set, or from the
647 * ParserOptions object otherwise
649 * @return User object
652 if ( !is_null( $this->mUser
) ) {
655 return $this->mOptions
->getUser();
659 * Get a preprocessor object
661 * @return Preprocessor instance
663 function getPreprocessor() {
664 if ( !isset( $this->mPreprocessor
) ) {
665 $class = $this->mPreprocessorClass
;
666 $this->mPreprocessor
= new $class( $this );
668 return $this->mPreprocessor
;
672 * Replaces all occurrences of HTML-style comments and the given tags
673 * in the text with a random marker and returns the next text. The output
674 * parameter $matches will be an associative array filled with data in
676 * 'UNIQ-xxxxx' => array(
679 * array( 'param' => 'x' ),
680 * '<element param="x">tag content</element>' ) )
682 * @param $elements list of element names. Comments are always extracted.
683 * @param $text Source text string.
684 * @param $matches Out parameter, Array: extracted tags
685 * @param $uniq_prefix
686 * @return String: stripped text
690 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
695 $taglist = implode( '|', $elements );
696 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
698 while ( $text != '' ) {
699 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
701 if ( count( $p ) < 5 ) {
704 if ( count( $p ) > 5 ) {
718 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
719 $stripped .= $marker;
721 if ( $close === '/>' ) {
722 # Empty element tag, <tag />
727 if ( $element === '!--' ) {
730 $end = "/(<\\/$element\\s*>)/i";
732 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
734 if ( count( $q ) < 3 ) {
735 # No end tag -- let it run out to the end of the text.
744 $matches[$marker] = array( $element,
746 Sanitizer
::decodeTagAttributes( $attributes ),
747 "<$element$attributes$close$content$tail" );
753 * Get a list of strippable XML-like elements
755 function getStripList() {
756 return $this->mStripList
;
760 * @deprecated use replaceVariables
762 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
767 * Restores pre, math, and other extensions removed by strip()
769 * always call unstripNoWiki() after this one
771 * @deprecated use $this->mStripState->unstrip()
773 function unstrip( $text, $state ) {
774 return $state->unstripGeneral( $text );
778 * Always call this after unstrip() to preserve the order
781 * @deprecated use $this->mStripState->unstrip()
783 function unstripNoWiki( $text, $state ) {
784 return $state->unstripNoWiki( $text );
788 * @deprecated use $this->mStripState->unstripBoth()
790 function unstripForHTML( $text ) {
791 return $this->mStripState
->unstripBoth( $text );
795 * Add an item to the strip state
796 * Returns the unique tag which must be inserted into the stripped text
797 * The tag will be replaced with the original text in unstrip()
801 function insertStripItem( $text ) {
802 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
803 $this->mMarkerIndex++
;
804 $this->mStripState
->addGeneral( $rnd, $text );
809 * Interface with html tidy
810 * @deprecated Use MWTidy::tidy()
812 public static function tidy( $text ) {
813 wfDeprecated( __METHOD__
);
814 return MWTidy
::tidy( $text );
818 * parse the wiki syntax used to render tables
822 function doTableStuff( $text ) {
823 wfProfileIn( __METHOD__
);
825 $lines = StringUtils
::explode( "\n", $text );
829 foreach ( $lines as $outLine ) {
830 $line = trim( $outLine );
832 if ( $line == '') { //empty line, go to next line
833 $out .= $outLine."\n";
836 $first_chars = $line[0];
837 if ( strlen($line) > 1) {
838 $first_chars .= in_array($line[1], array('}', '+', '-')) ?
$line[1] : '';
842 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
844 $table =& $this->last($tables);
845 $table[0] = array(); //first row
846 $current_row =& $table[0];
848 $table['indent'] = strlen( $matches[1] );
850 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
851 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
853 if ( $attributes !== '' ) {
854 $table['attributes'] = $attributes;
856 } else if ( !isset($tables[0]) ) {
857 // we're outside the table
859 $out .= $outLine."\n";
860 } else if ( $first_chars === '|}' ) {
861 // trim the |} code from the line
862 $line = substr ( $line , 2 );
864 // Shorthand for last row
865 $last_row =& $this->last($table);
867 // a thead at the end becomes a tfoot, unless there is only one row
868 // Do this before deleting empty last lines to allow headers at the bottom of tables
869 if ( isset($last_row['type'] ) && $last_row['type'] == 'thead' && isset($table[1])) {
870 $last_row['type'] = 'tfoot';
871 for($i = 0; isset($last_row[$i]); $i++
) {
872 $last_row[$i]['type'] = 'td';
876 // Delete empty last lines
877 if ( empty($last_row) ) {
880 $o = $this->printTableHtml( array_pop($tables) ) . $line;
882 if ( count($tables) > 0 ) {
883 $table =& $this->last($tables);
884 $current_row =& $this->last($table);
885 $current_element =& $this->last($current_row);
887 $output =& $current_element['content'];
894 } else if ( $first_chars === '|-' ) {
895 // start a new row element
896 // but only when we haven't started one already
897 if( count($current_row) != 0 ) {
899 $current_row =& $this->last($table);
901 // Get the attributes, there's nothing else useful in $line now
902 $line = substr ( $line , 2 );
903 $attributes = $this->mStripState
->unstripBoth( $line );
904 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
905 if( $attributes !== '') {
906 $current_row['attributes'] = $attributes;
909 } else if ( $first_chars === '|+' ) {
911 $line = substr ( $line , 2 );
913 $c = $this->getCellAttr($line , 'caption');
914 $table['caption'] = array();
915 $table['caption']['content'] = $c[0];
916 if(isset($c[1])) $table['caption']['attributes'] = $c[1];
919 $output =& $table['caption'];
920 } else if ( $first_chars === '|' ||
$first_chars === '!' ||
$first_chars === '!+' ) {
921 // Which kind of cells are we dealing with
923 $line = substr ( $line , 1 );
925 if ( $first_chars === '!' ||
$first_chars === '!+' ) {
926 $line = str_replace ( '!!' , '||' , $line );
930 // Split up multiple cells on the same line.
931 $cells = StringUtils
::explodeMarkup( '||' , $line );
932 $line = ''; // save memory
934 // decide whether thead to tbody
935 if ( !array_key_exists('type', $current_row) ) {
936 $current_row['type'] = ( $first_chars === '!' ) ?
'thead' : 'tbody' ;
937 } else if( $first_chars === '|' ) {
938 $current_row['type'] = 'tbody';
941 // Loop through each table cell
942 foreach ( $cells as $cell ) {
944 $current_row[] = array();
945 $current_element =& $this->last($current_row);
947 $current_element['type'] = $this_tag;
949 $c = $this->getCellAttr($cell , $this_tag);
950 $current_element['content'] = $c[0];
951 if(isset($c[1])) $current_element['attributes'] = $c[1];
954 $output =& $current_element['content'];
957 $output .= $outLine."\n";
961 # Remove trailing line-ending (b/c)
962 if ( substr( $out, -1 ) === "\n" ) {
963 $out = substr( $out, 0, -1 );
966 #Close any unclosed tables
967 if (isset($tables) && count($tables) > 0 ) {
968 for ($i = 0; $i < count($tables); $i++
) {
969 $out .= $this->printTableHtml( array_pop($tables) );
973 wfProfileOut( __METHOD__
);
980 * Helper function for doTableStuff() separating the contents of cells from
981 * attributes. Particularly useful as there's a possible bug and this action
986 function getCellAttr ($cell , $tag_name) {
990 $cell = trim ( $cell );
992 // A cell could contain both parameters and data
993 $cell_data = explode ( '|' , $cell , 2 );
995 // Bug 553: Note that a '|' inside an invalid link should not
996 // be mistaken as delimiting cell parameters
997 if ( strpos( $cell_data[0], '[[' ) !== false ) {
998 $content = trim ( $cell );
1000 else if ( count ( $cell_data ) == 1 ) {
1001 $content = trim ( $cell_data[0] );
1004 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1005 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tag_name );
1007 $content = trim ( $cell_data[1] );
1009 return array($content, $attributes);
1014 * Helper function for doTableStuff(). This converts the structured array into html.
1018 function printTableHtml (&$t) {
1020 $r .= str_repeat( '<dl><dd>' , $t['indent'] );
1022 $r .= isset($t['attributes']) ?
$t['attributes'] : '';
1024 unset($t['attributes']);
1026 if ( isset($t['caption']) ) {
1028 $r .= isset($t['caption']['attributes']) ?
$t['caption']['attributes'] : '';
1030 $r .= $t['caption']['content'];
1037 //If we only have tbodies, mark table as simple
1038 for($i = 0; isset($t[$i]); $i++
) {
1039 if ( !count( $t[$i]) ) continue;
1040 if ( !$last_section ) {
1041 $last_section = $t[$i]['type'];
1042 } else if ($last_section != $t[$i]['type']) {
1048 for($i = 0; isset($t[$i]); $i++
) {
1049 // Check for empty tables
1050 if ( count( $t[$i]) ) {
1055 if( $t[$i]['type'] != $last_section && !$simple ) {
1056 $r .= "\n<" . $t[$i]['type'] . '>';
1060 $r .= isset($t[$i]['attributes']) ?
$t[$i]['attributes'] : '';
1062 for($j = 0; isset($t[$i][$j]); $j++
) {
1063 $r .= "\n<" . $t[$i][$j]['type'];
1064 $r .= isset($t[$i][$j]['attributes']) ?
$t[$i][$j]['attributes'] : '';
1067 $r .= $t[$i][$j]['content'];
1069 $r .= '</' . $t[$i][$j]['type'] . '>';
1074 if( ( !isset($t[$i+
1]) && !$simple )||
( isset($t[$i+
1]) && ($t[$i]['type'] != $t[$i+
1]['type'])) ) {
1075 $r .= '</' . $t[$i]['type'] . '>';
1077 $last_section = $t[$i]['type'];
1081 if ( isset($t['caption']) ) {
1082 $r .= "\n<tr><td></td></tr>";
1088 $r .= str_repeat( '</dd></dl>' , $t['indent'] );
1094 * like end() but only works on the numeric array index and php's internal pointers
1095 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1096 * ignores associative elements and will create a 0 key will a NULL value if there were
1097 * no numric elements and an array itself if not previously defined.
1101 function &last (&$arr) {
1102 for($i = count($arr); (!isset($arr[$i]) && $i > 0); $i--) { }
1107 * Helper function for parse() that transforms wiki markup into
1108 * HTML. Only called for $mOutputType == self::OT_HTML.
1112 function internalParse( $text, $isMain = true, $frame=false ) {
1113 wfProfileIn( __METHOD__
);
1117 # Hook to suspend the parser in this state
1118 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1119 wfProfileOut( __METHOD__
);
1123 # if $frame is provided, then use $frame for replacing any variables
1125 # use frame depth to infer how include/noinclude tags should be handled
1126 # depth=0 means this is the top-level document; otherwise it's an included document
1127 if ( !$frame->depth
) {
1130 $flag = Parser
::PTD_FOR_INCLUSION
;
1132 $dom = $this->preprocessToDom( $text, $flag );
1133 $text = $frame->expand( $dom );
1135 # if $frame is not provided, then use old-style replaceVariables
1136 $text = $this->replaceVariables( $text );
1139 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1140 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1142 # Tables need to come after variable replacement for things to work
1143 # properly; putting them before other transformations should keep
1144 # exciting things like link expansions from showing up in surprising
1146 $text = $this->doTableStuff( $text );
1148 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1150 $text = $this->doDoubleUnderscore( $text );
1152 $text = $this->doHeadings( $text );
1153 if ( $this->mOptions
->getUseDynamicDates() ) {
1154 $df = DateFormatter
::getInstance();
1155 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1157 $text = $this->replaceInternalLinks( $text );
1158 $text = $this->doAllQuotes( $text );
1159 $text = $this->replaceExternalLinks( $text );
1161 # replaceInternalLinks may sometimes leave behind
1162 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1163 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1165 $text = $this->doMagicLinks( $text );
1166 $text = $this->formatHeadings( $text, $origText, $isMain );
1168 wfProfileOut( __METHOD__
);
1173 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1174 * magic external links.
1179 function doMagicLinks( $text ) {
1180 wfProfileIn( __METHOD__
);
1181 $prots = $this->mUrlProtocols
;
1182 $urlChar = self
::EXT_LINK_URL_CLASS
;
1183 $text = preg_replace_callback(
1185 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1186 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1187 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1188 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1189 ISBN\s+(\b # m[5]: ISBN, capture number
1190 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1191 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1192 [0-9Xx] # check digit
1194 )!x', array( &$this, 'magicLinkCallback' ), $text );
1195 wfProfileOut( __METHOD__
);
1199 function magicLinkCallback( $m ) {
1200 if ( isset( $m[1] ) && $m[1] !== '' ) {
1203 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1206 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1207 # Free external link
1208 return $this->makeFreeExternalLink( $m[0] );
1209 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1211 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1214 $CssClass = 'mw-magiclink-rfc';
1216 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1218 $urlmsg = 'pubmedurl';
1219 $CssClass = 'mw-magiclink-pmid';
1222 throw new MWException( __METHOD__
.': unrecognised match type "' .
1223 substr( $m[0], 0, 20 ) . '"' );
1225 $url = wfMsgForContent( $urlmsg, $id );
1226 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1227 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1230 $num = strtr( $isbn, array(
1235 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1237 $titleObj->escapeLocalUrl() .
1238 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1245 * Make a free external link, given a user-supplied URL
1249 function makeFreeExternalLink( $url ) {
1251 wfProfileIn( __METHOD__
);
1255 # The characters '<' and '>' (which were escaped by
1256 # removeHTMLtags()) should not be included in
1257 # URLs, per RFC 2396.
1259 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1260 $trail = substr( $url, $m2[0][1] ) . $trail;
1261 $url = substr( $url, 0, $m2[0][1] );
1264 # Move trailing punctuation to $trail
1266 # If there is no left bracket, then consider right brackets fair game too
1267 if ( strpos( $url, '(' ) === false ) {
1271 $numSepChars = strspn( strrev( $url ), $sep );
1272 if ( $numSepChars ) {
1273 $trail = substr( $url, -$numSepChars ) . $trail;
1274 $url = substr( $url, 0, -$numSepChars );
1277 $url = Sanitizer
::cleanUrl( $url );
1279 # Is this an external image?
1280 $text = $this->maybeMakeExternalImage( $url );
1281 if ( $text === false ) {
1282 # Not an image, make a link
1283 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1284 $this->getExternalLinkAttribs( $url ) );
1285 # Register it in the output object...
1286 # Replace unnecessary URL escape codes with their equivalent characters
1287 $pasteurized = self
::replaceUnusualEscapes( $url );
1288 $this->mOutput
->addExternalLink( $pasteurized );
1290 wfProfileOut( __METHOD__
);
1291 return $text . $trail;
1296 * Parse headers and return html
1300 function doHeadings( $text ) {
1301 wfProfileIn( __METHOD__
);
1302 for ( $i = 6; $i >= 1; --$i ) {
1303 $h = str_repeat( '=', $i );
1304 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1305 "<h$i>\\1</h$i>", $text );
1307 wfProfileOut( __METHOD__
);
1312 * Replace single quotes with HTML markup
1314 * @return string the altered text
1316 function doAllQuotes( $text ) {
1317 wfProfileIn( __METHOD__
);
1319 $lines = StringUtils
::explode( "\n", $text );
1320 foreach ( $lines as $line ) {
1321 $outtext .= $this->doQuotes( $line ) . "\n";
1323 $outtext = substr( $outtext, 0,-1 );
1324 wfProfileOut( __METHOD__
);
1329 * Helper function for doAllQuotes()
1331 public function doQuotes( $text ) {
1332 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1333 if ( count( $arr ) == 1 ) {
1336 # First, do some preliminary work. This may shift some apostrophes from
1337 # being mark-up to being text. It also counts the number of occurrences
1338 # of bold and italics mark-ups.
1341 for ( $i = 0; $i < count( $arr ); $i++
) {
1342 if ( ( $i %
2 ) == 1 ) {
1343 # If there are ever four apostrophes, assume the first is supposed to
1344 # be text, and the remaining three constitute mark-up for bold text.
1345 if ( strlen( $arr[$i] ) == 4 ) {
1348 } elseif ( strlen( $arr[$i] ) > 5 ) {
1349 # If there are more than 5 apostrophes in a row, assume they're all
1350 # text except for the last 5.
1351 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1354 # Count the number of occurrences of bold and italics mark-ups.
1355 # We are not counting sequences of five apostrophes.
1356 if ( strlen( $arr[$i] ) == 2 ) {
1358 } elseif ( strlen( $arr[$i] ) == 3 ) {
1360 } elseif ( strlen( $arr[$i] ) == 5 ) {
1367 # If there is an odd number of both bold and italics, it is likely
1368 # that one of the bold ones was meant to be an apostrophe followed
1369 # by italics. Which one we cannot know for certain, but it is more
1370 # likely to be one that has a single-letter word before it.
1371 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1373 $firstsingleletterword = -1;
1374 $firstmultiletterword = -1;
1376 foreach ( $arr as $r ) {
1377 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1378 $x1 = substr( $arr[$i-1], -1 );
1379 $x2 = substr( $arr[$i-1], -2, 1 );
1380 if ( $x1 === ' ' ) {
1381 if ( $firstspace == -1 ) {
1384 } elseif ( $x2 === ' ') {
1385 if ( $firstsingleletterword == -1 ) {
1386 $firstsingleletterword = $i;
1389 if ( $firstmultiletterword == -1 ) {
1390 $firstmultiletterword = $i;
1397 # If there is a single-letter word, use it!
1398 if ( $firstsingleletterword > -1 ) {
1399 $arr[$firstsingleletterword] = "''";
1400 $arr[$firstsingleletterword-1] .= "'";
1401 } elseif ( $firstmultiletterword > -1 ) {
1402 # If not, but there's a multi-letter word, use that one.
1403 $arr[$firstmultiletterword] = "''";
1404 $arr[$firstmultiletterword-1] .= "'";
1405 } elseif ( $firstspace > -1 ) {
1406 # ... otherwise use the first one that has neither.
1407 # (notice that it is possible for all three to be -1 if, for example,
1408 # there is only one pentuple-apostrophe in the line)
1409 $arr[$firstspace] = "''";
1410 $arr[$firstspace-1] .= "'";
1414 # Now let's actually convert our apostrophic mush to HTML!
1419 foreach ( $arr as $r ) {
1420 if ( ( $i %
2 ) == 0 ) {
1421 if ( $state === 'both' ) {
1427 if ( strlen( $r ) == 2 ) {
1428 if ( $state === 'i' ) {
1429 $output .= '</i>'; $state = '';
1430 } elseif ( $state === 'bi' ) {
1431 $output .= '</i>'; $state = 'b';
1432 } elseif ( $state === 'ib' ) {
1433 $output .= '</b></i><b>'; $state = 'b';
1434 } elseif ( $state === 'both' ) {
1435 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1436 } else { # $state can be 'b' or ''
1437 $output .= '<i>'; $state .= 'i';
1439 } elseif ( strlen( $r ) == 3 ) {
1440 if ( $state === 'b' ) {
1441 $output .= '</b>'; $state = '';
1442 } elseif ( $state === 'bi' ) {
1443 $output .= '</i></b><i>'; $state = 'i';
1444 } elseif ( $state === 'ib' ) {
1445 $output .= '</b>'; $state = 'i';
1446 } elseif ( $state === 'both' ) {
1447 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1448 } else { # $state can be 'i' or ''
1449 $output .= '<b>'; $state .= 'b';
1451 } elseif ( strlen( $r ) == 5 ) {
1452 if ( $state === 'b' ) {
1453 $output .= '</b><i>'; $state = 'i';
1454 } elseif ( $state === 'i' ) {
1455 $output .= '</i><b>'; $state = 'b';
1456 } elseif ( $state === 'bi' ) {
1457 $output .= '</i></b>'; $state = '';
1458 } elseif ( $state === 'ib' ) {
1459 $output .= '</b></i>'; $state = '';
1460 } elseif ( $state === 'both' ) {
1461 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1462 } else { # ($state == '')
1463 $buffer = ''; $state = 'both';
1469 # Now close all remaining tags. Notice that the order is important.
1470 if ( $state === 'b' ||
$state === 'ib' ) {
1473 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1476 if ( $state === 'bi' ) {
1479 # There might be lonely ''''', so make sure we have a buffer
1480 if ( $state === 'both' && $buffer ) {
1481 $output .= '<b><i>'.$buffer.'</i></b>';
1488 * Replace external links (REL)
1490 * Note: this is all very hackish and the order of execution matters a lot.
1491 * Make sure to run maintenance/parserTests.php if you change this code.
1495 function replaceExternalLinks( $text ) {
1497 wfProfileIn( __METHOD__
);
1499 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1500 $s = array_shift( $bits );
1503 while ( $i<count( $bits ) ) {
1505 $protocol = $bits[$i++
];
1506 $text = $bits[$i++
];
1507 $trail = $bits[$i++
];
1509 # The characters '<' and '>' (which were escaped by
1510 # removeHTMLtags()) should not be included in
1511 # URLs, per RFC 2396.
1513 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1514 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1515 $url = substr( $url, 0, $m2[0][1] );
1518 # If the link text is an image URL, replace it with an <img> tag
1519 # This happened by accident in the original parser, but some people used it extensively
1520 $img = $this->maybeMakeExternalImage( $text );
1521 if ( $img !== false ) {
1527 # Set linktype for CSS - if URL==text, link is essentially free
1528 $linktype = ( $text === $url ) ?
'free' : 'text';
1530 # No link text, e.g. [http://domain.tld/some.link]
1531 if ( $text == '' ) {
1532 # Autonumber if allowed. See bug #5918
1533 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1534 $langObj = $this->getFunctionLang();
1535 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1536 $linktype = 'autonumber';
1538 # Otherwise just use the URL
1539 $text = htmlspecialchars( $url );
1543 # Have link text, e.g. [http://domain.tld/some.link text]s
1545 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1548 $text = $wgContLang->markNoConversion( $text );
1550 $url = Sanitizer
::cleanUrl( $url );
1552 # Use the encoded URL
1553 # This means that users can paste URLs directly into the text
1554 # Funny characters like ö aren't valid in URLs anyway
1555 # This was changed in August 2004
1556 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1557 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1559 # Register link in the output object.
1560 # Replace unnecessary URL escape codes with the referenced character
1561 # This prevents spammers from hiding links from the filters
1562 $pasteurized = self
::replaceUnusualEscapes( $url );
1563 $this->mOutput
->addExternalLink( $pasteurized );
1566 wfProfileOut( __METHOD__
);
1571 * Get an associative array of additional HTML attributes appropriate for a
1572 * particular external link. This currently may include rel => nofollow
1573 * (depending on configuration, namespace, and the URL's domain) and/or a
1574 * target attribute (depending on configuration).
1576 * @param $url String: optional URL, to extract the domain from for rel =>
1577 * nofollow if appropriate
1578 * @return Array: associative array of HTML attributes
1580 function getExternalLinkAttribs( $url = false ) {
1582 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1583 $ns = $this->mTitle
->getNamespace();
1584 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1585 $attribs['rel'] = 'nofollow';
1587 global $wgNoFollowDomainExceptions;
1588 if ( $wgNoFollowDomainExceptions ) {
1589 $bits = wfParseUrl( $url );
1590 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1591 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1592 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1593 unset( $attribs['rel'] );
1600 if ( $this->mOptions
->getExternalLinkTarget() ) {
1601 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1608 * Replace unusual URL escape codes with their equivalent characters
1610 * @param $url String
1613 * @todo This can merge genuinely required bits in the path or query string,
1614 * breaking legit URLs. A proper fix would treat the various parts of
1615 * the URL differently; as a workaround, just use the output for
1616 * statistical records, not for actual linking/output.
1618 static function replaceUnusualEscapes( $url ) {
1619 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1620 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1624 * Callback function used in replaceUnusualEscapes().
1625 * Replaces unusual URL escape codes with their equivalent character
1627 private static function replaceUnusualEscapesCallback( $matches ) {
1628 $char = urldecode( $matches[0] );
1629 $ord = ord( $char );
1630 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1631 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1632 # No, shouldn't be escaped
1635 # Yes, leave it escaped
1641 * make an image if it's allowed, either through the global
1642 * option, through the exception, or through the on-wiki whitelist
1645 function maybeMakeExternalImage( $url ) {
1646 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1647 $imagesexception = !empty( $imagesfrom );
1649 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1650 if ( $imagesexception && is_array( $imagesfrom ) ) {
1651 $imagematch = false;
1652 foreach ( $imagesfrom as $match ) {
1653 if ( strpos( $url, $match ) === 0 ) {
1658 } elseif ( $imagesexception ) {
1659 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1661 $imagematch = false;
1663 if ( $this->mOptions
->getAllowExternalImages()
1664 ||
( $imagesexception && $imagematch ) ) {
1665 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1667 $text = Linker
::makeExternalImage( $url );
1670 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1671 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1672 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1673 foreach ( $whitelist as $entry ) {
1674 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1675 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1678 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1679 # Image matches a whitelist entry
1680 $text = Linker
::makeExternalImage( $url );
1689 * Process [[ ]] wikilinks
1690 * @return String: processed text
1694 function replaceInternalLinks( $s ) {
1695 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1700 * Process [[ ]] wikilinks (RIL)
1701 * @return LinkHolderArray
1705 function replaceInternalLinks2( &$s ) {
1708 wfProfileIn( __METHOD__
);
1710 wfProfileIn( __METHOD__
.'-setup' );
1711 static $tc = FALSE, $e1, $e1_img;
1712 # the % is needed to support urlencoded titles as well
1714 $tc = Title
::legalChars() . '#%';
1715 # Match a link having the form [[namespace:link|alternate]]trail
1716 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1717 # Match cases where there is no "]]", which might still be images
1718 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1721 $holders = new LinkHolderArray( $this );
1723 # split the entire text string on occurences of [[
1724 $a = StringUtils
::explode( '[[', ' ' . $s );
1725 # get the first element (all text up to first [[), and remove the space we added
1728 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1729 $s = substr( $s, 1 );
1731 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1733 if ( $useLinkPrefixExtension ) {
1734 # Match the end of a line for a word that's not followed by whitespace,
1735 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1736 $e2 = wfMsgForContent( 'linkprefix' );
1739 if ( is_null( $this->mTitle
) ) {
1740 wfProfileOut( __METHOD__
.'-setup' );
1741 wfProfileOut( __METHOD__
);
1742 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1744 $nottalk = !$this->mTitle
->isTalkPage();
1746 if ( $useLinkPrefixExtension ) {
1748 if ( preg_match( $e2, $s, $m ) ) {
1749 $first_prefix = $m[2];
1751 $first_prefix = false;
1757 if ( $wgContLang->hasVariants() ) {
1758 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1760 $selflink = array( $this->mTitle
->getPrefixedText() );
1762 $useSubpages = $this->areSubpagesAllowed();
1763 wfProfileOut( __METHOD__
.'-setup' );
1765 # Loop for each link
1766 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1767 # Check for excessive memory usage
1768 if ( $holders->isBig() ) {
1770 # Do the existence check, replace the link holders and clear the array
1771 $holders->replace( $s );
1775 if ( $useLinkPrefixExtension ) {
1776 wfProfileIn( __METHOD__
.'-prefixhandling' );
1777 if ( preg_match( $e2, $s, $m ) ) {
1784 if ( $first_prefix ) {
1785 $prefix = $first_prefix;
1786 $first_prefix = false;
1788 wfProfileOut( __METHOD__
.'-prefixhandling' );
1791 $might_be_img = false;
1793 wfProfileIn( __METHOD__
."-e1" );
1794 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1796 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1797 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1798 # the real problem is with the $e1 regex
1801 # Still some problems for cases where the ] is meant to be outside punctuation,
1802 # and no image is in sight. See bug 2095.
1804 if ( $text !== '' &&
1805 substr( $m[3], 0, 1 ) === ']' &&
1806 strpos( $text, '[' ) !== false
1809 $text .= ']'; # so that replaceExternalLinks($text) works later
1810 $m[3] = substr( $m[3], 1 );
1812 # fix up urlencoded title texts
1813 if ( strpos( $m[1], '%' ) !== false ) {
1814 # Should anchors '#' also be rejected?
1815 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1818 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1819 $might_be_img = true;
1821 if ( strpos( $m[1], '%' ) !== false ) {
1822 $m[1] = rawurldecode( $m[1] );
1825 } else { # Invalid form; output directly
1826 $s .= $prefix . '[[' . $line ;
1827 wfProfileOut( __METHOD__
."-e1" );
1830 wfProfileOut( __METHOD__
."-e1" );
1831 wfProfileIn( __METHOD__
."-misc" );
1833 # Don't allow internal links to pages containing
1834 # PROTO: where PROTO is a valid URL protocol; these
1835 # should be external links.
1836 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1837 $s .= $prefix . '[[' . $line ;
1838 wfProfileOut( __METHOD__
."-misc" );
1842 # Make subpage if necessary
1843 if ( $useSubpages ) {
1844 $link = $this->maybeDoSubpageLink( $m[1], $text );
1849 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1851 # Strip off leading ':'
1852 $link = substr( $link, 1 );
1855 wfProfileOut( __METHOD__
."-misc" );
1856 wfProfileIn( __METHOD__
."-title" );
1857 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1858 if ( $nt === null ) {
1859 $s .= $prefix . '[[' . $line;
1860 wfProfileOut( __METHOD__
."-title" );
1864 $ns = $nt->getNamespace();
1865 $iw = $nt->getInterWiki();
1866 wfProfileOut( __METHOD__
."-title" );
1868 if ( $might_be_img ) { # if this is actually an invalid link
1869 wfProfileIn( __METHOD__
."-might_be_img" );
1870 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1873 # look at the next 'line' to see if we can close it there
1875 $next_line = $a->current();
1876 if ( $next_line === false ||
$next_line === null ) {
1879 $m = explode( ']]', $next_line, 3 );
1880 if ( count( $m ) == 3 ) {
1881 # the first ]] closes the inner link, the second the image
1883 $text .= "[[{$m[0]}]]{$m[1]}";
1886 } elseif ( count( $m ) == 2 ) {
1887 # if there's exactly one ]] that's fine, we'll keep looking
1888 $text .= "[[{$m[0]}]]{$m[1]}";
1890 # if $next_line is invalid too, we need look no further
1891 $text .= '[[' . $next_line;
1896 # we couldn't find the end of this imageLink, so output it raw
1897 # but don't ignore what might be perfectly normal links in the text we've examined
1898 $holders->merge( $this->replaceInternalLinks2( $text ) );
1899 $s .= "{$prefix}[[$link|$text";
1900 # note: no $trail, because without an end, there *is* no trail
1901 wfProfileOut( __METHOD__
."-might_be_img" );
1904 } else { # it's not an image, so output it raw
1905 $s .= "{$prefix}[[$link|$text";
1906 # note: no $trail, because without an end, there *is* no trail
1907 wfProfileOut( __METHOD__
."-might_be_img" );
1910 wfProfileOut( __METHOD__
."-might_be_img" );
1913 $wasblank = ( $text == '' );
1917 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1918 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1919 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1920 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1921 $text = $this->doQuotes( $text );
1924 # Link not escaped by : , create the various objects
1928 wfProfileIn( __METHOD__
."-interwiki" );
1929 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1930 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1931 $s = rtrim( $s . $prefix );
1932 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1933 wfProfileOut( __METHOD__
."-interwiki" );
1936 wfProfileOut( __METHOD__
."-interwiki" );
1938 if ( $ns == NS_FILE
) {
1939 wfProfileIn( __METHOD__
."-image" );
1940 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1942 # if no parameters were passed, $text
1943 # becomes something like "File:Foo.png",
1944 # which we don't want to pass on to the
1948 # recursively parse links inside the image caption
1949 # actually, this will parse them in any other parameters, too,
1950 # but it might be hard to fix that, and it doesn't matter ATM
1951 $text = $this->replaceExternalLinks( $text );
1952 $holders->merge( $this->replaceInternalLinks2( $text ) );
1954 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1955 $s .= $prefix . $this->armorLinks(
1956 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1958 $s .= $prefix . $trail;
1960 wfProfileOut( __METHOD__
."-image" );
1964 if ( $ns == NS_CATEGORY
) {
1965 wfProfileIn( __METHOD__
."-category" );
1966 $s = rtrim( $s . "\n" ); # bug 87
1969 $sortkey = $this->getDefaultSort();
1973 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1974 $sortkey = str_replace( "\n", '', $sortkey );
1975 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1976 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1979 * Strip the whitespace Category links produce, see bug 87
1980 * @todo We might want to use trim($tmp, "\n") here.
1982 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1984 wfProfileOut( __METHOD__
."-category" );
1989 # Self-link checking
1990 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1991 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1992 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
1997 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1998 # FIXME: Should do batch file existence checks, see comment below
1999 if ( $ns == NS_MEDIA
) {
2000 wfProfileIn( __METHOD__
."-media" );
2001 # Give extensions a chance to select the file revision for us
2002 $time = $sha1 = $descQuery = false;
2003 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2004 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
2005 # Fetch and register the file (file title may be different via hooks)
2006 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
2007 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2008 $s .= $prefix . $this->armorLinks(
2009 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2010 wfProfileOut( __METHOD__
."-media" );
2014 wfProfileIn( __METHOD__
."-always_known" );
2015 # Some titles, such as valid special pages or files in foreign repos, should
2016 # be shown as bluelinks even though they're not included in the page table
2018 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2019 # batch file existence checks for NS_FILE and NS_MEDIA
2020 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2021 $this->mOutput
->addLink( $nt );
2022 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2024 # Links will be added to the output link list after checking
2025 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2027 wfProfileOut( __METHOD__
."-always_known" );
2029 wfProfileOut( __METHOD__
);
2034 * Make a link placeholder. The text returned can be later resolved to a real link with
2035 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
2036 * parsing of interwiki links, and secondly to allow all existence checks and
2037 * article length checks (for stub links) to be bundled into a single query.
2041 function makeLinkHolder( &$nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2042 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
2046 * Render a forced-blue link inline; protect against double expansion of
2047 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2048 * Since this little disaster has to split off the trail text to avoid
2049 * breaking URLs in the following text without breaking trails on the
2050 * wiki links, it's been made into a horrible function.
2053 * @param $text String
2054 * @param $query Array or String
2055 * @param $trail String
2056 * @param $prefix String
2057 * @return String: HTML-wikitext mix oh yuck
2059 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2060 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2062 if ( is_string( $query ) ) {
2063 $query = wfCgiToArray( $query );
2065 if ( $text == '' ) {
2066 $text = htmlspecialchars( $nt->getPrefixedText() );
2069 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2071 return $this->armorLinks( $link ) . $trail;
2075 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2076 * going to go through further parsing steps before inline URL expansion.
2078 * Not needed quite as much as it used to be since free links are a bit
2079 * more sensible these days. But bracketed links are still an issue.
2081 * @param $text String: more-or-less HTML
2082 * @return String: less-or-more HTML with NOPARSE bits
2084 function armorLinks( $text ) {
2085 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2086 "{$this->mUniqPrefix}NOPARSE$1", $text );
2090 * Return true if subpage links should be expanded on this page.
2093 function areSubpagesAllowed() {
2094 # Some namespaces don't allow subpages
2095 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2099 * Handle link to subpage if necessary
2101 * @param $target String: the source of the link
2102 * @param &$text String: the link text, modified as necessary
2103 * @return string the full name of the link
2106 function maybeDoSubpageLink( $target, &$text ) {
2107 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2111 * Used by doBlockLevels()
2114 function closeParagraph() {
2116 if ( $this->mLastSection
!= '' ) {
2117 $result = '</' . $this->mLastSection
. ">\n";
2119 $this->mInPre
= false;
2120 $this->mLastSection
= '';
2125 * getCommon() returns the length of the longest common substring
2126 * of both arguments, starting at the beginning of both.
2129 function getCommon( $st1, $st2 ) {
2130 $fl = strlen( $st1 );
2131 $shorter = strlen( $st2 );
2132 if ( $fl < $shorter ) {
2136 for ( $i = 0; $i < $shorter; ++
$i ) {
2137 if ( $st1{$i} != $st2{$i} ) {
2145 * These next three functions open, continue, and close the list
2146 * element appropriate to the prefix character passed into them.
2149 function openList( $char ) {
2150 $result = $this->closeParagraph();
2152 if ( '*' === $char ) {
2153 $result .= '<ul><li>';
2154 } elseif ( '#' === $char ) {
2155 $result .= '<ol><li>';
2156 } elseif ( ':' === $char ) {
2157 $result .= '<dl><dd>';
2158 } elseif ( ';' === $char ) {
2159 $result .= '<dl><dt>';
2160 $this->mDTopen
= true;
2162 $result = '<!-- ERR 1 -->';
2170 * @param $char String
2173 function nextItem( $char ) {
2174 if ( '*' === $char ||
'#' === $char ) {
2176 } elseif ( ':' === $char ||
';' === $char ) {
2178 if ( $this->mDTopen
) {
2181 if ( ';' === $char ) {
2182 $this->mDTopen
= true;
2183 return $close . '<dt>';
2185 $this->mDTopen
= false;
2186 return $close . '<dd>';
2189 return '<!-- ERR 2 -->';
2194 * @param $char String
2197 function closeList( $char ) {
2198 if ( '*' === $char ) {
2199 $text = '</li></ul>';
2200 } elseif ( '#' === $char ) {
2201 $text = '</li></ol>';
2202 } elseif ( ':' === $char ) {
2203 if ( $this->mDTopen
) {
2204 $this->mDTopen
= false;
2205 $text = '</dt></dl>';
2207 $text = '</dd></dl>';
2210 return '<!-- ERR 3 -->';
2217 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2219 * @param $text String
2220 * @param $linestart Boolean: whether or not this is at the start of a line.
2222 * @return string the lists rendered as HTML
2224 function doBlockLevels( $text, $linestart ) {
2225 wfProfileIn( __METHOD__
);
2227 # Parsing through the text line by line. The main thing
2228 # happening here is handling of block-level elements p, pre,
2229 # and making lists from lines starting with * # : etc.
2231 $textLines = StringUtils
::explode( "\n", $text );
2233 $lastPrefix = $output = '';
2234 $this->mDTopen
= $inBlockElem = false;
2236 $paragraphStack = false;
2238 foreach ( $textLines as $oLine ) {
2240 if ( !$linestart ) {
2250 $lastPrefixLength = strlen( $lastPrefix );
2251 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2252 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2253 # If not in a <pre> element, scan for and figure out what prefixes are there.
2254 if ( !$this->mInPre
) {
2255 # Multiple prefixes may abut each other for nested lists.
2256 $prefixLength = strspn( $oLine, '*#:;' );
2257 $prefix = substr( $oLine, 0, $prefixLength );
2260 # ; and : are both from definition-lists, so they're equivalent
2261 # for the purposes of determining whether or not we need to open/close
2263 $prefix2 = str_replace( ';', ':', $prefix );
2264 $t = substr( $oLine, $prefixLength );
2265 $this->mInPre
= (bool)$preOpenMatch;
2267 # Don't interpret any other prefixes in preformatted text
2269 $prefix = $prefix2 = '';
2274 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2275 # Same as the last item, so no need to deal with nesting or opening stuff
2276 $output .= $this->nextItem( substr( $prefix, -1 ) );
2277 $paragraphStack = false;
2279 if ( substr( $prefix, -1 ) === ';') {
2280 # The one nasty exception: definition lists work like this:
2281 # ; title : definition text
2282 # So we check for : in the remainder text to split up the
2283 # title and definition, without b0rking links.
2285 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2287 $output .= $term . $this->nextItem( ':' );
2290 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2291 # We need to open or close prefixes, or both.
2293 # Either open or close a level...
2294 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2295 $paragraphStack = false;
2297 # Close all the prefixes which aren't shared.
2298 while ( $commonPrefixLength < $lastPrefixLength ) {
2299 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2300 --$lastPrefixLength;
2303 # Continue the current prefix if appropriate.
2304 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2305 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2308 # Open prefixes where appropriate.
2309 while ( $prefixLength > $commonPrefixLength ) {
2310 $char = substr( $prefix, $commonPrefixLength, 1 );
2311 $output .= $this->openList( $char );
2313 if ( ';' === $char ) {
2314 # FIXME: This is dupe of code above
2315 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2317 $output .= $term . $this->nextItem( ':' );
2320 ++
$commonPrefixLength;
2322 $lastPrefix = $prefix2;
2325 # If we have no prefixes, go to paragraph mode.
2326 if ( 0 == $prefixLength ) {
2327 wfProfileIn( __METHOD__
."-paragraph" );
2328 # No prefix (not in list)--go to paragraph mode
2329 # XXX: use a stack for nestable elements like span, table and div
2330 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2331 $closematch = preg_match(
2332 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2333 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2334 if ( $openmatch or $closematch ) {
2335 $paragraphStack = false;
2336 # TODO bug 5718: paragraph closed
2337 $output .= $this->closeParagraph();
2338 if ( $preOpenMatch and !$preCloseMatch ) {
2339 $this->mInPre
= true;
2341 $inBlockElem = !$closematch;
2342 } elseif ( !$inBlockElem && !$this->mInPre
) {
2343 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2345 if ( $this->mLastSection
!== 'pre' ) {
2346 $paragraphStack = false;
2347 $output .= $this->closeParagraph().'<pre>';
2348 $this->mLastSection
= 'pre';
2350 $t = substr( $t, 1 );
2353 if ( trim( $t ) === '' ) {
2354 if ( $paragraphStack ) {
2355 $output .= $paragraphStack.'<br />';
2356 $paragraphStack = false;
2357 $this->mLastSection
= 'p';
2359 if ( $this->mLastSection
!== 'p' ) {
2360 $output .= $this->closeParagraph();
2361 $this->mLastSection
= '';
2362 $paragraphStack = '<p>';
2364 $paragraphStack = '</p><p>';
2368 if ( $paragraphStack ) {
2369 $output .= $paragraphStack;
2370 $paragraphStack = false;
2371 $this->mLastSection
= 'p';
2372 } elseif ( $this->mLastSection
!== 'p' ) {
2373 $output .= $this->closeParagraph().'<p>';
2374 $this->mLastSection
= 'p';
2379 wfProfileOut( __METHOD__
."-paragraph" );
2381 # somewhere above we forget to get out of pre block (bug 785)
2382 if ( $preCloseMatch && $this->mInPre
) {
2383 $this->mInPre
= false;
2385 if ( $paragraphStack === false ) {
2389 while ( $prefixLength ) {
2390 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2393 if ( $this->mLastSection
!= '' ) {
2394 $output .= '</' . $this->mLastSection
. '>';
2395 $this->mLastSection
= '';
2398 wfProfileOut( __METHOD__
);
2403 * Split up a string on ':', ignoring any occurences inside tags
2404 * to prevent illegal overlapping.
2406 * @param $str String: the string to split
2407 * @param &$before String: set to everything before the ':'
2408 * @param &$after String: set to everything after the ':'
2409 * return String: the position of the ':', or false if none found
2411 function findColonNoLinks( $str, &$before, &$after ) {
2412 wfProfileIn( __METHOD__
);
2414 $pos = strpos( $str, ':' );
2415 if ( $pos === false ) {
2417 wfProfileOut( __METHOD__
);
2421 $lt = strpos( $str, '<' );
2422 if ( $lt === false ||
$lt > $pos ) {
2423 # Easy; no tag nesting to worry about
2424 $before = substr( $str, 0, $pos );
2425 $after = substr( $str, $pos+
1 );
2426 wfProfileOut( __METHOD__
);
2430 # Ugly state machine to walk through avoiding tags.
2431 $state = self
::COLON_STATE_TEXT
;
2433 $len = strlen( $str );
2434 for( $i = 0; $i < $len; $i++
) {
2438 # (Using the number is a performance hack for common cases)
2439 case 0: # self::COLON_STATE_TEXT:
2442 # Could be either a <start> tag or an </end> tag
2443 $state = self
::COLON_STATE_TAGSTART
;
2446 if ( $stack == 0 ) {
2448 $before = substr( $str, 0, $i );
2449 $after = substr( $str, $i +
1 );
2450 wfProfileOut( __METHOD__
);
2453 # Embedded in a tag; don't break it.
2456 # Skip ahead looking for something interesting
2457 $colon = strpos( $str, ':', $i );
2458 if ( $colon === false ) {
2459 # Nothing else interesting
2460 wfProfileOut( __METHOD__
);
2463 $lt = strpos( $str, '<', $i );
2464 if ( $stack === 0 ) {
2465 if ( $lt === false ||
$colon < $lt ) {
2467 $before = substr( $str, 0, $colon );
2468 $after = substr( $str, $colon +
1 );
2469 wfProfileOut( __METHOD__
);
2473 if ( $lt === false ) {
2474 # Nothing else interesting to find; abort!
2475 # We're nested, but there's no close tags left. Abort!
2478 # Skip ahead to next tag start
2480 $state = self
::COLON_STATE_TAGSTART
;
2483 case 1: # self::COLON_STATE_TAG:
2488 $state = self
::COLON_STATE_TEXT
;
2491 # Slash may be followed by >?
2492 $state = self
::COLON_STATE_TAGSLASH
;
2498 case 2: # self::COLON_STATE_TAGSTART:
2501 $state = self
::COLON_STATE_CLOSETAG
;
2504 $state = self
::COLON_STATE_COMMENT
;
2507 # Illegal early close? This shouldn't happen D:
2508 $state = self
::COLON_STATE_TEXT
;
2511 $state = self
::COLON_STATE_TAG
;
2514 case 3: # self::COLON_STATE_CLOSETAG:
2519 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2520 wfProfileOut( __METHOD__
);
2523 $state = self
::COLON_STATE_TEXT
;
2526 case self
::COLON_STATE_TAGSLASH
:
2528 # Yes, a self-closed tag <blah/>
2529 $state = self
::COLON_STATE_TEXT
;
2531 # Probably we're jumping the gun, and this is an attribute
2532 $state = self
::COLON_STATE_TAG
;
2535 case 5: # self::COLON_STATE_COMMENT:
2537 $state = self
::COLON_STATE_COMMENTDASH
;
2540 case self
::COLON_STATE_COMMENTDASH
:
2542 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2544 $state = self
::COLON_STATE_COMMENT
;
2547 case self
::COLON_STATE_COMMENTDASHDASH
:
2549 $state = self
::COLON_STATE_TEXT
;
2551 $state = self
::COLON_STATE_COMMENT
;
2555 throw new MWException( "State machine error in " . __METHOD__
);
2559 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2560 wfProfileOut( __METHOD__
);
2563 wfProfileOut( __METHOD__
);
2568 * Return value of a magic variable (like PAGENAME)
2572 function getVariableValue( $index, $frame=false ) {
2573 global $wgContLang, $wgSitename, $wgServer;
2574 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2577 * Some of these require message or data lookups and can be
2578 * expensive to check many times.
2580 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2581 if ( isset( $this->mVarCache
[$index] ) ) {
2582 return $this->mVarCache
[$index];
2586 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2587 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2590 global $wgLocaltimezone;
2591 if ( isset( $wgLocaltimezone ) ) {
2592 $oldtz = date_default_timezone_get();
2593 date_default_timezone_set( $wgLocaltimezone );
2596 $localTimestamp = date( 'YmdHis', $ts );
2597 $localMonth = date( 'm', $ts );
2598 $localMonth1 = date( 'n', $ts );
2599 $localMonthName = date( 'n', $ts );
2600 $localDay = date( 'j', $ts );
2601 $localDay2 = date( 'd', $ts );
2602 $localDayOfWeek = date( 'w', $ts );
2603 $localWeek = date( 'W', $ts );
2604 $localYear = date( 'Y', $ts );
2605 $localHour = date( 'H', $ts );
2606 if ( isset( $wgLocaltimezone ) ) {
2607 date_default_timezone_set( $oldtz );
2611 case 'currentmonth':
2612 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2614 case 'currentmonth1':
2615 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2617 case 'currentmonthname':
2618 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2620 case 'currentmonthnamegen':
2621 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2623 case 'currentmonthabbrev':
2624 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2627 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2630 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2633 $value = $wgContLang->formatNum( $localMonth );
2636 $value = $wgContLang->formatNum( $localMonth1 );
2638 case 'localmonthname':
2639 $value = $wgContLang->getMonthName( $localMonthName );
2641 case 'localmonthnamegen':
2642 $value = $wgContLang->getMonthNameGen( $localMonthName );
2644 case 'localmonthabbrev':
2645 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2648 $value = $wgContLang->formatNum( $localDay );
2651 $value = $wgContLang->formatNum( $localDay2 );
2654 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2657 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2659 case 'fullpagename':
2660 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2662 case 'fullpagenamee':
2663 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2666 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2668 case 'subpagenamee':
2669 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2671 case 'basepagename':
2672 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2674 case 'basepagenamee':
2675 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2677 case 'talkpagename':
2678 if ( $this->mTitle
->canTalk() ) {
2679 $talkPage = $this->mTitle
->getTalkPage();
2680 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2685 case 'talkpagenamee':
2686 if ( $this->mTitle
->canTalk() ) {
2687 $talkPage = $this->mTitle
->getTalkPage();
2688 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2693 case 'subjectpagename':
2694 $subjPage = $this->mTitle
->getSubjectPage();
2695 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2697 case 'subjectpagenamee':
2698 $subjPage = $this->mTitle
->getSubjectPage();
2699 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2702 # Let the edit saving system know we should parse the page
2703 # *after* a revision ID has been assigned.
2704 $this->mOutput
->setFlag( 'vary-revision' );
2705 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2706 $value = $this->mRevisionId
;
2709 # Let the edit saving system know we should parse the page
2710 # *after* a revision ID has been assigned. This is for null edits.
2711 $this->mOutput
->setFlag( 'vary-revision' );
2712 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2713 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2715 case 'revisionday2':
2716 # Let the edit saving system know we should parse the page
2717 # *after* a revision ID has been assigned. This is for null edits.
2718 $this->mOutput
->setFlag( 'vary-revision' );
2719 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2720 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2722 case 'revisionmonth':
2723 # Let the edit saving system know we should parse the page
2724 # *after* a revision ID has been assigned. This is for null edits.
2725 $this->mOutput
->setFlag( 'vary-revision' );
2726 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2727 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2729 case 'revisionmonth1':
2730 # Let the edit saving system know we should parse the page
2731 # *after* a revision ID has been assigned. This is for null edits.
2732 $this->mOutput
->setFlag( 'vary-revision' );
2733 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2734 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2736 case 'revisionyear':
2737 # Let the edit saving system know we should parse the page
2738 # *after* a revision ID has been assigned. This is for null edits.
2739 $this->mOutput
->setFlag( 'vary-revision' );
2740 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2741 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2743 case 'revisiontimestamp':
2744 # Let the edit saving system know we should parse the page
2745 # *after* a revision ID has been assigned. This is for null edits.
2746 $this->mOutput
->setFlag( 'vary-revision' );
2747 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2748 $value = $this->getRevisionTimestamp();
2750 case 'revisionuser':
2751 # Let the edit saving system know we should parse the page
2752 # *after* a revision ID has been assigned. This is for null edits.
2753 $this->mOutput
->setFlag( 'vary-revision' );
2754 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2755 $value = $this->getRevisionUser();
2758 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2761 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2764 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2767 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2769 case 'subjectspace':
2770 $value = $this->mTitle
->getSubjectNsText();
2772 case 'subjectspacee':
2773 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2775 case 'currentdayname':
2776 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2779 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2782 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2785 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2788 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2789 # int to remove the padding
2790 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2793 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2795 case 'localdayname':
2796 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2799 $value = $wgContLang->formatNum( $localYear, true );
2802 $value = $wgContLang->time( $localTimestamp, false, false );
2805 $value = $wgContLang->formatNum( $localHour, true );
2808 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2809 # int to remove the padding
2810 $value = $wgContLang->formatNum( (int)$localWeek );
2813 $value = $wgContLang->formatNum( $localDayOfWeek );
2815 case 'numberofarticles':
2816 $value = $wgContLang->formatNum( SiteStats
::articles() );
2818 case 'numberoffiles':
2819 $value = $wgContLang->formatNum( SiteStats
::images() );
2821 case 'numberofusers':
2822 $value = $wgContLang->formatNum( SiteStats
::users() );
2824 case 'numberofactiveusers':
2825 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2827 case 'numberofpages':
2828 $value = $wgContLang->formatNum( SiteStats
::pages() );
2830 case 'numberofadmins':
2831 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2833 case 'numberofedits':
2834 $value = $wgContLang->formatNum( SiteStats
::edits() );
2836 case 'numberofviews':
2837 $value = $wgContLang->formatNum( SiteStats
::views() );
2839 case 'currenttimestamp':
2840 $value = wfTimestamp( TS_MW
, $ts );
2842 case 'localtimestamp':
2843 $value = $localTimestamp;
2845 case 'currentversion':
2846 $value = SpecialVersion
::getVersion();
2849 return $wgArticlePath;
2855 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2856 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2857 wfRestoreWarnings();
2858 return $serverName ?
$serverName : $wgServer;
2860 return $wgScriptPath;
2862 return $wgStylePath;
2863 case 'directionmark':
2864 return $wgContLang->getDirMark();
2865 case 'contentlanguage':
2866 global $wgLanguageCode;
2867 return $wgLanguageCode;
2870 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2878 $this->mVarCache
[$index] = $value;
2884 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2888 function initialiseVariables() {
2889 wfProfileIn( __METHOD__
);
2890 $variableIDs = MagicWord
::getVariableIDs();
2891 $substIDs = MagicWord
::getSubstIDs();
2893 $this->mVariables
= new MagicWordArray( $variableIDs );
2894 $this->mSubstWords
= new MagicWordArray( $substIDs );
2895 wfProfileOut( __METHOD__
);
2899 * Preprocess some wikitext and return the document tree.
2900 * This is the ghost of replace_variables().
2902 * @param $text String: The text to parse
2903 * @param $flags Integer: bitwise combination of:
2904 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2905 * included. Default is to assume a direct page view.
2907 * The generated DOM tree must depend only on the input text and the flags.
2908 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2910 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2911 * change in the DOM tree for a given text, must be passed through the section identifier
2912 * in the section edit link and thus back to extractSections().
2914 * The output of this function is currently only cached in process memory, but a persistent
2915 * cache may be implemented at a later date which takes further advantage of these strict
2916 * dependency requirements.
2920 function preprocessToDom( $text, $flags = 0 ) {
2921 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2926 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2928 public static function splitWhitespace( $s ) {
2929 $ltrimmed = ltrim( $s );
2930 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2931 $trimmed = rtrim( $ltrimmed );
2932 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2934 $w2 = substr( $ltrimmed, -$diff );
2938 return array( $w1, $trimmed, $w2 );
2942 * Replace magic variables, templates, and template arguments
2943 * with the appropriate text. Templates are substituted recursively,
2944 * taking care to avoid infinite loops.
2946 * Note that the substitution depends on value of $mOutputType:
2947 * self::OT_WIKI: only {{subst:}} templates
2948 * self::OT_PREPROCESS: templates but not extension tags
2949 * self::OT_HTML: all templates and extension tags
2951 * @param $text String: the text to transform
2952 * @param $frame PPFrame Object describing the arguments passed to the template.
2953 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2954 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2955 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2958 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2959 # Is there any text? Also, Prevent too big inclusions!
2960 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2963 wfProfileIn( __METHOD__
);
2965 if ( $frame === false ) {
2966 $frame = $this->getPreprocessor()->newFrame();
2967 } elseif ( !( $frame instanceof PPFrame
) ) {
2968 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2969 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2972 $dom = $this->preprocessToDom( $text );
2973 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2974 $text = $frame->expand( $dom, $flags );
2976 wfProfileOut( __METHOD__
);
2980 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2981 static function createAssocArgs( $args ) {
2982 $assocArgs = array();
2984 foreach ( $args as $arg ) {
2985 $eqpos = strpos( $arg, '=' );
2986 if ( $eqpos === false ) {
2987 $assocArgs[$index++
] = $arg;
2989 $name = trim( substr( $arg, 0, $eqpos ) );
2990 $value = trim( substr( $arg, $eqpos+
1 ) );
2991 if ( $value === false ) {
2994 if ( $name !== false ) {
2995 $assocArgs[$name] = $value;
3004 * Warn the user when a parser limitation is reached
3005 * Will warn at most once the user per limitation type
3007 * @param $limitationType String: should be one of:
3008 * 'expensive-parserfunction' (corresponding messages:
3009 * 'expensive-parserfunction-warning',
3010 * 'expensive-parserfunction-category')
3011 * 'post-expand-template-argument' (corresponding messages:
3012 * 'post-expand-template-argument-warning',
3013 * 'post-expand-template-argument-category')
3014 * 'post-expand-template-inclusion' (corresponding messages:
3015 * 'post-expand-template-inclusion-warning',
3016 * 'post-expand-template-inclusion-category')
3017 * @param $current Current value
3018 * @param $max Maximum allowed, when an explicit limit has been
3019 * exceeded, provide the values (optional)
3021 function limitationWarn( $limitationType, $current=null, $max=null) {
3022 # does no harm if $current and $max are present but are unnecessary for the message
3023 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3024 $this->mOutput
->addWarning( $warning );
3025 $this->addTrackingCategory( "$limitationType-category" );
3029 * Return the text of a template, after recursively
3030 * replacing any variables or templates within the template.
3032 * @param $piece Array: the parts of the template
3033 * $piece['title']: the title, i.e. the part before the |
3034 * $piece['parts']: the parameter array
3035 * $piece['lineStart']: whether the brace was at the start of a line
3036 * @param $frame PPFrame The current frame, contains template arguments
3037 * @return String: the text of the template
3040 function braceSubstitution( $piece, $frame ) {
3041 global $wgContLang, $wgNonincludableNamespaces;
3042 wfProfileIn( __METHOD__
);
3043 wfProfileIn( __METHOD__
.'-setup' );
3046 $found = false; # $text has been filled
3047 $nowiki = false; # wiki markup in $text should be escaped
3048 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3049 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3050 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3051 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3053 # Title object, where $text came from
3056 # $part1 is the bit before the first |, and must contain only title characters.
3057 # Various prefixes will be stripped from it later.
3058 $titleWithSpaces = $frame->expand( $piece['title'] );
3059 $part1 = trim( $titleWithSpaces );
3062 # Original title text preserved for various purposes
3063 $originalTitle = $part1;
3065 # $args is a list of argument nodes, starting from index 0, not including $part1
3066 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3067 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3068 wfProfileOut( __METHOD__
.'-setup' );
3071 wfProfileIn( __METHOD__
.'-modifiers' );
3074 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3076 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3077 # Decide whether to expand template or keep wikitext as-is.
3078 if ( $this->ot
['wiki'] ) {
3079 if ( $substMatch === false ) {
3080 $literal = true; # literal when in PST with no prefix
3082 $literal = false; # expand when in PST with subst: or safesubst:
3085 if ( $substMatch == 'subst' ) {
3086 $literal = true; # literal when not in PST with plain subst:
3088 $literal = false; # expand when not in PST with safesubst: or no prefix
3092 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3099 if ( !$found && $args->getLength() == 0 ) {
3100 $id = $this->mVariables
->matchStartToEnd( $part1 );
3101 if ( $id !== false ) {
3102 $text = $this->getVariableValue( $id, $frame );
3103 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3104 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3110 # MSG, MSGNW and RAW
3113 $mwMsgnw = MagicWord
::get( 'msgnw' );
3114 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3117 # Remove obsolete MSG:
3118 $mwMsg = MagicWord
::get( 'msg' );
3119 $mwMsg->matchStartAndRemove( $part1 );
3123 $mwRaw = MagicWord
::get( 'raw' );
3124 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3125 $forceRawInterwiki = true;
3128 wfProfileOut( __METHOD__
.'-modifiers' );
3132 wfProfileIn( __METHOD__
. '-pfunc' );
3134 $colonPos = strpos( $part1, ':' );
3135 if ( $colonPos !== false ) {
3136 # Case sensitive functions
3137 $function = substr( $part1, 0, $colonPos );
3138 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3139 $function = $this->mFunctionSynonyms
[1][$function];
3141 # Case insensitive functions
3142 $function = $wgContLang->lc( $function );
3143 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3144 $function = $this->mFunctionSynonyms
[0][$function];
3150 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3151 $initialArgs = array( &$this );
3152 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3153 if ( $flags & SFH_OBJECT_ARGS
) {
3154 # Add a frame parameter, and pass the arguments as an array
3155 $allArgs = $initialArgs;
3156 $allArgs[] = $frame;
3157 for ( $i = 0; $i < $args->getLength(); $i++
) {
3158 $funcArgs[] = $args->item( $i );
3160 $allArgs[] = $funcArgs;
3162 # Convert arguments to plain text
3163 for ( $i = 0; $i < $args->getLength(); $i++
) {
3164 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3166 $allArgs = array_merge( $initialArgs, $funcArgs );
3169 # Workaround for PHP bug 35229 and similar
3170 if ( !is_callable( $callback ) ) {
3171 wfProfileOut( __METHOD__
. '-pfunc' );
3172 wfProfileOut( __METHOD__
);
3173 throw new MWException( "Tag hook for $function is not callable\n" );
3175 $result = call_user_func_array( $callback, $allArgs );
3178 $preprocessFlags = 0;
3180 if ( is_array( $result ) ) {
3181 if ( isset( $result[0] ) ) {
3183 unset( $result[0] );
3186 # Extract flags into the local scope
3187 # This allows callers to set flags such as nowiki, found, etc.
3193 $text = $this->preprocessToDom( $text, $preprocessFlags );
3198 wfProfileOut( __METHOD__
. '-pfunc' );
3201 # Finish mangling title and then check for loops.
3202 # Set $title to a Title object and $titleText to the PDBK
3205 # Split the title into page and subpage
3207 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3208 if ( $subpage !== '' ) {
3209 $ns = $this->mTitle
->getNamespace();
3211 $title = Title
::newFromText( $part1, $ns );
3213 $titleText = $title->getPrefixedText();
3214 # Check for language variants if the template is not found
3215 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3216 $wgContLang->findVariantLink( $part1, $title, true );
3218 # Do recursion depth check
3219 $limit = $this->mOptions
->getMaxTemplateDepth();
3220 if ( $frame->depth
>= $limit ) {
3222 $text = '<span class="error">'
3223 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3229 # Load from database
3230 if ( !$found && $title ) {
3231 wfProfileIn( __METHOD__
. '-loadtpl' );
3232 if ( !$title->isExternal() ) {
3233 if ( $title->getNamespace() == NS_SPECIAL
3234 && $this->mOptions
->getAllowSpecialInclusion()
3235 && $this->ot
['html'] )
3237 $text = SpecialPage
::capturePath( $title );
3238 if ( is_string( $text ) ) {
3241 $this->disableCache();
3243 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3244 $found = false; # access denied
3245 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3247 list( $text, $title ) = $this->getTemplateDom( $title );
3248 if ( $text !== false ) {
3254 # If the title is valid but undisplayable, make a link to it
3255 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3256 $text = "[[:$titleText]]";
3259 } elseif ( $title->isTrans() ) {
3260 # Interwiki transclusion
3261 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3262 $text = $this->interwikiTransclude( $title, 'render' );
3265 $text = $this->interwikiTransclude( $title, 'raw' );
3266 # Preprocess it like a template
3267 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3273 # Do infinite loop check
3274 # This has to be done after redirect resolution to avoid infinite loops via redirects
3275 if ( !$frame->loopCheck( $title ) ) {
3277 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3278 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3280 wfProfileOut( __METHOD__
. '-loadtpl' );
3283 # If we haven't found text to substitute by now, we're done
3284 # Recover the source wikitext and return it
3286 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3287 wfProfileOut( __METHOD__
);
3288 return array( 'object' => $text );
3291 # Expand DOM-style return values in a child frame
3292 if ( $isChildObj ) {
3293 # Clean up argument array
3294 $newFrame = $frame->newChild( $args, $title );
3297 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3298 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3299 # Expansion is eligible for the empty-frame cache
3300 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3301 $text = $this->mTplExpandCache
[$titleText];
3303 $text = $newFrame->expand( $text );
3304 $this->mTplExpandCache
[$titleText] = $text;
3307 # Uncached expansion
3308 $text = $newFrame->expand( $text );
3311 if ( $isLocalObj && $nowiki ) {
3312 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3313 $isLocalObj = false;
3316 # Replace raw HTML by a placeholder
3317 # Add a blank line preceding, to prevent it from mucking up
3318 # immediately preceding headings
3320 $text = "\n\n" . $this->insertStripItem( $text );
3321 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3322 # Escape nowiki-style return values
3323 $text = wfEscapeWikiText( $text );
3324 } elseif ( is_string( $text )
3325 && !$piece['lineStart']
3326 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3328 # Bug 529: if the template begins with a table or block-level
3329 # element, it should be treated as beginning a new line.
3330 # This behaviour is somewhat controversial.
3331 $text = "\n" . $text;
3334 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3335 # Error, oversize inclusion
3336 if ( $titleText !== false ) {
3337 # Make a working, properly escaped link if possible (bug 23588)
3338 $text = "[[:$titleText]]";
3340 # This will probably not be a working link, but at least it may
3341 # provide some hint of where the problem is
3342 preg_replace( '/^:/', '', $originalTitle );
3343 $text = "[[:$originalTitle]]";
3345 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3346 $this->limitationWarn( 'post-expand-template-inclusion' );
3349 if ( $isLocalObj ) {
3350 $ret = array( 'object' => $text );
3352 $ret = array( 'text' => $text );
3355 wfProfileOut( __METHOD__
);
3360 * Get the semi-parsed DOM representation of a template with a given title,
3361 * and its redirect destination title. Cached.
3363 function getTemplateDom( $title ) {
3364 $cacheTitle = $title;
3365 $titleText = $title->getPrefixedDBkey();
3367 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3368 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3369 $title = Title
::makeTitle( $ns, $dbk );
3370 $titleText = $title->getPrefixedDBkey();
3372 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3373 return array( $this->mTplDomCache
[$titleText], $title );
3376 # Cache miss, go to the database
3377 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3379 if ( $text === false ) {
3380 $this->mTplDomCache
[$titleText] = false;
3381 return array( false, $title );
3384 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3385 $this->mTplDomCache
[ $titleText ] = $dom;
3387 if ( !$title->equals( $cacheTitle ) ) {
3388 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3389 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3392 return array( $dom, $title );
3396 * Fetch the unparsed text of a template and register a reference to it.
3397 * @param Title $title
3398 * @return Array ( string or false, Title )
3400 function fetchTemplateAndTitle( $title ) {
3401 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3402 $stuff = call_user_func( $templateCb, $title, $this );
3403 $text = $stuff['text'];
3404 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3405 if ( isset( $stuff['deps'] ) ) {
3406 foreach ( $stuff['deps'] as $dep ) {
3407 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3410 return array( $text, $finalTitle );
3414 * Fetch the unparsed text of a template and register a reference to it.
3415 * @param Title $title
3416 * @return mixed string or false
3418 function fetchTemplate( $title ) {
3419 $rv = $this->fetchTemplateAndTitle( $title );
3424 * Static function to get a template
3425 * Can be overridden via ParserOptions::setTemplateCallback().
3427 static function statelessFetchTemplate( $title, $parser=false ) {
3428 $text = $skip = false;
3429 $finalTitle = $title;
3432 # Loop to fetch the article, with up to 1 redirect
3433 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3434 # Give extensions a chance to select the revision instead
3435 $id = false; # Assume current
3436 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3437 array( $parser, $title, &$skip, &$id ) );
3443 'page_id' => $title->getArticleID(),
3450 ? Revision
::newFromId( $id )
3451 : Revision
::newFromTitle( $title );
3452 $rev_id = $rev ?
$rev->getId() : 0;
3453 # If there is no current revision, there is no page
3454 if ( $id === false && !$rev ) {
3455 $linkCache = LinkCache
::singleton();
3456 $linkCache->addBadLinkObj( $title );
3461 'page_id' => $title->getArticleID(),
3462 'rev_id' => $rev_id );
3463 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3464 # We fetched a rev from a different title; register it too...
3466 'title' => $rev->getTitle(),
3467 'page_id' => $rev->getPage(),
3468 'rev_id' => $rev_id );
3472 $text = $rev->getText();
3473 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3475 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3476 if ( !$message->exists() ) {
3480 $text = $message->plain();
3484 if ( $text === false ) {
3488 $finalTitle = $title;
3489 $title = Title
::newFromRedirect( $text );
3493 'finalTitle' => $finalTitle,
3498 * Fetch a file and its title and register a reference to it.
3499 * @param Title $title
3500 * @param string $time MW timestamp
3501 * @param string $sha1 base 36 SHA-1
3502 * @return mixed File or false
3504 function fetchFile( $title, $time = false, $sha1 = false ) {
3505 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3510 * Fetch a file and its title and register a reference to it.
3511 * @param Title $title
3512 * @param string $time MW timestamp
3513 * @param string $sha1 base 36 SHA-1
3514 * @return Array ( File or false, Title of file )
3516 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3517 if ( $time === '0' ) {
3518 $file = false; // broken thumbnail forced by hook
3519 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3520 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3521 } else { // get by (name,timestamp)
3522 $file = wfFindFile( $title, array( 'time' => $time ) );
3524 $time = $file ?
$file->getTimestamp() : false;
3525 $sha1 = $file ?
$file->getSha1() : false;
3526 # Register the file as a dependency...
3527 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3528 if ( $file && !$title->equals( $file->getTitle() ) ) {
3529 # We fetched a rev from a different title; register it too...
3530 $this->mOutput
->addImage( $file->getTitle()->getDBkey(), $time, $sha1 );
3531 # Update fetched file title
3532 $title = $file->getTitle();
3534 return array( $file, $title );
3538 * Transclude an interwiki link.
3540 function interwikiTransclude( $title, $action ) {
3541 global $wgEnableScaryTranscluding;
3543 if ( !$wgEnableScaryTranscluding ) {
3544 return wfMsgForContent('scarytranscludedisabled');
3547 $url = $title->getFullUrl( "action=$action" );
3549 if ( strlen( $url ) > 255 ) {
3550 return wfMsgForContent( 'scarytranscludetoolong' );
3552 return $this->fetchScaryTemplateMaybeFromCache( $url );
3555 function fetchScaryTemplateMaybeFromCache( $url ) {
3556 global $wgTranscludeCacheExpiry;
3557 $dbr = wfGetDB( DB_SLAVE
);
3558 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3559 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3560 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3562 return $obj->tc_contents
;
3565 $text = Http
::get( $url );
3567 return wfMsgForContent( 'scarytranscludefailed', $url );
3570 $dbw = wfGetDB( DB_MASTER
);
3571 $dbw->replace( 'transcache', array('tc_url'), array(
3573 'tc_time' => $dbw->timestamp( time() ),
3574 'tc_contents' => $text)
3581 * Triple brace replacement -- used for template arguments
3584 function argSubstitution( $piece, $frame ) {
3585 wfProfileIn( __METHOD__
);
3588 $parts = $piece['parts'];
3589 $nameWithSpaces = $frame->expand( $piece['title'] );
3590 $argName = trim( $nameWithSpaces );
3592 $text = $frame->getArgument( $argName );
3593 if ( $text === false && $parts->getLength() > 0
3597 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3600 # No match in frame, use the supplied default
3601 $object = $parts->item( 0 )->getChildren();
3603 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3604 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3605 $this->limitationWarn( 'post-expand-template-argument' );
3608 if ( $text === false && $object === false ) {
3610 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3612 if ( $error !== false ) {
3615 if ( $object !== false ) {
3616 $ret = array( 'object' => $object );
3618 $ret = array( 'text' => $text );
3621 wfProfileOut( __METHOD__
);
3626 * Return the text to be used for a given extension tag.
3627 * This is the ghost of strip().
3629 * @param $params Associative array of parameters:
3630 * name PPNode for the tag name
3631 * attr PPNode for unparsed text where tag attributes are thought to be
3632 * attributes Optional associative array of parsed attributes
3633 * inner Contents of extension element
3634 * noClose Original text did not have a close tag
3635 * @param $frame PPFrame
3637 function extensionSubstitution( $params, $frame ) {
3638 $name = $frame->expand( $params['name'] );
3639 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3640 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3641 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3643 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3644 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3645 if ( $isFunctionTag ) {
3646 $markerType = 'none';
3648 $markerType = 'general';
3650 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3651 $name = strtolower( $name );
3652 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3653 if ( isset( $params['attributes'] ) ) {
3654 $attributes = $attributes +
$params['attributes'];
3657 if ( isset( $this->mTagHooks
[$name] ) ) {
3658 # Workaround for PHP bug 35229 and similar
3659 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3660 throw new MWException( "Tag hook for $name is not callable\n" );
3662 $output = call_user_func_array( $this->mTagHooks
[$name],
3663 array( $content, $attributes, $this, $frame ) );
3664 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3665 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3666 if ( !is_callable( $callback ) ) {
3667 throw new MWException( "Tag hook for $name is not callable\n" );
3670 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3672 $output = '<span class="error">Invalid tag extension name: ' .
3673 htmlspecialchars( $name ) . '</span>';
3676 if ( is_array( $output ) ) {
3677 # Extract flags to local scope (to override $markerType)
3679 $output = $flags[0];
3684 if ( is_null( $attrText ) ) {
3687 if ( isset( $params['attributes'] ) ) {
3688 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3689 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3690 htmlspecialchars( $attrValue ) . '"';
3693 if ( $content === null ) {
3694 $output = "<$name$attrText/>";
3696 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3697 $output = "<$name$attrText>$content$close";
3701 if ( $markerType === 'none' ) {
3703 } elseif ( $markerType === 'nowiki' ) {
3704 $this->mStripState
->addNoWiki( $marker, $output );
3705 } elseif ( $markerType === 'general' ) {
3706 $this->mStripState
->addGeneral( $marker, $output );
3708 throw new MWException( __METHOD__
.': invalid marker type' );
3714 * Increment an include size counter
3716 * @param $type String: the type of expansion
3717 * @param $size Integer: the size of the text
3718 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3720 function incrementIncludeSize( $type, $size ) {
3721 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3724 $this->mIncludeSizes
[$type] +
= $size;
3730 * Increment the expensive function count
3732 * @return Boolean: false if the limit has been exceeded
3734 function incrementExpensiveFunctionCount() {
3735 global $wgExpensiveParserFunctionLimit;
3736 $this->mExpensiveFunctionCount++
;
3737 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3744 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3745 * Fills $this->mDoubleUnderscores, returns the modified text
3747 function doDoubleUnderscore( $text ) {
3748 wfProfileIn( __METHOD__
);
3750 # The position of __TOC__ needs to be recorded
3751 $mw = MagicWord
::get( 'toc' );
3752 if ( $mw->match( $text ) ) {
3753 $this->mShowToc
= true;
3754 $this->mForceTocPosition
= true;
3756 # Set a placeholder. At the end we'll fill it in with the TOC.
3757 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3759 # Only keep the first one.
3760 $text = $mw->replace( '', $text );
3763 # Now match and remove the rest of them
3764 $mwa = MagicWord
::getDoubleUnderscoreArray();
3765 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3767 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3768 $this->mOutput
->mNoGallery
= true;
3770 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3771 $this->mShowToc
= false;
3773 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3774 $this->addTrackingCategory( 'hidden-category-category' );
3776 # (bug 8068) Allow control over whether robots index a page.
3778 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3779 # is not desirable, the last one on the page should win.
3780 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3781 $this->mOutput
->setIndexPolicy( 'noindex' );
3782 $this->addTrackingCategory( 'noindex-category' );
3784 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3785 $this->mOutput
->setIndexPolicy( 'index' );
3786 $this->addTrackingCategory( 'index-category' );
3789 # Cache all double underscores in the database
3790 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3791 $this->mOutput
->setProperty( $key, '' );
3794 wfProfileOut( __METHOD__
);
3799 * Add a tracking category, getting the title from a system message,
3800 * or print a debug message if the title is invalid.
3802 * @param $msg String: message key
3803 * @return Boolean: whether the addition was successful
3805 protected function addTrackingCategory( $msg ) {
3806 $cat = wfMsgForContent( $msg );
3808 # Allow tracking categories to be disabled by setting them to "-"
3809 if ( $cat === '-' ) {
3813 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3814 if ( $containerCategory ) {
3815 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3818 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3824 * This function accomplishes several tasks:
3825 * 1) Auto-number headings if that option is enabled
3826 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3827 * 3) Add a Table of contents on the top for users who have enabled the option
3828 * 4) Auto-anchor headings
3830 * It loops through all headlines, collects the necessary data, then splits up the
3831 * string and re-inserts the newly formatted headlines.
3833 * @param $text String
3834 * @param $origText String: original, untouched wikitext
3835 * @param $isMain Boolean
3838 function formatHeadings( $text, $origText, $isMain=true ) {
3839 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3841 # Inhibit editsection links if requested in the page
3842 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3845 $showEditLink = $this->mOptions
->getEditSection();
3847 if ( $showEditLink ) {
3848 $this->mOutput
->setEditSectionTokens( true );
3851 # Get all headlines for numbering them and adding funky stuff like [edit]
3852 # links - this is for later, but we need the number of headlines right now
3854 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3856 # if there are fewer than 4 headlines in the article, do not show TOC
3857 # unless it's been explicitly enabled.
3858 $enoughToc = $this->mShowToc
&&
3859 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3861 # Allow user to stipulate that a page should have a "new section"
3862 # link added via __NEWSECTIONLINK__
3863 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3864 $this->mOutput
->setNewSection( true );
3867 # Allow user to remove the "new section"
3868 # link via __NONEWSECTIONLINK__
3869 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3870 $this->mOutput
->hideNewSection( true );
3873 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3874 # override above conditions and always show TOC above first header
3875 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3876 $this->mShowToc
= true;
3884 # Ugh .. the TOC should have neat indentation levels which can be
3885 # passed to the skin functions. These are determined here
3889 $sublevelCount = array();
3890 $levelCount = array();
3895 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3896 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3897 $oldType = $this->mOutputType
;
3898 $this->setOutputType( self
::OT_WIKI
);
3899 $frame = $this->getPreprocessor()->newFrame();
3900 $root = $this->preprocessToDom( $origText );
3901 $node = $root->getFirstChild();
3906 foreach ( $matches[3] as $headline ) {
3907 $isTemplate = false;
3909 $sectionIndex = false;
3911 $markerMatches = array();
3912 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3913 $serial = $markerMatches[1];
3914 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3915 $isTemplate = ( $titleText != $baseTitleText );
3916 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3920 $prevlevel = $level;
3922 $level = $matches[1][$headlineCount];
3924 if ( $level > $prevlevel ) {
3925 # Increase TOC level
3927 $sublevelCount[$toclevel] = 0;
3928 if ( $toclevel<$wgMaxTocLevel ) {
3929 $prevtoclevel = $toclevel;
3930 $toc .= Linker
::tocIndent();
3933 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3934 # Decrease TOC level, find level to jump to
3936 for ( $i = $toclevel; $i > 0; $i-- ) {
3937 if ( $levelCount[$i] == $level ) {
3938 # Found last matching level
3941 } elseif ( $levelCount[$i] < $level ) {
3942 # Found first matching level below current level
3950 if ( $toclevel<$wgMaxTocLevel ) {
3951 if ( $prevtoclevel < $wgMaxTocLevel ) {
3952 # Unindent only if the previous toc level was shown :p
3953 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3954 $prevtoclevel = $toclevel;
3956 $toc .= Linker
::tocLineEnd();
3960 # No change in level, end TOC line
3961 if ( $toclevel<$wgMaxTocLevel ) {
3962 $toc .= Linker
::tocLineEnd();
3966 $levelCount[$toclevel] = $level;
3968 # count number of headlines for each level
3969 @$sublevelCount[$toclevel]++
;
3971 for( $i = 1; $i <= $toclevel; $i++
) {
3972 if ( !empty( $sublevelCount[$i] ) ) {
3976 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3981 # The safe header is a version of the header text safe to use for links
3982 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3983 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3985 # Remove link placeholders by the link text.
3986 # <!--LINK number-->
3988 # link text with suffix
3989 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3991 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3992 $tocline = preg_replace(
3993 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3994 array( '', '<$1>' ),
3997 $tocline = trim( $tocline );
3999 # For the anchor, strip out HTML-y stuff period
4000 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4001 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4003 # Save headline for section edit hint before it's escaped
4004 $headlineHint = $safeHeadline;
4006 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4007 # For reverse compatibility, provide an id that's
4008 # HTML4-compatible, like we used to.
4010 # It may be worth noting, academically, that it's possible for
4011 # the legacy anchor to conflict with a non-legacy headline
4012 # anchor on the page. In this case likely the "correct" thing
4013 # would be to either drop the legacy anchors or make sure
4014 # they're numbered first. However, this would require people
4015 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4016 # manually, so let's not bother worrying about it.
4017 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4018 array( 'noninitial', 'legacy' ) );
4019 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4021 if ( $legacyHeadline == $safeHeadline ) {
4022 # No reason to have both (in fact, we can't)
4023 $legacyHeadline = false;
4026 $legacyHeadline = false;
4027 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4031 # HTML names must be case-insensitively unique (bug 10721).
4032 # This does not apply to Unicode characters per
4033 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4034 # FIXME: We may be changing them depending on the current locale.
4035 $arrayKey = strtolower( $safeHeadline );
4036 if ( $legacyHeadline === false ) {
4037 $legacyArrayKey = false;
4039 $legacyArrayKey = strtolower( $legacyHeadline );
4042 # count how many in assoc. array so we can track dupes in anchors
4043 if ( isset( $refers[$arrayKey] ) ) {
4044 $refers[$arrayKey]++
;
4046 $refers[$arrayKey] = 1;
4048 if ( isset( $refers[$legacyArrayKey] ) ) {
4049 $refers[$legacyArrayKey]++
;
4051 $refers[$legacyArrayKey] = 1;
4054 # Don't number the heading if it is the only one (looks silly)
4055 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4056 # the two are different if the line contains a link
4057 $headline = $numbering . ' ' . $headline;
4060 # Create the anchor for linking from the TOC to the section
4061 $anchor = $safeHeadline;
4062 $legacyAnchor = $legacyHeadline;
4063 if ( $refers[$arrayKey] > 1 ) {
4064 $anchor .= '_' . $refers[$arrayKey];
4066 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4067 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4069 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4070 $toc .= Linker
::tocLine( $anchor, $tocline,
4071 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4074 # Add the section to the section tree
4075 # Find the DOM node for this header
4076 while ( $node && !$isTemplate ) {
4077 if ( $node->getName() === 'h' ) {
4078 $bits = $node->splitHeading();
4079 if ( $bits['i'] == $sectionIndex ) {
4083 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4084 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4085 $node = $node->getNextSibling();
4088 'toclevel' => $toclevel,
4091 'number' => $numbering,
4092 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4093 'fromtitle' => $titleText,
4094 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4095 'anchor' => $anchor,
4098 # give headline the correct <h#> tag
4099 if ( $showEditLink && $sectionIndex !== false ) {
4100 // Output edit section links as markers with styles that can be customized by skins
4101 if ( $isTemplate ) {
4102 # Put a T flag in the section identifier, to indicate to extractSections()
4103 # that sections inside <includeonly> should be counted.
4104 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4106 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4108 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4109 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4110 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4111 // so we don't have to worry about a user trying to input one of these markers directly.
4112 // We use a page and section attribute to stop the language converter from converting these important bits
4113 // of data, but put the headline hint inside a content block because the language converter is supposed to
4114 // be able to convert that piece of data.
4115 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4116 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4117 if ( isset($editlinkArgs[2]) ) {
4118 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4125 $head[$headlineCount] = Linker
::makeHeadline( $level,
4126 $matches['attrib'][$headlineCount], $anchor, $headline,
4127 $editlink, $legacyAnchor );
4132 $this->setOutputType( $oldType );
4134 # Never ever show TOC if no headers
4135 if ( $numVisible < 1 ) {
4140 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4141 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4143 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4144 $this->mOutput
->setTOCHTML( $toc );
4148 $this->mOutput
->setSections( $tocraw );
4151 # split up and insert constructed headlines
4153 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4156 foreach ( $blocks as $block ) {
4157 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4158 # This is the [edit] link that appears for the top block of text when
4159 # section editing is enabled
4161 # Disabled because it broke block formatting
4162 # For example, a bullet point in the top line
4163 # $full .= $sk->editSectionLink(0);
4166 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4167 # Top anchor now in skin
4171 if ( !empty( $head[$i] ) ) {
4176 if ( $this->mForceTocPosition
) {
4177 return str_replace( '<!--MWTOC-->', $toc, $full );
4184 * Transform wiki markup when saving a page by doing \r\n -> \n
4185 * conversion, substitting signatures, {{subst:}} templates, etc.
4187 * @param $text String: the text to transform
4188 * @param $title Title: the Title object for the current article
4189 * @param $user User: the User object describing the current user
4190 * @param $options ParserOptions: parsing options
4191 * @param $clearState Boolean: whether to clear the parser state first
4192 * @return String: the altered wiki markup
4194 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4195 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4196 $this->setUser( $user );
4201 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4202 if( $options->getPreSaveTransform() ) {
4203 $text = $this->pstPass2( $text, $user );
4205 $text = $this->mStripState
->unstripBoth( $text );
4207 $this->setUser( null ); #Reset
4213 * Pre-save transform helper function
4216 function pstPass2( $text, $user ) {
4217 global $wgContLang, $wgLocaltimezone;
4219 # Note: This is the timestamp saved as hardcoded wikitext to
4220 # the database, we use $wgContLang here in order to give
4221 # everyone the same signature and use the default one rather
4222 # than the one selected in each user's preferences.
4223 # (see also bug 12815)
4224 $ts = $this->mOptions
->getTimestamp();
4225 if ( isset( $wgLocaltimezone ) ) {
4226 $tz = $wgLocaltimezone;
4228 $tz = date_default_timezone_get();
4231 $unixts = wfTimestamp( TS_UNIX
, $ts );
4232 $oldtz = date_default_timezone_get();
4233 date_default_timezone_set( $tz );
4234 $ts = date( 'YmdHis', $unixts );
4235 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4237 # Allow translation of timezones through wiki. date() can return
4238 # whatever crap the system uses, localised or not, so we cannot
4239 # ship premade translations.
4240 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4241 $msg = wfMessage( $key )->inContentLanguage();
4242 if ( $msg->exists() ) {
4243 $tzMsg = $msg->text();
4246 date_default_timezone_set( $oldtz );
4248 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4250 # Variable replacement
4251 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4252 $text = $this->replaceVariables( $text );
4254 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4255 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4258 $sigText = $this->getUserSig( $user );
4259 $text = strtr( $text, array(
4261 '~~~~' => "$sigText $d",
4265 # Context links: [[|name]] and [[name (context)|]]
4266 global $wgLegalTitleChars;
4267 $tc = "[$wgLegalTitleChars]";
4268 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4270 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4271 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4272 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4273 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4275 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4276 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4277 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4278 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4280 $t = $this->mTitle
->getText();
4282 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4283 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4284 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4285 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4287 # if there's no context, don't bother duplicating the title
4288 $text = preg_replace( $p2, '[[\\1]]', $text );
4291 # Trim trailing whitespace
4292 $text = rtrim( $text );
4298 * Fetch the user's signature text, if any, and normalize to
4299 * validated, ready-to-insert wikitext.
4300 * If you have pre-fetched the nickname or the fancySig option, you can
4301 * specify them here to save a database query.
4302 * Do not reuse this parser instance after calling getUserSig(),
4303 * as it may have changed if it's the $wgParser.
4306 * @param $nickname String: nickname to use or false to use user's default nickname
4307 * @param $fancySig Boolean: whether the nicknname is the complete signature
4308 * or null to use default value
4311 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4312 global $wgMaxSigChars;
4314 $username = $user->getName();
4316 # If not given, retrieve from the user object.
4317 if ( $nickname === false )
4318 $nickname = $user->getOption( 'nickname' );
4320 if ( is_null( $fancySig ) ) {
4321 $fancySig = $user->getBoolOption( 'fancysig' );
4324 $nickname = $nickname == null ?
$username : $nickname;
4326 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4327 $nickname = $username;
4328 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4329 } elseif ( $fancySig !== false ) {
4330 # Sig. might contain markup; validate this
4331 if ( $this->validateSig( $nickname ) !== false ) {
4332 # Validated; clean up (if needed) and return it
4333 return $this->cleanSig( $nickname, true );
4335 # Failed to validate; fall back to the default
4336 $nickname = $username;
4337 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4341 # Make sure nickname doesnt get a sig in a sig
4342 $nickname = $this->cleanSigInSig( $nickname );
4344 # If we're still here, make it a link to the user page
4345 $userText = wfEscapeWikiText( $username );
4346 $nickText = wfEscapeWikiText( $nickname );
4347 if ( $user->isAnon() ) {
4348 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4350 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4355 * Check that the user's signature contains no bad XML
4357 * @param $text String
4358 * @return mixed An expanded string, or false if invalid.
4360 function validateSig( $text ) {
4361 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4365 * Clean up signature text
4367 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4368 * 2) Substitute all transclusions
4370 * @param $text String
4371 * @param $parsing Whether we're cleaning (preferences save) or parsing
4372 * @return String: signature text
4374 function cleanSig( $text, $parsing = false ) {
4377 $this->mOptions
= new ParserOptions
;
4378 $this->clearState();
4379 $this->setTitle( $wgTitle );
4380 $this->setOutputType
= self
::OT_PREPROCESS
;
4383 # Option to disable this feature
4384 if ( !$this->mOptions
->getCleanSignatures() ) {
4388 # FIXME: regex doesn't respect extension tags or nowiki
4389 # => Move this logic to braceSubstitution()
4390 $substWord = MagicWord
::get( 'subst' );
4391 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4392 $substText = '{{' . $substWord->getSynonym( 0 );
4394 $text = preg_replace( $substRegex, $substText, $text );
4395 $text = $this->cleanSigInSig( $text );
4396 $dom = $this->preprocessToDom( $text );
4397 $frame = $this->getPreprocessor()->newFrame();
4398 $text = $frame->expand( $dom );
4401 $text = $this->mStripState
->unstripBoth( $text );
4408 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4410 * @param $text String
4411 * @return String: signature text with /~{3,5}/ removed
4413 function cleanSigInSig( $text ) {
4414 $text = preg_replace( '/~{3,5}/', '', $text );
4419 * Set up some variables which are usually set up in parse()
4420 * so that an external function can call some class members with confidence
4422 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4423 $this->startParse( $title, $options, $outputType, $clearState );
4426 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4427 $this->setTitle( $title );
4428 $this->mOptions
= $options;
4429 $this->setOutputType( $outputType );
4430 if ( $clearState ) {
4431 $this->clearState();
4436 * Wrapper for preprocess()
4438 * @param $text String: the text to preprocess
4439 * @param $options ParserOptions: options
4440 * @param $title Title object or null to use $wgTitle
4443 public function transformMsg( $text, $options, $title = null ) {
4444 static $executing = false;
4446 # Guard against infinite recursion
4452 wfProfileIn( __METHOD__
);
4458 # It's not uncommon having a null $wgTitle in scripts. See r80898
4459 # Create a ghost title in such case
4460 $title = Title
::newFromText( 'Dwimmerlaik' );
4462 $text = $this->preprocess( $text, $title, $options );
4465 wfProfileOut( __METHOD__
);
4470 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4471 * The callback should have the following form:
4472 * function myParserHook( $text, $params, $parser ) { ... }
4474 * Transform and return $text. Use $parser for any required context, e.g. use
4475 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4477 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4478 * @param $callback Mixed: the callback function (and object) to use for the tag
4479 * @return The old value of the mTagHooks array associated with the hook
4481 public function setHook( $tag, $callback ) {
4482 $tag = strtolower( $tag );
4483 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4484 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4485 $this->mTagHooks
[$tag] = $callback;
4486 if ( !in_array( $tag, $this->mStripList
) ) {
4487 $this->mStripList
[] = $tag;
4493 function setTransparentTagHook( $tag, $callback ) {
4494 $tag = strtolower( $tag );
4495 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4496 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4497 $this->mTransparentTagHooks
[$tag] = $callback;
4503 * Remove all tag hooks
4505 function clearTagHooks() {
4506 $this->mTagHooks
= array();
4507 $this->mStripList
= $this->mDefaultStripList
;
4511 * Create a function, e.g. {{sum:1|2|3}}
4512 * The callback function should have the form:
4513 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4515 * Or with SFH_OBJECT_ARGS:
4516 * function myParserFunction( $parser, $frame, $args ) { ... }
4518 * The callback may either return the text result of the function, or an array with the text
4519 * in element 0, and a number of flags in the other elements. The names of the flags are
4520 * specified in the keys. Valid flags are:
4521 * found The text returned is valid, stop processing the template. This
4523 * nowiki Wiki markup in the return value should be escaped
4524 * isHTML The returned text is HTML, armour it against wikitext transformation
4526 * @param $id String: The magic word ID
4527 * @param $callback Mixed: the callback function (and object) to use
4528 * @param $flags Integer: a combination of the following flags:
4529 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4531 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4532 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4533 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4534 * the arguments, and to control the way they are expanded.
4536 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4537 * arguments, for instance:
4538 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4540 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4541 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4542 * working if/when this is changed.
4544 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4547 * Please read the documentation in includes/parser/Preprocessor.php for more information
4548 * about the methods available in PPFrame and PPNode.
4550 * @return The old callback function for this name, if any
4552 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4555 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4556 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4558 # Add to function cache
4559 $mw = MagicWord
::get( $id );
4561 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4563 $synonyms = $mw->getSynonyms();
4564 $sensitive = intval( $mw->isCaseSensitive() );
4566 foreach ( $synonyms as $syn ) {
4568 if ( !$sensitive ) {
4569 $syn = $wgContLang->lc( $syn );
4572 if ( !( $flags & SFH_NO_HASH
) ) {
4575 # Remove trailing colon
4576 if ( substr( $syn, -1, 1 ) === ':' ) {
4577 $syn = substr( $syn, 0, -1 );
4579 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4585 * Get all registered function hook identifiers
4589 function getFunctionHooks() {
4590 return array_keys( $this->mFunctionHooks
);
4594 * Create a tag function, e.g. <test>some stuff</test>.
4595 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4596 * Unlike parser functions, their content is not preprocessed.
4598 function setFunctionTagHook( $tag, $callback, $flags ) {
4599 $tag = strtolower( $tag );
4600 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4601 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4602 $this->mFunctionTagHooks
[$tag] : null;
4603 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4605 if ( !in_array( $tag, $this->mStripList
) ) {
4606 $this->mStripList
[] = $tag;
4613 * FIXME: update documentation. makeLinkObj() is deprecated.
4614 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4615 * Placeholders created in Skin::makeLinkObj()
4616 * Returns an array of link CSS classes, indexed by PDBK.
4618 function replaceLinkHolders( &$text, $options = 0 ) {
4619 return $this->mLinkHolders
->replace( $text );
4623 * Replace <!--LINK--> link placeholders with plain text of links
4624 * (not HTML-formatted).
4626 * @param $text String
4629 function replaceLinkHoldersText( $text ) {
4630 return $this->mLinkHolders
->replaceText( $text );
4634 * Renders an image gallery from a text with one line per image.
4635 * text labels may be given by using |-style alternative text. E.g.
4636 * Image:one.jpg|The number "1"
4637 * Image:tree.jpg|A tree
4638 * given as text will return the HTML of a gallery with two images,
4639 * labeled 'The number "1"' and
4642 function renderImageGallery( $text, $params ) {
4643 $ig = new ImageGallery();
4644 $ig->setContextTitle( $this->mTitle
);
4645 $ig->setShowBytes( false );
4646 $ig->setShowFilename( false );
4647 $ig->setParser( $this );
4648 $ig->setHideBadImages();
4649 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4651 if ( isset( $params['showfilename'] ) ) {
4652 $ig->setShowFilename( true );
4654 $ig->setShowFilename( false );
4656 if ( isset( $params['caption'] ) ) {
4657 $caption = $params['caption'];
4658 $caption = htmlspecialchars( $caption );
4659 $caption = $this->replaceInternalLinks( $caption );
4660 $ig->setCaptionHtml( $caption );
4662 if ( isset( $params['perrow'] ) ) {
4663 $ig->setPerRow( $params['perrow'] );
4665 if ( isset( $params['widths'] ) ) {
4666 $ig->setWidths( $params['widths'] );
4668 if ( isset( $params['heights'] ) ) {
4669 $ig->setHeights( $params['heights'] );
4672 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4674 $lines = StringUtils
::explode( "\n", $text );
4675 foreach ( $lines as $line ) {
4676 # match lines like these:
4677 # Image:someimage.jpg|This is some image
4679 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4681 if ( count( $matches ) == 0 ) {
4685 if ( strpos( $matches[0], '%' ) !== false ) {
4686 $matches[1] = rawurldecode( $matches[1] );
4688 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4690 if ( is_null( $nt ) ) {
4691 # Bogus title. Ignore these so we don't bomb out later.
4694 if ( isset( $matches[3] ) ) {
4695 $label = $matches[3];
4700 $html = $this->recursiveTagParse( trim( $label ) );
4702 $ig->add( $nt, $html );
4704 return $ig->toHTML();
4707 function getImageParams( $handler ) {
4709 $handlerClass = get_class( $handler );
4713 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4714 # Initialise static lists
4715 static $internalParamNames = array(
4716 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4717 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4718 'bottom', 'text-bottom' ),
4719 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4720 'upright', 'border', 'link', 'alt' ),
4722 static $internalParamMap;
4723 if ( !$internalParamMap ) {
4724 $internalParamMap = array();
4725 foreach ( $internalParamNames as $type => $names ) {
4726 foreach ( $names as $name ) {
4727 $magicName = str_replace( '-', '_', "img_$name" );
4728 $internalParamMap[$magicName] = array( $type, $name );
4733 # Add handler params
4734 $paramMap = $internalParamMap;
4736 $handlerParamMap = $handler->getParamMap();
4737 foreach ( $handlerParamMap as $magic => $paramName ) {
4738 $paramMap[$magic] = array( 'handler', $paramName );
4741 $this->mImageParams
[$handlerClass] = $paramMap;
4742 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4744 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4748 * Parse image options text and use it to make an image
4750 * @param $title Title
4751 * @param $options String
4752 * @param $holders LinkHolderArray
4753 * @return string HTML
4755 function makeImage( $title, $options, $holders = false ) {
4756 # Check if the options text is of the form "options|alt text"
4758 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4759 # * left no resizing, just left align. label is used for alt= only
4760 # * right same, but right aligned
4761 # * none same, but not aligned
4762 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4763 # * center center the image
4764 # * frame Keep original image size, no magnify-button.
4765 # * framed Same as "frame"
4766 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4767 # * upright reduce width for upright images, rounded to full __0 px
4768 # * border draw a 1px border around the image
4769 # * alt Text for HTML alt attribute (defaults to empty)
4770 # * link Set the target of the image link. Can be external, interwiki, or local
4771 # vertical-align values (no % or length right now):
4781 $parts = StringUtils
::explode( "|", $options );
4783 # Give extensions a chance to select the file revision for us
4784 $time = $sha1 = $descQuery = false;
4785 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4786 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4787 # Fetch and register the file (file title may be different via hooks)
4788 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4791 $handler = $file ?
$file->getHandler() : false;
4793 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4795 # Process the input parameters
4797 $params = array( 'frame' => array(), 'handler' => array(),
4798 'horizAlign' => array(), 'vertAlign' => array() );
4799 foreach ( $parts as $part ) {
4800 $part = trim( $part );
4801 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4803 if ( isset( $paramMap[$magicName] ) ) {
4804 list( $type, $paramName ) = $paramMap[$magicName];
4806 # Special case; width and height come in one variable together
4807 if ( $type === 'handler' && $paramName === 'width' ) {
4809 # (bug 13500) In both cases (width/height and width only),
4810 # permit trailing "px" for backward compatibility.
4811 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4812 $width = intval( $m[1] );
4813 $height = intval( $m[2] );
4814 if ( $handler->validateParam( 'width', $width ) ) {
4815 $params[$type]['width'] = $width;
4818 if ( $handler->validateParam( 'height', $height ) ) {
4819 $params[$type]['height'] = $height;
4822 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4823 $width = intval( $value );
4824 if ( $handler->validateParam( 'width', $width ) ) {
4825 $params[$type]['width'] = $width;
4828 } # else no validation -- bug 13436
4830 if ( $type === 'handler' ) {
4831 # Validate handler parameter
4832 $validated = $handler->validateParam( $paramName, $value );
4834 # Validate internal parameters
4835 switch( $paramName ) {
4838 # @todo Fixme: possibly check validity here for
4839 # manualthumb? downstream behavior seems odd with
4840 # missing manual thumbs.
4842 $value = $this->stripAltText( $value, $holders );
4845 $chars = self
::EXT_LINK_URL_CLASS
;
4846 $prots = $this->mUrlProtocols
;
4847 if ( $value === '' ) {
4848 $paramName = 'no-link';
4851 } elseif ( preg_match( "/^$prots/", $value ) ) {
4852 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4853 $paramName = 'link-url';
4854 $this->mOutput
->addExternalLink( $value );
4855 if ( $this->mOptions
->getExternalLinkTarget() ) {
4856 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4861 $linkTitle = Title
::newFromText( $value );
4863 $paramName = 'link-title';
4864 $value = $linkTitle;
4865 $this->mOutput
->addLink( $linkTitle );
4871 # Most other things appear to be empty or numeric...
4872 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4877 $params[$type][$paramName] = $value;
4881 if ( !$validated ) {
4886 # Process alignment parameters
4887 if ( $params['horizAlign'] ) {
4888 $params['frame']['align'] = key( $params['horizAlign'] );
4890 if ( $params['vertAlign'] ) {
4891 $params['frame']['valign'] = key( $params['vertAlign'] );
4894 $params['frame']['caption'] = $caption;
4896 # Will the image be presented in a frame, with the caption below?
4897 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4898 isset( $params['frame']['framed'] ) ||
4899 isset( $params['frame']['thumbnail'] ) ||
4900 isset( $params['frame']['manualthumb'] );
4902 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4903 # came to also set the caption, ordinary text after the image -- which
4904 # makes no sense, because that just repeats the text multiple times in
4905 # screen readers. It *also* came to set the title attribute.
4907 # Now that we have an alt attribute, we should not set the alt text to
4908 # equal the caption: that's worse than useless, it just repeats the
4909 # text. This is the framed/thumbnail case. If there's no caption, we
4910 # use the unnamed parameter for alt text as well, just for the time be-
4911 # ing, if the unnamed param is set and the alt param is not.
4913 # For the future, we need to figure out if we want to tweak this more,
4914 # e.g., introducing a title= parameter for the title; ignoring the un-
4915 # named parameter entirely for images without a caption; adding an ex-
4916 # plicit caption= parameter and preserving the old magic unnamed para-
4918 if ( $imageIsFramed ) { # Framed image
4919 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4920 # No caption or alt text, add the filename as the alt text so
4921 # that screen readers at least get some description of the image
4922 $params['frame']['alt'] = $title->getText();
4924 # Do not set $params['frame']['title'] because tooltips don't make sense
4926 } else { # Inline image
4927 if ( !isset( $params['frame']['alt'] ) ) {
4928 # No alt text, use the "caption" for the alt text
4929 if ( $caption !== '') {
4930 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4932 # No caption, fall back to using the filename for the
4934 $params['frame']['alt'] = $title->getText();
4937 # Use the "caption" for the tooltip text
4938 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4941 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4943 # Linker does the rest
4944 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
4945 $time, $descQuery, $this->mOptions
->getThumbSize() );
4947 # Give the handler a chance to modify the parser object
4949 $handler->parserTransformHook( $this, $file );
4955 protected function stripAltText( $caption, $holders ) {
4956 # Strip bad stuff out of the title (tooltip). We can't just use
4957 # replaceLinkHoldersText() here, because if this function is called
4958 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4960 $tooltip = $holders->replaceText( $caption );
4962 $tooltip = $this->replaceLinkHoldersText( $caption );
4965 # make sure there are no placeholders in thumbnail attributes
4966 # that are later expanded to html- so expand them now and
4968 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4969 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4975 * Set a flag in the output object indicating that the content is dynamic and
4976 * shouldn't be cached.
4978 function disableCache() {
4979 wfDebug( "Parser output marked as uncacheable.\n" );
4980 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4981 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4985 * Callback from the Sanitizer for expanding items found in HTML attribute
4986 * values, so they can be safely tested and escaped.
4988 * @param $text String
4989 * @param $frame PPFrame
4993 function attributeStripCallback( &$text, $frame = false ) {
4994 $text = $this->replaceVariables( $text, $frame );
4995 $text = $this->mStripState
->unstripBoth( $text );
5002 function getTags() {
5003 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5007 * Replace transparent tags in $text with the values given by the callbacks.
5009 * Transparent tag hooks are like regular XML-style tag hooks, except they
5010 * operate late in the transformation sequence, on HTML instead of wikitext.
5012 function replaceTransparentTags( $text ) {
5014 $elements = array_keys( $this->mTransparentTagHooks
);
5015 $text = $this->extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5017 foreach ( $matches as $marker => $data ) {
5018 list( $element, $content, $params, $tag ) = $data;
5019 $tagName = strtolower( $element );
5020 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5021 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5025 $this->mStripState
->addGeneral( $marker, $output );
5031 * Break wikitext input into sections, and either pull or replace
5032 * some particular section's text.
5034 * External callers should use the getSection and replaceSection methods.
5036 * @param $text String: Page wikitext
5037 * @param $section String: a section identifier string of the form:
5038 * <flag1> - <flag2> - ... - <section number>
5040 * Currently the only recognised flag is "T", which means the target section number
5041 * was derived during a template inclusion parse, in other words this is a template
5042 * section edit link. If no flags are given, it was an ordinary section edit link.
5043 * This flag is required to avoid a section numbering mismatch when a section is
5044 * enclosed by <includeonly> (bug 6563).
5046 * The section number 0 pulls the text before the first heading; other numbers will
5047 * pull the given section along with its lower-level subsections. If the section is
5048 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5050 * @param $mode String: one of "get" or "replace"
5051 * @param $newText String: replacement text for section data.
5052 * @return String: for "get", the extracted section text.
5053 * for "replace", the whole page with the section replaced.
5055 private function extractSections( $text, $section, $mode, $newText='' ) {
5056 global $wgTitle; # not generally used but removes an ugly failure mode
5057 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5059 $frame = $this->getPreprocessor()->newFrame();
5061 # Process section extraction flags
5063 $sectionParts = explode( '-', $section );
5064 $sectionIndex = array_pop( $sectionParts );
5065 foreach ( $sectionParts as $part ) {
5066 if ( $part === 'T' ) {
5067 $flags |
= self
::PTD_FOR_INCLUSION
;
5070 # Preprocess the text
5071 $root = $this->preprocessToDom( $text, $flags );
5073 # <h> nodes indicate section breaks
5074 # They can only occur at the top level, so we can find them by iterating the root's children
5075 $node = $root->getFirstChild();
5077 # Find the target section
5078 if ( $sectionIndex == 0 ) {
5079 # Section zero doesn't nest, level=big
5080 $targetLevel = 1000;
5082 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5087 if ( $node->getName() === 'h' ) {
5088 $bits = $node->splitHeading();
5089 if ( $bits['i'] == $sectionIndex ) {
5090 $targetLevel = $bits['level'];
5094 if ( $mode === 'replace' ) {
5095 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5097 $node = $node->getNextSibling();
5103 if ( $mode === 'get' ) {
5110 # Find the end of the section, including nested sections
5112 if ( $node->getName() === 'h' ) {
5113 $bits = $node->splitHeading();
5114 $curLevel = $bits['level'];
5115 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5119 if ( $mode === 'get' ) {
5120 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5122 $node = $node->getNextSibling();
5125 # Write out the remainder (in replace mode only)
5126 if ( $mode === 'replace' ) {
5127 # Output the replacement text
5128 # Add two newlines on -- trailing whitespace in $newText is conventionally
5129 # stripped by the editor, so we need both newlines to restore the paragraph gap
5130 # Only add trailing whitespace if there is newText
5131 if ( $newText != "" ) {
5132 $outText .= $newText . "\n\n";
5136 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5137 $node = $node->getNextSibling();
5141 if ( is_string( $outText ) ) {
5142 # Re-insert stripped tags
5143 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5150 * This function returns the text of a section, specified by a number ($section).
5151 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5152 * the first section before any such heading (section 0).
5154 * If a section contains subsections, these are also returned.
5156 * @param $text String: text to look in
5157 * @param $section String: section identifier
5158 * @param $deftext String: default to return if section is not found
5159 * @return string text of the requested section
5161 public function getSection( $text, $section, $deftext='' ) {
5162 return $this->extractSections( $text, $section, "get", $deftext );
5166 * This function returns $oldtext after the content of the section
5167 * specified by $section has been replaced with $text.
5169 * @param $text String: former text of the article
5170 * @param $section Numeric: section identifier
5171 * @param $text String: replacing text
5172 * #return String: modified text
5174 public function replaceSection( $oldtext, $section, $text ) {
5175 return $this->extractSections( $oldtext, $section, "replace", $text );
5179 * Get the ID of the revision we are parsing
5181 * @return Mixed: integer or null
5183 function getRevisionId() {
5184 return $this->mRevisionId
;
5188 * Get the revision object for $this->mRevisionId
5190 * @return either a Revision object or null
5192 protected function getRevisionObject() {
5193 if ( !is_null( $this->mRevisionObject
) ) {
5194 return $this->mRevisionObject
;
5196 if ( is_null( $this->mRevisionId
) ) {
5200 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5201 return $this->mRevisionObject
;
5205 * Get the timestamp associated with the current revision, adjusted for
5206 * the default server-local timestamp
5208 function getRevisionTimestamp() {
5209 if ( is_null( $this->mRevisionTimestamp
) ) {
5210 wfProfileIn( __METHOD__
);
5212 $revObject = $this->getRevisionObject();
5213 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5215 if( $timestamp !== false ) {
5218 # The cryptic '' timezone parameter tells to use the site-default
5219 # timezone offset instead of the user settings.
5221 # Since this value will be saved into the parser cache, served
5222 # to other users, and potentially even used inside links and such,
5223 # it needs to be consistent for all visitors.
5224 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5227 wfProfileOut( __METHOD__
);
5229 return $this->mRevisionTimestamp
;
5233 * Get the name of the user that edited the last revision
5235 * @return String: user name
5237 function getRevisionUser() {
5238 if( is_null( $this->mRevisionUser
) ) {
5239 $revObject = $this->getRevisionObject();
5241 # if this template is subst: the revision id will be blank,
5242 # so just use the current user's name
5244 $this->mRevisionUser
= $revObject->getUserText();
5245 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5246 $this->mRevisionUser
= $this->getUser()->getName();
5249 return $this->mRevisionUser
;
5253 * Mutator for $mDefaultSort
5255 * @param $sort New value
5257 public function setDefaultSort( $sort ) {
5258 $this->mDefaultSort
= $sort;
5259 $this->mOutput
->setProperty( 'defaultsort', $sort );
5263 * Accessor for $mDefaultSort
5264 * Will use the empty string if none is set.
5266 * This value is treated as a prefix, so the
5267 * empty string is equivalent to sorting by
5272 public function getDefaultSort() {
5273 if ( $this->mDefaultSort
!== false ) {
5274 return $this->mDefaultSort
;
5281 * Accessor for $mDefaultSort
5282 * Unlike getDefaultSort(), will return false if none is set
5284 * @return string or false
5286 public function getCustomDefaultSort() {
5287 return $this->mDefaultSort
;
5291 * Try to guess the section anchor name based on a wikitext fragment
5292 * presumably extracted from a heading, for example "Header" from
5295 public function guessSectionNameFromWikiText( $text ) {
5296 # Strip out wikitext links(they break the anchor)
5297 $text = $this->stripSectionName( $text );
5298 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5299 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5303 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5304 * instead. For use in redirects, since IE6 interprets Redirect: headers
5305 * as something other than UTF-8 (apparently?), resulting in breakage.
5307 * @param $text String: The section name
5308 * @return string An anchor
5310 public function guessLegacySectionNameFromWikiText( $text ) {
5311 # Strip out wikitext links(they break the anchor)
5312 $text = $this->stripSectionName( $text );
5313 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5314 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5318 * Strips a text string of wikitext for use in a section anchor
5320 * Accepts a text string and then removes all wikitext from the
5321 * string and leaves only the resultant text (i.e. the result of
5322 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5323 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5324 * to create valid section anchors by mimicing the output of the
5325 * parser when headings are parsed.
5327 * @param $text String: text string to be stripped of wikitext
5328 * for use in a Section anchor
5329 * @return Filtered text string
5331 public function stripSectionName( $text ) {
5332 # Strip internal link markup
5333 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5334 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5336 # Strip external link markup (FIXME: Not Tolerant to blank link text
5337 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5338 # on how many empty links there are on the page - need to figure that out.
5339 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5341 # Parse wikitext quotes (italics & bold)
5342 $text = $this->doQuotes( $text );
5345 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5350 * strip/replaceVariables/unstrip for preprocessor regression testing
5352 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5353 if ( !$title instanceof Title
) {
5354 $title = Title
::newFromText( $title );
5356 $this->startParse( $title, $options, $outputType, true );
5358 $text = $this->replaceVariables( $text );
5359 $text = $this->mStripState
->unstripBoth( $text );
5360 $text = Sanitizer
::removeHTMLtags( $text );
5364 function testPst( $text, $title, $options ) {
5366 if ( !$title instanceof Title
) {
5367 $title = Title
::newFromText( $title );
5369 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5372 function testPreprocess( $text, $title, $options ) {
5373 if ( !$title instanceof Title
) {
5374 $title = Title
::newFromText( $title );
5376 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5380 * Call a callback function on all regions of the given text that are not
5381 * inside strip markers, and replace those regions with the return value
5382 * of the callback. For example, with input:
5386 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5387 * two strings will be replaced with the value returned by the callback in
5390 function markerSkipCallback( $s, $callback ) {
5393 while ( $i < strlen( $s ) ) {
5394 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5395 if ( $markerStart === false ) {
5396 $out .= call_user_func( $callback, substr( $s, $i ) );
5399 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5400 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5401 if ( $markerEnd === false ) {
5402 $out .= substr( $s, $markerStart );
5405 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5406 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5415 * Save the parser state required to convert the given half-parsed text to
5416 * HTML. "Half-parsed" in this context means the output of
5417 * recursiveTagParse() or internalParse(). This output has strip markers
5418 * from replaceVariables (extensionSubstitution() etc.), and link
5419 * placeholders from replaceLinkHolders().
5421 * Returns an array which can be serialized and stored persistently. This
5422 * array can later be loaded into another parser instance with
5423 * unserializeHalfParsedText(). The text can then be safely incorporated into
5424 * the return value of a parser hook.
5426 function serializeHalfParsedText( $text ) {
5427 wfProfileIn( __METHOD__
);
5430 'version' => self
::HALF_PARSED_VERSION
,
5431 'stripState' => $this->mStripState
->getSubState( $text ),
5432 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5434 wfProfileOut( __METHOD__
);
5439 * Load the parser state given in the $data array, which is assumed to
5440 * have been generated by serializeHalfParsedText(). The text contents is
5441 * extracted from the array, and its markers are transformed into markers
5442 * appropriate for the current Parser instance. This transformed text is
5443 * returned, and can be safely included in the return value of a parser
5446 * If the $data array has been stored persistently, the caller should first
5447 * check whether it is still valid, by calling isValidHalfParsedText().
5449 * @param $data Serialized data
5452 function unserializeHalfParsedText( $data ) {
5453 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5454 throw new MWException( __METHOD__
.': invalid version' );
5457 # First, extract the strip state.
5458 $texts = array( $data['text'] );
5459 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5461 # Now renumber links
5462 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5464 # Should be good to go.
5469 * Returns true if the given array, presumed to be generated by
5470 * serializeHalfParsedText(), is compatible with the current version of the
5473 * @param $data Array.
5475 function isValidHalfParsedText( $data ) {
5476 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;