3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
40 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.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():
116 var $mOutput, $mAutonumber, $mDTopen;
123 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
124 var $mLinkHolders, $mLinkID;
125 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
126 var $mTplExpandCache; # empty-frame expansion cache
127 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
128 var $mExpensiveFunctionCount; # number of expensive parser function calls
133 var $mUser; # User object; only used when doing pre-save transform
136 # These are variables reset at least once per parse regardless of $clearState
146 var $mTitle; # Title context, used for self-link rendering and similar things
147 var $mOutputType; # Output type, one of the OT_xxx constants
148 var $ot; # Shortcut alias, see setOutputType()
149 var $mRevisionObject; # The revision object of the specified revision ID
150 var $mRevisionId; # ID to display in {{REVISIONID}} tags
151 var $mRevisionTimestamp; # The timestamp of the specified revision ID
152 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
153 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
160 function __construct( $conf = array() ) {
161 $this->mConf
= $conf;
162 $this->mUrlProtocols
= wfUrlProtocols();
163 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
164 '(?:[^\]\[<>"\x00-\x20\x7F]|\[\])+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
165 if ( isset( $conf['preprocessorClass'] ) ) {
166 $this->mPreprocessorClass
= $conf['preprocessorClass'];
167 } elseif ( extension_loaded( 'domxml' ) ) {
168 # PECL extension that conflicts with the core DOM extension (bug 13770)
169 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
170 $this->mPreprocessorClass
= 'Preprocessor_Hash';
171 } elseif ( extension_loaded( 'dom' ) ) {
172 $this->mPreprocessorClass
= 'Preprocessor_DOM';
174 $this->mPreprocessorClass
= 'Preprocessor_Hash';
179 * Reduce memory usage to reduce the impact of circular references
181 function __destruct() {
182 if ( isset( $this->mLinkHolders
) ) {
183 $this->mLinkHolders
->__destruct();
185 foreach ( $this as $name => $value ) {
186 unset( $this->$name );
191 * Do various kinds of initialisation on the first call of the parser
193 function firstCallInit() {
194 if ( !$this->mFirstCall
) {
197 $this->mFirstCall
= false;
199 wfProfileIn( __METHOD__
);
201 CoreParserFunctions
::register( $this );
202 CoreTagHooks
::register( $this );
203 $this->initialiseVariables();
205 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
206 wfProfileOut( __METHOD__
);
214 function clearState() {
215 wfProfileIn( __METHOD__
);
216 if ( $this->mFirstCall
) {
217 $this->firstCallInit();
219 $this->mOutput
= new ParserOutput
;
220 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
221 $this->mAutonumber
= 0;
222 $this->mLastSection
= '';
223 $this->mDTopen
= false;
224 $this->mIncludeCount
= array();
225 $this->mArgStack
= false;
226 $this->mInPre
= false;
227 $this->mLinkHolders
= new LinkHolderArray( $this );
229 $this->mRevisionObject
= $this->mRevisionTimestamp
=
230 $this->mRevisionId
= $this->mRevisionUser
= null;
231 $this->mVarCache
= array();
235 * Prefix for temporary replacement strings for the multipass parser.
236 * \x07 should never appear in input as it's disallowed in XML.
237 * Using it at the front also gives us a little extra robustness
238 * since it shouldn't match when butted up against identifier-like
241 * Must not consist of all title characters, or else it will change
242 * the behaviour of <nowiki> in a link.
244 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
245 # Changed to \x7f to allow XML double-parsing -- TS
246 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
247 $this->mStripState
= new StripState( $this->mUniqPrefix
);
250 # Clear these on every parse, bug 4549
251 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
253 $this->mShowToc
= true;
254 $this->mForceTocPosition
= false;
255 $this->mIncludeSizes
= array(
259 $this->mPPNodeCount
= 0;
260 $this->mDefaultSort
= false;
261 $this->mHeadings
= array();
262 $this->mDoubleUnderscores
= array();
263 $this->mExpensiveFunctionCount
= 0;
266 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
267 $this->mPreprocessor
= null;
270 wfRunHooks( 'ParserClearState', array( &$this ) );
271 wfProfileOut( __METHOD__
);
275 * Convert wikitext to HTML
276 * Do not call this function recursively.
278 * @param $text String: text we want to parse
279 * @param $title A title object
280 * @param $options ParserOptions
281 * @param $linestart boolean
282 * @param $clearState boolean
283 * @param $revid Int: number to pass in {{REVISIONID}}
284 * @return ParserOutput a ParserOutput
286 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
288 * First pass--just handle <nowiki> sections, pass the rest off
289 * to internalParse() which does all the real work.
292 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
293 $fname = __METHOD__
.'-' . wfGetCaller();
294 wfProfileIn( __METHOD__
);
295 wfProfileIn( $fname );
297 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
299 $oldRevisionId = $this->mRevisionId
;
300 $oldRevisionObject = $this->mRevisionObject
;
301 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
302 $oldRevisionUser = $this->mRevisionUser
;
303 if ( $revid !== null ) {
304 $this->mRevisionId
= $revid;
305 $this->mRevisionObject
= null;
306 $this->mRevisionTimestamp
= null;
307 $this->mRevisionUser
= null;
310 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
312 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
313 $text = $this->internalParse( $text );
315 $text = $this->mStripState
->unstripGeneral( $text );
317 # Clean up special characters, only run once, next-to-last before doBlockLevels
319 # french spaces, last one Guillemet-left
320 # only if there is something before the space
321 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
322 # french spaces, Guillemet-right
323 '/(\\302\\253) /' => '\\1 ',
324 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
326 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
328 $text = $this->doBlockLevels( $text, $linestart );
330 $this->replaceLinkHolders( $text );
333 * The page doesn't get language converted if
335 * b) Content isn't converted
336 * c) It's a conversion table
338 if ( !( $wgDisableLangConversion
339 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
340 ||
$this->mTitle
->isConversionTable() ) ) {
342 # The position of the convert() call should not be changed. it
343 # assumes that the links are all replaced and the only thing left
344 # is the <nowiki> mark.
346 $text = $wgContLang->convert( $text );
350 * A converted title will be provided in the output object if title and
351 * content conversion are enabled, the article text does not contain
352 * a conversion-suppressing double-underscore tag, and no
353 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
354 * automatic link conversion.
356 if ( !( $wgDisableLangConversion
357 ||
$wgDisableTitleConversion
358 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
359 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
360 ||
$this->mOutput
->getDisplayTitle() !== false ) )
362 $convruletitle = $wgContLang->getConvRuleTitle();
363 if ( $convruletitle ) {
364 $this->mOutput
->setTitleText( $convruletitle );
366 $titleText = $wgContLang->convertTitle( $title );
367 $this->mOutput
->setTitleText( $titleText );
371 $text = $this->mStripState
->unstripNoWiki( $text );
373 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
375 $text = $this->replaceTransparentTags( $text );
376 $text = $this->mStripState
->unstripGeneral( $text );
378 $text = Sanitizer
::normalizeCharReferences( $text );
380 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
381 $text = MWTidy
::tidy( $text );
383 # attempt to sanitize at least some nesting problems
384 # (bug #2702 and quite a few others)
386 # ''Something [http://www.cool.com cool''] -->
387 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
388 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
389 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
390 # fix up an anchor inside another anchor, only
391 # at least for a single single nested link (bug 3695)
392 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
393 '\\1\\2</a>\\3</a>\\1\\4</a>',
394 # fix div inside inline elements- doBlockLevels won't wrap a line which
395 # contains a div, so fix it up here; replace
396 # div with escaped text
397 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
398 '\\1\\3<div\\5>\\6</div>\\8\\9',
399 # remove empty italic or bold tag pairs, some
400 # introduced by rules above
401 '/<([bi])><\/\\1>/' => '',
404 $text = preg_replace(
405 array_keys( $tidyregs ),
406 array_values( $tidyregs ),
409 global $wgExpensiveParserFunctionLimit;
410 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
411 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
414 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
416 # Information on include size limits, for the benefit of users who try to skirt them
417 if ( $this->mOptions
->getEnableLimitReport() ) {
418 $max = $this->mOptions
->getMaxIncludeSize();
419 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
421 "NewPP limit report\n" .
422 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
423 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
424 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
426 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
427 $text .= "\n<!-- \n$limitReport-->\n";
429 $this->mOutput
->setText( $text );
431 $this->mRevisionId
= $oldRevisionId;
432 $this->mRevisionObject
= $oldRevisionObject;
433 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
434 $this->mRevisionUser
= $oldRevisionUser;
435 wfProfileOut( $fname );
436 wfProfileOut( __METHOD__
);
438 return $this->mOutput
;
442 * Recursive parser entry point that can be called from an extension tag
445 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
447 * @param $text String: text extension wants to have parsed
448 * @param $frame PPFrame: The frame to use for expanding any template variables
450 function recursiveTagParse( $text, $frame=false ) {
451 wfProfileIn( __METHOD__
);
452 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
453 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
454 $text = $this->internalParse( $text, false, $frame );
455 wfProfileOut( __METHOD__
);
460 * Expand templates and variables in the text, producing valid, static wikitext.
461 * Also removes comments.
463 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
464 wfProfileIn( __METHOD__
);
465 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
466 if ( $revid !== null ) {
467 $this->mRevisionId
= $revid;
469 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
470 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
471 $text = $this->replaceVariables( $text );
472 $text = $this->mStripState
->unstripBoth( $text );
473 wfProfileOut( __METHOD__
);
478 * Process the wikitext for the ?preload= feature. (bug 5210)
480 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
481 * comments, templates, arguments, tags hooks and parser functions are untouched.
483 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
484 # Parser (re)initialisation
485 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
487 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
488 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
489 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
490 $text = $this->mStripState
->unstripBoth( $text );
495 * Get a random string
499 static public function getRandomString() {
500 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
504 * Set the current user.
505 * Should only be used when doing pre-save transform.
507 * @param $user Mixed: User object or null (to reset)
509 function setUser( $user ) {
510 $this->mUser
= $user;
514 * Accessor for mUniqPrefix.
518 public function uniqPrefix() {
519 if ( !isset( $this->mUniqPrefix
) ) {
520 # @todo Fixme: this is probably *horribly wrong*
521 # LanguageConverter seems to want $wgParser's uniqPrefix, however
522 # if this is called for a parser cache hit, the parser may not
523 # have ever been initialized in the first place.
524 # Not really sure what the heck is supposed to be going on here.
526 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
528 return $this->mUniqPrefix
;
532 * Set the context title
534 function setTitle( $t ) {
535 if ( !$t ||
$t instanceof FakeTitle
) {
536 $t = Title
::newFromText( 'NO TITLE' );
539 if ( strval( $t->getFragment() ) !== '' ) {
540 # Strip the fragment to avoid various odd effects
541 $this->mTitle
= clone $t;
542 $this->mTitle
->setFragment( '' );
549 * Accessor for the Title object
551 * @return Title object
553 function getTitle() {
554 return $this->mTitle
;
558 * Accessor/mutator for the Title object
560 * @param $x New Title object or null to just get the current one
561 * @return Title object
563 function Title( $x = null ) {
564 return wfSetVar( $this->mTitle
, $x );
568 * Set the output type
570 * @param $ot Integer: new value
572 function setOutputType( $ot ) {
573 $this->mOutputType
= $ot;
576 'html' => $ot == self
::OT_HTML
,
577 'wiki' => $ot == self
::OT_WIKI
,
578 'pre' => $ot == self
::OT_PREPROCESS
,
579 'plain' => $ot == self
::OT_PLAIN
,
584 * Accessor/mutator for the output type
586 * @param $x New value or null to just get the current one
589 function OutputType( $x = null ) {
590 return wfSetVar( $this->mOutputType
, $x );
594 * Get the ParserOutput object
596 * @return ParserOutput object
598 function getOutput() {
599 return $this->mOutput
;
603 * Get the ParserOptions object
605 * @return ParserOptions object
607 function getOptions() {
608 return $this->mOptions
;
612 * Accessor/mutator for the ParserOptions object
614 * @param $x New value or null to just get the current one
615 * @return Current ParserOptions object
617 function Options( $x = null ) {
618 return wfSetVar( $this->mOptions
, $x );
621 function nextLinkID() {
622 return $this->mLinkID++
;
625 function setLinkID( $id ) {
626 $this->mLinkID
= $id;
632 function getFunctionLang() {
633 global $wgLang, $wgContLang;
635 $target = $this->mOptions
->getTargetLanguage();
636 if ( $target !== null ) {
639 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
644 * Get a User object either from $this->mUser, if set, or from the
645 * ParserOptions object otherwise
647 * @return User object
650 if ( !is_null( $this->mUser
) ) {
653 return $this->mOptions
->getUser();
657 * Get a preprocessor object
659 * @return Preprocessor instance
661 function getPreprocessor() {
662 if ( !isset( $this->mPreprocessor
) ) {
663 $class = $this->mPreprocessorClass
;
664 $this->mPreprocessor
= new $class( $this );
666 return $this->mPreprocessor
;
670 * Replaces all occurrences of HTML-style comments and the given tags
671 * in the text with a random marker and returns the next text. The output
672 * parameter $matches will be an associative array filled with data in
674 * 'UNIQ-xxxxx' => array(
677 * array( 'param' => 'x' ),
678 * '<element param="x">tag content</element>' ) )
680 * @param $elements list of element names. Comments are always extracted.
681 * @param $text Source text string.
682 * @param $matches Out parameter, Array: extracted tags
683 * @param $uniq_prefix
684 * @return String: stripped text
688 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
693 $taglist = implode( '|', $elements );
694 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
696 while ( $text != '' ) {
697 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
699 if ( count( $p ) < 5 ) {
702 if ( count( $p ) > 5 ) {
716 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
717 $stripped .= $marker;
719 if ( $close === '/>' ) {
720 # Empty element tag, <tag />
725 if ( $element === '!--' ) {
728 $end = "/(<\\/$element\\s*>)/i";
730 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
732 if ( count( $q ) < 3 ) {
733 # No end tag -- let it run out to the end of the text.
742 $matches[$marker] = array( $element,
744 Sanitizer
::decodeTagAttributes( $attributes ),
745 "<$element$attributes$close$content$tail" );
751 * Get a list of strippable XML-like elements
753 function getStripList() {
754 return $this->mStripList
;
758 * @deprecated use replaceVariables
760 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
765 * Restores pre, math, and other extensions removed by strip()
767 * always call unstripNoWiki() after this one
769 * @deprecated use $this->mStripState->unstrip()
771 function unstrip( $text, $state ) {
772 return $state->unstripGeneral( $text );
776 * Always call this after unstrip() to preserve the order
779 * @deprecated use $this->mStripState->unstrip()
781 function unstripNoWiki( $text, $state ) {
782 return $state->unstripNoWiki( $text );
786 * @deprecated use $this->mStripState->unstripBoth()
788 function unstripForHTML( $text ) {
789 return $this->mStripState
->unstripBoth( $text );
793 * Add an item to the strip state
794 * Returns the unique tag which must be inserted into the stripped text
795 * The tag will be replaced with the original text in unstrip()
799 function insertStripItem( $text ) {
800 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
801 $this->mMarkerIndex++
;
802 $this->mStripState
->addGeneral( $rnd, $text );
807 * Interface with html tidy
808 * @deprecated Use MWTidy::tidy()
810 public static function tidy( $text ) {
811 wfDeprecated( __METHOD__
);
812 return MWTidy
::tidy( $text );
816 * parse the wiki syntax used to render tables
820 function doTableStuff( $text ) {
821 wfProfileIn( __METHOD__
);
823 $lines = StringUtils
::explode( "\n", $text );
825 $td_history = array(); # Is currently a td tag open?
826 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
827 $tr_history = array(); # Is currently a tr tag open?
828 $tr_attributes = array(); # history of tr attributes
829 $has_opened_tr = array(); # Did this table open a <tr> element?
830 $indent_level = 0; # indent level of the table
832 foreach ( $lines as $outLine ) {
833 $line = trim( $outLine );
835 if ( $line === '' ) { # empty line, go to next line
836 $out .= $outLine."\n";
840 $first_character = $line[0];
843 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
844 # First check if we are starting a new table
845 $indent_level = strlen( $matches[1] );
847 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
848 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
850 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
851 array_push( $td_history , false );
852 array_push( $last_tag_history , '' );
853 array_push( $tr_history , false );
854 array_push( $tr_attributes , '' );
855 array_push( $has_opened_tr , false );
856 } elseif ( count( $td_history ) == 0 ) {
857 # Don't do any of the following
858 $out .= $outLine."\n";
860 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
861 # We are ending a table
862 $line = '</table>' . substr( $line , 2 );
863 $last_tag = array_pop( $last_tag_history );
865 if ( !array_pop( $has_opened_tr ) ) {
866 $line = "<tr><td></td></tr>{$line}";
869 if ( array_pop( $tr_history ) ) {
870 $line = "</tr>{$line}";
873 if ( array_pop( $td_history ) ) {
874 $line = "</{$last_tag}>{$line}";
876 array_pop( $tr_attributes );
877 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
878 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
879 # Now we have a table row
880 $line = preg_replace( '#^\|-+#', '', $line );
882 # Whats after the tag is now only attributes
883 $attributes = $this->mStripState
->unstripBoth( $line );
884 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
885 array_pop( $tr_attributes );
886 array_push( $tr_attributes, $attributes );
889 $last_tag = array_pop( $last_tag_history );
890 array_pop( $has_opened_tr );
891 array_push( $has_opened_tr , true );
893 if ( array_pop( $tr_history ) ) {
897 if ( array_pop( $td_history ) ) {
898 $line = "</{$last_tag}>{$line}";
902 array_push( $tr_history , false );
903 array_push( $td_history , false );
904 array_push( $last_tag_history , '' );
905 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
906 # This might be cell elements, td, th or captions
907 if ( substr( $line , 0 , 2 ) === '|+' ) {
908 $first_character = '+';
909 $line = substr( $line , 1 );
912 $line = substr( $line , 1 );
914 if ( $first_character === '!' ) {
915 $line = str_replace( '!!' , '||' , $line );
918 # Split up multiple cells on the same line.
919 # FIXME : This can result in improper nesting of tags processed
920 # by earlier parser steps, but should avoid splitting up eg
921 # attribute values containing literal "||".
922 $cells = StringUtils
::explodeMarkup( '||' , $line );
926 # Loop through each table cell
927 foreach ( $cells as $cell ) {
929 if ( $first_character !== '+' ) {
930 $tr_after = array_pop( $tr_attributes );
931 if ( !array_pop( $tr_history ) ) {
932 $previous = "<tr{$tr_after}>\n";
934 array_push( $tr_history , true );
935 array_push( $tr_attributes , '' );
936 array_pop( $has_opened_tr );
937 array_push( $has_opened_tr , true );
940 $last_tag = array_pop( $last_tag_history );
942 if ( array_pop( $td_history ) ) {
943 $previous = "</{$last_tag}>\n{$previous}";
946 if ( $first_character === '|' ) {
948 } elseif ( $first_character === '!' ) {
950 } elseif ( $first_character === '+' ) {
951 $last_tag = 'caption';
956 array_push( $last_tag_history , $last_tag );
958 # A cell could contain both parameters and data
959 $cell_data = explode( '|' , $cell , 2 );
961 # Bug 553: Note that a '|' inside an invalid link should not
962 # be mistaken as delimiting cell parameters
963 if ( strpos( $cell_data[0], '[[' ) !== false ) {
964 $cell = "{$previous}<{$last_tag}>{$cell}";
965 } elseif ( count( $cell_data ) == 1 ) {
966 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
968 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
969 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
970 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
974 array_push( $td_history , true );
977 $out .= $outLine . "\n";
980 # Closing open td, tr && table
981 while ( count( $td_history ) > 0 ) {
982 if ( array_pop( $td_history ) ) {
985 if ( array_pop( $tr_history ) ) {
988 if ( !array_pop( $has_opened_tr ) ) {
989 $out .= "<tr><td></td></tr>\n" ;
992 $out .= "</table>\n";
995 # Remove trailing line-ending (b/c)
996 if ( substr( $out, -1 ) === "\n" ) {
997 $out = substr( $out, 0, -1 );
1000 # special case: don't return empty table
1001 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1005 wfProfileOut( __METHOD__
);
1011 * Helper function for parse() that transforms wiki markup into
1012 * HTML. Only called for $mOutputType == self::OT_HTML.
1016 function internalParse( $text, $isMain = true, $frame=false ) {
1017 wfProfileIn( __METHOD__
);
1021 # Hook to suspend the parser in this state
1022 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1023 wfProfileOut( __METHOD__
);
1027 # if $frame is provided, then use $frame for replacing any variables
1029 # use frame depth to infer how include/noinclude tags should be handled
1030 # depth=0 means this is the top-level document; otherwise it's an included document
1031 if ( !$frame->depth
) {
1034 $flag = Parser
::PTD_FOR_INCLUSION
;
1036 $dom = $this->preprocessToDom( $text, $flag );
1037 $text = $frame->expand( $dom );
1039 # if $frame is not provided, then use old-style replaceVariables
1040 $text = $this->replaceVariables( $text );
1043 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1044 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1046 # Tables need to come after variable replacement for things to work
1047 # properly; putting them before other transformations should keep
1048 # exciting things like link expansions from showing up in surprising
1050 $text = $this->doTableStuff( $text );
1052 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1054 $text = $this->doDoubleUnderscore( $text );
1056 $text = $this->doHeadings( $text );
1057 if ( $this->mOptions
->getUseDynamicDates() ) {
1058 $df = DateFormatter
::getInstance();
1059 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1061 $text = $this->replaceInternalLinks( $text );
1062 $text = $this->doAllQuotes( $text );
1063 $text = $this->replaceExternalLinks( $text );
1065 # replaceInternalLinks may sometimes leave behind
1066 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1067 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1069 $text = $this->doMagicLinks( $text );
1070 $text = $this->formatHeadings( $text, $origText, $isMain );
1072 wfProfileOut( __METHOD__
);
1077 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1078 * magic external links.
1083 function doMagicLinks( $text ) {
1084 wfProfileIn( __METHOD__
);
1085 $prots = $this->mUrlProtocols
;
1086 $urlChar = self
::EXT_LINK_URL_CLASS
;
1087 $text = preg_replace_callback(
1089 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1090 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1091 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1092 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1093 ISBN\s+(\b # m[5]: ISBN, capture number
1094 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1095 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1096 [0-9Xx] # check digit
1098 )!x', array( &$this, 'magicLinkCallback' ), $text );
1099 wfProfileOut( __METHOD__
);
1103 function magicLinkCallback( $m ) {
1104 if ( isset( $m[1] ) && $m[1] !== '' ) {
1107 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1110 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1111 # Free external link
1112 return $this->makeFreeExternalLink( $m[0] );
1113 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1115 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1118 $CssClass = 'mw-magiclink-rfc';
1120 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1122 $urlmsg = 'pubmedurl';
1123 $CssClass = 'mw-magiclink-pmid';
1126 throw new MWException( __METHOD__
.': unrecognised match type "' .
1127 substr( $m[0], 0, 20 ) . '"' );
1129 $url = wfMsgForContent( $urlmsg, $id );
1130 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1131 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1132 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1135 $num = strtr( $isbn, array(
1140 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1142 $titleObj->escapeLocalUrl() .
1143 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1150 * Make a free external link, given a user-supplied URL
1154 function makeFreeExternalLink( $url ) {
1156 wfProfileIn( __METHOD__
);
1158 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1161 # The characters '<' and '>' (which were escaped by
1162 # removeHTMLtags()) should not be included in
1163 # URLs, per RFC 2396.
1165 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1166 $trail = substr( $url, $m2[0][1] ) . $trail;
1167 $url = substr( $url, 0, $m2[0][1] );
1170 # Move trailing punctuation to $trail
1172 # If there is no left bracket, then consider right brackets fair game too
1173 if ( strpos( $url, '(' ) === false ) {
1177 $numSepChars = strspn( strrev( $url ), $sep );
1178 if ( $numSepChars ) {
1179 $trail = substr( $url, -$numSepChars ) . $trail;
1180 $url = substr( $url, 0, -$numSepChars );
1183 $url = Sanitizer
::cleanUrl( $url );
1185 # Is this an external image?
1186 $text = $this->maybeMakeExternalImage( $url );
1187 if ( $text === false ) {
1188 # Not an image, make a link
1189 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1190 $this->getExternalLinkAttribs( $url ) );
1191 # Register it in the output object...
1192 # Replace unnecessary URL escape codes with their equivalent characters
1193 $pasteurized = self
::replaceUnusualEscapes( $url );
1194 $this->mOutput
->addExternalLink( $pasteurized );
1196 wfProfileOut( __METHOD__
);
1197 return $text . $trail;
1202 * Parse headers and return html
1206 function doHeadings( $text ) {
1207 wfProfileIn( __METHOD__
);
1208 for ( $i = 6; $i >= 1; --$i ) {
1209 $h = str_repeat( '=', $i );
1210 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1211 "<h$i>\\1</h$i>", $text );
1213 wfProfileOut( __METHOD__
);
1218 * Replace single quotes with HTML markup
1220 * @return string the altered text
1222 function doAllQuotes( $text ) {
1223 wfProfileIn( __METHOD__
);
1225 $lines = StringUtils
::explode( "\n", $text );
1226 foreach ( $lines as $line ) {
1227 $outtext .= $this->doQuotes( $line ) . "\n";
1229 $outtext = substr( $outtext, 0,-1 );
1230 wfProfileOut( __METHOD__
);
1235 * Helper function for doAllQuotes()
1237 public function doQuotes( $text ) {
1238 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1239 if ( count( $arr ) == 1 ) {
1242 # First, do some preliminary work. This may shift some apostrophes from
1243 # being mark-up to being text. It also counts the number of occurrences
1244 # of bold and italics mark-ups.
1247 for ( $i = 0; $i < count( $arr ); $i++
) {
1248 if ( ( $i %
2 ) == 1 ) {
1249 # If there are ever four apostrophes, assume the first is supposed to
1250 # be text, and the remaining three constitute mark-up for bold text.
1251 if ( strlen( $arr[$i] ) == 4 ) {
1254 } elseif ( strlen( $arr[$i] ) > 5 ) {
1255 # If there are more than 5 apostrophes in a row, assume they're all
1256 # text except for the last 5.
1257 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1260 # Count the number of occurrences of bold and italics mark-ups.
1261 # We are not counting sequences of five apostrophes.
1262 if ( strlen( $arr[$i] ) == 2 ) {
1264 } elseif ( strlen( $arr[$i] ) == 3 ) {
1266 } elseif ( strlen( $arr[$i] ) == 5 ) {
1273 # If there is an odd number of both bold and italics, it is likely
1274 # that one of the bold ones was meant to be an apostrophe followed
1275 # by italics. Which one we cannot know for certain, but it is more
1276 # likely to be one that has a single-letter word before it.
1277 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1279 $firstsingleletterword = -1;
1280 $firstmultiletterword = -1;
1282 foreach ( $arr as $r ) {
1283 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1284 $x1 = substr( $arr[$i-1], -1 );
1285 $x2 = substr( $arr[$i-1], -2, 1 );
1286 if ( $x1 === ' ' ) {
1287 if ( $firstspace == -1 ) {
1290 } elseif ( $x2 === ' ') {
1291 if ( $firstsingleletterword == -1 ) {
1292 $firstsingleletterword = $i;
1295 if ( $firstmultiletterword == -1 ) {
1296 $firstmultiletterword = $i;
1303 # If there is a single-letter word, use it!
1304 if ( $firstsingleletterword > -1 ) {
1305 $arr[$firstsingleletterword] = "''";
1306 $arr[$firstsingleletterword-1] .= "'";
1307 } elseif ( $firstmultiletterword > -1 ) {
1308 # If not, but there's a multi-letter word, use that one.
1309 $arr[$firstmultiletterword] = "''";
1310 $arr[$firstmultiletterword-1] .= "'";
1311 } elseif ( $firstspace > -1 ) {
1312 # ... otherwise use the first one that has neither.
1313 # (notice that it is possible for all three to be -1 if, for example,
1314 # there is only one pentuple-apostrophe in the line)
1315 $arr[$firstspace] = "''";
1316 $arr[$firstspace-1] .= "'";
1320 # Now let's actually convert our apostrophic mush to HTML!
1325 foreach ( $arr as $r ) {
1326 if ( ( $i %
2 ) == 0 ) {
1327 if ( $state === 'both' ) {
1333 if ( strlen( $r ) == 2 ) {
1334 if ( $state === 'i' ) {
1335 $output .= '</i>'; $state = '';
1336 } elseif ( $state === 'bi' ) {
1337 $output .= '</i>'; $state = 'b';
1338 } elseif ( $state === 'ib' ) {
1339 $output .= '</b></i><b>'; $state = 'b';
1340 } elseif ( $state === 'both' ) {
1341 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1342 } else { # $state can be 'b' or ''
1343 $output .= '<i>'; $state .= 'i';
1345 } elseif ( strlen( $r ) == 3 ) {
1346 if ( $state === 'b' ) {
1347 $output .= '</b>'; $state = '';
1348 } elseif ( $state === 'bi' ) {
1349 $output .= '</i></b><i>'; $state = 'i';
1350 } elseif ( $state === 'ib' ) {
1351 $output .= '</b>'; $state = 'i';
1352 } elseif ( $state === 'both' ) {
1353 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1354 } else { # $state can be 'i' or ''
1355 $output .= '<b>'; $state .= 'b';
1357 } elseif ( strlen( $r ) == 5 ) {
1358 if ( $state === 'b' ) {
1359 $output .= '</b><i>'; $state = 'i';
1360 } elseif ( $state === 'i' ) {
1361 $output .= '</i><b>'; $state = 'b';
1362 } elseif ( $state === 'bi' ) {
1363 $output .= '</i></b>'; $state = '';
1364 } elseif ( $state === 'ib' ) {
1365 $output .= '</b></i>'; $state = '';
1366 } elseif ( $state === 'both' ) {
1367 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1368 } else { # ($state == '')
1369 $buffer = ''; $state = 'both';
1375 # Now close all remaining tags. Notice that the order is important.
1376 if ( $state === 'b' ||
$state === 'ib' ) {
1379 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1382 if ( $state === 'bi' ) {
1385 # There might be lonely ''''', so make sure we have a buffer
1386 if ( $state === 'both' && $buffer ) {
1387 $output .= '<b><i>'.$buffer.'</i></b>';
1394 * Replace external links (REL)
1396 * Note: this is all very hackish and the order of execution matters a lot.
1397 * Make sure to run maintenance/parserTests.php if you change this code.
1401 function replaceExternalLinks( $text ) {
1403 wfProfileIn( __METHOD__
);
1405 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1407 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1408 $s = array_shift( $bits );
1411 while ( $i<count( $bits ) ) {
1413 $protocol = $bits[$i++
];
1414 $text = $bits[$i++
];
1415 $trail = $bits[$i++
];
1417 # The characters '<' and '>' (which were escaped by
1418 # removeHTMLtags()) should not be included in
1419 # URLs, per RFC 2396.
1421 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1422 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1423 $url = substr( $url, 0, $m2[0][1] );
1426 # If the link text is an image URL, replace it with an <img> tag
1427 # This happened by accident in the original parser, but some people used it extensively
1428 $img = $this->maybeMakeExternalImage( $text );
1429 if ( $img !== false ) {
1435 # Set linktype for CSS - if URL==text, link is essentially free
1436 $linktype = ( $text === $url ) ?
'free' : 'text';
1438 # No link text, e.g. [http://domain.tld/some.link]
1439 if ( $text == '' ) {
1440 # Autonumber if allowed. See bug #5918
1441 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1442 $langObj = $this->getFunctionLang();
1443 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1444 $linktype = 'autonumber';
1446 # Otherwise just use the URL
1447 $text = htmlspecialchars( $url );
1451 # Have link text, e.g. [http://domain.tld/some.link text]s
1453 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1456 $text = $wgContLang->markNoConversion( $text );
1458 $url = Sanitizer
::cleanUrl( $url );
1460 # Use the encoded URL
1461 # This means that users can paste URLs directly into the text
1462 # Funny characters like ö aren't valid in URLs anyway
1463 # This was changed in August 2004
1464 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1465 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1467 # Register link in the output object.
1468 # Replace unnecessary URL escape codes with the referenced character
1469 # This prevents spammers from hiding links from the filters
1470 $pasteurized = self
::replaceUnusualEscapes( $url );
1471 $this->mOutput
->addExternalLink( $pasteurized );
1474 wfProfileOut( __METHOD__
);
1479 * Get an associative array of additional HTML attributes appropriate for a
1480 * particular external link. This currently may include rel => nofollow
1481 * (depending on configuration, namespace, and the URL's domain) and/or a
1482 * target attribute (depending on configuration).
1484 * @param $url String: optional URL, to extract the domain from for rel =>
1485 * nofollow if appropriate
1486 * @return Array: associative array of HTML attributes
1488 function getExternalLinkAttribs( $url = false ) {
1490 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1491 $ns = $this->mTitle
->getNamespace();
1492 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1493 $attribs['rel'] = 'nofollow';
1495 global $wgNoFollowDomainExceptions;
1496 if ( $wgNoFollowDomainExceptions ) {
1497 $bits = wfParseUrl( $url );
1498 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1499 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1500 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1501 unset( $attribs['rel'] );
1508 if ( $this->mOptions
->getExternalLinkTarget() ) {
1509 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1516 * Replace unusual URL escape codes with their equivalent characters
1518 * @param $url String
1521 * @todo This can merge genuinely required bits in the path or query string,
1522 * breaking legit URLs. A proper fix would treat the various parts of
1523 * the URL differently; as a workaround, just use the output for
1524 * statistical records, not for actual linking/output.
1526 static function replaceUnusualEscapes( $url ) {
1527 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1528 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1532 * Callback function used in replaceUnusualEscapes().
1533 * Replaces unusual URL escape codes with their equivalent character
1535 private static function replaceUnusualEscapesCallback( $matches ) {
1536 $char = urldecode( $matches[0] );
1537 $ord = ord( $char );
1538 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1539 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1540 # No, shouldn't be escaped
1543 # Yes, leave it escaped
1549 * make an image if it's allowed, either through the global
1550 * option, through the exception, or through the on-wiki whitelist
1553 function maybeMakeExternalImage( $url ) {
1554 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1555 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1556 $imagesexception = !empty( $imagesfrom );
1558 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1559 if ( $imagesexception && is_array( $imagesfrom ) ) {
1560 $imagematch = false;
1561 foreach ( $imagesfrom as $match ) {
1562 if ( strpos( $url, $match ) === 0 ) {
1567 } elseif ( $imagesexception ) {
1568 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1570 $imagematch = false;
1572 if ( $this->mOptions
->getAllowExternalImages()
1573 ||
( $imagesexception && $imagematch ) ) {
1574 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1576 $text = $sk->makeExternalImage( $url );
1579 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1580 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1581 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1582 foreach ( $whitelist as $entry ) {
1583 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1584 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1587 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1588 # Image matches a whitelist entry
1589 $text = $sk->makeExternalImage( $url );
1598 * Process [[ ]] wikilinks
1599 * @return String: processed text
1603 function replaceInternalLinks( $s ) {
1604 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1609 * Process [[ ]] wikilinks (RIL)
1610 * @return LinkHolderArray
1614 function replaceInternalLinks2( &$s ) {
1617 wfProfileIn( __METHOD__
);
1619 wfProfileIn( __METHOD__
.'-setup' );
1620 static $tc = FALSE, $e1, $e1_img;
1621 # the % is needed to support urlencoded titles as well
1623 $tc = Title
::legalChars() . '#%';
1624 # Match a link having the form [[namespace:link|alternate]]trail
1625 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1626 # Match cases where there is no "]]", which might still be images
1627 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1630 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1631 $holders = new LinkHolderArray( $this );
1633 # split the entire text string on occurences of [[
1634 $a = StringUtils
::explode( '[[', ' ' . $s );
1635 # get the first element (all text up to first [[), and remove the space we added
1638 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1639 $s = substr( $s, 1 );
1641 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1643 if ( $useLinkPrefixExtension ) {
1644 # Match the end of a line for a word that's not followed by whitespace,
1645 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1646 $e2 = wfMsgForContent( 'linkprefix' );
1649 if ( is_null( $this->mTitle
) ) {
1650 wfProfileOut( __METHOD__
.'-setup' );
1651 wfProfileOut( __METHOD__
);
1652 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1654 $nottalk = !$this->mTitle
->isTalkPage();
1656 if ( $useLinkPrefixExtension ) {
1658 if ( preg_match( $e2, $s, $m ) ) {
1659 $first_prefix = $m[2];
1661 $first_prefix = false;
1667 if ( $wgContLang->hasVariants() ) {
1668 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1670 $selflink = array( $this->mTitle
->getPrefixedText() );
1672 $useSubpages = $this->areSubpagesAllowed();
1673 wfProfileOut( __METHOD__
.'-setup' );
1675 # Loop for each link
1676 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1677 # Check for excessive memory usage
1678 if ( $holders->isBig() ) {
1680 # Do the existence check, replace the link holders and clear the array
1681 $holders->replace( $s );
1685 if ( $useLinkPrefixExtension ) {
1686 wfProfileIn( __METHOD__
.'-prefixhandling' );
1687 if ( preg_match( $e2, $s, $m ) ) {
1694 if ( $first_prefix ) {
1695 $prefix = $first_prefix;
1696 $first_prefix = false;
1698 wfProfileOut( __METHOD__
.'-prefixhandling' );
1701 $might_be_img = false;
1703 wfProfileIn( __METHOD__
."-e1" );
1704 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1706 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1707 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1708 # the real problem is with the $e1 regex
1711 # Still some problems for cases where the ] is meant to be outside punctuation,
1712 # and no image is in sight. See bug 2095.
1714 if ( $text !== '' &&
1715 substr( $m[3], 0, 1 ) === ']' &&
1716 strpos( $text, '[' ) !== false
1719 $text .= ']'; # so that replaceExternalLinks($text) works later
1720 $m[3] = substr( $m[3], 1 );
1722 # fix up urlencoded title texts
1723 if ( strpos( $m[1], '%' ) !== false ) {
1724 # Should anchors '#' also be rejected?
1725 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1728 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1729 $might_be_img = true;
1731 if ( strpos( $m[1], '%' ) !== false ) {
1732 $m[1] = rawurldecode( $m[1] );
1735 } else { # Invalid form; output directly
1736 $s .= $prefix . '[[' . $line ;
1737 wfProfileOut( __METHOD__
."-e1" );
1740 wfProfileOut( __METHOD__
."-e1" );
1741 wfProfileIn( __METHOD__
."-misc" );
1743 # Don't allow internal links to pages containing
1744 # PROTO: where PROTO is a valid URL protocol; these
1745 # should be external links.
1746 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1747 $s .= $prefix . '[[' . $line ;
1748 wfProfileOut( __METHOD__
."-misc" );
1752 # Make subpage if necessary
1753 if ( $useSubpages ) {
1754 $link = $this->maybeDoSubpageLink( $m[1], $text );
1759 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1761 # Strip off leading ':'
1762 $link = substr( $link, 1 );
1765 wfProfileOut( __METHOD__
."-misc" );
1766 wfProfileIn( __METHOD__
."-title" );
1767 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1768 if ( $nt === null ) {
1769 $s .= $prefix . '[[' . $line;
1770 wfProfileOut( __METHOD__
."-title" );
1774 $ns = $nt->getNamespace();
1775 $iw = $nt->getInterWiki();
1776 wfProfileOut( __METHOD__
."-title" );
1778 if ( $might_be_img ) { # if this is actually an invalid link
1779 wfProfileIn( __METHOD__
."-might_be_img" );
1780 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1783 # look at the next 'line' to see if we can close it there
1785 $next_line = $a->current();
1786 if ( $next_line === false ||
$next_line === null ) {
1789 $m = explode( ']]', $next_line, 3 );
1790 if ( count( $m ) == 3 ) {
1791 # the first ]] closes the inner link, the second the image
1793 $text .= "[[{$m[0]}]]{$m[1]}";
1796 } elseif ( count( $m ) == 2 ) {
1797 # if there's exactly one ]] that's fine, we'll keep looking
1798 $text .= "[[{$m[0]}]]{$m[1]}";
1800 # if $next_line is invalid too, we need look no further
1801 $text .= '[[' . $next_line;
1806 # we couldn't find the end of this imageLink, so output it raw
1807 # but don't ignore what might be perfectly normal links in the text we've examined
1808 $holders->merge( $this->replaceInternalLinks2( $text ) );
1809 $s .= "{$prefix}[[$link|$text";
1810 # note: no $trail, because without an end, there *is* no trail
1811 wfProfileOut( __METHOD__
."-might_be_img" );
1814 } else { # it's not an image, so output it raw
1815 $s .= "{$prefix}[[$link|$text";
1816 # note: no $trail, because without an end, there *is* no trail
1817 wfProfileOut( __METHOD__
."-might_be_img" );
1820 wfProfileOut( __METHOD__
."-might_be_img" );
1823 $wasblank = ( $text == '' );
1827 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1828 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1829 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1830 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1831 $text = $this->doQuotes( $text );
1834 # Link not escaped by : , create the various objects
1838 wfProfileIn( __METHOD__
."-interwiki" );
1839 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1840 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1841 $s = rtrim( $s . $prefix );
1842 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1843 wfProfileOut( __METHOD__
."-interwiki" );
1846 wfProfileOut( __METHOD__
."-interwiki" );
1848 if ( $ns == NS_FILE
) {
1849 wfProfileIn( __METHOD__
."-image" );
1850 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1852 # if no parameters were passed, $text
1853 # becomes something like "File:Foo.png",
1854 # which we don't want to pass on to the
1858 # recursively parse links inside the image caption
1859 # actually, this will parse them in any other parameters, too,
1860 # but it might be hard to fix that, and it doesn't matter ATM
1861 $text = $this->replaceExternalLinks( $text );
1862 $holders->merge( $this->replaceInternalLinks2( $text ) );
1864 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1865 $s .= $prefix . $this->armorLinks(
1866 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1868 $s .= $prefix . $trail;
1870 wfProfileOut( __METHOD__
."-image" );
1874 if ( $ns == NS_CATEGORY
) {
1875 wfProfileIn( __METHOD__
."-category" );
1876 $s = rtrim( $s . "\n" ); # bug 87
1879 $sortkey = $this->getDefaultSort();
1883 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1884 $sortkey = str_replace( "\n", '', $sortkey );
1885 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1886 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1889 * Strip the whitespace Category links produce, see bug 87
1890 * @todo We might want to use trim($tmp, "\n") here.
1892 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1894 wfProfileOut( __METHOD__
."-category" );
1899 # Self-link checking
1900 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1901 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1902 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1907 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1908 # FIXME: Should do batch file existence checks, see comment below
1909 if ( $ns == NS_MEDIA
) {
1910 wfProfileIn( __METHOD__
."-media" );
1911 # Give extensions a chance to select the file revision for us
1912 $skip = $time = $sha1 = $descQuery = false;
1913 wfRunHooks( 'BeforeParserMakeImageLinkObj',
1914 array( &$this, &$nt, &$skip, &$time, &$descQuery, &$sha1 ) );
1916 $this->mOutput
->addImage( $nt->getDBkey(), null, null ); // register
1917 $link = $sk->link( $nt );
1919 # Fetch and register the file (file title may be different via hooks)
1920 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
1921 $link = $sk->makeMediaLinkFile( $nt, $file, $text );
1923 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1924 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1925 wfProfileOut( __METHOD__
."-media" );
1929 wfProfileIn( __METHOD__
."-always_known" );
1930 # Some titles, such as valid special pages or files in foreign repos, should
1931 # be shown as bluelinks even though they're not included in the page table
1933 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1934 # batch file existence checks for NS_FILE and NS_MEDIA
1935 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1936 $this->mOutput
->addLink( $nt );
1937 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
1939 # Links will be added to the output link list after checking
1940 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
1942 wfProfileOut( __METHOD__
."-always_known" );
1944 wfProfileOut( __METHOD__
);
1949 * Make a link placeholder. The text returned can be later resolved to a real link with
1950 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1951 * parsing of interwiki links, and secondly to allow all existence checks and
1952 * article length checks (for stub links) to be bundled into a single query.
1956 function makeLinkHolder( &$nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
1957 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1961 * Render a forced-blue link inline; protect against double expansion of
1962 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1963 * Since this little disaster has to split off the trail text to avoid
1964 * breaking URLs in the following text without breaking trails on the
1965 * wiki links, it's been made into a horrible function.
1968 * @param $text String
1969 * @param $query Array or String
1970 * @param $trail String
1971 * @param $prefix String
1972 * @return String: HTML-wikitext mix oh yuck
1974 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
1975 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1977 if ( is_string( $query ) ) {
1978 $query = wfCgiToArray( $query );
1980 if ( $text == '' ) {
1981 $text = htmlspecialchars( $nt->getPrefixedText() );
1984 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1985 $link = $sk->linkKnown( $nt, "$prefix$text$inside", array(), $query );
1987 return $this->armorLinks( $link ) . $trail;
1991 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1992 * going to go through further parsing steps before inline URL expansion.
1994 * Not needed quite as much as it used to be since free links are a bit
1995 * more sensible these days. But bracketed links are still an issue.
1997 * @param $text String: more-or-less HTML
1998 * @return String: less-or-more HTML with NOPARSE bits
2000 function armorLinks( $text ) {
2001 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2002 "{$this->mUniqPrefix}NOPARSE$1", $text );
2006 * Return true if subpage links should be expanded on this page.
2009 function areSubpagesAllowed() {
2010 # Some namespaces don't allow subpages
2011 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2015 * Handle link to subpage if necessary
2017 * @param $target String: the source of the link
2018 * @param &$text String: the link text, modified as necessary
2019 * @return string the full name of the link
2022 function maybeDoSubpageLink( $target, &$text ) {
2023 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2027 * Used by doBlockLevels()
2030 function closeParagraph() {
2032 if ( $this->mLastSection
!= '' ) {
2033 $result = '</' . $this->mLastSection
. ">\n";
2035 $this->mInPre
= false;
2036 $this->mLastSection
= '';
2041 * getCommon() returns the length of the longest common substring
2042 * of both arguments, starting at the beginning of both.
2045 function getCommon( $st1, $st2 ) {
2046 $fl = strlen( $st1 );
2047 $shorter = strlen( $st2 );
2048 if ( $fl < $shorter ) {
2052 for ( $i = 0; $i < $shorter; ++
$i ) {
2053 if ( $st1{$i} != $st2{$i} ) {
2061 * These next three functions open, continue, and close the list
2062 * element appropriate to the prefix character passed into them.
2065 function openList( $char ) {
2066 $result = $this->closeParagraph();
2068 if ( '*' === $char ) {
2069 $result .= '<ul><li>';
2070 } elseif ( '#' === $char ) {
2071 $result .= '<ol><li>';
2072 } elseif ( ':' === $char ) {
2073 $result .= '<dl><dd>';
2074 } elseif ( ';' === $char ) {
2075 $result .= '<dl><dt>';
2076 $this->mDTopen
= true;
2078 $result = '<!-- ERR 1 -->';
2086 * @param $char String
2089 function nextItem( $char ) {
2090 if ( '*' === $char ||
'#' === $char ) {
2092 } elseif ( ':' === $char ||
';' === $char ) {
2094 if ( $this->mDTopen
) {
2097 if ( ';' === $char ) {
2098 $this->mDTopen
= true;
2099 return $close . '<dt>';
2101 $this->mDTopen
= false;
2102 return $close . '<dd>';
2105 return '<!-- ERR 2 -->';
2110 * @param $char String
2113 function closeList( $char ) {
2114 if ( '*' === $char ) {
2115 $text = '</li></ul>';
2116 } elseif ( '#' === $char ) {
2117 $text = '</li></ol>';
2118 } elseif ( ':' === $char ) {
2119 if ( $this->mDTopen
) {
2120 $this->mDTopen
= false;
2121 $text = '</dt></dl>';
2123 $text = '</dd></dl>';
2126 return '<!-- ERR 3 -->';
2133 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2135 * @param $text String
2136 * @param $linestart Boolean: whether or not this is at the start of a line.
2138 * @return string the lists rendered as HTML
2140 function doBlockLevels( $text, $linestart ) {
2141 wfProfileIn( __METHOD__
);
2143 # Parsing through the text line by line. The main thing
2144 # happening here is handling of block-level elements p, pre,
2145 # and making lists from lines starting with * # : etc.
2147 $textLines = StringUtils
::explode( "\n", $text );
2149 $lastPrefix = $output = '';
2150 $this->mDTopen
= $inBlockElem = false;
2152 $paragraphStack = false;
2154 foreach ( $textLines as $oLine ) {
2156 if ( !$linestart ) {
2166 $lastPrefixLength = strlen( $lastPrefix );
2167 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2168 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2169 # If not in a <pre> element, scan for and figure out what prefixes are there.
2170 if ( !$this->mInPre
) {
2171 # Multiple prefixes may abut each other for nested lists.
2172 $prefixLength = strspn( $oLine, '*#:;' );
2173 $prefix = substr( $oLine, 0, $prefixLength );
2176 # ; and : are both from definition-lists, so they're equivalent
2177 # for the purposes of determining whether or not we need to open/close
2179 $prefix2 = str_replace( ';', ':', $prefix );
2180 $t = substr( $oLine, $prefixLength );
2181 $this->mInPre
= (bool)$preOpenMatch;
2183 # Don't interpret any other prefixes in preformatted text
2185 $prefix = $prefix2 = '';
2190 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2191 # Same as the last item, so no need to deal with nesting or opening stuff
2192 $output .= $this->nextItem( substr( $prefix, -1 ) );
2193 $paragraphStack = false;
2195 if ( substr( $prefix, -1 ) === ';') {
2196 # The one nasty exception: definition lists work like this:
2197 # ; title : definition text
2198 # So we check for : in the remainder text to split up the
2199 # title and definition, without b0rking links.
2201 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2203 $output .= $term . $this->nextItem( ':' );
2206 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2207 # We need to open or close prefixes, or both.
2209 # Either open or close a level...
2210 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2211 $paragraphStack = false;
2213 # Close all the prefixes which aren't shared.
2214 while ( $commonPrefixLength < $lastPrefixLength ) {
2215 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2216 --$lastPrefixLength;
2219 # Continue the current prefix if appropriate.
2220 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2221 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2224 # Open prefixes where appropriate.
2225 while ( $prefixLength > $commonPrefixLength ) {
2226 $char = substr( $prefix, $commonPrefixLength, 1 );
2227 $output .= $this->openList( $char );
2229 if ( ';' === $char ) {
2230 # FIXME: This is dupe of code above
2231 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2233 $output .= $term . $this->nextItem( ':' );
2236 ++
$commonPrefixLength;
2238 $lastPrefix = $prefix2;
2241 # If we have no prefixes, go to paragraph mode.
2242 if ( 0 == $prefixLength ) {
2243 wfProfileIn( __METHOD__
."-paragraph" );
2244 # No prefix (not in list)--go to paragraph mode
2245 # XXX: use a stack for nestable elements like span, table and div
2246 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2247 $closematch = preg_match(
2248 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2249 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2250 if ( $openmatch or $closematch ) {
2251 $paragraphStack = false;
2252 #Â TODO bug 5718: paragraph closed
2253 $output .= $this->closeParagraph();
2254 if ( $preOpenMatch and !$preCloseMatch ) {
2255 $this->mInPre
= true;
2257 $inBlockElem = !$closematch;
2258 } elseif ( !$inBlockElem && !$this->mInPre
) {
2259 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2261 if ( $this->mLastSection
!== 'pre' ) {
2262 $paragraphStack = false;
2263 $output .= $this->closeParagraph().'<pre>';
2264 $this->mLastSection
= 'pre';
2266 $t = substr( $t, 1 );
2269 if ( trim( $t ) === '' ) {
2270 if ( $paragraphStack ) {
2271 $output .= $paragraphStack.'<br />';
2272 $paragraphStack = false;
2273 $this->mLastSection
= 'p';
2275 if ( $this->mLastSection
!== 'p' ) {
2276 $output .= $this->closeParagraph();
2277 $this->mLastSection
= '';
2278 $paragraphStack = '<p>';
2280 $paragraphStack = '</p><p>';
2284 if ( $paragraphStack ) {
2285 $output .= $paragraphStack;
2286 $paragraphStack = false;
2287 $this->mLastSection
= 'p';
2288 } elseif ( $this->mLastSection
!== 'p' ) {
2289 $output .= $this->closeParagraph().'<p>';
2290 $this->mLastSection
= 'p';
2295 wfProfileOut( __METHOD__
."-paragraph" );
2297 # somewhere above we forget to get out of pre block (bug 785)
2298 if ( $preCloseMatch && $this->mInPre
) {
2299 $this->mInPre
= false;
2301 if ( $paragraphStack === false ) {
2305 while ( $prefixLength ) {
2306 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2309 if ( $this->mLastSection
!= '' ) {
2310 $output .= '</' . $this->mLastSection
. '>';
2311 $this->mLastSection
= '';
2314 wfProfileOut( __METHOD__
);
2319 * Split up a string on ':', ignoring any occurences inside tags
2320 * to prevent illegal overlapping.
2322 * @param $str String: the string to split
2323 * @param &$before String: set to everything before the ':'
2324 * @param &$after String: set to everything after the ':'
2325 * return String: the position of the ':', or false if none found
2327 function findColonNoLinks( $str, &$before, &$after ) {
2328 wfProfileIn( __METHOD__
);
2330 $pos = strpos( $str, ':' );
2331 if ( $pos === false ) {
2333 wfProfileOut( __METHOD__
);
2337 $lt = strpos( $str, '<' );
2338 if ( $lt === false ||
$lt > $pos ) {
2339 # Easy; no tag nesting to worry about
2340 $before = substr( $str, 0, $pos );
2341 $after = substr( $str, $pos+
1 );
2342 wfProfileOut( __METHOD__
);
2346 # Ugly state machine to walk through avoiding tags.
2347 $state = self
::COLON_STATE_TEXT
;
2349 $len = strlen( $str );
2350 for( $i = 0; $i < $len; $i++
) {
2354 # (Using the number is a performance hack for common cases)
2355 case 0: # self::COLON_STATE_TEXT:
2358 # Could be either a <start> tag or an </end> tag
2359 $state = self
::COLON_STATE_TAGSTART
;
2362 if ( $stack == 0 ) {
2364 $before = substr( $str, 0, $i );
2365 $after = substr( $str, $i +
1 );
2366 wfProfileOut( __METHOD__
);
2369 # Embedded in a tag; don't break it.
2372 # Skip ahead looking for something interesting
2373 $colon = strpos( $str, ':', $i );
2374 if ( $colon === false ) {
2375 # Nothing else interesting
2376 wfProfileOut( __METHOD__
);
2379 $lt = strpos( $str, '<', $i );
2380 if ( $stack === 0 ) {
2381 if ( $lt === false ||
$colon < $lt ) {
2383 $before = substr( $str, 0, $colon );
2384 $after = substr( $str, $colon +
1 );
2385 wfProfileOut( __METHOD__
);
2389 if ( $lt === false ) {
2390 # Nothing else interesting to find; abort!
2391 # We're nested, but there's no close tags left. Abort!
2394 # Skip ahead to next tag start
2396 $state = self
::COLON_STATE_TAGSTART
;
2399 case 1: # self::COLON_STATE_TAG:
2404 $state = self
::COLON_STATE_TEXT
;
2407 # Slash may be followed by >?
2408 $state = self
::COLON_STATE_TAGSLASH
;
2414 case 2: # self::COLON_STATE_TAGSTART:
2417 $state = self
::COLON_STATE_CLOSETAG
;
2420 $state = self
::COLON_STATE_COMMENT
;
2423 # Illegal early close? This shouldn't happen D:
2424 $state = self
::COLON_STATE_TEXT
;
2427 $state = self
::COLON_STATE_TAG
;
2430 case 3: # self::COLON_STATE_CLOSETAG:
2435 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2436 wfProfileOut( __METHOD__
);
2439 $state = self
::COLON_STATE_TEXT
;
2442 case self
::COLON_STATE_TAGSLASH
:
2444 # Yes, a self-closed tag <blah/>
2445 $state = self
::COLON_STATE_TEXT
;
2447 # Probably we're jumping the gun, and this is an attribute
2448 $state = self
::COLON_STATE_TAG
;
2451 case 5: # self::COLON_STATE_COMMENT:
2453 $state = self
::COLON_STATE_COMMENTDASH
;
2456 case self
::COLON_STATE_COMMENTDASH
:
2458 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2460 $state = self
::COLON_STATE_COMMENT
;
2463 case self
::COLON_STATE_COMMENTDASHDASH
:
2465 $state = self
::COLON_STATE_TEXT
;
2467 $state = self
::COLON_STATE_COMMENT
;
2471 throw new MWException( "State machine error in " . __METHOD__
);
2475 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2476 wfProfileOut( __METHOD__
);
2479 wfProfileOut( __METHOD__
);
2484 * Return value of a magic variable (like PAGENAME)
2488 function getVariableValue( $index, $frame=false ) {
2489 global $wgContLang, $wgSitename, $wgServer;
2490 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2493 * Some of these require message or data lookups and can be
2494 * expensive to check many times.
2496 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2497 if ( isset( $this->mVarCache
[$index] ) ) {
2498 return $this->mVarCache
[$index];
2502 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2503 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2506 global $wgLocaltimezone;
2507 if ( isset( $wgLocaltimezone ) ) {
2508 $oldtz = date_default_timezone_get();
2509 date_default_timezone_set( $wgLocaltimezone );
2512 $localTimestamp = date( 'YmdHis', $ts );
2513 $localMonth = date( 'm', $ts );
2514 $localMonth1 = date( 'n', $ts );
2515 $localMonthName = date( 'n', $ts );
2516 $localDay = date( 'j', $ts );
2517 $localDay2 = date( 'd', $ts );
2518 $localDayOfWeek = date( 'w', $ts );
2519 $localWeek = date( 'W', $ts );
2520 $localYear = date( 'Y', $ts );
2521 $localHour = date( 'H', $ts );
2522 if ( isset( $wgLocaltimezone ) ) {
2523 date_default_timezone_set( $oldtz );
2527 case 'currentmonth':
2528 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2530 case 'currentmonth1':
2531 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2533 case 'currentmonthname':
2534 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2536 case 'currentmonthnamegen':
2537 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2539 case 'currentmonthabbrev':
2540 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2543 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2546 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2549 $value = $wgContLang->formatNum( $localMonth );
2552 $value = $wgContLang->formatNum( $localMonth1 );
2554 case 'localmonthname':
2555 $value = $wgContLang->getMonthName( $localMonthName );
2557 case 'localmonthnamegen':
2558 $value = $wgContLang->getMonthNameGen( $localMonthName );
2560 case 'localmonthabbrev':
2561 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2564 $value = $wgContLang->formatNum( $localDay );
2567 $value = $wgContLang->formatNum( $localDay2 );
2570 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2573 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2575 case 'fullpagename':
2576 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2578 case 'fullpagenamee':
2579 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2582 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2584 case 'subpagenamee':
2585 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2587 case 'basepagename':
2588 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2590 case 'basepagenamee':
2591 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2593 case 'talkpagename':
2594 if ( $this->mTitle
->canTalk() ) {
2595 $talkPage = $this->mTitle
->getTalkPage();
2596 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2601 case 'talkpagenamee':
2602 if ( $this->mTitle
->canTalk() ) {
2603 $talkPage = $this->mTitle
->getTalkPage();
2604 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2609 case 'subjectpagename':
2610 $subjPage = $this->mTitle
->getSubjectPage();
2611 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2613 case 'subjectpagenamee':
2614 $subjPage = $this->mTitle
->getSubjectPage();
2615 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2618 # Let the edit saving system know we should parse the page
2619 # *after* a revision ID has been assigned.
2620 $this->mOutput
->setFlag( 'vary-revision' );
2621 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2622 $value = $this->mRevisionId
;
2625 # Let the edit saving system know we should parse the page
2626 # *after* a revision ID has been assigned. This is for null edits.
2627 $this->mOutput
->setFlag( 'vary-revision' );
2628 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2629 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2631 case 'revisionday2':
2632 # Let the edit saving system know we should parse the page
2633 # *after* a revision ID has been assigned. This is for null edits.
2634 $this->mOutput
->setFlag( 'vary-revision' );
2635 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2636 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2638 case 'revisionmonth':
2639 # Let the edit saving system know we should parse the page
2640 # *after* a revision ID has been assigned. This is for null edits.
2641 $this->mOutput
->setFlag( 'vary-revision' );
2642 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2643 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2645 case 'revisionmonth1':
2646 # Let the edit saving system know we should parse the page
2647 # *after* a revision ID has been assigned. This is for null edits.
2648 $this->mOutput
->setFlag( 'vary-revision' );
2649 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2650 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2652 case 'revisionyear':
2653 # Let the edit saving system know we should parse the page
2654 # *after* a revision ID has been assigned. This is for null edits.
2655 $this->mOutput
->setFlag( 'vary-revision' );
2656 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2657 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2659 case 'revisiontimestamp':
2660 # Let the edit saving system know we should parse the page
2661 # *after* a revision ID has been assigned. This is for null edits.
2662 $this->mOutput
->setFlag( 'vary-revision' );
2663 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2664 $value = $this->getRevisionTimestamp();
2666 case 'revisionuser':
2667 # Let the edit saving system know we should parse the page
2668 # *after* a revision ID has been assigned. This is for null edits.
2669 $this->mOutput
->setFlag( 'vary-revision' );
2670 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2671 $value = $this->getRevisionUser();
2674 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2677 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2680 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2683 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2685 case 'subjectspace':
2686 $value = $this->mTitle
->getSubjectNsText();
2688 case 'subjectspacee':
2689 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2691 case 'currentdayname':
2692 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2695 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2698 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2701 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2704 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2705 # int to remove the padding
2706 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2709 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2711 case 'localdayname':
2712 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2715 $value = $wgContLang->formatNum( $localYear, true );
2718 $value = $wgContLang->time( $localTimestamp, false, false );
2721 $value = $wgContLang->formatNum( $localHour, true );
2724 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2725 # int to remove the padding
2726 $value = $wgContLang->formatNum( (int)$localWeek );
2729 $value = $wgContLang->formatNum( $localDayOfWeek );
2731 case 'numberofarticles':
2732 $value = $wgContLang->formatNum( SiteStats
::articles() );
2734 case 'numberoffiles':
2735 $value = $wgContLang->formatNum( SiteStats
::images() );
2737 case 'numberofusers':
2738 $value = $wgContLang->formatNum( SiteStats
::users() );
2740 case 'numberofactiveusers':
2741 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2743 case 'numberofpages':
2744 $value = $wgContLang->formatNum( SiteStats
::pages() );
2746 case 'numberofadmins':
2747 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2749 case 'numberofedits':
2750 $value = $wgContLang->formatNum( SiteStats
::edits() );
2752 case 'numberofviews':
2753 $value = $wgContLang->formatNum( SiteStats
::views() );
2755 case 'currenttimestamp':
2756 $value = wfTimestamp( TS_MW
, $ts );
2758 case 'localtimestamp':
2759 $value = $localTimestamp;
2761 case 'currentversion':
2762 $value = SpecialVersion
::getVersion();
2765 return $wgArticlePath;
2771 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2772 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2773 wfRestoreWarnings();
2774 return $serverName ?
$serverName : $wgServer;
2776 return $wgScriptPath;
2778 return $wgStylePath;
2779 case 'directionmark':
2780 return $wgContLang->getDirMark();
2781 case 'contentlanguage':
2782 global $wgLanguageCode;
2783 return $wgLanguageCode;
2786 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2794 $this->mVarCache
[$index] = $value;
2800 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2804 function initialiseVariables() {
2805 wfProfileIn( __METHOD__
);
2806 $variableIDs = MagicWord
::getVariableIDs();
2807 $substIDs = MagicWord
::getSubstIDs();
2809 $this->mVariables
= new MagicWordArray( $variableIDs );
2810 $this->mSubstWords
= new MagicWordArray( $substIDs );
2811 wfProfileOut( __METHOD__
);
2815 * Preprocess some wikitext and return the document tree.
2816 * This is the ghost of replace_variables().
2818 * @param $text String: The text to parse
2819 * @param $flags Integer: bitwise combination of:
2820 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2821 * included. Default is to assume a direct page view.
2823 * The generated DOM tree must depend only on the input text and the flags.
2824 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2826 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2827 * change in the DOM tree for a given text, must be passed through the section identifier
2828 * in the section edit link and thus back to extractSections().
2830 * The output of this function is currently only cached in process memory, but a persistent
2831 * cache may be implemented at a later date which takes further advantage of these strict
2832 * dependency requirements.
2836 function preprocessToDom( $text, $flags = 0 ) {
2837 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2842 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2844 public static function splitWhitespace( $s ) {
2845 $ltrimmed = ltrim( $s );
2846 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2847 $trimmed = rtrim( $ltrimmed );
2848 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2850 $w2 = substr( $ltrimmed, -$diff );
2854 return array( $w1, $trimmed, $w2 );
2858 * Replace magic variables, templates, and template arguments
2859 * with the appropriate text. Templates are substituted recursively,
2860 * taking care to avoid infinite loops.
2862 * Note that the substitution depends on value of $mOutputType:
2863 * self::OT_WIKI: only {{subst:}} templates
2864 * self::OT_PREPROCESS: templates but not extension tags
2865 * self::OT_HTML: all templates and extension tags
2867 * @param $text String: the text to transform
2868 * @param $frame PPFrame Object describing the arguments passed to the template.
2869 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2870 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2871 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2874 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2875 # Is there any text? Also, Prevent too big inclusions!
2876 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2879 wfProfileIn( __METHOD__
);
2881 if ( $frame === false ) {
2882 $frame = $this->getPreprocessor()->newFrame();
2883 } elseif ( !( $frame instanceof PPFrame
) ) {
2884 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2885 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2888 $dom = $this->preprocessToDom( $text );
2889 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2890 $text = $frame->expand( $dom, $flags );
2892 wfProfileOut( __METHOD__
);
2896 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2897 static function createAssocArgs( $args ) {
2898 $assocArgs = array();
2900 foreach ( $args as $arg ) {
2901 $eqpos = strpos( $arg, '=' );
2902 if ( $eqpos === false ) {
2903 $assocArgs[$index++
] = $arg;
2905 $name = trim( substr( $arg, 0, $eqpos ) );
2906 $value = trim( substr( $arg, $eqpos+
1 ) );
2907 if ( $value === false ) {
2910 if ( $name !== false ) {
2911 $assocArgs[$name] = $value;
2920 * Warn the user when a parser limitation is reached
2921 * Will warn at most once the user per limitation type
2923 * @param $limitationType String: should be one of:
2924 * 'expensive-parserfunction' (corresponding messages:
2925 * 'expensive-parserfunction-warning',
2926 * 'expensive-parserfunction-category')
2927 * 'post-expand-template-argument' (corresponding messages:
2928 * 'post-expand-template-argument-warning',
2929 * 'post-expand-template-argument-category')
2930 * 'post-expand-template-inclusion' (corresponding messages:
2931 * 'post-expand-template-inclusion-warning',
2932 * 'post-expand-template-inclusion-category')
2933 * @param $current Current value
2934 * @param $max Maximum allowed, when an explicit limit has been
2935 * exceeded, provide the values (optional)
2937 function limitationWarn( $limitationType, $current=null, $max=null) {
2938 # does no harm if $current and $max are present but are unnecessary for the message
2939 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2940 $this->mOutput
->addWarning( $warning );
2941 $this->addTrackingCategory( "$limitationType-category" );
2945 * Return the text of a template, after recursively
2946 * replacing any variables or templates within the template.
2948 * @param $piece Array: the parts of the template
2949 * $piece['title']: the title, i.e. the part before the |
2950 * $piece['parts']: the parameter array
2951 * $piece['lineStart']: whether the brace was at the start of a line
2952 * @param $frame PPFrame The current frame, contains template arguments
2953 * @return String: the text of the template
2956 function braceSubstitution( $piece, $frame ) {
2957 global $wgContLang, $wgNonincludableNamespaces;
2958 wfProfileIn( __METHOD__
);
2959 wfProfileIn( __METHOD__
.'-setup' );
2962 $found = false; # $text has been filled
2963 $nowiki = false; # wiki markup in $text should be escaped
2964 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2965 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2966 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2967 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2969 # Title object, where $text came from
2972 # $part1 is the bit before the first |, and must contain only title characters.
2973 # Various prefixes will be stripped from it later.
2974 $titleWithSpaces = $frame->expand( $piece['title'] );
2975 $part1 = trim( $titleWithSpaces );
2978 # Original title text preserved for various purposes
2979 $originalTitle = $part1;
2981 # $args is a list of argument nodes, starting from index 0, not including $part1
2982 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2983 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2984 wfProfileOut( __METHOD__
.'-setup' );
2987 wfProfileIn( __METHOD__
.'-modifiers' );
2990 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2992 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2993 # Decide whether to expand template or keep wikitext as-is.
2994 if ( $this->ot
['wiki'] ) {
2995 if ( $substMatch === false ) {
2996 $literal = true; # literal when in PST with no prefix
2998 $literal = false; # expand when in PST with subst: or safesubst:
3001 if ( $substMatch == 'subst' ) {
3002 $literal = true; # literal when not in PST with plain subst:
3004 $literal = false; # expand when not in PST with safesubst: or no prefix
3008 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3015 if ( !$found && $args->getLength() == 0 ) {
3016 $id = $this->mVariables
->matchStartToEnd( $part1 );
3017 if ( $id !== false ) {
3018 $text = $this->getVariableValue( $id, $frame );
3019 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3020 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3026 # MSG, MSGNW and RAW
3029 $mwMsgnw = MagicWord
::get( 'msgnw' );
3030 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3033 # Remove obsolete MSG:
3034 $mwMsg = MagicWord
::get( 'msg' );
3035 $mwMsg->matchStartAndRemove( $part1 );
3039 $mwRaw = MagicWord
::get( 'raw' );
3040 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3041 $forceRawInterwiki = true;
3044 wfProfileOut( __METHOD__
.'-modifiers' );
3048 wfProfileIn( __METHOD__
. '-pfunc' );
3050 $colonPos = strpos( $part1, ':' );
3051 if ( $colonPos !== false ) {
3052 # Case sensitive functions
3053 $function = substr( $part1, 0, $colonPos );
3054 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3055 $function = $this->mFunctionSynonyms
[1][$function];
3057 # Case insensitive functions
3058 $function = $wgContLang->lc( $function );
3059 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3060 $function = $this->mFunctionSynonyms
[0][$function];
3066 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3067 $initialArgs = array( &$this );
3068 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3069 if ( $flags & SFH_OBJECT_ARGS
) {
3070 # Add a frame parameter, and pass the arguments as an array
3071 $allArgs = $initialArgs;
3072 $allArgs[] = $frame;
3073 for ( $i = 0; $i < $args->getLength(); $i++
) {
3074 $funcArgs[] = $args->item( $i );
3076 $allArgs[] = $funcArgs;
3078 # Convert arguments to plain text
3079 for ( $i = 0; $i < $args->getLength(); $i++
) {
3080 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3082 $allArgs = array_merge( $initialArgs, $funcArgs );
3085 # Workaround for PHP bug 35229 and similar
3086 if ( !is_callable( $callback ) ) {
3087 wfProfileOut( __METHOD__
. '-pfunc' );
3088 wfProfileOut( __METHOD__
);
3089 throw new MWException( "Tag hook for $function is not callable\n" );
3091 $result = call_user_func_array( $callback, $allArgs );
3094 $preprocessFlags = 0;
3096 if ( is_array( $result ) ) {
3097 if ( isset( $result[0] ) ) {
3099 unset( $result[0] );
3102 # Extract flags into the local scope
3103 # This allows callers to set flags such as nowiki, found, etc.
3109 $text = $this->preprocessToDom( $text, $preprocessFlags );
3114 wfProfileOut( __METHOD__
. '-pfunc' );
3117 # Finish mangling title and then check for loops.
3118 # Set $title to a Title object and $titleText to the PDBK
3121 # Split the title into page and subpage
3123 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3124 if ( $subpage !== '' ) {
3125 $ns = $this->mTitle
->getNamespace();
3127 $title = Title
::newFromText( $part1, $ns );
3129 $titleText = $title->getPrefixedText();
3130 # Check for language variants if the template is not found
3131 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3132 $wgContLang->findVariantLink( $part1, $title, true );
3134 # Do recursion depth check
3135 $limit = $this->mOptions
->getMaxTemplateDepth();
3136 if ( $frame->depth
>= $limit ) {
3138 $text = '<span class="error">'
3139 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3145 # Load from database
3146 if ( !$found && $title ) {
3147 wfProfileIn( __METHOD__
. '-loadtpl' );
3148 if ( !$title->isExternal() ) {
3149 if ( $title->getNamespace() == NS_SPECIAL
3150 && $this->mOptions
->getAllowSpecialInclusion()
3151 && $this->ot
['html'] )
3153 $text = SpecialPage
::capturePath( $title );
3154 if ( is_string( $text ) ) {
3157 $this->disableCache();
3159 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3160 $found = false; # access denied
3161 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3163 list( $text, $title ) = $this->getTemplateDom( $title );
3164 if ( $text !== false ) {
3170 # If the title is valid but undisplayable, make a link to it
3171 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3172 $text = "[[:$titleText]]";
3175 } elseif ( $title->isTrans() ) {
3176 # Interwiki transclusion
3177 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3178 $text = $this->interwikiTransclude( $title, 'render' );
3181 $text = $this->interwikiTransclude( $title, 'raw' );
3182 # Preprocess it like a template
3183 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3189 # Do infinite loop check
3190 # This has to be done after redirect resolution to avoid infinite loops via redirects
3191 if ( !$frame->loopCheck( $title ) ) {
3193 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3194 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3196 wfProfileOut( __METHOD__
. '-loadtpl' );
3199 # If we haven't found text to substitute by now, we're done
3200 # Recover the source wikitext and return it
3202 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3203 wfProfileOut( __METHOD__
);
3204 return array( 'object' => $text );
3207 # Expand DOM-style return values in a child frame
3208 if ( $isChildObj ) {
3209 # Clean up argument array
3210 $newFrame = $frame->newChild( $args, $title );
3213 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3214 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3215 # Expansion is eligible for the empty-frame cache
3216 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3217 $text = $this->mTplExpandCache
[$titleText];
3219 $text = $newFrame->expand( $text );
3220 $this->mTplExpandCache
[$titleText] = $text;
3223 # Uncached expansion
3224 $text = $newFrame->expand( $text );
3227 if ( $isLocalObj && $nowiki ) {
3228 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3229 $isLocalObj = false;
3232 # Replace raw HTML by a placeholder
3233 # Add a blank line preceding, to prevent it from mucking up
3234 # immediately preceding headings
3236 $text = "\n\n" . $this->insertStripItem( $text );
3237 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3238 # Escape nowiki-style return values
3239 $text = wfEscapeWikiText( $text );
3240 } elseif ( is_string( $text )
3241 && !$piece['lineStart']
3242 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3244 # Bug 529: if the template begins with a table or block-level
3245 # element, it should be treated as beginning a new line.
3246 # This behaviour is somewhat controversial.
3247 $text = "\n" . $text;
3250 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3251 # Error, oversize inclusion
3252 if ( $titleText !== false ) {
3253 # Make a working, properly escaped link if possible (bug 23588)
3254 $text = "[[:$titleText]]";
3256 # This will probably not be a working link, but at least it may
3257 # provide some hint of where the problem is
3258 preg_replace( '/^:/', '', $originalTitle );
3259 $text = "[[:$originalTitle]]";
3261 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3262 $this->limitationWarn( 'post-expand-template-inclusion' );
3265 if ( $isLocalObj ) {
3266 $ret = array( 'object' => $text );
3268 $ret = array( 'text' => $text );
3271 wfProfileOut( __METHOD__
);
3276 * Get the semi-parsed DOM representation of a template with a given title,
3277 * and its redirect destination title. Cached.
3279 function getTemplateDom( $title ) {
3280 $cacheTitle = $title;
3281 $titleText = $title->getPrefixedDBkey();
3283 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3284 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3285 $title = Title
::makeTitle( $ns, $dbk );
3286 $titleText = $title->getPrefixedDBkey();
3288 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3289 return array( $this->mTplDomCache
[$titleText], $title );
3292 # Cache miss, go to the database
3293 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3295 if ( $text === false ) {
3296 $this->mTplDomCache
[$titleText] = false;
3297 return array( false, $title );
3300 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3301 $this->mTplDomCache
[ $titleText ] = $dom;
3303 if ( !$title->equals( $cacheTitle ) ) {
3304 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3305 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3308 return array( $dom, $title );
3312 * Fetch the unparsed text of a template and register a reference to it.
3313 * @param Title $title
3314 * @return Array ( string or false, Title )
3316 function fetchTemplateAndTitle( $title ) {
3317 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3318 $stuff = call_user_func( $templateCb, $title, $this );
3319 $text = $stuff['text'];
3320 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3321 if ( isset( $stuff['deps'] ) ) {
3322 foreach ( $stuff['deps'] as $dep ) {
3323 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3326 return array( $text, $finalTitle );
3330 * Fetch the unparsed text of a template and register a reference to it.
3331 * @param Title $title
3332 * @return mixed string or false
3334 function fetchTemplate( $title ) {
3335 $rv = $this->fetchTemplateAndTitle( $title );
3340 * Static function to get a template
3341 * Can be overridden via ParserOptions::setTemplateCallback().
3343 static function statelessFetchTemplate( $title, $parser=false ) {
3344 $text = $skip = false;
3345 $finalTitle = $title;
3348 # Loop to fetch the article, with up to 1 redirect
3349 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3350 # Give extensions a chance to select the revision instead
3351 $id = false; # Assume current
3352 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3353 array( $parser, &$title, &$skip, &$id ) );
3359 'page_id' => $title->getArticleID(),
3366 ? Revision
::newFromId( $id )
3367 : Revision
::newFromTitle( $title );
3368 $rev_id = $rev ?
$rev->getId() : 0;
3369 # If there is no current revision, there is no page
3370 if ( $id === false && !$rev ) {
3371 $linkCache = LinkCache
::singleton();
3372 $linkCache->addBadLinkObj( $title );
3377 'page_id' => $title->getArticleID(),
3378 'rev_id' => $rev_id );
3379 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3380 # We fetched a rev from a different title; register it too...
3382 'title' => $rev->getTitle(),
3383 'page_id' => $rev->getPage(),
3384 'rev_id' => $rev_id );
3388 $text = $rev->getText();
3389 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3391 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3392 if ( !$message->exists() ) {
3396 $text = $message->plain();
3400 if ( $text === false ) {
3404 $finalTitle = $title;
3405 $title = Title
::newFromRedirect( $text );
3409 'finalTitle' => $finalTitle,
3414 * Fetch a file and its title and register a reference to it.
3415 * @param Title $title
3416 * @param string $time MW timestamp
3417 * @param string $sha1 base 36 SHA-1
3418 * @return mixed File or false
3420 function fetchFile( $title, $time = false, $sha1 = false ) {
3421 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3426 * Fetch a file and its title and register a reference to it.
3427 * @param Title $title
3428 * @param string $time MW timestamp
3429 * @param string $sha1 base 36 SHA-1
3430 * @return Array ( File or false, Title of file )
3432 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3433 if ( $time === '0' ) {
3434 $file = false; // broken thumbnail forced by hook
3435 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3436 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3437 } else { // get by (name,timestamp)
3438 $file = wfFindFile( $title, array( 'time' => $time ) );
3440 $time = $file ?
$file->getTimestamp() : null;
3441 $sha1 = $file ?
$file->getSha1() : null;
3442 # Register the file as a dependency...
3443 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3444 if ( $file && !$title->equals( $file->getTitle() ) ) {
3445 # We fetched a rev from a different title; register it too...
3446 $this->mOutput
->addImage( $file->getTitle()->getDBkey(), $time, $sha1 );
3447 # Update fetched file title
3448 $title = $file->getTitle();
3450 return array( $file, $title );
3454 * Transclude an interwiki link.
3456 function interwikiTransclude( $title, $action ) {
3457 global $wgEnableScaryTranscluding;
3459 if ( !$wgEnableScaryTranscluding ) {
3460 return wfMsgForContent('scarytranscludedisabled');
3463 $url = $title->getFullUrl( "action=$action" );
3465 if ( strlen( $url ) > 255 ) {
3466 return wfMsgForContent( 'scarytranscludetoolong' );
3468 return $this->fetchScaryTemplateMaybeFromCache( $url );
3471 function fetchScaryTemplateMaybeFromCache( $url ) {
3472 global $wgTranscludeCacheExpiry;
3473 $dbr = wfGetDB( DB_SLAVE
);
3474 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3475 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3476 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3478 return $obj->tc_contents
;
3481 $text = Http
::get( $url );
3483 return wfMsgForContent( 'scarytranscludefailed', $url );
3486 $dbw = wfGetDB( DB_MASTER
);
3487 $dbw->replace( 'transcache', array('tc_url'), array(
3489 'tc_time' => $dbw->timestamp( time() ),
3490 'tc_contents' => $text)
3497 * Triple brace replacement -- used for template arguments
3500 function argSubstitution( $piece, $frame ) {
3501 wfProfileIn( __METHOD__
);
3504 $parts = $piece['parts'];
3505 $nameWithSpaces = $frame->expand( $piece['title'] );
3506 $argName = trim( $nameWithSpaces );
3508 $text = $frame->getArgument( $argName );
3509 if ( $text === false && $parts->getLength() > 0
3513 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3516 # No match in frame, use the supplied default
3517 $object = $parts->item( 0 )->getChildren();
3519 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3520 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3521 $this->limitationWarn( 'post-expand-template-argument' );
3524 if ( $text === false && $object === false ) {
3526 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3528 if ( $error !== false ) {
3531 if ( $object !== false ) {
3532 $ret = array( 'object' => $object );
3534 $ret = array( 'text' => $text );
3537 wfProfileOut( __METHOD__
);
3542 * Return the text to be used for a given extension tag.
3543 * This is the ghost of strip().
3545 * @param $params Associative array of parameters:
3546 * name PPNode for the tag name
3547 * attr PPNode for unparsed text where tag attributes are thought to be
3548 * attributes Optional associative array of parsed attributes
3549 * inner Contents of extension element
3550 * noClose Original text did not have a close tag
3551 * @param $frame PPFrame
3553 function extensionSubstitution( $params, $frame ) {
3554 $name = $frame->expand( $params['name'] );
3555 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3556 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3557 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3559 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3560 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3561 if ( $isFunctionTag ) {
3562 $markerType = 'none';
3564 $markerType = 'general';
3566 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3567 $name = strtolower( $name );
3568 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3569 if ( isset( $params['attributes'] ) ) {
3570 $attributes = $attributes +
$params['attributes'];
3573 if ( isset( $this->mTagHooks
[$name] ) ) {
3574 # Workaround for PHP bug 35229 and similar
3575 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3576 throw new MWException( "Tag hook for $name is not callable\n" );
3578 $output = call_user_func_array( $this->mTagHooks
[$name],
3579 array( $content, $attributes, $this, $frame ) );
3580 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3581 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3582 if ( !is_callable( $callback ) ) {
3583 throw new MWException( "Tag hook for $name is not callable\n" );
3586 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3588 $output = '<span class="error">Invalid tag extension name: ' .
3589 htmlspecialchars( $name ) . '</span>';
3592 if ( is_array( $output ) ) {
3593 # Extract flags to local scope (to override $markerType)
3595 $output = $flags[0];
3600 if ( is_null( $attrText ) ) {
3603 if ( isset( $params['attributes'] ) ) {
3604 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3605 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3606 htmlspecialchars( $attrValue ) . '"';
3609 if ( $content === null ) {
3610 $output = "<$name$attrText/>";
3612 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3613 $output = "<$name$attrText>$content$close";
3617 if ( $markerType === 'none' ) {
3619 } elseif ( $markerType === 'nowiki' ) {
3620 $this->mStripState
->addNoWiki( $marker, $output );
3621 } elseif ( $markerType === 'general' ) {
3622 $this->mStripState
->addGeneral( $marker, $output );
3624 throw new MWException( __METHOD__
.': invalid marker type' );
3630 * Increment an include size counter
3632 * @param $type String: the type of expansion
3633 * @param $size Integer: the size of the text
3634 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3636 function incrementIncludeSize( $type, $size ) {
3637 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3640 $this->mIncludeSizes
[$type] +
= $size;
3646 * Increment the expensive function count
3648 * @return Boolean: false if the limit has been exceeded
3650 function incrementExpensiveFunctionCount() {
3651 global $wgExpensiveParserFunctionLimit;
3652 $this->mExpensiveFunctionCount++
;
3653 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3660 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3661 * Fills $this->mDoubleUnderscores, returns the modified text
3663 function doDoubleUnderscore( $text ) {
3664 wfProfileIn( __METHOD__
);
3666 # The position of __TOC__ needs to be recorded
3667 $mw = MagicWord
::get( 'toc' );
3668 if ( $mw->match( $text ) ) {
3669 $this->mShowToc
= true;
3670 $this->mForceTocPosition
= true;
3672 # Set a placeholder. At the end we'll fill it in with the TOC.
3673 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3675 # Only keep the first one.
3676 $text = $mw->replace( '', $text );
3679 # Now match and remove the rest of them
3680 $mwa = MagicWord
::getDoubleUnderscoreArray();
3681 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3683 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3684 $this->mOutput
->mNoGallery
= true;
3686 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3687 $this->mShowToc
= false;
3689 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3690 $this->addTrackingCategory( 'hidden-category-category' );
3692 # (bug 8068) Allow control over whether robots index a page.
3694 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3695 # is not desirable, the last one on the page should win.
3696 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3697 $this->mOutput
->setIndexPolicy( 'noindex' );
3698 $this->addTrackingCategory( 'noindex-category' );
3700 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3701 $this->mOutput
->setIndexPolicy( 'index' );
3702 $this->addTrackingCategory( 'index-category' );
3705 # Cache all double underscores in the database
3706 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3707 $this->mOutput
->setProperty( $key, '' );
3710 wfProfileOut( __METHOD__
);
3715 * Add a tracking category, getting the title from a system message,
3716 * or print a debug message if the title is invalid.
3718 * @param $msg String: message key
3719 * @return Boolean: whether the addition was successful
3721 protected function addTrackingCategory( $msg ) {
3722 $cat = wfMsgForContent( $msg );
3724 # Allow tracking categories to be disabled by setting them to "-"
3725 if ( $cat === '-' ) {
3729 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3730 if ( $containerCategory ) {
3731 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3734 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3740 * This function accomplishes several tasks:
3741 * 1) Auto-number headings if that option is enabled
3742 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3743 * 3) Add a Table of contents on the top for users who have enabled the option
3744 * 4) Auto-anchor headings
3746 * It loops through all headlines, collects the necessary data, then splits up the
3747 * string and re-inserts the newly formatted headlines.
3749 * @param $text String
3750 * @param $origText String: original, untouched wikitext
3751 * @param $isMain Boolean
3754 function formatHeadings( $text, $origText, $isMain=true ) {
3755 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3757 # Inhibit editsection links if requested in the page
3758 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3761 $showEditLink = $this->mOptions
->getEditSection();
3763 if ( $showEditLink ) {
3764 $this->mOutput
->setEditSectionTokens( true );
3767 # Get all headlines for numbering them and adding funky stuff like [edit]
3768 # links - this is for later, but we need the number of headlines right now
3770 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3772 # if there are fewer than 4 headlines in the article, do not show TOC
3773 # unless it's been explicitly enabled.
3774 $enoughToc = $this->mShowToc
&&
3775 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3777 # Allow user to stipulate that a page should have a "new section"
3778 # link added via __NEWSECTIONLINK__
3779 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3780 $this->mOutput
->setNewSection( true );
3783 # Allow user to remove the "new section"
3784 # link via __NONEWSECTIONLINK__
3785 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3786 $this->mOutput
->hideNewSection( true );
3789 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3790 # override above conditions and always show TOC above first header
3791 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3792 $this->mShowToc
= true;
3796 # We need this to perform operations on the HTML
3797 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3803 # Ugh .. the TOC should have neat indentation levels which can be
3804 # passed to the skin functions. These are determined here
3808 $sublevelCount = array();
3809 $levelCount = array();
3814 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3815 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3816 $oldType = $this->mOutputType
;
3817 $this->setOutputType( self
::OT_WIKI
);
3818 $frame = $this->getPreprocessor()->newFrame();
3819 $root = $this->preprocessToDom( $origText );
3820 $node = $root->getFirstChild();
3825 foreach ( $matches[3] as $headline ) {
3826 $isTemplate = false;
3828 $sectionIndex = false;
3830 $markerMatches = array();
3831 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3832 $serial = $markerMatches[1];
3833 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3834 $isTemplate = ( $titleText != $baseTitleText );
3835 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3839 $prevlevel = $level;
3841 $level = $matches[1][$headlineCount];
3843 if ( $level > $prevlevel ) {
3844 # Increase TOC level
3846 $sublevelCount[$toclevel] = 0;
3847 if ( $toclevel<$wgMaxTocLevel ) {
3848 $prevtoclevel = $toclevel;
3849 $toc .= $sk->tocIndent();
3852 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3853 # Decrease TOC level, find level to jump to
3855 for ( $i = $toclevel; $i > 0; $i-- ) {
3856 if ( $levelCount[$i] == $level ) {
3857 # Found last matching level
3860 } elseif ( $levelCount[$i] < $level ) {
3861 # Found first matching level below current level
3869 if ( $toclevel<$wgMaxTocLevel ) {
3870 if ( $prevtoclevel < $wgMaxTocLevel ) {
3871 # Unindent only if the previous toc level was shown :p
3872 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3873 $prevtoclevel = $toclevel;
3875 $toc .= $sk->tocLineEnd();
3879 # No change in level, end TOC line
3880 if ( $toclevel<$wgMaxTocLevel ) {
3881 $toc .= $sk->tocLineEnd();
3885 $levelCount[$toclevel] = $level;
3887 # count number of headlines for each level
3888 @$sublevelCount[$toclevel]++
;
3890 for( $i = 1; $i <= $toclevel; $i++
) {
3891 if ( !empty( $sublevelCount[$i] ) ) {
3895 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3900 # The safe header is a version of the header text safe to use for links
3901 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3902 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3904 # Remove link placeholders by the link text.
3905 # <!--LINK number-->
3907 # link text with suffix
3908 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3910 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3911 $tocline = preg_replace(
3912 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3913 array( '', '<$1>' ),
3916 $tocline = trim( $tocline );
3918 # For the anchor, strip out HTML-y stuff period
3919 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3920 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3922 # Save headline for section edit hint before it's escaped
3923 $headlineHint = $safeHeadline;
3925 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3926 # For reverse compatibility, provide an id that's
3927 # HTML4-compatible, like we used to.
3929 # It may be worth noting, academically, that it's possible for
3930 # the legacy anchor to conflict with a non-legacy headline
3931 # anchor on the page. In this case likely the "correct" thing
3932 # would be to either drop the legacy anchors or make sure
3933 # they're numbered first. However, this would require people
3934 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3935 # manually, so let's not bother worrying about it.
3936 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3937 array( 'noninitial', 'legacy' ) );
3938 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3940 if ( $legacyHeadline == $safeHeadline ) {
3941 # No reason to have both (in fact, we can't)
3942 $legacyHeadline = false;
3945 $legacyHeadline = false;
3946 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3950 # HTML names must be case-insensitively unique (bug 10721).
3951 # This does not apply to Unicode characters per
3952 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3953 # FIXME: We may be changing them depending on the current locale.
3954 $arrayKey = strtolower( $safeHeadline );
3955 if ( $legacyHeadline === false ) {
3956 $legacyArrayKey = false;
3958 $legacyArrayKey = strtolower( $legacyHeadline );
3961 # count how many in assoc. array so we can track dupes in anchors
3962 if ( isset( $refers[$arrayKey] ) ) {
3963 $refers[$arrayKey]++
;
3965 $refers[$arrayKey] = 1;
3967 if ( isset( $refers[$legacyArrayKey] ) ) {
3968 $refers[$legacyArrayKey]++
;
3970 $refers[$legacyArrayKey] = 1;
3973 # Don't number the heading if it is the only one (looks silly)
3974 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
3975 # the two are different if the line contains a link
3976 $headline = $numbering . ' ' . $headline;
3979 # Create the anchor for linking from the TOC to the section
3980 $anchor = $safeHeadline;
3981 $legacyAnchor = $legacyHeadline;
3982 if ( $refers[$arrayKey] > 1 ) {
3983 $anchor .= '_' . $refers[$arrayKey];
3985 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3986 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3988 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3989 $toc .= $sk->tocLine( $anchor, $tocline,
3990 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3993 # Add the section to the section tree
3994 # Find the DOM node for this header
3995 while ( $node && !$isTemplate ) {
3996 if ( $node->getName() === 'h' ) {
3997 $bits = $node->splitHeading();
3998 if ( $bits['i'] == $sectionIndex ) {
4002 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4003 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4004 $node = $node->getNextSibling();
4007 'toclevel' => $toclevel,
4010 'number' => $numbering,
4011 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4012 'fromtitle' => $titleText,
4013 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4014 'anchor' => $anchor,
4017 # give headline the correct <h#> tag
4018 if ( $showEditLink && $sectionIndex !== false ) {
4019 // Output edit section links as markers with styles that can be customized by skins
4020 if ( $isTemplate ) {
4021 # Put a T flag in the section identifier, to indicate to extractSections()
4022 # that sections inside <includeonly> should be counted.
4023 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4025 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4027 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4028 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4029 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4030 // so we don't have to worry about a user trying to input one of these markers directly.
4031 // We use a page and section attribute to stop the language converter from converting these important bits
4032 // of data, but put the headline hint inside a content block because the language converter is supposed to
4033 // be able to convert that piece of data.
4034 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4035 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4036 if ( isset($editlinkArgs[2]) ) {
4037 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4044 $head[$headlineCount] = $sk->makeHeadline( $level,
4045 $matches['attrib'][$headlineCount], $anchor, $headline,
4046 $editlink, $legacyAnchor );
4051 $this->setOutputType( $oldType );
4053 # Never ever show TOC if no headers
4054 if ( $numVisible < 1 ) {
4059 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4060 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
4062 $toc = $sk->tocList( $toc, $this->mOptions
->getUserLang() );
4063 $this->mOutput
->setTOCHTML( $toc );
4067 $this->mOutput
->setSections( $tocraw );
4070 # split up and insert constructed headlines
4072 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4075 foreach ( $blocks as $block ) {
4076 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4077 # This is the [edit] link that appears for the top block of text when
4078 # section editing is enabled
4080 # Disabled because it broke block formatting
4081 # For example, a bullet point in the top line
4082 # $full .= $sk->editSectionLink(0);
4085 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4086 # Top anchor now in skin
4090 if ( !empty( $head[$i] ) ) {
4095 if ( $this->mForceTocPosition
) {
4096 return str_replace( '<!--MWTOC-->', $toc, $full );
4103 * Transform wiki markup when saving a page by doing \r\n -> \n
4104 * conversion, substitting signatures, {{subst:}} templates, etc.
4106 * @param $text String: the text to transform
4107 * @param $title Title: the Title object for the current article
4108 * @param $user User: the User object describing the current user
4109 * @param $options ParserOptions: parsing options
4110 * @param $clearState Boolean: whether to clear the parser state first
4111 * @return String: the altered wiki markup
4113 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4114 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4115 $this->setUser( $user );
4120 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4121 if( $options->getPreSaveTransform() ) {
4122 $text = $this->pstPass2( $text, $user );
4124 $text = $this->mStripState
->unstripBoth( $text );
4126 $this->setUser( null ); #Reset
4132 * Pre-save transform helper function
4135 function pstPass2( $text, $user ) {
4136 global $wgContLang, $wgLocaltimezone;
4138 # Note: This is the timestamp saved as hardcoded wikitext to
4139 # the database, we use $wgContLang here in order to give
4140 # everyone the same signature and use the default one rather
4141 # than the one selected in each user's preferences.
4142 # (see also bug 12815)
4143 $ts = $this->mOptions
->getTimestamp();
4144 if ( isset( $wgLocaltimezone ) ) {
4145 $tz = $wgLocaltimezone;
4147 $tz = date_default_timezone_get();
4150 $unixts = wfTimestamp( TS_UNIX
, $ts );
4151 $oldtz = date_default_timezone_get();
4152 date_default_timezone_set( $tz );
4153 $ts = date( 'YmdHis', $unixts );
4154 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4156 # Allow translation of timezones through wiki. date() can return
4157 # whatever crap the system uses, localised or not, so we cannot
4158 # ship premade translations.
4159 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4160 $msg = wfMessage( $key )->inContentLanguage();
4161 if ( $msg->exists() ) {
4162 $tzMsg = $msg->text();
4165 date_default_timezone_set( $oldtz );
4167 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4169 # Variable replacement
4170 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4171 $text = $this->replaceVariables( $text );
4173 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4174 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4177 $sigText = $this->getUserSig( $user );
4178 $text = strtr( $text, array(
4180 '~~~~' => "$sigText $d",
4184 # Context links: [[|name]] and [[name (context)|]]
4185 global $wgLegalTitleChars;
4186 $tc = "[$wgLegalTitleChars]";
4187 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4189 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4190 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4191 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4192 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4194 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4195 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4196 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4197 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4199 $t = $this->mTitle
->getText();
4201 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4202 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4203 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4204 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4206 # if there's no context, don't bother duplicating the title
4207 $text = preg_replace( $p2, '[[\\1]]', $text );
4210 # Trim trailing whitespace
4211 $text = rtrim( $text );
4217 * Fetch the user's signature text, if any, and normalize to
4218 * validated, ready-to-insert wikitext.
4219 * If you have pre-fetched the nickname or the fancySig option, you can
4220 * specify them here to save a database query.
4221 * Do not reuse this parser instance after calling getUserSig(),
4222 * as it may have changed if it's the $wgParser.
4225 * @param $nickname String: nickname to use or false to use user's default nickname
4226 * @param $fancySig Boolean: whether the nicknname is the complete signature
4227 * or null to use default value
4230 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4231 global $wgMaxSigChars;
4233 $username = $user->getName();
4235 # If not given, retrieve from the user object.
4236 if ( $nickname === false )
4237 $nickname = $user->getOption( 'nickname' );
4239 if ( is_null( $fancySig ) ) {
4240 $fancySig = $user->getBoolOption( 'fancysig' );
4243 $nickname = $nickname == null ?
$username : $nickname;
4245 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4246 $nickname = $username;
4247 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4248 } elseif ( $fancySig !== false ) {
4249 # Sig. might contain markup; validate this
4250 if ( $this->validateSig( $nickname ) !== false ) {
4251 # Validated; clean up (if needed) and return it
4252 return $this->cleanSig( $nickname, true );
4254 # Failed to validate; fall back to the default
4255 $nickname = $username;
4256 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4260 # Make sure nickname doesnt get a sig in a sig
4261 $nickname = $this->cleanSigInSig( $nickname );
4263 # If we're still here, make it a link to the user page
4264 $userText = wfEscapeWikiText( $username );
4265 $nickText = wfEscapeWikiText( $nickname );
4266 if ( $user->isAnon() ) {
4267 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4269 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4274 * Check that the user's signature contains no bad XML
4276 * @param $text String
4277 * @return mixed An expanded string, or false if invalid.
4279 function validateSig( $text ) {
4280 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4284 * Clean up signature text
4286 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4287 * 2) Substitute all transclusions
4289 * @param $text String
4290 * @param $parsing Whether we're cleaning (preferences save) or parsing
4291 * @return String: signature text
4293 function cleanSig( $text, $parsing = false ) {
4296 $this->mOptions
= new ParserOptions
;
4297 $this->clearState();
4298 $this->setTitle( $wgTitle );
4299 $this->setOutputType
= self
::OT_PREPROCESS
;
4302 # Option to disable this feature
4303 if ( !$this->mOptions
->getCleanSignatures() ) {
4307 # FIXME: regex doesn't respect extension tags or nowiki
4308 # => Move this logic to braceSubstitution()
4309 $substWord = MagicWord
::get( 'subst' );
4310 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4311 $substText = '{{' . $substWord->getSynonym( 0 );
4313 $text = preg_replace( $substRegex, $substText, $text );
4314 $text = $this->cleanSigInSig( $text );
4315 $dom = $this->preprocessToDom( $text );
4316 $frame = $this->getPreprocessor()->newFrame();
4317 $text = $frame->expand( $dom );
4320 $text = $this->mStripState
->unstripBoth( $text );
4327 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4329 * @param $text String
4330 * @return String: signature text with /~{3,5}/ removed
4332 function cleanSigInSig( $text ) {
4333 $text = preg_replace( '/~{3,5}/', '', $text );
4338 * Set up some variables which are usually set up in parse()
4339 * so that an external function can call some class members with confidence
4341 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4342 $this->startParse( $title, $options, $outputType, $clearState );
4345 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4346 $this->setTitle( $title );
4347 $this->mOptions
= $options;
4348 $this->setOutputType( $outputType );
4349 if ( $clearState ) {
4350 $this->clearState();
4355 * Wrapper for preprocess()
4357 * @param $text String: the text to preprocess
4358 * @param $options ParserOptions: options
4359 * @param $title Title object or null to use $wgTitle
4362 public function transformMsg( $text, $options, $title = null ) {
4363 static $executing = false;
4365 # Guard against infinite recursion
4371 wfProfileIn( __METHOD__
);
4377 # It's not uncommon having a null $wgTitle in scripts. See r80898
4378 # Create a ghost title in such case
4379 $title = Title
::newFromText( 'Dwimmerlaik' );
4381 $text = $this->preprocess( $text, $title, $options );
4384 wfProfileOut( __METHOD__
);
4389 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4390 * The callback should have the following form:
4391 * function myParserHook( $text, $params, $parser ) { ... }
4393 * Transform and return $text. Use $parser for any required context, e.g. use
4394 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4396 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4397 * @param $callback Mixed: the callback function (and object) to use for the tag
4398 * @return The old value of the mTagHooks array associated with the hook
4400 public function setHook( $tag, $callback ) {
4401 $tag = strtolower( $tag );
4402 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4403 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4404 $this->mTagHooks
[$tag] = $callback;
4405 if ( !in_array( $tag, $this->mStripList
) ) {
4406 $this->mStripList
[] = $tag;
4412 function setTransparentTagHook( $tag, $callback ) {
4413 $tag = strtolower( $tag );
4414 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4415 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4416 $this->mTransparentTagHooks
[$tag] = $callback;
4422 * Remove all tag hooks
4424 function clearTagHooks() {
4425 $this->mTagHooks
= array();
4426 $this->mStripList
= $this->mDefaultStripList
;
4430 * Create a function, e.g. {{sum:1|2|3}}
4431 * The callback function should have the form:
4432 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4434 * Or with SFH_OBJECT_ARGS:
4435 * function myParserFunction( $parser, $frame, $args ) { ... }
4437 * The callback may either return the text result of the function, or an array with the text
4438 * in element 0, and a number of flags in the other elements. The names of the flags are
4439 * specified in the keys. Valid flags are:
4440 * found The text returned is valid, stop processing the template. This
4442 * nowiki Wiki markup in the return value should be escaped
4443 * isHTML The returned text is HTML, armour it against wikitext transformation
4445 * @param $id String: The magic word ID
4446 * @param $callback Mixed: the callback function (and object) to use
4447 * @param $flags Integer: a combination of the following flags:
4448 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4450 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4451 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4452 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4453 * the arguments, and to control the way they are expanded.
4455 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4456 * arguments, for instance:
4457 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4459 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4460 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4461 * working if/when this is changed.
4463 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4466 * Please read the documentation in includes/parser/Preprocessor.php for more information
4467 * about the methods available in PPFrame and PPNode.
4469 * @return The old callback function for this name, if any
4471 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4474 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4475 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4477 # Add to function cache
4478 $mw = MagicWord
::get( $id );
4480 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4482 $synonyms = $mw->getSynonyms();
4483 $sensitive = intval( $mw->isCaseSensitive() );
4485 foreach ( $synonyms as $syn ) {
4487 if ( !$sensitive ) {
4488 $syn = $wgContLang->lc( $syn );
4491 if ( !( $flags & SFH_NO_HASH
) ) {
4494 # Remove trailing colon
4495 if ( substr( $syn, -1, 1 ) === ':' ) {
4496 $syn = substr( $syn, 0, -1 );
4498 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4504 * Get all registered function hook identifiers
4508 function getFunctionHooks() {
4509 return array_keys( $this->mFunctionHooks
);
4513 * Create a tag function, e.g. <test>some stuff</test>.
4514 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4515 * Unlike parser functions, their content is not preprocessed.
4517 function setFunctionTagHook( $tag, $callback, $flags ) {
4518 $tag = strtolower( $tag );
4519 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4520 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4521 $this->mFunctionTagHooks
[$tag] : null;
4522 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4524 if ( !in_array( $tag, $this->mStripList
) ) {
4525 $this->mStripList
[] = $tag;
4532 * FIXME: update documentation. makeLinkObj() is deprecated.
4533 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4534 * Placeholders created in Skin::makeLinkObj()
4535 * Returns an array of link CSS classes, indexed by PDBK.
4537 function replaceLinkHolders( &$text, $options = 0 ) {
4538 return $this->mLinkHolders
->replace( $text );
4542 * Replace <!--LINK--> link placeholders with plain text of links
4543 * (not HTML-formatted).
4545 * @param $text String
4548 function replaceLinkHoldersText( $text ) {
4549 return $this->mLinkHolders
->replaceText( $text );
4553 * Renders an image gallery from a text with one line per image.
4554 * text labels may be given by using |-style alternative text. E.g.
4555 * Image:one.jpg|The number "1"
4556 * Image:tree.jpg|A tree
4557 * given as text will return the HTML of a gallery with two images,
4558 * labeled 'The number "1"' and
4561 function renderImageGallery( $text, $params ) {
4562 $ig = new ImageGallery();
4563 $ig->setContextTitle( $this->mTitle
);
4564 $ig->setShowBytes( false );
4565 $ig->setShowFilename( false );
4566 $ig->setParser( $this );
4567 $ig->setHideBadImages();
4568 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4569 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4571 if ( isset( $params['showfilename'] ) ) {
4572 $ig->setShowFilename( true );
4574 $ig->setShowFilename( false );
4576 if ( isset( $params['caption'] ) ) {
4577 $caption = $params['caption'];
4578 $caption = htmlspecialchars( $caption );
4579 $caption = $this->replaceInternalLinks( $caption );
4580 $ig->setCaptionHtml( $caption );
4582 if ( isset( $params['perrow'] ) ) {
4583 $ig->setPerRow( $params['perrow'] );
4585 if ( isset( $params['widths'] ) ) {
4586 $ig->setWidths( $params['widths'] );
4588 if ( isset( $params['heights'] ) ) {
4589 $ig->setHeights( $params['heights'] );
4592 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4594 $lines = StringUtils
::explode( "\n", $text );
4595 foreach ( $lines as $line ) {
4596 # match lines like these:
4597 # Image:someimage.jpg|This is some image
4599 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4601 if ( count( $matches ) == 0 ) {
4605 if ( strpos( $matches[0], '%' ) !== false ) {
4606 $matches[1] = rawurldecode( $matches[1] );
4608 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4610 if ( is_null( $nt ) ) {
4611 # Bogus title. Ignore these so we don't bomb out later.
4614 if ( isset( $matches[3] ) ) {
4615 $label = $matches[3];
4620 $html = $this->recursiveTagParse( trim( $label ) );
4622 $ig->add( $nt, $html );
4624 return $ig->toHTML();
4627 function getImageParams( $handler ) {
4629 $handlerClass = get_class( $handler );
4633 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4634 # Initialise static lists
4635 static $internalParamNames = array(
4636 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4637 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4638 'bottom', 'text-bottom' ),
4639 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4640 'upright', 'border', 'link', 'alt' ),
4642 static $internalParamMap;
4643 if ( !$internalParamMap ) {
4644 $internalParamMap = array();
4645 foreach ( $internalParamNames as $type => $names ) {
4646 foreach ( $names as $name ) {
4647 $magicName = str_replace( '-', '_', "img_$name" );
4648 $internalParamMap[$magicName] = array( $type, $name );
4653 # Add handler params
4654 $paramMap = $internalParamMap;
4656 $handlerParamMap = $handler->getParamMap();
4657 foreach ( $handlerParamMap as $magic => $paramName ) {
4658 $paramMap[$magic] = array( 'handler', $paramName );
4661 $this->mImageParams
[$handlerClass] = $paramMap;
4662 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4664 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4668 * Parse image options text and use it to make an image
4670 * @param $title Title
4671 * @param $options String
4672 * @param $holders LinkHolderArray
4673 * @return string HTML
4675 function makeImage( $title, $options, $holders = false ) {
4676 # Check if the options text is of the form "options|alt text"
4678 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4679 # * left no resizing, just left align. label is used for alt= only
4680 # * right same, but right aligned
4681 # * none same, but not aligned
4682 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4683 # * center center the image
4684 # * frame Keep original image size, no magnify-button.
4685 # * framed Same as "frame"
4686 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4687 # * upright reduce width for upright images, rounded to full __0 px
4688 # * border draw a 1px border around the image
4689 # * alt Text for HTML alt attribute (defaults to empty)
4690 # * link Set the target of the image link. Can be external, interwiki, or local
4691 # vertical-align values (no % or length right now):
4701 $parts = StringUtils
::explode( "|", $options );
4702 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4704 # Give extensions a chance to select the file revision for us
4705 $skip = $time = $sha1 = $descQuery = false;
4706 wfRunHooks( 'BeforeParserMakeImageLinkObj',
4707 array( &$this, &$title, &$skip, &$time, &$descQuery, &$sha1 ) );
4709 $this->mOutput
->addImage( $title->getDBkey(), null, null ); // register
4710 return $sk->link( $title );
4712 # Fetch and register the file (file title may be different via hooks)
4713 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4715 $handler = $file ?
$file->getHandler() : false;
4717 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4719 # Process the input parameters
4721 $params = array( 'frame' => array(), 'handler' => array(),
4722 'horizAlign' => array(), 'vertAlign' => array() );
4723 foreach ( $parts as $part ) {
4724 $part = trim( $part );
4725 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4727 if ( isset( $paramMap[$magicName] ) ) {
4728 list( $type, $paramName ) = $paramMap[$magicName];
4730 # Special case; width and height come in one variable together
4731 if ( $type === 'handler' && $paramName === 'width' ) {
4733 # (bug 13500) In both cases (width/height and width only),
4734 # permit trailing "px" for backward compatibility.
4735 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4736 $width = intval( $m[1] );
4737 $height = intval( $m[2] );
4738 if ( $handler->validateParam( 'width', $width ) ) {
4739 $params[$type]['width'] = $width;
4742 if ( $handler->validateParam( 'height', $height ) ) {
4743 $params[$type]['height'] = $height;
4746 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4747 $width = intval( $value );
4748 if ( $handler->validateParam( 'width', $width ) ) {
4749 $params[$type]['width'] = $width;
4752 } # else no validation -- bug 13436
4754 if ( $type === 'handler' ) {
4755 # Validate handler parameter
4756 $validated = $handler->validateParam( $paramName, $value );
4758 # Validate internal parameters
4759 switch( $paramName ) {
4762 # @todo Fixme: possibly check validity here for
4763 # manualthumb? downstream behavior seems odd with
4764 # missing manual thumbs.
4766 $value = $this->stripAltText( $value, $holders );
4769 $chars = self
::EXT_LINK_URL_CLASS
;
4770 $prots = $this->mUrlProtocols
;
4771 if ( $value === '' ) {
4772 $paramName = 'no-link';
4775 } elseif ( preg_match( "/^$prots/", $value ) ) {
4776 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4777 $paramName = 'link-url';
4778 $this->mOutput
->addExternalLink( $value );
4779 if ( $this->mOptions
->getExternalLinkTarget() ) {
4780 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4785 $linkTitle = Title
::newFromText( $value );
4787 $paramName = 'link-title';
4788 $value = $linkTitle;
4789 $this->mOutput
->addLink( $linkTitle );
4795 # Most other things appear to be empty or numeric...
4796 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4801 $params[$type][$paramName] = $value;
4805 if ( !$validated ) {
4810 # Process alignment parameters
4811 if ( $params['horizAlign'] ) {
4812 $params['frame']['align'] = key( $params['horizAlign'] );
4814 if ( $params['vertAlign'] ) {
4815 $params['frame']['valign'] = key( $params['vertAlign'] );
4818 $params['frame']['caption'] = $caption;
4820 # Will the image be presented in a frame, with the caption below?
4821 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4822 isset( $params['frame']['framed'] ) ||
4823 isset( $params['frame']['thumbnail'] ) ||
4824 isset( $params['frame']['manualthumb'] );
4826 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4827 # came to also set the caption, ordinary text after the image -- which
4828 # makes no sense, because that just repeats the text multiple times in
4829 # screen readers. It *also* came to set the title attribute.
4831 # Now that we have an alt attribute, we should not set the alt text to
4832 # equal the caption: that's worse than useless, it just repeats the
4833 # text. This is the framed/thumbnail case. If there's no caption, we
4834 # use the unnamed parameter for alt text as well, just for the time be-
4835 # ing, if the unnamed param is set and the alt param is not.
4837 # For the future, we need to figure out if we want to tweak this more,
4838 # e.g., introducing a title= parameter for the title; ignoring the un-
4839 # named parameter entirely for images without a caption; adding an ex-
4840 # plicit caption= parameter and preserving the old magic unnamed para-
4842 if ( $imageIsFramed ) { # Framed image
4843 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4844 # No caption or alt text, add the filename as the alt text so
4845 # that screen readers at least get some description of the image
4846 $params['frame']['alt'] = $title->getText();
4848 # Do not set $params['frame']['title'] because tooltips don't make sense
4850 } else { # Inline image
4851 if ( !isset( $params['frame']['alt'] ) ) {
4852 # No alt text, use the "caption" for the alt text
4853 if ( $caption !== '') {
4854 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4856 # No caption, fall back to using the filename for the
4858 $params['frame']['alt'] = $title->getText();
4861 # Use the "caption" for the tooltip text
4862 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4865 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4867 # Linker does the rest
4868 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'],
4869 $time, $descQuery, $this->mOptions
->getThumbSize() );
4871 # Give the handler a chance to modify the parser object
4873 $handler->parserTransformHook( $this, $file );
4879 protected function stripAltText( $caption, $holders ) {
4880 # Strip bad stuff out of the title (tooltip). We can't just use
4881 # replaceLinkHoldersText() here, because if this function is called
4882 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4884 $tooltip = $holders->replaceText( $caption );
4886 $tooltip = $this->replaceLinkHoldersText( $caption );
4889 # make sure there are no placeholders in thumbnail attributes
4890 # that are later expanded to html- so expand them now and
4892 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4893 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4899 * Set a flag in the output object indicating that the content is dynamic and
4900 * shouldn't be cached.
4902 function disableCache() {
4903 wfDebug( "Parser output marked as uncacheable.\n" );
4904 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4905 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4909 * Callback from the Sanitizer for expanding items found in HTML attribute
4910 * values, so they can be safely tested and escaped.
4912 * @param $text String
4913 * @param $frame PPFrame
4917 function attributeStripCallback( &$text, $frame = false ) {
4918 $text = $this->replaceVariables( $text, $frame );
4919 $text = $this->mStripState
->unstripBoth( $text );
4926 function getTags() {
4927 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4931 * Replace transparent tags in $text with the values given by the callbacks.
4933 * Transparent tag hooks are like regular XML-style tag hooks, except they
4934 * operate late in the transformation sequence, on HTML instead of wikitext.
4936 function replaceTransparentTags( $text ) {
4938 $elements = array_keys( $this->mTransparentTagHooks
);
4939 $text = $this->extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
4941 foreach ( $matches as $marker => $data ) {
4942 list( $element, $content, $params, $tag ) = $data;
4943 $tagName = strtolower( $element );
4944 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
4945 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
4949 $this->mStripState
->addGeneral( $marker, $output );
4955 * Break wikitext input into sections, and either pull or replace
4956 * some particular section's text.
4958 * External callers should use the getSection and replaceSection methods.
4960 * @param $text String: Page wikitext
4961 * @param $section String: a section identifier string of the form:
4962 * <flag1> - <flag2> - ... - <section number>
4964 * Currently the only recognised flag is "T", which means the target section number
4965 * was derived during a template inclusion parse, in other words this is a template
4966 * section edit link. If no flags are given, it was an ordinary section edit link.
4967 * This flag is required to avoid a section numbering mismatch when a section is
4968 * enclosed by <includeonly> (bug 6563).
4970 * The section number 0 pulls the text before the first heading; other numbers will
4971 * pull the given section along with its lower-level subsections. If the section is
4972 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4974 * @param $mode String: one of "get" or "replace"
4975 * @param $newText String: replacement text for section data.
4976 * @return String: for "get", the extracted section text.
4977 * for "replace", the whole page with the section replaced.
4979 private function extractSections( $text, $section, $mode, $newText='' ) {
4980 global $wgTitle; # not generally used but removes an ugly failure mode
4981 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4983 $frame = $this->getPreprocessor()->newFrame();
4985 # Process section extraction flags
4987 $sectionParts = explode( '-', $section );
4988 $sectionIndex = array_pop( $sectionParts );
4989 foreach ( $sectionParts as $part ) {
4990 if ( $part === 'T' ) {
4991 $flags |
= self
::PTD_FOR_INCLUSION
;
4994 # Preprocess the text
4995 $root = $this->preprocessToDom( $text, $flags );
4997 # <h> nodes indicate section breaks
4998 # They can only occur at the top level, so we can find them by iterating the root's children
4999 $node = $root->getFirstChild();
5001 # Find the target section
5002 if ( $sectionIndex == 0 ) {
5003 # Section zero doesn't nest, level=big
5004 $targetLevel = 1000;
5006 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5011 if ( $node->getName() === 'h' ) {
5012 $bits = $node->splitHeading();
5013 if ( $bits['i'] == $sectionIndex ) {
5014 $targetLevel = $bits['level'];
5018 if ( $mode === 'replace' ) {
5019 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5021 $node = $node->getNextSibling();
5027 if ( $mode === 'get' ) {
5034 # Find the end of the section, including nested sections
5036 if ( $node->getName() === 'h' ) {
5037 $bits = $node->splitHeading();
5038 $curLevel = $bits['level'];
5039 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5043 if ( $mode === 'get' ) {
5044 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5046 $node = $node->getNextSibling();
5049 # Write out the remainder (in replace mode only)
5050 if ( $mode === 'replace' ) {
5051 # Output the replacement text
5052 # Add two newlines on -- trailing whitespace in $newText is conventionally
5053 # stripped by the editor, so we need both newlines to restore the paragraph gap
5054 # Only add trailing whitespace if there is newText
5055 if ( $newText != "" ) {
5056 $outText .= $newText . "\n\n";
5060 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5061 $node = $node->getNextSibling();
5065 if ( is_string( $outText ) ) {
5066 # Re-insert stripped tags
5067 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5074 * This function returns the text of a section, specified by a number ($section).
5075 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5076 * the first section before any such heading (section 0).
5078 * If a section contains subsections, these are also returned.
5080 * @param $text String: text to look in
5081 * @param $section String: section identifier
5082 * @param $deftext String: default to return if section is not found
5083 * @return string text of the requested section
5085 public function getSection( $text, $section, $deftext='' ) {
5086 return $this->extractSections( $text, $section, "get", $deftext );
5090 * This function returns $oldtext after the content of the section
5091 * specified by $section has been replaced with $text.
5093 * @param $text String: former text of the article
5094 * @param $section Numeric: section identifier
5095 * @param $text String: replacing text
5096 * #return String: modified text
5098 public function replaceSection( $oldtext, $section, $text ) {
5099 return $this->extractSections( $oldtext, $section, "replace", $text );
5103 * Get the ID of the revision we are parsing
5105 * @return Mixed: integer or null
5107 function getRevisionId() {
5108 return $this->mRevisionId
;
5112 * Get the revision object for $this->mRevisionId
5114 * @return either a Revision object or null
5116 protected function getRevisionObject() {
5117 if ( !is_null( $this->mRevisionObject
) ) {
5118 return $this->mRevisionObject
;
5120 if ( is_null( $this->mRevisionId
) ) {
5124 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5125 return $this->mRevisionObject
;
5129 * Get the timestamp associated with the current revision, adjusted for
5130 * the default server-local timestamp
5132 function getRevisionTimestamp() {
5133 if ( is_null( $this->mRevisionTimestamp
) ) {
5134 wfProfileIn( __METHOD__
);
5136 $revObject = $this->getRevisionObject();
5137 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5139 if( $timestamp !== false ) {
5142 # The cryptic '' timezone parameter tells to use the site-default
5143 # timezone offset instead of the user settings.
5145 # Since this value will be saved into the parser cache, served
5146 # to other users, and potentially even used inside links and such,
5147 # it needs to be consistent for all visitors.
5148 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5151 wfProfileOut( __METHOD__
);
5153 return $this->mRevisionTimestamp
;
5157 * Get the name of the user that edited the last revision
5159 * @return String: user name
5161 function getRevisionUser() {
5162 if( is_null( $this->mRevisionUser
) ) {
5163 $revObject = $this->getRevisionObject();
5165 # if this template is subst: the revision id will be blank,
5166 # so just use the current user's name
5168 $this->mRevisionUser
= $revObject->getUserText();
5169 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5170 $this->mRevisionUser
= $this->getUser()->getName();
5173 return $this->mRevisionUser
;
5177 * Mutator for $mDefaultSort
5179 * @param $sort New value
5181 public function setDefaultSort( $sort ) {
5182 $this->mDefaultSort
= $sort;
5183 $this->mOutput
->setProperty( 'defaultsort', $sort );
5187 * Accessor for $mDefaultSort
5188 * Will use the empty string if none is set.
5190 * This value is treated as a prefix, so the
5191 * empty string is equivalent to sorting by
5196 public function getDefaultSort() {
5197 if ( $this->mDefaultSort
!== false ) {
5198 return $this->mDefaultSort
;
5205 * Accessor for $mDefaultSort
5206 * Unlike getDefaultSort(), will return false if none is set
5208 * @return string or false
5210 public function getCustomDefaultSort() {
5211 return $this->mDefaultSort
;
5215 * Try to guess the section anchor name based on a wikitext fragment
5216 * presumably extracted from a heading, for example "Header" from
5219 public function guessSectionNameFromWikiText( $text ) {
5220 # Strip out wikitext links(they break the anchor)
5221 $text = $this->stripSectionName( $text );
5222 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5223 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5227 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5228 * instead. For use in redirects, since IE6 interprets Redirect: headers
5229 * as something other than UTF-8 (apparently?), resulting in breakage.
5231 * @param $text String: The section name
5232 * @return string An anchor
5234 public function guessLegacySectionNameFromWikiText( $text ) {
5235 # Strip out wikitext links(they break the anchor)
5236 $text = $this->stripSectionName( $text );
5237 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5238 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5242 * Strips a text string of wikitext for use in a section anchor
5244 * Accepts a text string and then removes all wikitext from the
5245 * string and leaves only the resultant text (i.e. the result of
5246 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5247 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5248 * to create valid section anchors by mimicing the output of the
5249 * parser when headings are parsed.
5251 * @param $text String: text string to be stripped of wikitext
5252 * for use in a Section anchor
5253 * @return Filtered text string
5255 public function stripSectionName( $text ) {
5256 # Strip internal link markup
5257 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5258 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5260 # Strip external link markup (FIXME: Not Tolerant to blank link text
5261 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5262 # on how many empty links there are on the page - need to figure that out.
5263 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5265 # Parse wikitext quotes (italics & bold)
5266 $text = $this->doQuotes( $text );
5269 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5274 * strip/replaceVariables/unstrip for preprocessor regression testing
5276 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5277 if ( !$title instanceof Title
) {
5278 $title = Title
::newFromText( $title );
5280 $this->startParse( $title, $options, $outputType, true );
5282 $text = $this->replaceVariables( $text );
5283 $text = $this->mStripState
->unstripBoth( $text );
5284 $text = Sanitizer
::removeHTMLtags( $text );
5288 function testPst( $text, $title, $options ) {
5290 if ( !$title instanceof Title
) {
5291 $title = Title
::newFromText( $title );
5293 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5296 function testPreprocess( $text, $title, $options ) {
5297 if ( !$title instanceof Title
) {
5298 $title = Title
::newFromText( $title );
5300 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5304 * Call a callback function on all regions of the given text that are not
5305 * inside strip markers, and replace those regions with the return value
5306 * of the callback. For example, with input:
5310 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5311 * two strings will be replaced with the value returned by the callback in
5314 function markerSkipCallback( $s, $callback ) {
5317 while ( $i < strlen( $s ) ) {
5318 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5319 if ( $markerStart === false ) {
5320 $out .= call_user_func( $callback, substr( $s, $i ) );
5323 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5324 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5325 if ( $markerEnd === false ) {
5326 $out .= substr( $s, $markerStart );
5329 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5330 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5339 * Save the parser state required to convert the given half-parsed text to
5340 * HTML. "Half-parsed" in this context means the output of
5341 * recursiveTagParse() or internalParse(). This output has strip markers
5342 * from replaceVariables (extensionSubstitution() etc.), and link
5343 * placeholders from replaceLinkHolders().
5345 * Returns an array which can be serialized and stored persistently. This
5346 * array can later be loaded into another parser instance with
5347 * unserializeHalfParsedText(). The text can then be safely incorporated into
5348 * the return value of a parser hook.
5350 function serializeHalfParsedText( $text ) {
5351 wfProfileIn( __METHOD__
);
5354 'version' => self
::HALF_PARSED_VERSION
,
5355 'stripState' => $this->mStripState
->getSubState( $text ),
5356 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5358 wfProfileOut( __METHOD__
);
5363 * Load the parser state given in the $data array, which is assumed to
5364 * have been generated by serializeHalfParsedText(). The text contents is
5365 * extracted from the array, and its markers are transformed into markers
5366 * appropriate for the current Parser instance. This transformed text is
5367 * returned, and can be safely included in the return value of a parser
5370 * If the $data array has been stored persistently, the caller should first
5371 * check whether it is still valid, by calling isValidHalfParsedText().
5373 * @param $data Serialized data
5376 function unserializeHalfParsedText( $data ) {
5377 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5378 throw new MWException( __METHOD__
.': invalid version' );
5381 # First, extract the strip state.
5382 $texts = array( $data['text'] );
5383 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5385 # Now renumber links
5386 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5388 # Should be good to go.
5393 * Returns true if the given array, presumed to be generated by
5394 * serializeHalfParsedText(), is compatible with the current version of the
5397 * @param $data Array.
5399 function isValidHalfParsedText( $data ) {
5400 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;