3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
40 * $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.5';
59 * Update this version number when the output of serialiseHalfParsedText()
60 * changes in an incompatible way
62 const HALF_PARSED_VERSION
= 2;
64 # Flags for Parser::setFunctionHook
65 # Also available as global constants from Defines.php
66 const SFH_NO_HASH
= 1;
67 const SFH_OBJECT_ARGS
= 2;
69 # Constants needed for external link processing
70 # Everything except bracket, space, or control characters
71 const EXT_LINK_URL_CLASS
= '(?:[^\]\[<>"\\x00-\\x20\\x7F]|(?:\[\]))';
72 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
73 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
75 # State constants for the definition list colon extraction
76 const COLON_STATE_TEXT
= 0;
77 const COLON_STATE_TAG
= 1;
78 const COLON_STATE_TAGSTART
= 2;
79 const COLON_STATE_CLOSETAG
= 3;
80 const COLON_STATE_TAGSLASH
= 4;
81 const COLON_STATE_COMMENT
= 5;
82 const COLON_STATE_COMMENTDASH
= 6;
83 const COLON_STATE_COMMENTDASHDASH
= 7;
85 # Flags for preprocessToDom
86 const PTD_FOR_INCLUSION
= 1;
88 # Allowed values for $this->mOutputType
89 # Parameter to startExternalParse().
90 const OT_HTML
= 1; # like parse()
91 const OT_WIKI
= 2; # like preSaveTransform()
92 const OT_PREPROCESS
= 3; # like preprocess()
94 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
96 # Marker Suffix needs to be accessible staticly.
97 const MARKER_SUFFIX
= "-QINU\x7f";
100 var $mTagHooks = array();
101 var $mTransparentTagHooks = array();
102 var $mFunctionHooks = array();
103 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
104 var $mFunctionTagHooks = array();
105 var $mStripList = array();
106 var $mDefaultStripList = array();
107 var $mVarCache = array();
108 var $mImageParams = array();
109 var $mImageParamsMagicArray = array();
110 var $mMarkerIndex = 0;
111 var $mFirstCall = true;
112 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
113 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
115 # Cleared with clearState():
120 var $mAutonumber, $mDTopen;
127 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
128 var $mLinkHolders, $mLinkID;
129 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
130 var $mTplExpandCache; # empty-frame expansion cache
131 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
132 var $mExpensiveFunctionCount; # number of expensive parser function calls
137 var $mUser; # User object; only used when doing pre-save transform
140 # These are variables reset at least once per parse regardless of $clearState
150 var $mTitle; # Title context, used for self-link rendering and similar things
151 var $mOutputType; # Output type, one of the OT_xxx constants
152 var $ot; # Shortcut alias, see setOutputType()
153 var $mRevisionObject; # The revision object of the specified revision ID
154 var $mRevisionId; # ID to display in {{REVISIONID}} tags
155 var $mRevisionTimestamp; # The timestamp of the specified revision ID
156 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
157 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
162 public function __construct( $conf = array() ) {
163 $this->mConf
= $conf;
164 $this->mUrlProtocols
= wfUrlProtocols();
165 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
166 '(?:[^\]\[<>"\x00-\x20\x7F]|\[\])+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
167 if ( isset( $conf['preprocessorClass'] ) ) {
168 $this->mPreprocessorClass
= $conf['preprocessorClass'];
169 } elseif ( extension_loaded( 'domxml' ) ) {
170 # PECL extension that conflicts with the core DOM extension (bug 13770)
171 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
172 $this->mPreprocessorClass
= 'Preprocessor_Hash';
173 } elseif ( extension_loaded( 'dom' ) ) {
174 $this->mPreprocessorClass
= 'Preprocessor_DOM';
176 $this->mPreprocessorClass
= 'Preprocessor_Hash';
181 * Reduce memory usage to reduce the impact of circular references
183 function __destruct() {
184 if ( isset( $this->mLinkHolders
) ) {
185 unset( $this->mLinkHolders
);
187 foreach ( $this as $name => $value ) {
188 unset( $this->$name );
193 * Do various kinds of initialisation on the first call of the parser
195 function firstCallInit() {
196 if ( !$this->mFirstCall
) {
199 $this->mFirstCall
= false;
201 wfProfileIn( __METHOD__
);
203 CoreParserFunctions
::register( $this );
204 CoreTagHooks
::register( $this );
205 $this->initialiseVariables();
207 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
208 wfProfileOut( __METHOD__
);
216 function clearState() {
217 wfProfileIn( __METHOD__
);
218 if ( $this->mFirstCall
) {
219 $this->firstCallInit();
221 $this->mOutput
= new ParserOutput
;
222 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
223 $this->mAutonumber
= 0;
224 $this->mLastSection
= '';
225 $this->mDTopen
= false;
226 $this->mIncludeCount
= array();
227 $this->mArgStack
= false;
228 $this->mInPre
= false;
229 $this->mLinkHolders
= new LinkHolderArray( $this );
231 $this->mRevisionObject
= $this->mRevisionTimestamp
=
232 $this->mRevisionId
= $this->mRevisionUser
= null;
233 $this->mVarCache
= array();
237 * Prefix for temporary replacement strings for the multipass parser.
238 * \x07 should never appear in input as it's disallowed in XML.
239 * Using it at the front also gives us a little extra robustness
240 * since it shouldn't match when butted up against identifier-like
243 * Must not consist of all title characters, or else it will change
244 * the behaviour of <nowiki> in a link.
246 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
247 # Changed to \x7f to allow XML double-parsing -- TS
248 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
249 $this->mStripState
= new StripState( $this->mUniqPrefix
);
252 # Clear these on every parse, bug 4549
253 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
255 $this->mShowToc
= true;
256 $this->mForceTocPosition
= false;
257 $this->mIncludeSizes
= array(
261 $this->mPPNodeCount
= 0;
262 $this->mDefaultSort
= false;
263 $this->mHeadings
= array();
264 $this->mDoubleUnderscores
= array();
265 $this->mExpensiveFunctionCount
= 0;
268 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
269 $this->mPreprocessor
= null;
272 wfRunHooks( 'ParserClearState', array( &$this ) );
273 wfProfileOut( __METHOD__
);
277 * Convert wikitext to HTML
278 * Do not call this function recursively.
280 * @param $text String: text we want to parse
281 * @param $title Title object
282 * @param $options ParserOptions
283 * @param $linestart boolean
284 * @param $clearState boolean
285 * @param $revid Int: number to pass in {{REVISIONID}}
286 * @return ParserOutput a ParserOutput
288 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
290 * First pass--just handle <nowiki> sections, pass the rest off
291 * to internalParse() which does all the real work.
294 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
295 $fname = __METHOD__
.'-' . wfGetCaller();
296 wfProfileIn( __METHOD__
);
297 wfProfileIn( $fname );
299 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
301 $oldRevisionId = $this->mRevisionId
;
302 $oldRevisionObject = $this->mRevisionObject
;
303 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
304 $oldRevisionUser = $this->mRevisionUser
;
305 if ( $revid !== null ) {
306 $this->mRevisionId
= $revid;
307 $this->mRevisionObject
= null;
308 $this->mRevisionTimestamp
= null;
309 $this->mRevisionUser
= null;
312 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
314 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
315 $text = $this->internalParse( $text );
317 $text = $this->mStripState
->unstripGeneral( $text );
319 # Clean up special characters, only run once, next-to-last before doBlockLevels
321 # french spaces, last one Guillemet-left
322 # only if there is something before the space
323 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
324 # french spaces, Guillemet-right
325 '/(\\302\\253) /' => '\\1 ',
326 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
328 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
330 $text = $this->doBlockLevels( $text, $linestart );
332 $this->replaceLinkHolders( $text );
335 * The page doesn't get language converted if
337 * b) Content isn't converted
338 * c) It's a conversion table
340 if ( !( $wgDisableLangConversion
341 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
342 ||
$this->mTitle
->isConversionTable() ) ) {
344 # The position of the convert() call should not be changed. it
345 # assumes that the links are all replaced and the only thing left
346 # is the <nowiki> mark.
348 $text = $wgContLang->convert( $text );
352 * A converted title will be provided in the output object if title and
353 * content conversion are enabled, the article text does not contain
354 * a conversion-suppressing double-underscore tag, and no
355 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
356 * automatic link conversion.
358 if ( !( $wgDisableLangConversion
359 ||
$wgDisableTitleConversion
360 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
361 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
362 ||
$this->mOutput
->getDisplayTitle() !== false ) )
364 $convruletitle = $wgContLang->getConvRuleTitle();
365 if ( $convruletitle ) {
366 $this->mOutput
->setTitleText( $convruletitle );
368 $titleText = $wgContLang->convertTitle( $title );
369 $this->mOutput
->setTitleText( $titleText );
373 $text = $this->mStripState
->unstripNoWiki( $text );
375 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
377 $text = $this->replaceTransparentTags( $text );
378 $text = $this->mStripState
->unstripGeneral( $text );
380 $text = Sanitizer
::normalizeCharReferences( $text );
382 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
383 $text = MWTidy
::tidy( $text );
385 # attempt to sanitize at least some nesting problems
386 # (bug #2702 and quite a few others)
388 # ''Something [http://www.cool.com cool''] -->
389 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
390 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
391 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
392 # fix up an anchor inside another anchor, only
393 # at least for a single single nested link (bug 3695)
394 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
395 '\\1\\2</a>\\3</a>\\1\\4</a>',
396 # fix div inside inline elements- doBlockLevels won't wrap a line which
397 # contains a div, so fix it up here; replace
398 # div with escaped text
399 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
400 '\\1\\3<div\\5>\\6</div>\\8\\9',
401 # remove empty italic or bold tag pairs, some
402 # introduced by rules above
403 '/<([bi])><\/\\1>/' => '',
406 $text = preg_replace(
407 array_keys( $tidyregs ),
408 array_values( $tidyregs ),
411 global $wgExpensiveParserFunctionLimit;
412 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
413 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
416 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
418 # Information on include size limits, for the benefit of users who try to skirt them
419 if ( $this->mOptions
->getEnableLimitReport() ) {
420 $max = $this->mOptions
->getMaxIncludeSize();
421 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
423 "NewPP limit report\n" .
424 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
425 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
426 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
428 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
429 $text .= "\n<!-- \n$limitReport-->\n";
431 $this->mOutput
->setText( $text );
433 $this->mRevisionId
= $oldRevisionId;
434 $this->mRevisionObject
= $oldRevisionObject;
435 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
436 $this->mRevisionUser
= $oldRevisionUser;
437 wfProfileOut( $fname );
438 wfProfileOut( __METHOD__
);
440 return $this->mOutput
;
444 * Recursive parser entry point that can be called from an extension tag
447 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
449 * @param $text String: text extension wants to have parsed
450 * @param $frame PPFrame: The frame to use for expanding any template variables
452 function recursiveTagParse( $text, $frame=false ) {
453 wfProfileIn( __METHOD__
);
454 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
455 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
456 $text = $this->internalParse( $text, false, $frame );
457 wfProfileOut( __METHOD__
);
462 * Expand templates and variables in the text, producing valid, static wikitext.
463 * Also removes comments.
465 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
466 wfProfileIn( __METHOD__
);
467 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
468 if ( $revid !== null ) {
469 $this->mRevisionId
= $revid;
471 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
472 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
473 $text = $this->replaceVariables( $text );
474 $text = $this->mStripState
->unstripBoth( $text );
475 wfProfileOut( __METHOD__
);
480 * Process the wikitext for the ?preload= feature. (bug 5210)
482 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
483 * comments, templates, arguments, tags hooks and parser functions are untouched.
485 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
486 # Parser (re)initialisation
487 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
489 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
490 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
491 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
492 $text = $this->mStripState
->unstripBoth( $text );
497 * Get a random string
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
686 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
691 $taglist = implode( '|', $elements );
692 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
694 while ( $text != '' ) {
695 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
697 if ( count( $p ) < 5 ) {
700 if ( count( $p ) > 5 ) {
714 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
715 $stripped .= $marker;
717 if ( $close === '/>' ) {
718 # Empty element tag, <tag />
723 if ( $element === '!--' ) {
726 $end = "/(<\\/$element\\s*>)/i";
728 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
730 if ( count( $q ) < 3 ) {
731 # No end tag -- let it run out to the end of the text.
740 $matches[$marker] = array( $element,
742 Sanitizer
::decodeTagAttributes( $attributes ),
743 "<$element$attributes$close$content$tail" );
749 * Get a list of strippable XML-like elements
751 function getStripList() {
752 return $this->mStripList
;
756 * @deprecated use replaceVariables
758 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
763 * Restores pre, math, and other extensions removed by strip()
765 * always call unstripNoWiki() after this one
767 * @deprecated use $this->mStripState->unstrip()
769 function unstrip( $text, $state ) {
770 return $state->unstripGeneral( $text );
774 * Always call this after unstrip() to preserve the order
777 * @deprecated use $this->mStripState->unstrip()
779 function unstripNoWiki( $text, $state ) {
780 return $state->unstripNoWiki( $text );
784 * @deprecated use $this->mStripState->unstripBoth()
786 function unstripForHTML( $text ) {
787 return $this->mStripState
->unstripBoth( $text );
791 * Add an item to the strip state
792 * Returns the unique tag which must be inserted into the stripped text
793 * The tag will be replaced with the original text in unstrip()
797 function insertStripItem( $text ) {
798 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
799 $this->mMarkerIndex++
;
800 $this->mStripState
->addGeneral( $rnd, $text );
805 * Interface with html tidy
806 * @deprecated Use MWTidy::tidy()
808 public static function tidy( $text ) {
809 wfDeprecated( __METHOD__
);
810 return MWTidy
::tidy( $text );
814 * parse the wiki syntax used to render tables
818 function doTableStuff( $text ) {
819 wfProfileIn( __METHOD__
);
821 $lines = StringUtils
::explode( "\n", $text );
825 foreach ( $lines as $outLine ) {
826 $line = trim( $outLine );
828 # empty line, go to next line,
829 # but only append \n if outside of table
831 $output .= $outLine . "\n";
834 $firstChars = $line[0];
835 if ( strlen( $line ) > 1 ) {
836 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
840 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
842 $table =& $this->last( $tables );
843 $table[0] = array(); // first row
844 $currentRow =& $table[0];
845 $table['indent'] = strlen( $matches[1] );
847 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
848 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
850 if ( $attributes !== '' ) {
851 $table['attributes'] = $attributes;
853 } else if ( !isset( $tables[0] ) ) {
854 // we're outside the table
856 $out .= $outLine . "\n";
857 } else if ( $firstChars === '|}' ) {
858 // trim the |} code from the line
859 $line = substr ( $line , 2 );
861 // Shorthand for last row
862 $lastRow =& $this->last( $table );
864 // a thead at the end becomes a tfoot, unless there is only one row
865 // Do this before deleting empty last lines to allow headers at the bottom of tables
866 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
867 $lastRow['type'] = 'tfoot';
868 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
869 $lastRow[$i]['type'] = 'th';
873 // Delete empty last lines
874 if ( empty( $lastRow ) ) {
878 $curtable = array_pop( $tables );
880 #Add a line-ending before the table, but only if there isn't one already
881 if ( substr( $out, -1 ) !== "\n" ) {
884 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
886 if ( count( $tables ) > 0 ) {
887 $table =& $this->last( $tables );
888 $currentRow =& $this->last( $table );
889 $currentElement =& $this->last( $currentRow );
891 $output =& $currentElement['content'];
898 } else if ( $firstChars === '|-' ) {
899 // start a new row element
900 // but only when we haven't started one already
901 if ( count( $currentRow ) != 0 ) {
903 $currentRow =& $this->last( $table );
905 // Get the attributes, there's nothing else useful in $line now
906 $line = substr ( $line , 2 );
907 $attributes = $this->mStripState
->unstripBoth( $line );
908 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
909 if ( $attributes !== '' ) {
910 $currentRow['attributes'] = $attributes;
913 } else if ( $firstChars === '|+' ) {
914 // a table caption, but only proceed if there isn't one already
915 if ( !isset ( $table['caption'] ) ) {
916 $line = substr ( $line , 2 );
918 $c = $this->getCellAttr( $line , 'caption' );
919 $table['caption'] = array();
920 $table['caption']['content'] = $c[0];
921 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
923 $output =& $table['caption']['content'];
925 } else if ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
926 // Which kind of cells are we dealing with
928 $line = substr ( $line , 1 );
930 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
931 $line = str_replace ( '!!' , '||' , $line );
935 // Split up multiple cells on the same line.
936 $cells = StringUtils
::explodeMarkup( '||' , $line );
937 $line = ''; // save memory
939 // decide whether thead to tbody
940 if ( !array_key_exists( 'type', $currentRow ) ) {
941 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
942 } else if ( $firstChars === '|' ) {
943 $currentRow['type'] = 'tbody';
946 // Loop through each table cell
947 foreach ( $cells as $cell ) {
949 $currentRow[] = array();
950 $currentElement =& $this->last( $currentRow );
952 $currentElement['type'] = $currentTag;
954 $c = $this->getCellAttr( $cell , $currentTag );
955 $currentElement['content'] = $c[0];
956 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
959 $output =& $currentElement['content'];
962 $output .= "\n$outLine";
966 # Remove trailing line-ending (b/c)
967 if ( substr( $out, -1 ) === "\n" ) {
968 $out = substr( $out, 0, -1 );
971 # Close any unclosed tables
972 if ( isset( $tables ) && count( $tables ) > 0 ) {
973 for ( $i = 0; $i < count( $tables ); $i++
) {
974 $curtable = array_pop( $tables );
975 $curtable = $this->generateTableHTML( $curtable );
976 #Add a line-ending before the table, but only if there isn't one already
977 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
984 wfProfileOut( __METHOD__
);
990 * Helper function for doTableStuff() separating the contents of cells from
991 * attributes. Particularly useful as there's a possible bug and this action
996 function getCellAttr ( $cell, $tagName ) {
1000 $cell = trim ( $cell );
1002 // A cell could contain both parameters and data
1003 $cellData = explode ( '|' , $cell , 2 );
1005 // Bug 553: Note that a '|' inside an invalid link should not
1006 // be mistaken as delimiting cell parameters
1007 if ( strpos( $cellData[0], '[[' ) !== false ) {
1008 $content = trim ( $cell );
1010 else if ( count ( $cellData ) == 1 ) {
1011 $content = trim ( $cellData[0] );
1014 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
1015 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
1017 $content = trim ( $cellData[1] );
1019 return array( $content, $attributes );
1024 * Helper function for doTableStuff(). This converts the structured array into html.
1028 function generateTableHTML ( &$table ) {
1030 $return .= str_repeat( '<dl><dd>' , $table['indent'] );
1031 $return .= '<table';
1032 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1034 unset( $table['attributes'] );
1036 if ( isset( $table['caption'] ) ) {
1037 $return .= "\n<caption";
1038 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1040 $return .= $table['caption']['content'];
1041 $return .= "\n</caption>";
1047 // If we only have tbodies, mark table as simple
1048 for ( $i = 0; isset( $table[$i] ); $i++
) {
1049 if ( !count( $table[$i] ) ) continue;
1050 if ( !isset( $table[$i]['type'] ) ) $table[$i]['type'] = 'tbody';
1051 if ( !$lastSection ) {
1052 $lastSection = $table[$i]['type'];
1053 } else if ( $lastSection != $table[$i]['type'] ) {
1059 for ( $i = 0; isset( $table[$i] ); $i++
) {
1060 // Check for empty tables
1061 if ( count( $table[$i] ) ) {
1066 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1067 $return .= "\n<" . $table[$i]['type'] . '>';
1071 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1073 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1074 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1075 $return .= "\n<" . $table[$i][$j]['type'];
1076 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1079 $return .= $table[$i][$j]['content'];
1080 if ( $table[$i][$j]['content'] != '' )
1083 $return .= '</' . $table[$i][$j]['type'] . '>';
1084 unset( $table[$i][$j] );
1086 $return .= "\n</tr>";
1088 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && ( $table[$i]['type'] != $table[$i +
1]['type'] ) ) ) {
1089 $return .= '</' . $table[$i]['type'] . '>';
1091 $lastSection = $table[$i]['type'];
1092 unset( $table[$i] );
1095 if ( isset( $table['caption'] ) ) {
1096 $return .= "\n<tr><td></td></tr>";
1101 $return .= "\n</table>";
1102 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1108 * like end() but only works on the numeric array index and php's internal pointers
1109 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1110 * ignores associative elements and will create a 0 key will a NULL value if there were
1111 * no numric elements and an array itself if not previously defined.
1115 function &last ( &$arr ) {
1116 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1121 * Helper function for parse() that transforms wiki markup into
1122 * HTML. Only called for $mOutputType == self::OT_HTML.
1126 function internalParse( $text, $isMain = true, $frame=false ) {
1127 wfProfileIn( __METHOD__
);
1131 # Hook to suspend the parser in this state
1132 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1133 wfProfileOut( __METHOD__
);
1137 # if $frame is provided, then use $frame for replacing any variables
1139 # use frame depth to infer how include/noinclude tags should be handled
1140 # depth=0 means this is the top-level document; otherwise it's an included document
1141 if ( !$frame->depth
) {
1144 $flag = Parser
::PTD_FOR_INCLUSION
;
1146 $dom = $this->preprocessToDom( $text, $flag );
1147 $text = $frame->expand( $dom );
1149 # if $frame is not provided, then use old-style replaceVariables
1150 $text = $this->replaceVariables( $text );
1153 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1154 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1156 # Tables need to come after variable replacement for things to work
1157 # properly; putting them before other transformations should keep
1158 # exciting things like link expansions from showing up in surprising
1160 $text = $this->doTableStuff( $text );
1162 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1164 $text = $this->doDoubleUnderscore( $text );
1166 $text = $this->doHeadings( $text );
1167 if ( $this->mOptions
->getUseDynamicDates() ) {
1168 $df = DateFormatter
::getInstance();
1169 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1171 $text = $this->replaceInternalLinks( $text );
1172 $text = $this->doAllQuotes( $text );
1173 $text = $this->replaceExternalLinks( $text );
1175 # replaceInternalLinks may sometimes leave behind
1176 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1177 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1179 $text = $this->doMagicLinks( $text );
1180 $text = $this->formatHeadings( $text, $origText, $isMain );
1182 wfProfileOut( __METHOD__
);
1187 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1188 * magic external links.
1193 function doMagicLinks( $text ) {
1194 wfProfileIn( __METHOD__
);
1195 $prots = $this->mUrlProtocols
;
1196 $urlChar = self
::EXT_LINK_URL_CLASS
;
1197 $text = preg_replace_callback(
1199 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1200 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1201 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1202 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1203 ISBN\s+(\b # m[5]: ISBN, capture number
1204 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1205 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1206 [0-9Xx] # check digit
1208 )!x', array( &$this, 'magicLinkCallback' ), $text );
1209 wfProfileOut( __METHOD__
);
1213 function magicLinkCallback( $m ) {
1214 if ( isset( $m[1] ) && $m[1] !== '' ) {
1217 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1220 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1221 # Free external link
1222 return $this->makeFreeExternalLink( $m[0] );
1223 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1225 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1228 $CssClass = 'mw-magiclink-rfc';
1230 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1232 $urlmsg = 'pubmedurl';
1233 $CssClass = 'mw-magiclink-pmid';
1236 throw new MWException( __METHOD__
.': unrecognised match type "' .
1237 substr( $m[0], 0, 20 ) . '"' );
1239 $url = wfMsgForContent( $urlmsg, $id );
1240 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1241 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1244 $num = strtr( $isbn, array(
1249 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1251 $titleObj->escapeLocalUrl() .
1252 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1259 * Make a free external link, given a user-supplied URL
1263 function makeFreeExternalLink( $url ) {
1265 wfProfileIn( __METHOD__
);
1269 # The characters '<' and '>' (which were escaped by
1270 # removeHTMLtags()) should not be included in
1271 # URLs, per RFC 2396.
1273 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1274 $trail = substr( $url, $m2[0][1] ) . $trail;
1275 $url = substr( $url, 0, $m2[0][1] );
1278 # Move trailing punctuation to $trail
1280 # If there is no left bracket, then consider right brackets fair game too
1281 if ( strpos( $url, '(' ) === false ) {
1285 $numSepChars = strspn( strrev( $url ), $sep );
1286 if ( $numSepChars ) {
1287 $trail = substr( $url, -$numSepChars ) . $trail;
1288 $url = substr( $url, 0, -$numSepChars );
1291 $url = Sanitizer
::cleanUrl( $url );
1293 # Is this an external image?
1294 $text = $this->maybeMakeExternalImage( $url );
1295 if ( $text === false ) {
1296 # Not an image, make a link
1297 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1298 $this->getExternalLinkAttribs( $url ) );
1299 # Register it in the output object...
1300 # Replace unnecessary URL escape codes with their equivalent characters
1301 $pasteurized = self
::replaceUnusualEscapes( $url );
1302 $this->mOutput
->addExternalLink( $pasteurized );
1304 wfProfileOut( __METHOD__
);
1305 return $text . $trail;
1310 * Parse headers and return html
1314 function doHeadings( $text ) {
1315 wfProfileIn( __METHOD__
);
1316 for ( $i = 6; $i >= 1; --$i ) {
1317 $h = str_repeat( '=', $i );
1318 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1319 "<h$i>\\1</h$i>", $text );
1321 wfProfileOut( __METHOD__
);
1326 * Replace single quotes with HTML markup
1328 * @return string the altered text
1330 function doAllQuotes( $text ) {
1331 wfProfileIn( __METHOD__
);
1333 $lines = StringUtils
::explode( "\n", $text );
1334 foreach ( $lines as $line ) {
1335 $outtext .= $this->doQuotes( $line ) . "\n";
1337 $outtext = substr( $outtext, 0,-1 );
1338 wfProfileOut( __METHOD__
);
1343 * Helper function for doAllQuotes()
1345 public function doQuotes( $text ) {
1346 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1347 if ( count( $arr ) == 1 ) {
1350 # First, do some preliminary work. This may shift some apostrophes from
1351 # being mark-up to being text. It also counts the number of occurrences
1352 # of bold and italics mark-ups.
1355 for ( $i = 0; $i < count( $arr ); $i++
) {
1356 if ( ( $i %
2 ) == 1 ) {
1357 # If there are ever four apostrophes, assume the first is supposed to
1358 # be text, and the remaining three constitute mark-up for bold text.
1359 if ( strlen( $arr[$i] ) == 4 ) {
1362 } elseif ( strlen( $arr[$i] ) > 5 ) {
1363 # If there are more than 5 apostrophes in a row, assume they're all
1364 # text except for the last 5.
1365 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1368 # Count the number of occurrences of bold and italics mark-ups.
1369 # We are not counting sequences of five apostrophes.
1370 if ( strlen( $arr[$i] ) == 2 ) {
1372 } elseif ( strlen( $arr[$i] ) == 3 ) {
1374 } elseif ( strlen( $arr[$i] ) == 5 ) {
1381 # If there is an odd number of both bold and italics, it is likely
1382 # that one of the bold ones was meant to be an apostrophe followed
1383 # by italics. Which one we cannot know for certain, but it is more
1384 # likely to be one that has a single-letter word before it.
1385 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1387 $firstsingleletterword = -1;
1388 $firstmultiletterword = -1;
1390 foreach ( $arr as $r ) {
1391 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1392 $x1 = substr( $arr[$i-1], -1 );
1393 $x2 = substr( $arr[$i-1], -2, 1 );
1394 if ( $x1 === ' ' ) {
1395 if ( $firstspace == -1 ) {
1398 } elseif ( $x2 === ' ') {
1399 if ( $firstsingleletterword == -1 ) {
1400 $firstsingleletterword = $i;
1403 if ( $firstmultiletterword == -1 ) {
1404 $firstmultiletterword = $i;
1411 # If there is a single-letter word, use it!
1412 if ( $firstsingleletterword > -1 ) {
1413 $arr[$firstsingleletterword] = "''";
1414 $arr[$firstsingleletterword-1] .= "'";
1415 } elseif ( $firstmultiletterword > -1 ) {
1416 # If not, but there's a multi-letter word, use that one.
1417 $arr[$firstmultiletterword] = "''";
1418 $arr[$firstmultiletterword-1] .= "'";
1419 } elseif ( $firstspace > -1 ) {
1420 # ... otherwise use the first one that has neither.
1421 # (notice that it is possible for all three to be -1 if, for example,
1422 # there is only one pentuple-apostrophe in the line)
1423 $arr[$firstspace] = "''";
1424 $arr[$firstspace-1] .= "'";
1428 # Now let's actually convert our apostrophic mush to HTML!
1433 foreach ( $arr as $r ) {
1434 if ( ( $i %
2 ) == 0 ) {
1435 if ( $state === 'both' ) {
1441 if ( strlen( $r ) == 2 ) {
1442 if ( $state === 'i' ) {
1443 $output .= '</i>'; $state = '';
1444 } elseif ( $state === 'bi' ) {
1445 $output .= '</i>'; $state = 'b';
1446 } elseif ( $state === 'ib' ) {
1447 $output .= '</b></i><b>'; $state = 'b';
1448 } elseif ( $state === 'both' ) {
1449 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1450 } else { # $state can be 'b' or ''
1451 $output .= '<i>'; $state .= 'i';
1453 } elseif ( strlen( $r ) == 3 ) {
1454 if ( $state === 'b' ) {
1455 $output .= '</b>'; $state = '';
1456 } elseif ( $state === 'bi' ) {
1457 $output .= '</i></b><i>'; $state = 'i';
1458 } elseif ( $state === 'ib' ) {
1459 $output .= '</b>'; $state = 'i';
1460 } elseif ( $state === 'both' ) {
1461 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1462 } else { # $state can be 'i' or ''
1463 $output .= '<b>'; $state .= 'b';
1465 } elseif ( strlen( $r ) == 5 ) {
1466 if ( $state === 'b' ) {
1467 $output .= '</b><i>'; $state = 'i';
1468 } elseif ( $state === 'i' ) {
1469 $output .= '</i><b>'; $state = 'b';
1470 } elseif ( $state === 'bi' ) {
1471 $output .= '</i></b>'; $state = '';
1472 } elseif ( $state === 'ib' ) {
1473 $output .= '</b></i>'; $state = '';
1474 } elseif ( $state === 'both' ) {
1475 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1476 } else { # ($state == '')
1477 $buffer = ''; $state = 'both';
1483 # Now close all remaining tags. Notice that the order is important.
1484 if ( $state === 'b' ||
$state === 'ib' ) {
1487 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1490 if ( $state === 'bi' ) {
1493 # There might be lonely ''''', so make sure we have a buffer
1494 if ( $state === 'both' && $buffer ) {
1495 $output .= '<b><i>'.$buffer.'</i></b>';
1502 * Replace external links (REL)
1504 * Note: this is all very hackish and the order of execution matters a lot.
1505 * Make sure to run maintenance/parserTests.php if you change this code.
1509 function replaceExternalLinks( $text ) {
1511 wfProfileIn( __METHOD__
);
1513 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1514 $s = array_shift( $bits );
1517 while ( $i<count( $bits ) ) {
1519 $protocol = $bits[$i++
];
1520 $text = $bits[$i++
];
1521 $trail = $bits[$i++
];
1523 # The characters '<' and '>' (which were escaped by
1524 # removeHTMLtags()) should not be included in
1525 # URLs, per RFC 2396.
1527 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1528 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1529 $url = substr( $url, 0, $m2[0][1] );
1532 # If the link text is an image URL, replace it with an <img> tag
1533 # This happened by accident in the original parser, but some people used it extensively
1534 $img = $this->maybeMakeExternalImage( $text );
1535 if ( $img !== false ) {
1541 # Set linktype for CSS - if URL==text, link is essentially free
1542 $linktype = ( $text === $url ) ?
'free' : 'text';
1544 # No link text, e.g. [http://domain.tld/some.link]
1545 if ( $text == '' ) {
1546 # Autonumber if allowed. See bug #5918
1547 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1548 $langObj = $this->getFunctionLang();
1549 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1550 $linktype = 'autonumber';
1552 # Otherwise just use the URL
1553 $text = htmlspecialchars( $url );
1557 # Have link text, e.g. [http://domain.tld/some.link text]s
1559 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1562 $text = $wgContLang->markNoConversion( $text );
1564 $url = Sanitizer
::cleanUrl( $url );
1566 # Use the encoded URL
1567 # This means that users can paste URLs directly into the text
1568 # Funny characters like ö aren't valid in URLs anyway
1569 # This was changed in August 2004
1570 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1571 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1573 # Register link in the output object.
1574 # Replace unnecessary URL escape codes with the referenced character
1575 # This prevents spammers from hiding links from the filters
1576 $pasteurized = self
::replaceUnusualEscapes( $url );
1577 $this->mOutput
->addExternalLink( $pasteurized );
1580 wfProfileOut( __METHOD__
);
1585 * Get an associative array of additional HTML attributes appropriate for a
1586 * particular external link. This currently may include rel => nofollow
1587 * (depending on configuration, namespace, and the URL's domain) and/or a
1588 * target attribute (depending on configuration).
1590 * @param $url String: optional URL, to extract the domain from for rel =>
1591 * nofollow if appropriate
1592 * @return Array: associative array of HTML attributes
1594 function getExternalLinkAttribs( $url = false ) {
1596 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1597 $ns = $this->mTitle
->getNamespace();
1598 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1599 $attribs['rel'] = 'nofollow';
1601 global $wgNoFollowDomainExceptions;
1602 if ( $wgNoFollowDomainExceptions ) {
1603 $bits = wfParseUrl( $url );
1604 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1605 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1606 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1607 unset( $attribs['rel'] );
1614 if ( $this->mOptions
->getExternalLinkTarget() ) {
1615 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1621 * Replace unusual URL escape codes with their equivalent characters
1623 * @param $url String
1626 * @todo This can merge genuinely required bits in the path or query string,
1627 * breaking legit URLs. A proper fix would treat the various parts of
1628 * the URL differently; as a workaround, just use the output for
1629 * statistical records, not for actual linking/output.
1631 static function replaceUnusualEscapes( $url ) {
1632 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1633 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1637 * Callback function used in replaceUnusualEscapes().
1638 * Replaces unusual URL escape codes with their equivalent character
1640 private static function replaceUnusualEscapesCallback( $matches ) {
1641 $char = urldecode( $matches[0] );
1642 $ord = ord( $char );
1643 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1644 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1645 # No, shouldn't be escaped
1648 # Yes, leave it escaped
1654 * make an image if it's allowed, either through the global
1655 * option, through the exception, or through the on-wiki whitelist
1658 function maybeMakeExternalImage( $url ) {
1659 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1660 $imagesexception = !empty( $imagesfrom );
1662 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1663 if ( $imagesexception && is_array( $imagesfrom ) ) {
1664 $imagematch = false;
1665 foreach ( $imagesfrom as $match ) {
1666 if ( strpos( $url, $match ) === 0 ) {
1671 } elseif ( $imagesexception ) {
1672 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1674 $imagematch = false;
1676 if ( $this->mOptions
->getAllowExternalImages()
1677 ||
( $imagesexception && $imagematch ) ) {
1678 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1680 $text = Linker
::makeExternalImage( $url );
1683 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1684 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1685 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1686 foreach ( $whitelist as $entry ) {
1687 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1688 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1691 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1692 # Image matches a whitelist entry
1693 $text = Linker
::makeExternalImage( $url );
1702 * Process [[ ]] wikilinks
1703 * @return String: processed text
1707 function replaceInternalLinks( $s ) {
1708 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1713 * Process [[ ]] wikilinks (RIL)
1714 * @return LinkHolderArray
1718 function replaceInternalLinks2( &$s ) {
1721 wfProfileIn( __METHOD__
);
1723 wfProfileIn( __METHOD__
.'-setup' );
1724 static $tc = FALSE, $e1, $e1_img;
1725 # the % is needed to support urlencoded titles as well
1727 $tc = Title
::legalChars() . '#%';
1728 # Match a link having the form [[namespace:link|alternate]]trail
1729 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1730 # Match cases where there is no "]]", which might still be images
1731 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1734 $holders = new LinkHolderArray( $this );
1736 # split the entire text string on occurences of [[
1737 $a = StringUtils
::explode( '[[', ' ' . $s );
1738 # get the first element (all text up to first [[), and remove the space we added
1741 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1742 $s = substr( $s, 1 );
1744 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1746 if ( $useLinkPrefixExtension ) {
1747 # Match the end of a line for a word that's not followed by whitespace,
1748 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1749 $e2 = wfMsgForContent( 'linkprefix' );
1752 if ( is_null( $this->mTitle
) ) {
1753 wfProfileOut( __METHOD__
.'-setup' );
1754 wfProfileOut( __METHOD__
);
1755 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1757 $nottalk = !$this->mTitle
->isTalkPage();
1759 if ( $useLinkPrefixExtension ) {
1761 if ( preg_match( $e2, $s, $m ) ) {
1762 $first_prefix = $m[2];
1764 $first_prefix = false;
1770 if ( $wgContLang->hasVariants() ) {
1771 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1773 $selflink = array( $this->mTitle
->getPrefixedText() );
1775 $useSubpages = $this->areSubpagesAllowed();
1776 wfProfileOut( __METHOD__
.'-setup' );
1778 # Loop for each link
1779 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1780 # Check for excessive memory usage
1781 if ( $holders->isBig() ) {
1783 # Do the existence check, replace the link holders and clear the array
1784 $holders->replace( $s );
1788 if ( $useLinkPrefixExtension ) {
1789 wfProfileIn( __METHOD__
.'-prefixhandling' );
1790 if ( preg_match( $e2, $s, $m ) ) {
1797 if ( $first_prefix ) {
1798 $prefix = $first_prefix;
1799 $first_prefix = false;
1801 wfProfileOut( __METHOD__
.'-prefixhandling' );
1804 $might_be_img = false;
1806 wfProfileIn( __METHOD__
."-e1" );
1807 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1809 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1810 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1811 # the real problem is with the $e1 regex
1814 # Still some problems for cases where the ] is meant to be outside punctuation,
1815 # and no image is in sight. See bug 2095.
1817 if ( $text !== '' &&
1818 substr( $m[3], 0, 1 ) === ']' &&
1819 strpos( $text, '[' ) !== false
1822 $text .= ']'; # so that replaceExternalLinks($text) works later
1823 $m[3] = substr( $m[3], 1 );
1825 # fix up urlencoded title texts
1826 if ( strpos( $m[1], '%' ) !== false ) {
1827 # Should anchors '#' also be rejected?
1828 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1831 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1832 $might_be_img = true;
1834 if ( strpos( $m[1], '%' ) !== false ) {
1835 $m[1] = rawurldecode( $m[1] );
1838 } else { # Invalid form; output directly
1839 $s .= $prefix . '[[' . $line ;
1840 wfProfileOut( __METHOD__
."-e1" );
1843 wfProfileOut( __METHOD__
."-e1" );
1844 wfProfileIn( __METHOD__
."-misc" );
1846 # Don't allow internal links to pages containing
1847 # PROTO: where PROTO is a valid URL protocol; these
1848 # should be external links.
1849 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1850 $s .= $prefix . '[[' . $line ;
1851 wfProfileOut( __METHOD__
."-misc" );
1855 # Make subpage if necessary
1856 if ( $useSubpages ) {
1857 $link = $this->maybeDoSubpageLink( $m[1], $text );
1862 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1864 # Strip off leading ':'
1865 $link = substr( $link, 1 );
1868 wfProfileOut( __METHOD__
."-misc" );
1869 wfProfileIn( __METHOD__
."-title" );
1870 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1871 if ( $nt === null ) {
1872 $s .= $prefix . '[[' . $line;
1873 wfProfileOut( __METHOD__
."-title" );
1877 $ns = $nt->getNamespace();
1878 $iw = $nt->getInterWiki();
1879 wfProfileOut( __METHOD__
."-title" );
1881 if ( $might_be_img ) { # if this is actually an invalid link
1882 wfProfileIn( __METHOD__
."-might_be_img" );
1883 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1886 # look at the next 'line' to see if we can close it there
1888 $next_line = $a->current();
1889 if ( $next_line === false ||
$next_line === null ) {
1892 $m = explode( ']]', $next_line, 3 );
1893 if ( count( $m ) == 3 ) {
1894 # the first ]] closes the inner link, the second the image
1896 $text .= "[[{$m[0]}]]{$m[1]}";
1899 } elseif ( count( $m ) == 2 ) {
1900 # if there's exactly one ]] that's fine, we'll keep looking
1901 $text .= "[[{$m[0]}]]{$m[1]}";
1903 # if $next_line is invalid too, we need look no further
1904 $text .= '[[' . $next_line;
1909 # we couldn't find the end of this imageLink, so output it raw
1910 # but don't ignore what might be perfectly normal links in the text we've examined
1911 $holders->merge( $this->replaceInternalLinks2( $text ) );
1912 $s .= "{$prefix}[[$link|$text";
1913 # note: no $trail, because without an end, there *is* no trail
1914 wfProfileOut( __METHOD__
."-might_be_img" );
1917 } else { # it's not an image, so output it raw
1918 $s .= "{$prefix}[[$link|$text";
1919 # note: no $trail, because without an end, there *is* no trail
1920 wfProfileOut( __METHOD__
."-might_be_img" );
1923 wfProfileOut( __METHOD__
."-might_be_img" );
1926 $wasblank = ( $text == '' );
1930 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1931 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1932 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1933 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1934 $text = $this->doQuotes( $text );
1937 # Link not escaped by : , create the various objects
1941 wfProfileIn( __METHOD__
."-interwiki" );
1942 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1943 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1944 $s = rtrim( $s . $prefix );
1945 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1946 wfProfileOut( __METHOD__
."-interwiki" );
1949 wfProfileOut( __METHOD__
."-interwiki" );
1951 if ( $ns == NS_FILE
) {
1952 wfProfileIn( __METHOD__
."-image" );
1953 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1955 # if no parameters were passed, $text
1956 # becomes something like "File:Foo.png",
1957 # which we don't want to pass on to the
1961 # recursively parse links inside the image caption
1962 # actually, this will parse them in any other parameters, too,
1963 # but it might be hard to fix that, and it doesn't matter ATM
1964 $text = $this->replaceExternalLinks( $text );
1965 $holders->merge( $this->replaceInternalLinks2( $text ) );
1967 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1968 $s .= $prefix . $this->armorLinks(
1969 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1971 $s .= $prefix . $trail;
1973 wfProfileOut( __METHOD__
."-image" );
1977 if ( $ns == NS_CATEGORY
) {
1978 wfProfileIn( __METHOD__
."-category" );
1979 $s = rtrim( $s . "\n" ); # bug 87
1982 $sortkey = $this->getDefaultSort();
1986 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1987 $sortkey = str_replace( "\n", '', $sortkey );
1988 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1989 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1992 * Strip the whitespace Category links produce, see bug 87
1993 * @todo We might want to use trim($tmp, "\n") here.
1995 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1997 wfProfileOut( __METHOD__
."-category" );
2002 # Self-link checking
2003 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2004 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2005 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2010 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2011 # FIXME: Should do batch file existence checks, see comment below
2012 if ( $ns == NS_MEDIA
) {
2013 wfProfileIn( __METHOD__
."-media" );
2014 # Give extensions a chance to select the file revision for us
2015 $time = $sha1 = $descQuery = false;
2016 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2017 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
2018 # Fetch and register the file (file title may be different via hooks)
2019 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
2020 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2021 $s .= $prefix . $this->armorLinks(
2022 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2023 wfProfileOut( __METHOD__
."-media" );
2027 wfProfileIn( __METHOD__
."-always_known" );
2028 # Some titles, such as valid special pages or files in foreign repos, should
2029 # be shown as bluelinks even though they're not included in the page table
2031 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2032 # batch file existence checks for NS_FILE and NS_MEDIA
2033 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2034 $this->mOutput
->addLink( $nt );
2035 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2037 # Links will be added to the output link list after checking
2038 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2040 wfProfileOut( __METHOD__
."-always_known" );
2042 wfProfileOut( __METHOD__
);
2047 * Make a link placeholder. The text returned can be later resolved to a real link with
2048 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
2049 * parsing of interwiki links, and secondly to allow all existence checks and
2050 * article length checks (for stub links) to be bundled into a single query.
2054 function makeLinkHolder( &$nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2055 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
2059 * Render a forced-blue link inline; protect against double expansion of
2060 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2061 * Since this little disaster has to split off the trail text to avoid
2062 * breaking URLs in the following text without breaking trails on the
2063 * wiki links, it's been made into a horrible function.
2066 * @param $text String
2067 * @param $query Array or String
2068 * @param $trail String
2069 * @param $prefix String
2070 * @return String: HTML-wikitext mix oh yuck
2072 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2073 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2075 if ( is_string( $query ) ) {
2076 $query = wfCgiToArray( $query );
2078 if ( $text == '' ) {
2079 $text = htmlspecialchars( $nt->getPrefixedText() );
2082 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2084 return $this->armorLinks( $link ) . $trail;
2088 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2089 * going to go through further parsing steps before inline URL expansion.
2091 * Not needed quite as much as it used to be since free links are a bit
2092 * more sensible these days. But bracketed links are still an issue.
2094 * @param $text String: more-or-less HTML
2095 * @return String: less-or-more HTML with NOPARSE bits
2097 function armorLinks( $text ) {
2098 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2099 "{$this->mUniqPrefix}NOPARSE$1", $text );
2103 * Return true if subpage links should be expanded on this page.
2106 function areSubpagesAllowed() {
2107 # Some namespaces don't allow subpages
2108 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2112 * Handle link to subpage if necessary
2114 * @param $target String: the source of the link
2115 * @param &$text String: the link text, modified as necessary
2116 * @return string the full name of the link
2119 function maybeDoSubpageLink( $target, &$text ) {
2120 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2124 * Used by doBlockLevels()
2129 function closeParagraph() {
2131 if ( $this->mLastSection
!= '' ) {
2132 $result = '</' . $this->mLastSection
. ">\n";
2134 $this->mInPre
= false;
2135 $this->mLastSection
= '';
2140 * getCommon() returns the length of the longest common substring
2141 * of both arguments, starting at the beginning of both.
2144 function getCommon( $st1, $st2 ) {
2145 $fl = strlen( $st1 );
2146 $shorter = strlen( $st2 );
2147 if ( $fl < $shorter ) {
2151 for ( $i = 0; $i < $shorter; ++
$i ) {
2152 if ( $st1[$i] != $st2[$i] ) {
2160 * These next three functions open, continue, and close the list
2161 * element appropriate to the prefix character passed into them.
2166 function openList( $char ) {
2167 $result = $this->closeParagraph();
2169 if ( '*' === $char ) {
2170 $result .= '<ul><li>';
2171 } elseif ( '#' === $char ) {
2172 $result .= '<ol><li>';
2173 } elseif ( ':' === $char ) {
2174 $result .= '<dl><dd>';
2175 } elseif ( ';' === $char ) {
2176 $result .= '<dl><dt>';
2177 $this->mDTopen
= true;
2179 $result = '<!-- ERR 1 -->';
2187 * @param $char String
2192 function nextItem( $char ) {
2193 if ( '*' === $char ||
'#' === $char ) {
2195 } elseif ( ':' === $char ||
';' === $char ) {
2197 if ( $this->mDTopen
) {
2200 if ( ';' === $char ) {
2201 $this->mDTopen
= true;
2202 return $close . '<dt>';
2204 $this->mDTopen
= false;
2205 return $close . '<dd>';
2208 return '<!-- ERR 2 -->';
2213 * @param $char String
2218 function closeList( $char ) {
2219 if ( '*' === $char ) {
2220 $text = '</li></ul>';
2221 } elseif ( '#' === $char ) {
2222 $text = '</li></ol>';
2223 } elseif ( ':' === $char ) {
2224 if ( $this->mDTopen
) {
2225 $this->mDTopen
= false;
2226 $text = '</dt></dl>';
2228 $text = '</dd></dl>';
2231 return '<!-- ERR 3 -->';
2238 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2240 * @param $text String
2241 * @param $linestart Boolean: whether or not this is at the start of a line.
2243 * @return string the lists rendered as HTML
2245 function doBlockLevels( $text, $linestart ) {
2246 wfProfileIn( __METHOD__
);
2248 # Parsing through the text line by line. The main thing
2249 # happening here is handling of block-level elements p, pre,
2250 # and making lists from lines starting with * # : etc.
2252 $textLines = StringUtils
::explode( "\n", $text );
2254 $lastPrefix = $output = '';
2255 $this->mDTopen
= $inBlockElem = false;
2257 $paragraphStack = false;
2259 foreach ( $textLines as $oLine ) {
2261 if ( !$linestart ) {
2271 $lastPrefixLength = strlen( $lastPrefix );
2272 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2273 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2274 # If not in a <pre> element, scan for and figure out what prefixes are there.
2275 if ( !$this->mInPre
) {
2276 # Multiple prefixes may abut each other for nested lists.
2277 $prefixLength = strspn( $oLine, '*#:;' );
2278 $prefix = substr( $oLine, 0, $prefixLength );
2281 # ; and : are both from definition-lists, so they're equivalent
2282 # for the purposes of determining whether or not we need to open/close
2284 $prefix2 = str_replace( ';', ':', $prefix );
2285 $t = substr( $oLine, $prefixLength );
2286 $this->mInPre
= (bool)$preOpenMatch;
2288 # Don't interpret any other prefixes in preformatted text
2290 $prefix = $prefix2 = '';
2295 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2296 # Same as the last item, so no need to deal with nesting or opening stuff
2297 $output .= $this->nextItem( substr( $prefix, -1 ) );
2298 $paragraphStack = false;
2300 if ( substr( $prefix, -1 ) === ';') {
2301 # The one nasty exception: definition lists work like this:
2302 # ; title : definition text
2303 # So we check for : in the remainder text to split up the
2304 # title and definition, without b0rking links.
2306 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2308 $output .= $term . $this->nextItem( ':' );
2311 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2312 # We need to open or close prefixes, or both.
2314 # Either open or close a level...
2315 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2316 $paragraphStack = false;
2318 # Close all the prefixes which aren't shared.
2319 while ( $commonPrefixLength < $lastPrefixLength ) {
2320 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2321 --$lastPrefixLength;
2324 # Continue the current prefix if appropriate.
2325 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2326 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2329 # Open prefixes where appropriate.
2330 while ( $prefixLength > $commonPrefixLength ) {
2331 $char = substr( $prefix, $commonPrefixLength, 1 );
2332 $output .= $this->openList( $char );
2334 if ( ';' === $char ) {
2335 # FIXME: This is dupe of code above
2336 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2338 $output .= $term . $this->nextItem( ':' );
2341 ++
$commonPrefixLength;
2343 $lastPrefix = $prefix2;
2346 # If we have no prefixes, go to paragraph mode.
2347 if ( 0 == $prefixLength ) {
2348 wfProfileIn( __METHOD__
."-paragraph" );
2349 # No prefix (not in list)--go to paragraph mode
2350 # XXX: use a stack for nestable elements like span, table and div
2351 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2352 $closematch = preg_match(
2353 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2354 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2355 if ( $openmatch or $closematch ) {
2356 $paragraphStack = false;
2357 # TODO bug 5718: paragraph closed
2358 $output .= $this->closeParagraph();
2359 if ( $preOpenMatch and !$preCloseMatch ) {
2360 $this->mInPre
= true;
2362 $inBlockElem = !$closematch;
2363 } elseif ( !$inBlockElem && !$this->mInPre
) {
2364 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2366 if ( $this->mLastSection
!== 'pre' ) {
2367 $paragraphStack = false;
2368 $output .= $this->closeParagraph().'<pre>';
2369 $this->mLastSection
= 'pre';
2371 $t = substr( $t, 1 );
2374 if ( trim( $t ) === '' ) {
2375 if ( $paragraphStack ) {
2376 $output .= $paragraphStack.'<br />';
2377 $paragraphStack = false;
2378 $this->mLastSection
= 'p';
2380 if ( $this->mLastSection
!== 'p' ) {
2381 $output .= $this->closeParagraph();
2382 $this->mLastSection
= '';
2383 $paragraphStack = '<p>';
2385 $paragraphStack = '</p><p>';
2389 if ( $paragraphStack ) {
2390 $output .= $paragraphStack;
2391 $paragraphStack = false;
2392 $this->mLastSection
= 'p';
2393 } elseif ( $this->mLastSection
!== 'p' ) {
2394 $output .= $this->closeParagraph().'<p>';
2395 $this->mLastSection
= 'p';
2400 wfProfileOut( __METHOD__
."-paragraph" );
2402 # somewhere above we forget to get out of pre block (bug 785)
2403 if ( $preCloseMatch && $this->mInPre
) {
2404 $this->mInPre
= false;
2406 if ( $paragraphStack === false ) {
2410 while ( $prefixLength ) {
2411 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2414 if ( $this->mLastSection
!= '' ) {
2415 $output .= '</' . $this->mLastSection
. '>';
2416 $this->mLastSection
= '';
2419 wfProfileOut( __METHOD__
);
2424 * Split up a string on ':', ignoring any occurences inside tags
2425 * to prevent illegal overlapping.
2427 * @param $str String: the string to split
2428 * @param &$before String: set to everything before the ':'
2429 * @param &$after String: set to everything after the ':'
2430 * return String: the position of the ':', or false if none found
2432 function findColonNoLinks( $str, &$before, &$after ) {
2433 wfProfileIn( __METHOD__
);
2435 $pos = strpos( $str, ':' );
2436 if ( $pos === false ) {
2438 wfProfileOut( __METHOD__
);
2442 $lt = strpos( $str, '<' );
2443 if ( $lt === false ||
$lt > $pos ) {
2444 # Easy; no tag nesting to worry about
2445 $before = substr( $str, 0, $pos );
2446 $after = substr( $str, $pos+
1 );
2447 wfProfileOut( __METHOD__
);
2451 # Ugly state machine to walk through avoiding tags.
2452 $state = self
::COLON_STATE_TEXT
;
2454 $len = strlen( $str );
2455 for( $i = 0; $i < $len; $i++
) {
2459 # (Using the number is a performance hack for common cases)
2460 case 0: # self::COLON_STATE_TEXT:
2463 # Could be either a <start> tag or an </end> tag
2464 $state = self
::COLON_STATE_TAGSTART
;
2467 if ( $stack == 0 ) {
2469 $before = substr( $str, 0, $i );
2470 $after = substr( $str, $i +
1 );
2471 wfProfileOut( __METHOD__
);
2474 # Embedded in a tag; don't break it.
2477 # Skip ahead looking for something interesting
2478 $colon = strpos( $str, ':', $i );
2479 if ( $colon === false ) {
2480 # Nothing else interesting
2481 wfProfileOut( __METHOD__
);
2484 $lt = strpos( $str, '<', $i );
2485 if ( $stack === 0 ) {
2486 if ( $lt === false ||
$colon < $lt ) {
2488 $before = substr( $str, 0, $colon );
2489 $after = substr( $str, $colon +
1 );
2490 wfProfileOut( __METHOD__
);
2494 if ( $lt === false ) {
2495 # Nothing else interesting to find; abort!
2496 # We're nested, but there's no close tags left. Abort!
2499 # Skip ahead to next tag start
2501 $state = self
::COLON_STATE_TAGSTART
;
2504 case 1: # self::COLON_STATE_TAG:
2509 $state = self
::COLON_STATE_TEXT
;
2512 # Slash may be followed by >?
2513 $state = self
::COLON_STATE_TAGSLASH
;
2519 case 2: # self::COLON_STATE_TAGSTART:
2522 $state = self
::COLON_STATE_CLOSETAG
;
2525 $state = self
::COLON_STATE_COMMENT
;
2528 # Illegal early close? This shouldn't happen D:
2529 $state = self
::COLON_STATE_TEXT
;
2532 $state = self
::COLON_STATE_TAG
;
2535 case 3: # self::COLON_STATE_CLOSETAG:
2540 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2541 wfProfileOut( __METHOD__
);
2544 $state = self
::COLON_STATE_TEXT
;
2547 case self
::COLON_STATE_TAGSLASH
:
2549 # Yes, a self-closed tag <blah/>
2550 $state = self
::COLON_STATE_TEXT
;
2552 # Probably we're jumping the gun, and this is an attribute
2553 $state = self
::COLON_STATE_TAG
;
2556 case 5: # self::COLON_STATE_COMMENT:
2558 $state = self
::COLON_STATE_COMMENTDASH
;
2561 case self
::COLON_STATE_COMMENTDASH
:
2563 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2565 $state = self
::COLON_STATE_COMMENT
;
2568 case self
::COLON_STATE_COMMENTDASHDASH
:
2570 $state = self
::COLON_STATE_TEXT
;
2572 $state = self
::COLON_STATE_COMMENT
;
2576 throw new MWException( "State machine error in " . __METHOD__
);
2580 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2581 wfProfileOut( __METHOD__
);
2584 wfProfileOut( __METHOD__
);
2589 * Return value of a magic variable (like PAGENAME)
2593 * @param $index integer
2594 * @param $frame PPFrame
2596 function getVariableValue( $index, $frame=false ) {
2597 global $wgContLang, $wgSitename, $wgServer;
2598 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2601 * Some of these require message or data lookups and can be
2602 * expensive to check many times.
2604 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2605 if ( isset( $this->mVarCache
[$index] ) ) {
2606 return $this->mVarCache
[$index];
2610 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2611 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2614 global $wgLocaltimezone;
2615 if ( isset( $wgLocaltimezone ) ) {
2616 $oldtz = date_default_timezone_get();
2617 date_default_timezone_set( $wgLocaltimezone );
2620 $localTimestamp = date( 'YmdHis', $ts );
2621 $localMonth = date( 'm', $ts );
2622 $localMonth1 = date( 'n', $ts );
2623 $localMonthName = date( 'n', $ts );
2624 $localDay = date( 'j', $ts );
2625 $localDay2 = date( 'd', $ts );
2626 $localDayOfWeek = date( 'w', $ts );
2627 $localWeek = date( 'W', $ts );
2628 $localYear = date( 'Y', $ts );
2629 $localHour = date( 'H', $ts );
2630 if ( isset( $wgLocaltimezone ) ) {
2631 date_default_timezone_set( $oldtz );
2635 case 'currentmonth':
2636 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2638 case 'currentmonth1':
2639 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2641 case 'currentmonthname':
2642 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2644 case 'currentmonthnamegen':
2645 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2647 case 'currentmonthabbrev':
2648 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2651 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2654 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2657 $value = $wgContLang->formatNum( $localMonth );
2660 $value = $wgContLang->formatNum( $localMonth1 );
2662 case 'localmonthname':
2663 $value = $wgContLang->getMonthName( $localMonthName );
2665 case 'localmonthnamegen':
2666 $value = $wgContLang->getMonthNameGen( $localMonthName );
2668 case 'localmonthabbrev':
2669 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2672 $value = $wgContLang->formatNum( $localDay );
2675 $value = $wgContLang->formatNum( $localDay2 );
2678 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2681 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2683 case 'fullpagename':
2684 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2686 case 'fullpagenamee':
2687 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2690 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2692 case 'subpagenamee':
2693 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2695 case 'basepagename':
2696 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2698 case 'basepagenamee':
2699 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2701 case 'talkpagename':
2702 if ( $this->mTitle
->canTalk() ) {
2703 $talkPage = $this->mTitle
->getTalkPage();
2704 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2709 case 'talkpagenamee':
2710 if ( $this->mTitle
->canTalk() ) {
2711 $talkPage = $this->mTitle
->getTalkPage();
2712 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2717 case 'subjectpagename':
2718 $subjPage = $this->mTitle
->getSubjectPage();
2719 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2721 case 'subjectpagenamee':
2722 $subjPage = $this->mTitle
->getSubjectPage();
2723 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2726 # Let the edit saving system know we should parse the page
2727 # *after* a revision ID has been assigned.
2728 $this->mOutput
->setFlag( 'vary-revision' );
2729 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2730 $value = $this->mRevisionId
;
2733 # Let the edit saving system know we should parse the page
2734 # *after* a revision ID has been assigned. This is for null edits.
2735 $this->mOutput
->setFlag( 'vary-revision' );
2736 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2737 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2739 case 'revisionday2':
2740 # Let the edit saving system know we should parse the page
2741 # *after* a revision ID has been assigned. This is for null edits.
2742 $this->mOutput
->setFlag( 'vary-revision' );
2743 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2744 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2746 case 'revisionmonth':
2747 # Let the edit saving system know we should parse the page
2748 # *after* a revision ID has been assigned. This is for null edits.
2749 $this->mOutput
->setFlag( 'vary-revision' );
2750 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2751 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2753 case 'revisionmonth1':
2754 # Let the edit saving system know we should parse the page
2755 # *after* a revision ID has been assigned. This is for null edits.
2756 $this->mOutput
->setFlag( 'vary-revision' );
2757 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2758 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2760 case 'revisionyear':
2761 # Let the edit saving system know we should parse the page
2762 # *after* a revision ID has been assigned. This is for null edits.
2763 $this->mOutput
->setFlag( 'vary-revision' );
2764 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2765 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2767 case 'revisiontimestamp':
2768 # Let the edit saving system know we should parse the page
2769 # *after* a revision ID has been assigned. This is for null edits.
2770 $this->mOutput
->setFlag( 'vary-revision' );
2771 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2772 $value = $this->getRevisionTimestamp();
2774 case 'revisionuser':
2775 # Let the edit saving system know we should parse the page
2776 # *after* a revision ID has been assigned. This is for null edits.
2777 $this->mOutput
->setFlag( 'vary-revision' );
2778 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2779 $value = $this->getRevisionUser();
2782 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2785 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2788 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2791 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2793 case 'subjectspace':
2794 $value = $this->mTitle
->getSubjectNsText();
2796 case 'subjectspacee':
2797 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2799 case 'currentdayname':
2800 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2803 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2806 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2809 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2812 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2813 # int to remove the padding
2814 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2817 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2819 case 'localdayname':
2820 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2823 $value = $wgContLang->formatNum( $localYear, true );
2826 $value = $wgContLang->time( $localTimestamp, false, false );
2829 $value = $wgContLang->formatNum( $localHour, true );
2832 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2833 # int to remove the padding
2834 $value = $wgContLang->formatNum( (int)$localWeek );
2837 $value = $wgContLang->formatNum( $localDayOfWeek );
2839 case 'numberofarticles':
2840 $value = $wgContLang->formatNum( SiteStats
::articles() );
2842 case 'numberoffiles':
2843 $value = $wgContLang->formatNum( SiteStats
::images() );
2845 case 'numberofusers':
2846 $value = $wgContLang->formatNum( SiteStats
::users() );
2848 case 'numberofactiveusers':
2849 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2851 case 'numberofpages':
2852 $value = $wgContLang->formatNum( SiteStats
::pages() );
2854 case 'numberofadmins':
2855 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2857 case 'numberofedits':
2858 $value = $wgContLang->formatNum( SiteStats
::edits() );
2860 case 'numberofviews':
2861 $value = $wgContLang->formatNum( SiteStats
::views() );
2863 case 'currenttimestamp':
2864 $value = wfTimestamp( TS_MW
, $ts );
2866 case 'localtimestamp':
2867 $value = $localTimestamp;
2869 case 'currentversion':
2870 $value = SpecialVersion
::getVersion();
2873 return $wgArticlePath;
2879 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2880 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2881 wfRestoreWarnings();
2882 return $serverName ?
$serverName : $wgServer;
2884 return $wgScriptPath;
2886 return $wgStylePath;
2887 case 'directionmark':
2888 return $wgContLang->getDirMark();
2889 case 'contentlanguage':
2890 global $wgLanguageCode;
2891 return $wgLanguageCode;
2894 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2902 $this->mVarCache
[$index] = $value;
2908 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2912 function initialiseVariables() {
2913 wfProfileIn( __METHOD__
);
2914 $variableIDs = MagicWord
::getVariableIDs();
2915 $substIDs = MagicWord
::getSubstIDs();
2917 $this->mVariables
= new MagicWordArray( $variableIDs );
2918 $this->mSubstWords
= new MagicWordArray( $substIDs );
2919 wfProfileOut( __METHOD__
);
2923 * Preprocess some wikitext and return the document tree.
2924 * This is the ghost of replace_variables().
2926 * @param $text String: The text to parse
2927 * @param $flags Integer: bitwise combination of:
2928 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2929 * included. Default is to assume a direct page view.
2931 * The generated DOM tree must depend only on the input text and the flags.
2932 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2934 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2935 * change in the DOM tree for a given text, must be passed through the section identifier
2936 * in the section edit link and thus back to extractSections().
2938 * The output of this function is currently only cached in process memory, but a persistent
2939 * cache may be implemented at a later date which takes further advantage of these strict
2940 * dependency requirements.
2946 function preprocessToDom( $text, $flags = 0 ) {
2947 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2952 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2956 public static function splitWhitespace( $s ) {
2957 $ltrimmed = ltrim( $s );
2958 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2959 $trimmed = rtrim( $ltrimmed );
2960 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2962 $w2 = substr( $ltrimmed, -$diff );
2966 return array( $w1, $trimmed, $w2 );
2970 * Replace magic variables, templates, and template arguments
2971 * with the appropriate text. Templates are substituted recursively,
2972 * taking care to avoid infinite loops.
2974 * Note that the substitution depends on value of $mOutputType:
2975 * self::OT_WIKI: only {{subst:}} templates
2976 * self::OT_PREPROCESS: templates but not extension tags
2977 * self::OT_HTML: all templates and extension tags
2979 * @param $text String: the text to transform
2980 * @param $frame PPFrame Object describing the arguments passed to the template.
2981 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2982 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2983 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2988 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2989 # Is there any text? Also, Prevent too big inclusions!
2990 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2993 wfProfileIn( __METHOD__
);
2995 if ( $frame === false ) {
2996 $frame = $this->getPreprocessor()->newFrame();
2997 } elseif ( !( $frame instanceof PPFrame
) ) {
2998 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2999 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3002 $dom = $this->preprocessToDom( $text );
3003 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3004 $text = $frame->expand( $dom, $flags );
3006 wfProfileOut( __METHOD__
);
3011 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3015 static function createAssocArgs( $args ) {
3016 $assocArgs = array();
3018 foreach ( $args as $arg ) {
3019 $eqpos = strpos( $arg, '=' );
3020 if ( $eqpos === false ) {
3021 $assocArgs[$index++
] = $arg;
3023 $name = trim( substr( $arg, 0, $eqpos ) );
3024 $value = trim( substr( $arg, $eqpos+
1 ) );
3025 if ( $value === false ) {
3028 if ( $name !== false ) {
3029 $assocArgs[$name] = $value;
3038 * Warn the user when a parser limitation is reached
3039 * Will warn at most once the user per limitation type
3041 * @param $limitationType String: should be one of:
3042 * 'expensive-parserfunction' (corresponding messages:
3043 * 'expensive-parserfunction-warning',
3044 * 'expensive-parserfunction-category')
3045 * 'post-expand-template-argument' (corresponding messages:
3046 * 'post-expand-template-argument-warning',
3047 * 'post-expand-template-argument-category')
3048 * 'post-expand-template-inclusion' (corresponding messages:
3049 * 'post-expand-template-inclusion-warning',
3050 * 'post-expand-template-inclusion-category')
3051 * @param $current Current value
3052 * @param $max Maximum allowed, when an explicit limit has been
3053 * exceeded, provide the values (optional)
3055 function limitationWarn( $limitationType, $current=null, $max=null) {
3056 # does no harm if $current and $max are present but are unnecessary for the message
3057 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3058 $this->mOutput
->addWarning( $warning );
3059 $this->addTrackingCategory( "$limitationType-category" );
3063 * Return the text of a template, after recursively
3064 * replacing any variables or templates within the template.
3066 * @param $piece Array: the parts of the template
3067 * $piece['title']: the title, i.e. the part before the |
3068 * $piece['parts']: the parameter array
3069 * $piece['lineStart']: whether the brace was at the start of a line
3070 * @param $frame PPFrame The current frame, contains template arguments
3071 * @return String: the text of the template
3074 function braceSubstitution( $piece, $frame ) {
3075 global $wgContLang, $wgNonincludableNamespaces;
3076 wfProfileIn( __METHOD__
);
3077 wfProfileIn( __METHOD__
.'-setup' );
3080 $found = false; # $text has been filled
3081 $nowiki = false; # wiki markup in $text should be escaped
3082 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3083 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3084 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3085 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3087 # Title object, where $text came from
3090 # $part1 is the bit before the first |, and must contain only title characters.
3091 # Various prefixes will be stripped from it later.
3092 $titleWithSpaces = $frame->expand( $piece['title'] );
3093 $part1 = trim( $titleWithSpaces );
3096 # Original title text preserved for various purposes
3097 $originalTitle = $part1;
3099 # $args is a list of argument nodes, starting from index 0, not including $part1
3100 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3101 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3102 wfProfileOut( __METHOD__
.'-setup' );
3105 wfProfileIn( __METHOD__
.'-modifiers' );
3108 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3110 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3111 # Decide whether to expand template or keep wikitext as-is.
3112 if ( $this->ot
['wiki'] ) {
3113 if ( $substMatch === false ) {
3114 $literal = true; # literal when in PST with no prefix
3116 $literal = false; # expand when in PST with subst: or safesubst:
3119 if ( $substMatch == 'subst' ) {
3120 $literal = true; # literal when not in PST with plain subst:
3122 $literal = false; # expand when not in PST with safesubst: or no prefix
3126 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3133 if ( !$found && $args->getLength() == 0 ) {
3134 $id = $this->mVariables
->matchStartToEnd( $part1 );
3135 if ( $id !== false ) {
3136 $text = $this->getVariableValue( $id, $frame );
3137 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3138 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3144 # MSG, MSGNW and RAW
3147 $mwMsgnw = MagicWord
::get( 'msgnw' );
3148 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3151 # Remove obsolete MSG:
3152 $mwMsg = MagicWord
::get( 'msg' );
3153 $mwMsg->matchStartAndRemove( $part1 );
3157 $mwRaw = MagicWord
::get( 'raw' );
3158 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3159 $forceRawInterwiki = true;
3162 wfProfileOut( __METHOD__
.'-modifiers' );
3166 wfProfileIn( __METHOD__
. '-pfunc' );
3168 $colonPos = strpos( $part1, ':' );
3169 if ( $colonPos !== false ) {
3170 # Case sensitive functions
3171 $function = substr( $part1, 0, $colonPos );
3172 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3173 $function = $this->mFunctionSynonyms
[1][$function];
3175 # Case insensitive functions
3176 $function = $wgContLang->lc( $function );
3177 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3178 $function = $this->mFunctionSynonyms
[0][$function];
3184 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3185 $initialArgs = array( &$this );
3186 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3187 if ( $flags & SFH_OBJECT_ARGS
) {
3188 # Add a frame parameter, and pass the arguments as an array
3189 $allArgs = $initialArgs;
3190 $allArgs[] = $frame;
3191 for ( $i = 0; $i < $args->getLength(); $i++
) {
3192 $funcArgs[] = $args->item( $i );
3194 $allArgs[] = $funcArgs;
3196 # Convert arguments to plain text
3197 for ( $i = 0; $i < $args->getLength(); $i++
) {
3198 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3200 $allArgs = array_merge( $initialArgs, $funcArgs );
3203 # Workaround for PHP bug 35229 and similar
3204 if ( !is_callable( $callback ) ) {
3205 wfProfileOut( __METHOD__
. '-pfunc' );
3206 wfProfileOut( __METHOD__
);
3207 throw new MWException( "Tag hook for $function is not callable\n" );
3209 $result = call_user_func_array( $callback, $allArgs );
3212 $preprocessFlags = 0;
3214 if ( is_array( $result ) ) {
3215 if ( isset( $result[0] ) ) {
3217 unset( $result[0] );
3220 # Extract flags into the local scope
3221 # This allows callers to set flags such as nowiki, found, etc.
3227 $text = $this->preprocessToDom( $text, $preprocessFlags );
3232 wfProfileOut( __METHOD__
. '-pfunc' );
3235 # Finish mangling title and then check for loops.
3236 # Set $title to a Title object and $titleText to the PDBK
3239 # Split the title into page and subpage
3241 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3242 if ( $subpage !== '' ) {
3243 $ns = $this->mTitle
->getNamespace();
3245 $title = Title
::newFromText( $part1, $ns );
3247 $titleText = $title->getPrefixedText();
3248 # Check for language variants if the template is not found
3249 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3250 $wgContLang->findVariantLink( $part1, $title, true );
3252 # Do recursion depth check
3253 $limit = $this->mOptions
->getMaxTemplateDepth();
3254 if ( $frame->depth
>= $limit ) {
3256 $text = '<span class="error">'
3257 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3263 # Load from database
3264 if ( !$found && $title ) {
3265 wfProfileIn( __METHOD__
. '-loadtpl' );
3266 if ( !$title->isExternal() ) {
3267 if ( $title->getNamespace() == NS_SPECIAL
3268 && $this->mOptions
->getAllowSpecialInclusion()
3269 && $this->ot
['html'] )
3271 $text = SpecialPageFactory
::capturePath( $title );
3272 if ( is_string( $text ) ) {
3275 $this->disableCache();
3277 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3278 $found = false; # access denied
3279 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3281 list( $text, $title ) = $this->getTemplateDom( $title );
3282 if ( $text !== false ) {
3288 # If the title is valid but undisplayable, make a link to it
3289 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3290 $text = "[[:$titleText]]";
3293 } elseif ( $title->isTrans() ) {
3294 # Interwiki transclusion
3295 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3296 $text = $this->interwikiTransclude( $title, 'render' );
3299 $text = $this->interwikiTransclude( $title, 'raw' );
3300 # Preprocess it like a template
3301 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3307 # Do infinite loop check
3308 # This has to be done after redirect resolution to avoid infinite loops via redirects
3309 if ( !$frame->loopCheck( $title ) ) {
3311 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3312 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3314 wfProfileOut( __METHOD__
. '-loadtpl' );
3317 # If we haven't found text to substitute by now, we're done
3318 # Recover the source wikitext and return it
3320 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3321 wfProfileOut( __METHOD__
);
3322 return array( 'object' => $text );
3325 # Expand DOM-style return values in a child frame
3326 if ( $isChildObj ) {
3327 # Clean up argument array
3328 $newFrame = $frame->newChild( $args, $title );
3331 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3332 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3333 # Expansion is eligible for the empty-frame cache
3334 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3335 $text = $this->mTplExpandCache
[$titleText];
3337 $text = $newFrame->expand( $text );
3338 $this->mTplExpandCache
[$titleText] = $text;
3341 # Uncached expansion
3342 $text = $newFrame->expand( $text );
3345 if ( $isLocalObj && $nowiki ) {
3346 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3347 $isLocalObj = false;
3350 # Replace raw HTML by a placeholder
3351 # Add a blank line preceding, to prevent it from mucking up
3352 # immediately preceding headings
3354 $text = "\n\n" . $this->insertStripItem( $text );
3355 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3356 # Escape nowiki-style return values
3357 $text = wfEscapeWikiText( $text );
3358 } elseif ( is_string( $text )
3359 && !$piece['lineStart']
3360 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3362 # Bug 529: if the template begins with a table or block-level
3363 # element, it should be treated as beginning a new line.
3364 # This behaviour is somewhat controversial.
3365 $text = "\n" . $text;
3368 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3369 # Error, oversize inclusion
3370 if ( $titleText !== false ) {
3371 # Make a working, properly escaped link if possible (bug 23588)
3372 $text = "[[:$titleText]]";
3374 # This will probably not be a working link, but at least it may
3375 # provide some hint of where the problem is
3376 preg_replace( '/^:/', '', $originalTitle );
3377 $text = "[[:$originalTitle]]";
3379 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3380 $this->limitationWarn( 'post-expand-template-inclusion' );
3383 if ( $isLocalObj ) {
3384 $ret = array( 'object' => $text );
3386 $ret = array( 'text' => $text );
3389 wfProfileOut( __METHOD__
);
3394 * Get the semi-parsed DOM representation of a template with a given title,
3395 * and its redirect destination title. Cached.
3399 function getTemplateDom( $title ) {
3400 $cacheTitle = $title;
3401 $titleText = $title->getPrefixedDBkey();
3403 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3404 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3405 $title = Title
::makeTitle( $ns, $dbk );
3406 $titleText = $title->getPrefixedDBkey();
3408 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3409 return array( $this->mTplDomCache
[$titleText], $title );
3412 # Cache miss, go to the database
3413 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3415 if ( $text === false ) {
3416 $this->mTplDomCache
[$titleText] = false;
3417 return array( false, $title );
3420 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3421 $this->mTplDomCache
[ $titleText ] = $dom;
3423 if ( !$title->equals( $cacheTitle ) ) {
3424 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3425 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3428 return array( $dom, $title );
3432 * Fetch the unparsed text of a template and register a reference to it.
3433 * @param Title $title
3434 * @return Array ( string or false, Title )
3436 function fetchTemplateAndTitle( $title ) {
3437 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3438 $stuff = call_user_func( $templateCb, $title, $this );
3439 $text = $stuff['text'];
3440 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3441 if ( isset( $stuff['deps'] ) ) {
3442 foreach ( $stuff['deps'] as $dep ) {
3443 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3446 return array( $text, $finalTitle );
3450 * Fetch the unparsed text of a template and register a reference to it.
3451 * @param Title $title
3452 * @return mixed string or false
3454 function fetchTemplate( $title ) {
3455 $rv = $this->fetchTemplateAndTitle( $title );
3460 * Static function to get a template
3461 * Can be overridden via ParserOptions::setTemplateCallback().
3465 static function statelessFetchTemplate( $title, $parser = false ) {
3466 $text = $skip = false;
3467 $finalTitle = $title;
3470 # Loop to fetch the article, with up to 1 redirect
3471 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3472 # Give extensions a chance to select the revision instead
3473 $id = false; # Assume current
3474 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3475 array( $parser, $title, &$skip, &$id ) );
3481 'page_id' => $title->getArticleID(),
3488 ? Revision
::newFromId( $id )
3489 : Revision
::newFromTitle( $title );
3490 $rev_id = $rev ?
$rev->getId() : 0;
3491 # If there is no current revision, there is no page
3492 if ( $id === false && !$rev ) {
3493 $linkCache = LinkCache
::singleton();
3494 $linkCache->addBadLinkObj( $title );
3499 'page_id' => $title->getArticleID(),
3500 'rev_id' => $rev_id );
3501 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3502 # We fetched a rev from a different title; register it too...
3504 'title' => $rev->getTitle(),
3505 'page_id' => $rev->getPage(),
3506 'rev_id' => $rev_id );
3510 $text = $rev->getText();
3511 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3513 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3514 if ( !$message->exists() ) {
3518 $text = $message->plain();
3522 if ( $text === false ) {
3526 $finalTitle = $title;
3527 $title = Title
::newFromRedirect( $text );
3531 'finalTitle' => $finalTitle,
3536 * Fetch a file and its title and register a reference to it.
3537 * @param Title $title
3538 * @param string $time MW timestamp
3539 * @param string $sha1 base 36 SHA-1
3540 * @return mixed File or false
3542 function fetchFile( $title, $time = false, $sha1 = false ) {
3543 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3548 * Fetch a file and its title and register a reference to it.
3549 * @param Title $title
3550 * @param string $time MW timestamp
3551 * @param string $sha1 base 36 SHA-1
3552 * @return Array ( File or false, Title of file )
3554 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3555 if ( $time === '0' ) {
3556 $file = false; // broken thumbnail forced by hook
3557 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3558 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3559 } else { // get by (name,timestamp)
3560 $file = wfFindFile( $title, array( 'time' => $time ) );
3562 $time = $file ?
$file->getTimestamp() : false;
3563 $sha1 = $file ?
$file->getSha1() : false;
3564 # Register the file as a dependency...
3565 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3566 if ( $file && !$title->equals( $file->getTitle() ) ) {
3567 # We fetched a rev from a different title; register it too...
3568 $this->mOutput
->addImage( $file->getTitle()->getDBkey(), $time, $sha1 );
3569 # Update fetched file title
3570 $title = $file->getTitle();
3572 return array( $file, $title );
3576 * Transclude an interwiki link.
3580 function interwikiTransclude( $title, $action ) {
3581 global $wgEnableScaryTranscluding;
3583 if ( !$wgEnableScaryTranscluding ) {
3584 return wfMsgForContent('scarytranscludedisabled');
3587 $url = $title->getFullUrl( "action=$action" );
3589 if ( strlen( $url ) > 255 ) {
3590 return wfMsgForContent( 'scarytranscludetoolong' );
3592 return $this->fetchScaryTemplateMaybeFromCache( $url );
3596 * @param $url string
3597 * @return Mixed|String
3599 function fetchScaryTemplateMaybeFromCache( $url ) {
3600 global $wgTranscludeCacheExpiry;
3601 $dbr = wfGetDB( DB_SLAVE
);
3602 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3603 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3604 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3606 return $obj->tc_contents
;
3609 $text = Http
::get( $url );
3611 return wfMsgForContent( 'scarytranscludefailed', $url );
3614 $dbw = wfGetDB( DB_MASTER
);
3615 $dbw->replace( 'transcache', array('tc_url'), array(
3617 'tc_time' => $dbw->timestamp( time() ),
3618 'tc_contents' => $text)
3624 * Triple brace replacement -- used for template arguments
3627 * @param $peice array
3628 * @param $frame PPFrame
3632 function argSubstitution( $piece, $frame ) {
3633 wfProfileIn( __METHOD__
);
3636 $parts = $piece['parts'];
3637 $nameWithSpaces = $frame->expand( $piece['title'] );
3638 $argName = trim( $nameWithSpaces );
3640 $text = $frame->getArgument( $argName );
3641 if ( $text === false && $parts->getLength() > 0
3645 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3648 # No match in frame, use the supplied default
3649 $object = $parts->item( 0 )->getChildren();
3651 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3652 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3653 $this->limitationWarn( 'post-expand-template-argument' );
3656 if ( $text === false && $object === false ) {
3658 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3660 if ( $error !== false ) {
3663 if ( $object !== false ) {
3664 $ret = array( 'object' => $object );
3666 $ret = array( 'text' => $text );
3669 wfProfileOut( __METHOD__
);
3674 * Return the text to be used for a given extension tag.
3675 * This is the ghost of strip().
3677 * @param $params Associative array of parameters:
3678 * name PPNode for the tag name
3679 * attr PPNode for unparsed text where tag attributes are thought to be
3680 * attributes Optional associative array of parsed attributes
3681 * inner Contents of extension element
3682 * noClose Original text did not have a close tag
3683 * @param $frame PPFrame
3687 function extensionSubstitution( $params, $frame ) {
3688 $name = $frame->expand( $params['name'] );
3689 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3690 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3691 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3693 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3694 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3695 if ( $isFunctionTag ) {
3696 $markerType = 'none';
3698 $markerType = 'general';
3700 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3701 $name = strtolower( $name );
3702 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3703 if ( isset( $params['attributes'] ) ) {
3704 $attributes = $attributes +
$params['attributes'];
3707 if ( isset( $this->mTagHooks
[$name] ) ) {
3708 # Workaround for PHP bug 35229 and similar
3709 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3710 throw new MWException( "Tag hook for $name is not callable\n" );
3712 $output = call_user_func_array( $this->mTagHooks
[$name],
3713 array( $content, $attributes, $this, $frame ) );
3714 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3715 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3716 if ( !is_callable( $callback ) ) {
3717 throw new MWException( "Tag hook for $name is not callable\n" );
3720 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3722 $output = '<span class="error">Invalid tag extension name: ' .
3723 htmlspecialchars( $name ) . '</span>';
3726 if ( is_array( $output ) ) {
3727 # Extract flags to local scope (to override $markerType)
3729 $output = $flags[0];
3734 if ( is_null( $attrText ) ) {
3737 if ( isset( $params['attributes'] ) ) {
3738 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3739 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3740 htmlspecialchars( $attrValue ) . '"';
3743 if ( $content === null ) {
3744 $output = "<$name$attrText/>";
3746 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3747 $output = "<$name$attrText>$content$close";
3751 if ( $markerType === 'none' ) {
3753 } elseif ( $markerType === 'nowiki' ) {
3754 $this->mStripState
->addNoWiki( $marker, $output );
3755 } elseif ( $markerType === 'general' ) {
3756 $this->mStripState
->addGeneral( $marker, $output );
3758 throw new MWException( __METHOD__
.': invalid marker type' );
3764 * Increment an include size counter
3766 * @param $type String: the type of expansion
3767 * @param $size Integer: the size of the text
3768 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3770 function incrementIncludeSize( $type, $size ) {
3771 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3774 $this->mIncludeSizes
[$type] +
= $size;
3780 * Increment the expensive function count
3782 * @return Boolean: false if the limit has been exceeded
3784 function incrementExpensiveFunctionCount() {
3785 global $wgExpensiveParserFunctionLimit;
3786 $this->mExpensiveFunctionCount++
;
3787 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3794 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3795 * Fills $this->mDoubleUnderscores, returns the modified text
3797 function doDoubleUnderscore( $text ) {
3798 wfProfileIn( __METHOD__
);
3800 # The position of __TOC__ needs to be recorded
3801 $mw = MagicWord
::get( 'toc' );
3802 if ( $mw->match( $text ) ) {
3803 $this->mShowToc
= true;
3804 $this->mForceTocPosition
= true;
3806 # Set a placeholder. At the end we'll fill it in with the TOC.
3807 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3809 # Only keep the first one.
3810 $text = $mw->replace( '', $text );
3813 # Now match and remove the rest of them
3814 $mwa = MagicWord
::getDoubleUnderscoreArray();
3815 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3817 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3818 $this->mOutput
->mNoGallery
= true;
3820 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3821 $this->mShowToc
= false;
3823 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3824 $this->addTrackingCategory( 'hidden-category-category' );
3826 # (bug 8068) Allow control over whether robots index a page.
3828 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3829 # is not desirable, the last one on the page should win.
3830 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3831 $this->mOutput
->setIndexPolicy( 'noindex' );
3832 $this->addTrackingCategory( 'noindex-category' );
3834 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3835 $this->mOutput
->setIndexPolicy( 'index' );
3836 $this->addTrackingCategory( 'index-category' );
3839 # Cache all double underscores in the database
3840 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3841 $this->mOutput
->setProperty( $key, '' );
3844 wfProfileOut( __METHOD__
);
3849 * Add a tracking category, getting the title from a system message,
3850 * or print a debug message if the title is invalid.
3852 * @param $msg String: message key
3853 * @return Boolean: whether the addition was successful
3855 protected function addTrackingCategory( $msg ) {
3856 $cat = wfMsgForContent( $msg );
3858 # Allow tracking categories to be disabled by setting them to "-"
3859 if ( $cat === '-' ) {
3863 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3864 if ( $containerCategory ) {
3865 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3868 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3874 * This function accomplishes several tasks:
3875 * 1) Auto-number headings if that option is enabled
3876 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3877 * 3) Add a Table of contents on the top for users who have enabled the option
3878 * 4) Auto-anchor headings
3880 * It loops through all headlines, collects the necessary data, then splits up the
3881 * string and re-inserts the newly formatted headlines.
3883 * @param $text String
3884 * @param $origText String: original, untouched wikitext
3885 * @param $isMain Boolean
3888 function formatHeadings( $text, $origText, $isMain=true ) {
3889 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3891 # Inhibit editsection links if requested in the page
3892 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3895 $showEditLink = $this->mOptions
->getEditSection();
3897 if ( $showEditLink ) {
3898 $this->mOutput
->setEditSectionTokens( true );
3901 # Get all headlines for numbering them and adding funky stuff like [edit]
3902 # links - this is for later, but we need the number of headlines right now
3904 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3906 # if there are fewer than 4 headlines in the article, do not show TOC
3907 # unless it's been explicitly enabled.
3908 $enoughToc = $this->mShowToc
&&
3909 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3911 # Allow user to stipulate that a page should have a "new section"
3912 # link added via __NEWSECTIONLINK__
3913 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3914 $this->mOutput
->setNewSection( true );
3917 # Allow user to remove the "new section"
3918 # link via __NONEWSECTIONLINK__
3919 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3920 $this->mOutput
->hideNewSection( true );
3923 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3924 # override above conditions and always show TOC above first header
3925 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3926 $this->mShowToc
= true;
3934 # Ugh .. the TOC should have neat indentation levels which can be
3935 # passed to the skin functions. These are determined here
3939 $sublevelCount = array();
3940 $levelCount = array();
3945 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3946 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3947 $oldType = $this->mOutputType
;
3948 $this->setOutputType( self
::OT_WIKI
);
3949 $frame = $this->getPreprocessor()->newFrame();
3950 $root = $this->preprocessToDom( $origText );
3951 $node = $root->getFirstChild();
3956 foreach ( $matches[3] as $headline ) {
3957 $isTemplate = false;
3959 $sectionIndex = false;
3961 $markerMatches = array();
3962 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3963 $serial = $markerMatches[1];
3964 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3965 $isTemplate = ( $titleText != $baseTitleText );
3966 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3970 $prevlevel = $level;
3972 $level = $matches[1][$headlineCount];
3974 if ( $level > $prevlevel ) {
3975 # Increase TOC level
3977 $sublevelCount[$toclevel] = 0;
3978 if ( $toclevel<$wgMaxTocLevel ) {
3979 $prevtoclevel = $toclevel;
3980 $toc .= Linker
::tocIndent();
3983 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3984 # Decrease TOC level, find level to jump to
3986 for ( $i = $toclevel; $i > 0; $i-- ) {
3987 if ( $levelCount[$i] == $level ) {
3988 # Found last matching level
3991 } elseif ( $levelCount[$i] < $level ) {
3992 # Found first matching level below current level
4000 if ( $toclevel<$wgMaxTocLevel ) {
4001 if ( $prevtoclevel < $wgMaxTocLevel ) {
4002 # Unindent only if the previous toc level was shown :p
4003 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4004 $prevtoclevel = $toclevel;
4006 $toc .= Linker
::tocLineEnd();
4010 # No change in level, end TOC line
4011 if ( $toclevel<$wgMaxTocLevel ) {
4012 $toc .= Linker
::tocLineEnd();
4016 $levelCount[$toclevel] = $level;
4018 # count number of headlines for each level
4019 @$sublevelCount[$toclevel]++
;
4021 for( $i = 1; $i <= $toclevel; $i++
) {
4022 if ( !empty( $sublevelCount[$i] ) ) {
4026 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
4031 # The safe header is a version of the header text safe to use for links
4032 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4033 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4035 # Remove link placeholders by the link text.
4036 # <!--LINK number-->
4038 # link text with suffix
4039 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4041 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4042 $tocline = preg_replace(
4043 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4044 array( '', '<$1>' ),
4047 $tocline = trim( $tocline );
4049 # For the anchor, strip out HTML-y stuff period
4050 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4051 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4053 # Save headline for section edit hint before it's escaped
4054 $headlineHint = $safeHeadline;
4056 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4057 # For reverse compatibility, provide an id that's
4058 # HTML4-compatible, like we used to.
4060 # It may be worth noting, academically, that it's possible for
4061 # the legacy anchor to conflict with a non-legacy headline
4062 # anchor on the page. In this case likely the "correct" thing
4063 # would be to either drop the legacy anchors or make sure
4064 # they're numbered first. However, this would require people
4065 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4066 # manually, so let's not bother worrying about it.
4067 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4068 array( 'noninitial', 'legacy' ) );
4069 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4071 if ( $legacyHeadline == $safeHeadline ) {
4072 # No reason to have both (in fact, we can't)
4073 $legacyHeadline = false;
4076 $legacyHeadline = false;
4077 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4081 # HTML names must be case-insensitively unique (bug 10721).
4082 # This does not apply to Unicode characters per
4083 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4084 # FIXME: We may be changing them depending on the current locale.
4085 $arrayKey = strtolower( $safeHeadline );
4086 if ( $legacyHeadline === false ) {
4087 $legacyArrayKey = false;
4089 $legacyArrayKey = strtolower( $legacyHeadline );
4092 # count how many in assoc. array so we can track dupes in anchors
4093 if ( isset( $refers[$arrayKey] ) ) {
4094 $refers[$arrayKey]++
;
4096 $refers[$arrayKey] = 1;
4098 if ( isset( $refers[$legacyArrayKey] ) ) {
4099 $refers[$legacyArrayKey]++
;
4101 $refers[$legacyArrayKey] = 1;
4104 # Don't number the heading if it is the only one (looks silly)
4105 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4106 # the two are different if the line contains a link
4107 $headline = $numbering . ' ' . $headline;
4110 # Create the anchor for linking from the TOC to the section
4111 $anchor = $safeHeadline;
4112 $legacyAnchor = $legacyHeadline;
4113 if ( $refers[$arrayKey] > 1 ) {
4114 $anchor .= '_' . $refers[$arrayKey];
4116 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4117 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4119 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4120 $toc .= Linker
::tocLine( $anchor, $tocline,
4121 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4124 # Add the section to the section tree
4125 # Find the DOM node for this header
4126 while ( $node && !$isTemplate ) {
4127 if ( $node->getName() === 'h' ) {
4128 $bits = $node->splitHeading();
4129 if ( $bits['i'] == $sectionIndex ) {
4133 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4134 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4135 $node = $node->getNextSibling();
4138 'toclevel' => $toclevel,
4141 'number' => $numbering,
4142 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4143 'fromtitle' => $titleText,
4144 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4145 'anchor' => $anchor,
4148 # give headline the correct <h#> tag
4149 if ( $showEditLink && $sectionIndex !== false ) {
4150 // Output edit section links as markers with styles that can be customized by skins
4151 if ( $isTemplate ) {
4152 # Put a T flag in the section identifier, to indicate to extractSections()
4153 # that sections inside <includeonly> should be counted.
4154 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4156 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4158 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4159 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4160 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4161 // so we don't have to worry about a user trying to input one of these markers directly.
4162 // We use a page and section attribute to stop the language converter from converting these important bits
4163 // of data, but put the headline hint inside a content block because the language converter is supposed to
4164 // be able to convert that piece of data.
4165 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4166 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4167 if ( isset($editlinkArgs[2]) ) {
4168 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4175 $head[$headlineCount] = Linker
::makeHeadline( $level,
4176 $matches['attrib'][$headlineCount], $anchor, $headline,
4177 $editlink, $legacyAnchor );
4182 $this->setOutputType( $oldType );
4184 # Never ever show TOC if no headers
4185 if ( $numVisible < 1 ) {
4190 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4191 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4193 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4194 $this->mOutput
->setTOCHTML( $toc );
4198 $this->mOutput
->setSections( $tocraw );
4201 # split up and insert constructed headlines
4203 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4206 foreach ( $blocks as $block ) {
4207 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4208 # This is the [edit] link that appears for the top block of text when
4209 # section editing is enabled
4211 # Disabled because it broke block formatting
4212 # For example, a bullet point in the top line
4213 # $full .= $sk->editSectionLink(0);
4216 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4217 # Top anchor now in skin
4221 if ( !empty( $head[$i] ) ) {
4226 if ( $this->mForceTocPosition
) {
4227 return str_replace( '<!--MWTOC-->', $toc, $full );
4234 * Transform wiki markup when saving a page by doing \r\n -> \n
4235 * conversion, substitting signatures, {{subst:}} templates, etc.
4237 * @param $text String: the text to transform
4238 * @param $title Title: the Title object for the current article
4239 * @param $user User: the User object describing the current user
4240 * @param $options ParserOptions: parsing options
4241 * @param $clearState Boolean: whether to clear the parser state first
4242 * @return String: the altered wiki markup
4244 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4245 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4246 $this->setUser( $user );
4251 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4252 if( $options->getPreSaveTransform() ) {
4253 $text = $this->pstPass2( $text, $user );
4255 $text = $this->mStripState
->unstripBoth( $text );
4257 $this->setUser( null ); #Reset
4263 * Pre-save transform helper function
4266 function pstPass2( $text, $user ) {
4267 global $wgContLang, $wgLocaltimezone;
4269 # Note: This is the timestamp saved as hardcoded wikitext to
4270 # the database, we use $wgContLang here in order to give
4271 # everyone the same signature and use the default one rather
4272 # than the one selected in each user's preferences.
4273 # (see also bug 12815)
4274 $ts = $this->mOptions
->getTimestamp();
4275 if ( isset( $wgLocaltimezone ) ) {
4276 $tz = $wgLocaltimezone;
4278 $tz = date_default_timezone_get();
4281 $unixts = wfTimestamp( TS_UNIX
, $ts );
4282 $oldtz = date_default_timezone_get();
4283 date_default_timezone_set( $tz );
4284 $ts = date( 'YmdHis', $unixts );
4285 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4287 # Allow translation of timezones through wiki. date() can return
4288 # whatever crap the system uses, localised or not, so we cannot
4289 # ship premade translations.
4290 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4291 $msg = wfMessage( $key )->inContentLanguage();
4292 if ( $msg->exists() ) {
4293 $tzMsg = $msg->text();
4296 date_default_timezone_set( $oldtz );
4298 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4300 # Variable replacement
4301 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4302 $text = $this->replaceVariables( $text );
4304 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4305 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4308 $sigText = $this->getUserSig( $user );
4309 $text = strtr( $text, array(
4311 '~~~~' => "$sigText $d",
4315 # Context links: [[|name]] and [[name (context)|]]
4316 global $wgLegalTitleChars;
4317 $tc = "[$wgLegalTitleChars]";
4318 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4320 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4321 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4322 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4323 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4325 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4326 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4327 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4328 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4330 $t = $this->mTitle
->getText();
4332 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4333 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4334 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4335 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4337 # if there's no context, don't bother duplicating the title
4338 $text = preg_replace( $p2, '[[\\1]]', $text );
4341 # Trim trailing whitespace
4342 $text = rtrim( $text );
4348 * Fetch the user's signature text, if any, and normalize to
4349 * validated, ready-to-insert wikitext.
4350 * If you have pre-fetched the nickname or the fancySig option, you can
4351 * specify them here to save a database query.
4352 * Do not reuse this parser instance after calling getUserSig(),
4353 * as it may have changed if it's the $wgParser.
4356 * @param $nickname String: nickname to use or false to use user's default nickname
4357 * @param $fancySig Boolean: whether the nicknname is the complete signature
4358 * or null to use default value
4361 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4362 global $wgMaxSigChars;
4364 $username = $user->getName();
4366 # If not given, retrieve from the user object.
4367 if ( $nickname === false )
4368 $nickname = $user->getOption( 'nickname' );
4370 if ( is_null( $fancySig ) ) {
4371 $fancySig = $user->getBoolOption( 'fancysig' );
4374 $nickname = $nickname == null ?
$username : $nickname;
4376 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4377 $nickname = $username;
4378 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4379 } elseif ( $fancySig !== false ) {
4380 # Sig. might contain markup; validate this
4381 if ( $this->validateSig( $nickname ) !== false ) {
4382 # Validated; clean up (if needed) and return it
4383 return $this->cleanSig( $nickname, true );
4385 # Failed to validate; fall back to the default
4386 $nickname = $username;
4387 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4391 # Make sure nickname doesnt get a sig in a sig
4392 $nickname = $this->cleanSigInSig( $nickname );
4394 # If we're still here, make it a link to the user page
4395 $userText = wfEscapeWikiText( $username );
4396 $nickText = wfEscapeWikiText( $nickname );
4397 if ( $user->isAnon() ) {
4398 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4400 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4405 * Check that the user's signature contains no bad XML
4407 * @param $text String
4408 * @return mixed An expanded string, or false if invalid.
4410 function validateSig( $text ) {
4411 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4415 * Clean up signature text
4417 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4418 * 2) Substitute all transclusions
4420 * @param $text String
4421 * @param $parsing Whether we're cleaning (preferences save) or parsing
4422 * @return String: signature text
4424 function cleanSig( $text, $parsing = false ) {
4427 $this->mOptions
= new ParserOptions
;
4428 $this->clearState();
4429 $this->setTitle( $wgTitle );
4430 $this->setOutputType
= self
::OT_PREPROCESS
;
4433 # Option to disable this feature
4434 if ( !$this->mOptions
->getCleanSignatures() ) {
4438 # FIXME: regex doesn't respect extension tags or nowiki
4439 # => Move this logic to braceSubstitution()
4440 $substWord = MagicWord
::get( 'subst' );
4441 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4442 $substText = '{{' . $substWord->getSynonym( 0 );
4444 $text = preg_replace( $substRegex, $substText, $text );
4445 $text = $this->cleanSigInSig( $text );
4446 $dom = $this->preprocessToDom( $text );
4447 $frame = $this->getPreprocessor()->newFrame();
4448 $text = $frame->expand( $dom );
4451 $text = $this->mStripState
->unstripBoth( $text );
4458 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4460 * @param $text String
4461 * @return String: signature text with /~{3,5}/ removed
4463 function cleanSigInSig( $text ) {
4464 $text = preg_replace( '/~{3,5}/', '', $text );
4469 * Set up some variables which are usually set up in parse()
4470 * so that an external function can call some class members with confidence
4472 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4473 $this->startParse( $title, $options, $outputType, $clearState );
4476 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4477 $this->setTitle( $title );
4478 $this->mOptions
= $options;
4479 $this->setOutputType( $outputType );
4480 if ( $clearState ) {
4481 $this->clearState();
4486 * Wrapper for preprocess()
4488 * @param $text String: the text to preprocess
4489 * @param $options ParserOptions: options
4490 * @param $title Title object or null to use $wgTitle
4493 public function transformMsg( $text, $options, $title = null ) {
4494 static $executing = false;
4496 # Guard against infinite recursion
4502 wfProfileIn( __METHOD__
);
4508 # It's not uncommon having a null $wgTitle in scripts. See r80898
4509 # Create a ghost title in such case
4510 $title = Title
::newFromText( 'Dwimmerlaik' );
4512 $text = $this->preprocess( $text, $title, $options );
4515 wfProfileOut( __METHOD__
);
4520 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4521 * The callback should have the following form:
4522 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4524 * Transform and return $text. Use $parser for any required context, e.g. use
4525 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4527 * Hooks may return extended information by returning an array, of which the
4528 * first numbered element (index 0) must be the return string, and all other
4529 * entries are extracted into local variables within an internal function
4530 * in the Parser class.
4532 * This interface (introduced r61913) appears to be undocumented, but
4533 * 'markerName' is used by some core tag hooks to override which strip
4534 * array their results are placed in. **Use great caution if attempting
4535 * this interface, as it is not documented and injudicious use could smash
4536 * private variables.**
4538 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4539 * @param $callback Mixed: the callback function (and object) to use for the tag
4540 * @return The old value of the mTagHooks array associated with the hook
4542 public function setHook( $tag, $callback ) {
4543 $tag = strtolower( $tag );
4544 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4545 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4546 $this->mTagHooks
[$tag] = $callback;
4547 if ( !in_array( $tag, $this->mStripList
) ) {
4548 $this->mStripList
[] = $tag;
4555 * As setHook(), but letting the contents be parsed.
4557 * Transparent tag hooks are like regular XML-style tag hooks, except they
4558 * operate late in the transformation sequence, on HTML instead of wikitext.
4560 * This is probably obsoleted by things dealing with parser frames?
4561 * The only extension currently using it is geoserver.
4564 * @todo better document or deprecate this
4566 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4567 * @param $callback Mixed: the callback function (and object) to use for the tag
4568 * @return The old value of the mTagHooks array associated with the hook
4570 function setTransparentTagHook( $tag, $callback ) {
4571 $tag = strtolower( $tag );
4572 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4573 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4574 $this->mTransparentTagHooks
[$tag] = $callback;
4580 * Remove all tag hooks
4582 function clearTagHooks() {
4583 $this->mTagHooks
= array();
4584 $this->mStripList
= $this->mDefaultStripList
;
4588 * Create a function, e.g. {{sum:1|2|3}}
4589 * The callback function should have the form:
4590 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4592 * Or with SFH_OBJECT_ARGS:
4593 * function myParserFunction( $parser, $frame, $args ) { ... }
4595 * The callback may either return the text result of the function, or an array with the text
4596 * in element 0, and a number of flags in the other elements. The names of the flags are
4597 * specified in the keys. Valid flags are:
4598 * found The text returned is valid, stop processing the template. This
4600 * nowiki Wiki markup in the return value should be escaped
4601 * isHTML The returned text is HTML, armour it against wikitext transformation
4603 * @param $id String: The magic word ID
4604 * @param $callback Mixed: the callback function (and object) to use
4605 * @param $flags Integer: a combination of the following flags:
4606 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4608 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4609 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4610 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4611 * the arguments, and to control the way they are expanded.
4613 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4614 * arguments, for instance:
4615 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4617 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4618 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4619 * working if/when this is changed.
4621 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4624 * Please read the documentation in includes/parser/Preprocessor.php for more information
4625 * about the methods available in PPFrame and PPNode.
4627 * @return The old callback function for this name, if any
4629 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4632 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4633 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4635 # Add to function cache
4636 $mw = MagicWord
::get( $id );
4638 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4640 $synonyms = $mw->getSynonyms();
4641 $sensitive = intval( $mw->isCaseSensitive() );
4643 foreach ( $synonyms as $syn ) {
4645 if ( !$sensitive ) {
4646 $syn = $wgContLang->lc( $syn );
4649 if ( !( $flags & SFH_NO_HASH
) ) {
4652 # Remove trailing colon
4653 if ( substr( $syn, -1, 1 ) === ':' ) {
4654 $syn = substr( $syn, 0, -1 );
4656 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4662 * Get all registered function hook identifiers
4666 function getFunctionHooks() {
4667 return array_keys( $this->mFunctionHooks
);
4671 * Create a tag function, e.g. <test>some stuff</test>.
4672 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4673 * Unlike parser functions, their content is not preprocessed.
4675 function setFunctionTagHook( $tag, $callback, $flags ) {
4676 $tag = strtolower( $tag );
4677 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4678 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4679 $this->mFunctionTagHooks
[$tag] : null;
4680 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4682 if ( !in_array( $tag, $this->mStripList
) ) {
4683 $this->mStripList
[] = $tag;
4690 * FIXME: update documentation. makeLinkObj() is deprecated.
4691 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4692 * Placeholders created in Skin::makeLinkObj()
4693 * Returns an array of link CSS classes, indexed by PDBK.
4695 function replaceLinkHolders( &$text, $options = 0 ) {
4696 return $this->mLinkHolders
->replace( $text );
4700 * Replace <!--LINK--> link placeholders with plain text of links
4701 * (not HTML-formatted).
4703 * @param $text String
4706 function replaceLinkHoldersText( $text ) {
4707 return $this->mLinkHolders
->replaceText( $text );
4711 * Renders an image gallery from a text with one line per image.
4712 * text labels may be given by using |-style alternative text. E.g.
4713 * Image:one.jpg|The number "1"
4714 * Image:tree.jpg|A tree
4715 * given as text will return the HTML of a gallery with two images,
4716 * labeled 'The number "1"' and
4719 * @param string $text
4720 * @param array $param
4721 * @return string HTML
4723 function renderImageGallery( $text, $params ) {
4724 $ig = new ImageGallery();
4725 $ig->setContextTitle( $this->mTitle
);
4726 $ig->setShowBytes( false );
4727 $ig->setShowFilename( false );
4728 $ig->setParser( $this );
4729 $ig->setHideBadImages();
4730 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4732 if ( isset( $params['showfilename'] ) ) {
4733 $ig->setShowFilename( true );
4735 $ig->setShowFilename( false );
4737 if ( isset( $params['caption'] ) ) {
4738 $caption = $params['caption'];
4739 $caption = htmlspecialchars( $caption );
4740 $caption = $this->replaceInternalLinks( $caption );
4741 $ig->setCaptionHtml( $caption );
4743 if ( isset( $params['perrow'] ) ) {
4744 $ig->setPerRow( $params['perrow'] );
4746 if ( isset( $params['widths'] ) ) {
4747 $ig->setWidths( $params['widths'] );
4749 if ( isset( $params['heights'] ) ) {
4750 $ig->setHeights( $params['heights'] );
4753 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4755 $lines = StringUtils
::explode( "\n", $text );
4756 foreach ( $lines as $line ) {
4757 # match lines like these:
4758 # Image:someimage.jpg|This is some image
4760 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4762 if ( count( $matches ) == 0 ) {
4766 if ( strpos( $matches[0], '%' ) !== false ) {
4767 $matches[1] = rawurldecode( $matches[1] );
4769 $title = Title
::newFromText( $matches[1], NS_FILE
);
4770 if ( is_null( $title ) ) {
4771 # Bogus title. Ignore these so we don't bomb out later.
4777 if ( isset( $matches[3] ) ) {
4778 // look for an |alt= definition while trying not to break existing
4779 // captions with multiple pipes (|) in it, until a more sensible grammar
4780 // is defined for images in galleries
4782 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4783 $altmatches = StringUtils
::explode('|', $matches[3]);
4784 $magicWordAlt = MagicWord
::get( 'img_alt' );
4786 foreach ( $altmatches as $altmatch ) {
4787 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4789 $alt = $this->stripAltText( $match, false );
4792 // concatenate all other pipes
4793 $label .= '|' . $altmatch;
4796 // remove the first pipe
4797 $label = substr( $label, 1 );
4800 $ig->add( $title, $label, $alt );
4802 return $ig->toHTML();
4805 function getImageParams( $handler ) {
4807 $handlerClass = get_class( $handler );
4811 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4812 # Initialise static lists
4813 static $internalParamNames = array(
4814 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4815 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4816 'bottom', 'text-bottom' ),
4817 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4818 'upright', 'border', 'link', 'alt' ),
4820 static $internalParamMap;
4821 if ( !$internalParamMap ) {
4822 $internalParamMap = array();
4823 foreach ( $internalParamNames as $type => $names ) {
4824 foreach ( $names as $name ) {
4825 $magicName = str_replace( '-', '_', "img_$name" );
4826 $internalParamMap[$magicName] = array( $type, $name );
4831 # Add handler params
4832 $paramMap = $internalParamMap;
4834 $handlerParamMap = $handler->getParamMap();
4835 foreach ( $handlerParamMap as $magic => $paramName ) {
4836 $paramMap[$magic] = array( 'handler', $paramName );
4839 $this->mImageParams
[$handlerClass] = $paramMap;
4840 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4842 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4846 * Parse image options text and use it to make an image
4848 * @param $title Title
4849 * @param $options String
4850 * @param $holders LinkHolderArray
4851 * @return string HTML
4853 function makeImage( $title, $options, $holders = false ) {
4854 # Check if the options text is of the form "options|alt text"
4856 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4857 # * left no resizing, just left align. label is used for alt= only
4858 # * right same, but right aligned
4859 # * none same, but not aligned
4860 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4861 # * center center the image
4862 # * frame Keep original image size, no magnify-button.
4863 # * framed Same as "frame"
4864 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4865 # * upright reduce width for upright images, rounded to full __0 px
4866 # * border draw a 1px border around the image
4867 # * alt Text for HTML alt attribute (defaults to empty)
4868 # * link Set the target of the image link. Can be external, interwiki, or local
4869 # vertical-align values (no % or length right now):
4879 $parts = StringUtils
::explode( "|", $options );
4881 # Give extensions a chance to select the file revision for us
4882 $time = $sha1 = $descQuery = false;
4883 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4884 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4885 # Fetch and register the file (file title may be different via hooks)
4886 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4889 $handler = $file ?
$file->getHandler() : false;
4891 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4894 $this->addTrackingCategory( 'broken-file-category' );
4897 # Process the input parameters
4899 $params = array( 'frame' => array(), 'handler' => array(),
4900 'horizAlign' => array(), 'vertAlign' => array() );
4901 foreach ( $parts as $part ) {
4902 $part = trim( $part );
4903 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4905 if ( isset( $paramMap[$magicName] ) ) {
4906 list( $type, $paramName ) = $paramMap[$magicName];
4908 # Special case; width and height come in one variable together
4909 if ( $type === 'handler' && $paramName === 'width' ) {
4911 # (bug 13500) In both cases (width/height and width only),
4912 # permit trailing "px" for backward compatibility.
4913 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4914 $width = intval( $m[1] );
4915 $height = intval( $m[2] );
4916 if ( $handler->validateParam( 'width', $width ) ) {
4917 $params[$type]['width'] = $width;
4920 if ( $handler->validateParam( 'height', $height ) ) {
4921 $params[$type]['height'] = $height;
4924 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4925 $width = intval( $value );
4926 if ( $handler->validateParam( 'width', $width ) ) {
4927 $params[$type]['width'] = $width;
4930 } # else no validation -- bug 13436
4932 if ( $type === 'handler' ) {
4933 # Validate handler parameter
4934 $validated = $handler->validateParam( $paramName, $value );
4936 # Validate internal parameters
4937 switch( $paramName ) {
4940 # @todo Fixme: possibly check validity here for
4941 # manualthumb? downstream behavior seems odd with
4942 # missing manual thumbs.
4944 $value = $this->stripAltText( $value, $holders );
4947 $chars = self
::EXT_LINK_URL_CLASS
;
4948 $prots = $this->mUrlProtocols
;
4949 if ( $value === '' ) {
4950 $paramName = 'no-link';
4953 } elseif ( preg_match( "/^$prots/", $value ) ) {
4954 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4955 $paramName = 'link-url';
4956 $this->mOutput
->addExternalLink( $value );
4957 if ( $this->mOptions
->getExternalLinkTarget() ) {
4958 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4963 $linkTitle = Title
::newFromText( $value );
4965 $paramName = 'link-title';
4966 $value = $linkTitle;
4967 $this->mOutput
->addLink( $linkTitle );
4973 # Most other things appear to be empty or numeric...
4974 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4979 $params[$type][$paramName] = $value;
4983 if ( !$validated ) {
4988 # Process alignment parameters
4989 if ( $params['horizAlign'] ) {
4990 $params['frame']['align'] = key( $params['horizAlign'] );
4992 if ( $params['vertAlign'] ) {
4993 $params['frame']['valign'] = key( $params['vertAlign'] );
4996 $params['frame']['caption'] = $caption;
4998 # Will the image be presented in a frame, with the caption below?
4999 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5000 isset( $params['frame']['framed'] ) ||
5001 isset( $params['frame']['thumbnail'] ) ||
5002 isset( $params['frame']['manualthumb'] );
5004 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5005 # came to also set the caption, ordinary text after the image -- which
5006 # makes no sense, because that just repeats the text multiple times in
5007 # screen readers. It *also* came to set the title attribute.
5009 # Now that we have an alt attribute, we should not set the alt text to
5010 # equal the caption: that's worse than useless, it just repeats the
5011 # text. This is the framed/thumbnail case. If there's no caption, we
5012 # use the unnamed parameter for alt text as well, just for the time be-
5013 # ing, if the unnamed param is set and the alt param is not.
5015 # For the future, we need to figure out if we want to tweak this more,
5016 # e.g., introducing a title= parameter for the title; ignoring the un-
5017 # named parameter entirely for images without a caption; adding an ex-
5018 # plicit caption= parameter and preserving the old magic unnamed para-
5020 if ( $imageIsFramed ) { # Framed image
5021 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5022 # No caption or alt text, add the filename as the alt text so
5023 # that screen readers at least get some description of the image
5024 $params['frame']['alt'] = $title->getText();
5026 # Do not set $params['frame']['title'] because tooltips don't make sense
5028 } else { # Inline image
5029 if ( !isset( $params['frame']['alt'] ) ) {
5030 # No alt text, use the "caption" for the alt text
5031 if ( $caption !== '') {
5032 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5034 # No caption, fall back to using the filename for the
5036 $params['frame']['alt'] = $title->getText();
5039 # Use the "caption" for the tooltip text
5040 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5043 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5045 # Linker does the rest
5046 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5047 $time, $descQuery, $this->mOptions
->getThumbSize() );
5049 # Give the handler a chance to modify the parser object
5051 $handler->parserTransformHook( $this, $file );
5057 protected function stripAltText( $caption, $holders ) {
5058 # Strip bad stuff out of the title (tooltip). We can't just use
5059 # replaceLinkHoldersText() here, because if this function is called
5060 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5062 $tooltip = $holders->replaceText( $caption );
5064 $tooltip = $this->replaceLinkHoldersText( $caption );
5067 # make sure there are no placeholders in thumbnail attributes
5068 # that are later expanded to html- so expand them now and
5070 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5071 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5077 * Set a flag in the output object indicating that the content is dynamic and
5078 * shouldn't be cached.
5080 function disableCache() {
5081 wfDebug( "Parser output marked as uncacheable.\n" );
5082 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5083 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5087 * Callback from the Sanitizer for expanding items found in HTML attribute
5088 * values, so they can be safely tested and escaped.
5090 * @param $text String
5091 * @param $frame PPFrame
5094 function attributeStripCallback( &$text, $frame = false ) {
5095 $text = $this->replaceVariables( $text, $frame );
5096 $text = $this->mStripState
->unstripBoth( $text );
5105 function getTags() {
5106 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5110 * Replace transparent tags in $text with the values given by the callbacks.
5112 * Transparent tag hooks are like regular XML-style tag hooks, except they
5113 * operate late in the transformation sequence, on HTML instead of wikitext.
5115 function replaceTransparentTags( $text ) {
5117 $elements = array_keys( $this->mTransparentTagHooks
);
5118 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5120 foreach ( $matches as $marker => $data ) {
5121 list( $element, $content, $params, $tag ) = $data;
5122 $tagName = strtolower( $element );
5123 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5124 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5128 $this->mStripState
->addGeneral( $marker, $output );
5134 * Break wikitext input into sections, and either pull or replace
5135 * some particular section's text.
5137 * External callers should use the getSection and replaceSection methods.
5139 * @param $text String: Page wikitext
5140 * @param $section String: a section identifier string of the form:
5141 * <flag1> - <flag2> - ... - <section number>
5143 * Currently the only recognised flag is "T", which means the target section number
5144 * was derived during a template inclusion parse, in other words this is a template
5145 * section edit link. If no flags are given, it was an ordinary section edit link.
5146 * This flag is required to avoid a section numbering mismatch when a section is
5147 * enclosed by <includeonly> (bug 6563).
5149 * The section number 0 pulls the text before the first heading; other numbers will
5150 * pull the given section along with its lower-level subsections. If the section is
5151 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5153 * @param $mode String: one of "get" or "replace"
5154 * @param $newText String: replacement text for section data.
5155 * @return String: for "get", the extracted section text.
5156 * for "replace", the whole page with the section replaced.
5158 private function extractSections( $text, $section, $mode, $newText='' ) {
5159 global $wgTitle; # not generally used but removes an ugly failure mode
5160 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5162 $frame = $this->getPreprocessor()->newFrame();
5164 # Process section extraction flags
5166 $sectionParts = explode( '-', $section );
5167 $sectionIndex = array_pop( $sectionParts );
5168 foreach ( $sectionParts as $part ) {
5169 if ( $part === 'T' ) {
5170 $flags |
= self
::PTD_FOR_INCLUSION
;
5173 # Preprocess the text
5174 $root = $this->preprocessToDom( $text, $flags );
5176 # <h> nodes indicate section breaks
5177 # They can only occur at the top level, so we can find them by iterating the root's children
5178 $node = $root->getFirstChild();
5180 # Find the target section
5181 if ( $sectionIndex == 0 ) {
5182 # Section zero doesn't nest, level=big
5183 $targetLevel = 1000;
5185 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5190 if ( $node->getName() === 'h' ) {
5191 $bits = $node->splitHeading();
5192 if ( $bits['i'] == $sectionIndex ) {
5193 $targetLevel = $bits['level'];
5197 if ( $mode === 'replace' ) {
5198 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5200 $node = $node->getNextSibling();
5206 if ( $mode === 'get' ) {
5213 # Find the end of the section, including nested sections
5215 if ( $node->getName() === 'h' ) {
5216 $bits = $node->splitHeading();
5217 $curLevel = $bits['level'];
5218 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5222 if ( $mode === 'get' ) {
5223 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5225 $node = $node->getNextSibling();
5228 # Write out the remainder (in replace mode only)
5229 if ( $mode === 'replace' ) {
5230 # Output the replacement text
5231 # Add two newlines on -- trailing whitespace in $newText is conventionally
5232 # stripped by the editor, so we need both newlines to restore the paragraph gap
5233 # Only add trailing whitespace if there is newText
5234 if ( $newText != "" ) {
5235 $outText .= $newText . "\n\n";
5239 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5240 $node = $node->getNextSibling();
5244 if ( is_string( $outText ) ) {
5245 # Re-insert stripped tags
5246 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5253 * This function returns the text of a section, specified by a number ($section).
5254 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5255 * the first section before any such heading (section 0).
5257 * If a section contains subsections, these are also returned.
5259 * @param $text String: text to look in
5260 * @param $section String: section identifier
5261 * @param $deftext String: default to return if section is not found
5262 * @return string text of the requested section
5264 public function getSection( $text, $section, $deftext='' ) {
5265 return $this->extractSections( $text, $section, "get", $deftext );
5269 * This function returns $oldtext after the content of the section
5270 * specified by $section has been replaced with $text.
5272 * @param $oldtext String: former text of the article
5273 * @param $section Numeric: section identifier
5274 * @param $text String: replacing text
5275 * @return String: modified text
5277 public function replaceSection( $oldtext, $section, $text ) {
5278 return $this->extractSections( $oldtext, $section, "replace", $text );
5282 * Get the ID of the revision we are parsing
5284 * @return Mixed: integer or null
5286 function getRevisionId() {
5287 return $this->mRevisionId
;
5291 * Get the revision object for $this->mRevisionId
5293 * @return Revision|null either a Revision object or null
5295 protected function getRevisionObject() {
5296 if ( !is_null( $this->mRevisionObject
) ) {
5297 return $this->mRevisionObject
;
5299 if ( is_null( $this->mRevisionId
) ) {
5303 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5304 return $this->mRevisionObject
;
5308 * Get the timestamp associated with the current revision, adjusted for
5309 * the default server-local timestamp
5311 function getRevisionTimestamp() {
5312 if ( is_null( $this->mRevisionTimestamp
) ) {
5313 wfProfileIn( __METHOD__
);
5315 $revObject = $this->getRevisionObject();
5316 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5318 if( $timestamp !== false ) {
5321 # The cryptic '' timezone parameter tells to use the site-default
5322 # timezone offset instead of the user settings.
5324 # Since this value will be saved into the parser cache, served
5325 # to other users, and potentially even used inside links and such,
5326 # it needs to be consistent for all visitors.
5327 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5330 wfProfileOut( __METHOD__
);
5332 return $this->mRevisionTimestamp
;
5336 * Get the name of the user that edited the last revision
5338 * @return String: user name
5340 function getRevisionUser() {
5341 if( is_null( $this->mRevisionUser
) ) {
5342 $revObject = $this->getRevisionObject();
5344 # if this template is subst: the revision id will be blank,
5345 # so just use the current user's name
5347 $this->mRevisionUser
= $revObject->getUserText();
5348 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5349 $this->mRevisionUser
= $this->getUser()->getName();
5352 return $this->mRevisionUser
;
5356 * Mutator for $mDefaultSort
5358 * @param $sort New value
5360 public function setDefaultSort( $sort ) {
5361 $this->mDefaultSort
= $sort;
5362 $this->mOutput
->setProperty( 'defaultsort', $sort );
5366 * Accessor for $mDefaultSort
5367 * Will use the empty string if none is set.
5369 * This value is treated as a prefix, so the
5370 * empty string is equivalent to sorting by
5375 public function getDefaultSort() {
5376 if ( $this->mDefaultSort
!== false ) {
5377 return $this->mDefaultSort
;
5384 * Accessor for $mDefaultSort
5385 * Unlike getDefaultSort(), will return false if none is set
5387 * @return string or false
5389 public function getCustomDefaultSort() {
5390 return $this->mDefaultSort
;
5394 * Try to guess the section anchor name based on a wikitext fragment
5395 * presumably extracted from a heading, for example "Header" from
5398 public function guessSectionNameFromWikiText( $text ) {
5399 # Strip out wikitext links(they break the anchor)
5400 $text = $this->stripSectionName( $text );
5401 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5402 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5406 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5407 * instead. For use in redirects, since IE6 interprets Redirect: headers
5408 * as something other than UTF-8 (apparently?), resulting in breakage.
5410 * @param $text String: The section name
5411 * @return string An anchor
5413 public function guessLegacySectionNameFromWikiText( $text ) {
5414 # Strip out wikitext links(they break the anchor)
5415 $text = $this->stripSectionName( $text );
5416 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5417 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5421 * Strips a text string of wikitext for use in a section anchor
5423 * Accepts a text string and then removes all wikitext from the
5424 * string and leaves only the resultant text (i.e. the result of
5425 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5426 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5427 * to create valid section anchors by mimicing the output of the
5428 * parser when headings are parsed.
5430 * @param $text String: text string to be stripped of wikitext
5431 * for use in a Section anchor
5432 * @return Filtered text string
5434 public function stripSectionName( $text ) {
5435 # Strip internal link markup
5436 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5437 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5439 # Strip external link markup (FIXME: Not Tolerant to blank link text
5440 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5441 # on how many empty links there are on the page - need to figure that out.
5442 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5444 # Parse wikitext quotes (italics & bold)
5445 $text = $this->doQuotes( $text );
5448 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5453 * strip/replaceVariables/unstrip for preprocessor regression testing
5457 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5458 if ( !$title instanceof Title
) {
5459 $title = Title
::newFromText( $title );
5461 $this->startParse( $title, $options, $outputType, true );
5463 $text = $this->replaceVariables( $text );
5464 $text = $this->mStripState
->unstripBoth( $text );
5465 $text = Sanitizer
::removeHTMLtags( $text );
5469 function testPst( $text, $title, $options ) {
5471 if ( !$title instanceof Title
) {
5472 $title = Title
::newFromText( $title );
5474 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5477 function testPreprocess( $text, $title, $options ) {
5478 if ( !$title instanceof Title
) {
5479 $title = Title
::newFromText( $title );
5481 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5485 * Call a callback function on all regions of the given text that are not
5486 * inside strip markers, and replace those regions with the return value
5487 * of the callback. For example, with input:
5491 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5492 * two strings will be replaced with the value returned by the callback in
5497 function markerSkipCallback( $s, $callback ) {
5500 while ( $i < strlen( $s ) ) {
5501 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5502 if ( $markerStart === false ) {
5503 $out .= call_user_func( $callback, substr( $s, $i ) );
5506 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5507 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5508 if ( $markerEnd === false ) {
5509 $out .= substr( $s, $markerStart );
5512 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5513 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5522 * Save the parser state required to convert the given half-parsed text to
5523 * HTML. "Half-parsed" in this context means the output of
5524 * recursiveTagParse() or internalParse(). This output has strip markers
5525 * from replaceVariables (extensionSubstitution() etc.), and link
5526 * placeholders from replaceLinkHolders().
5528 * Returns an array which can be serialized and stored persistently. This
5529 * array can later be loaded into another parser instance with
5530 * unserializeHalfParsedText(). The text can then be safely incorporated into
5531 * the return value of a parser hook.
5535 function serializeHalfParsedText( $text ) {
5536 wfProfileIn( __METHOD__
);
5539 'version' => self
::HALF_PARSED_VERSION
,
5540 'stripState' => $this->mStripState
->getSubState( $text ),
5541 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5543 wfProfileOut( __METHOD__
);
5548 * Load the parser state given in the $data array, which is assumed to
5549 * have been generated by serializeHalfParsedText(). The text contents is
5550 * extracted from the array, and its markers are transformed into markers
5551 * appropriate for the current Parser instance. This transformed text is
5552 * returned, and can be safely included in the return value of a parser
5555 * If the $data array has been stored persistently, the caller should first
5556 * check whether it is still valid, by calling isValidHalfParsedText().
5558 * @param $data Serialized data
5561 function unserializeHalfParsedText( $data ) {
5562 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5563 throw new MWException( __METHOD__
.': invalid version' );
5566 # First, extract the strip state.
5567 $texts = array( $data['text'] );
5568 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5570 # Now renumber links
5571 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5573 # Should be good to go.
5578 * Returns true if the given array, presumed to be generated by
5579 * serializeHalfParsedText(), is compatible with the current version of the
5582 * @param $data Array
5586 function isValidHalfParsedText( $data ) {
5587 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;