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 $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.4';
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 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
72 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
73 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
74 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
75 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
77 # State constants for the definition list colon extraction
78 const COLON_STATE_TEXT
= 0;
79 const COLON_STATE_TAG
= 1;
80 const COLON_STATE_TAGSTART
= 2;
81 const COLON_STATE_CLOSETAG
= 3;
82 const COLON_STATE_TAGSLASH
= 4;
83 const COLON_STATE_COMMENT
= 5;
84 const COLON_STATE_COMMENTDASH
= 6;
85 const COLON_STATE_COMMENTDASHDASH
= 7;
87 # Flags for preprocessToDom
88 const PTD_FOR_INCLUSION
= 1;
90 # Allowed values for $this->mOutputType
91 # Parameter to startExternalParse().
92 const OT_HTML
= 1; # like parse()
93 const OT_WIKI
= 2; # like preSaveTransform()
94 const OT_PREPROCESS
= 3; # like preprocess()
96 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
98 # Marker Suffix needs to be accessible staticly.
99 const MARKER_SUFFIX
= "-QINU\x7f";
102 var $mTagHooks = array();
103 var $mTransparentTagHooks = array();
104 var $mFunctionHooks = array();
105 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
106 var $mFunctionTagHooks = array();
107 var $mStripList = array();
108 var $mDefaultStripList = array();
109 var $mVarCache = array();
110 var $mImageParams = array();
111 var $mImageParamsMagicArray = array();
112 var $mMarkerIndex = 0;
113 var $mFirstCall = true;
115 # Initialised by initialiseVariables()
118 * @var MagicWordArray
123 * @var MagicWordArray
126 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
128 # Cleared with clearState():
133 var $mAutonumber, $mDTopen;
140 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
142 * @var LinkHolderArray
147 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
148 var $mTplExpandCache; # empty-frame expansion cache
149 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
150 var $mExpensiveFunctionCount; # number of expensive parser function calls
151 var $mShowToc, $mForceTocPosition;
156 var $mUser; # User object; only used when doing pre-save transform
159 # These are variables reset at least once per parse regardless of $clearState
169 var $mTitle; # Title context, used for self-link rendering and similar things
170 var $mOutputType; # Output type, one of the OT_xxx constants
171 var $ot; # Shortcut alias, see setOutputType()
172 var $mRevisionObject; # The revision object of the specified revision ID
173 var $mRevisionId; # ID to display in {{REVISIONID}} tags
174 var $mRevisionTimestamp; # The timestamp of the specified revision ID
175 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
176 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
188 public function __construct( $conf = array() ) {
189 $this->mConf
= $conf;
190 $this->mUrlProtocols
= wfUrlProtocols();
191 $this->mExtLinkBracketedRegex
= '/\[((' . wfUrlProtocols() . ')'.
192 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
193 if ( isset( $conf['preprocessorClass'] ) ) {
194 $this->mPreprocessorClass
= $conf['preprocessorClass'];
195 } elseif ( defined( 'MW_COMPILED' ) ) {
196 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
197 $this->mPreprocessorClass
= 'Preprocessor_Hash';
198 } elseif ( extension_loaded( 'domxml' ) ) {
199 # PECL extension that conflicts with the core DOM extension (bug 13770)
200 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
201 $this->mPreprocessorClass
= 'Preprocessor_Hash';
202 } elseif ( extension_loaded( 'dom' ) ) {
203 $this->mPreprocessorClass
= 'Preprocessor_DOM';
205 $this->mPreprocessorClass
= 'Preprocessor_Hash';
207 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
211 * Reduce memory usage to reduce the impact of circular references
213 function __destruct() {
214 if ( isset( $this->mLinkHolders
) ) {
215 unset( $this->mLinkHolders
);
217 foreach ( $this as $name => $value ) {
218 unset( $this->$name );
223 * Do various kinds of initialisation on the first call of the parser
225 function firstCallInit() {
226 if ( !$this->mFirstCall
) {
229 $this->mFirstCall
= false;
231 wfProfileIn( __METHOD__
);
233 CoreParserFunctions
::register( $this );
234 CoreTagHooks
::register( $this );
235 $this->initialiseVariables();
237 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
238 wfProfileOut( __METHOD__
);
246 function clearState() {
247 wfProfileIn( __METHOD__
);
248 if ( $this->mFirstCall
) {
249 $this->firstCallInit();
251 $this->mOutput
= new ParserOutput
;
252 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
253 $this->mAutonumber
= 0;
254 $this->mLastSection
= '';
255 $this->mDTopen
= false;
256 $this->mIncludeCount
= array();
257 $this->mArgStack
= false;
258 $this->mInPre
= false;
259 $this->mLinkHolders
= new LinkHolderArray( $this );
261 $this->mRevisionObject
= $this->mRevisionTimestamp
=
262 $this->mRevisionId
= $this->mRevisionUser
= null;
263 $this->mVarCache
= array();
267 * Prefix for temporary replacement strings for the multipass parser.
268 * \x07 should never appear in input as it's disallowed in XML.
269 * Using it at the front also gives us a little extra robustness
270 * since it shouldn't match when butted up against identifier-like
273 * Must not consist of all title characters, or else it will change
274 * the behaviour of <nowiki> in a link.
276 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
277 # Changed to \x7f to allow XML double-parsing -- TS
278 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
279 $this->mStripState
= new StripState( $this->mUniqPrefix
);
282 # Clear these on every parse, bug 4549
283 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
285 $this->mShowToc
= true;
286 $this->mForceTocPosition
= false;
287 $this->mIncludeSizes
= array(
291 $this->mPPNodeCount
= 0;
292 $this->mDefaultSort
= false;
293 $this->mHeadings
= array();
294 $this->mDoubleUnderscores
= array();
295 $this->mExpensiveFunctionCount
= 0;
298 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
299 $this->mPreprocessor
= null;
302 wfRunHooks( 'ParserClearState', array( &$this ) );
303 wfProfileOut( __METHOD__
);
307 * Convert wikitext to HTML
308 * Do not call this function recursively.
310 * @param $text String: text we want to parse
311 * @param $title Title object
312 * @param $options ParserOptions
313 * @param $linestart boolean
314 * @param $clearState boolean
315 * @param $revid Int: number to pass in {{REVISIONID}}
316 * @return ParserOutput a ParserOutput
318 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
320 * First pass--just handle <nowiki> sections, pass the rest off
321 * to internalParse() which does all the real work.
324 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
325 $fname = __METHOD__
.'-' . wfGetCaller();
326 wfProfileIn( __METHOD__
);
327 wfProfileIn( $fname );
329 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
331 $oldRevisionId = $this->mRevisionId
;
332 $oldRevisionObject = $this->mRevisionObject
;
333 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
334 $oldRevisionUser = $this->mRevisionUser
;
335 if ( $revid !== null ) {
336 $this->mRevisionId
= $revid;
337 $this->mRevisionObject
= null;
338 $this->mRevisionTimestamp
= null;
339 $this->mRevisionUser
= null;
342 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
344 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
345 $text = $this->internalParse( $text );
347 $text = $this->mStripState
->unstripGeneral( $text );
349 # Clean up special characters, only run once, next-to-last before doBlockLevels
351 # french spaces, last one Guillemet-left
352 # only if there is something before the space
353 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
354 # french spaces, Guillemet-right
355 '/(\\302\\253) /' => '\\1 ',
356 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
358 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
360 $text = $this->doBlockLevels( $text, $linestart );
362 $this->replaceLinkHolders( $text );
365 * The input doesn't get language converted if
367 * b) Content isn't converted
368 * c) It's a conversion table
369 * d) it is an interface message (which is in the user language)
371 if ( !( $wgDisableLangConversion
372 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
373 ||
$this->mTitle
->isConversionTable()
374 ||
$this->mOptions
->getInterfaceMessage() ) ) {
376 # The position of the convert() call should not be changed. it
377 # assumes that the links are all replaced and the only thing left
378 # is the <nowiki> mark.
380 $text = $wgContLang->convert( $text );
384 * A converted title will be provided in the output object if title and
385 * content conversion are enabled, the article text does not contain
386 * a conversion-suppressing double-underscore tag, and no
387 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
388 * automatic link conversion.
390 if ( !( $wgDisableLangConversion
391 ||
$wgDisableTitleConversion
392 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
393 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
394 ||
$this->mOutput
->getDisplayTitle() !== false ) )
396 $convruletitle = $wgContLang->getConvRuleTitle();
397 if ( $convruletitle ) {
398 $this->mOutput
->setTitleText( $convruletitle );
400 $titleText = $wgContLang->convertTitle( $title );
401 $this->mOutput
->setTitleText( $titleText );
405 $text = $this->mStripState
->unstripNoWiki( $text );
407 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
409 $text = $this->replaceTransparentTags( $text );
410 $text = $this->mStripState
->unstripGeneral( $text );
412 $text = Sanitizer
::normalizeCharReferences( $text );
414 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
415 $text = MWTidy
::tidy( $text );
417 # attempt to sanitize at least some nesting problems
418 # (bug #2702 and quite a few others)
420 # ''Something [http://www.cool.com cool''] -->
421 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
422 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
423 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
424 # fix up an anchor inside another anchor, only
425 # at least for a single single nested link (bug 3695)
426 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
427 '\\1\\2</a>\\3</a>\\1\\4</a>',
428 # fix div inside inline elements- doBlockLevels won't wrap a line which
429 # contains a div, so fix it up here; replace
430 # div with escaped text
431 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
432 '\\1\\3<div\\5>\\6</div>\\8\\9',
433 # remove empty italic or bold tag pairs, some
434 # introduced by rules above
435 '/<([bi])><\/\\1>/' => '',
438 $text = preg_replace(
439 array_keys( $tidyregs ),
440 array_values( $tidyregs ),
443 global $wgExpensiveParserFunctionLimit;
444 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
445 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
448 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
450 # Information on include size limits, for the benefit of users who try to skirt them
451 if ( $this->mOptions
->getEnableLimitReport() ) {
452 $max = $this->mOptions
->getMaxIncludeSize();
453 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
455 "NewPP limit report\n" .
456 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
457 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
458 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
460 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
461 $text .= "\n<!-- \n$limitReport-->\n";
463 $this->mOutput
->setText( $text );
465 $this->mRevisionId
= $oldRevisionId;
466 $this->mRevisionObject
= $oldRevisionObject;
467 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
468 $this->mRevisionUser
= $oldRevisionUser;
469 wfProfileOut( $fname );
470 wfProfileOut( __METHOD__
);
472 return $this->mOutput
;
476 * Recursive parser entry point that can be called from an extension tag
479 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
481 * @param $text String: text extension wants to have parsed
482 * @param $frame PPFrame: The frame to use for expanding any template variables
486 function recursiveTagParse( $text, $frame=false ) {
487 wfProfileIn( __METHOD__
);
488 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
489 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
490 $text = $this->internalParse( $text, false, $frame );
491 wfProfileOut( __METHOD__
);
496 * Expand templates and variables in the text, producing valid, static wikitext.
497 * Also removes comments.
499 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
500 wfProfileIn( __METHOD__
);
501 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
502 if ( $revid !== null ) {
503 $this->mRevisionId
= $revid;
505 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
506 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
507 $text = $this->replaceVariables( $text );
508 $text = $this->mStripState
->unstripBoth( $text );
509 wfProfileOut( __METHOD__
);
514 * Recursive parser entry point that can be called from an extension tag
517 * @param $text String: text to be expanded
518 * @param $frame PPFrame: The frame to use for expanding any template variables
521 public function recursivePreprocess( $text, $frame = false ) {
522 wfProfileIn( __METHOD__
);
523 $text = $this->replaceVariables( $text, $frame );
524 $text = $this->mStripState
->unstripBoth( $text );
525 wfProfileOut( __METHOD__
);
530 * Process the wikitext for the ?preload= feature. (bug 5210)
532 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
533 * comments, templates, arguments, tags hooks and parser functions are untouched.
535 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
536 # Parser (re)initialisation
537 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
539 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
540 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
541 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
542 $text = $this->mStripState
->unstripBoth( $text );
547 * Get a random string
551 static public function getRandomString() {
552 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
556 * Set the current user.
557 * Should only be used when doing pre-save transform.
559 * @param $user Mixed: User object or null (to reset)
561 function setUser( $user ) {
562 $this->mUser
= $user;
566 * Accessor for mUniqPrefix.
570 public function uniqPrefix() {
571 if ( !isset( $this->mUniqPrefix
) ) {
572 # @todo FIXME: This is probably *horribly wrong*
573 # LanguageConverter seems to want $wgParser's uniqPrefix, however
574 # if this is called for a parser cache hit, the parser may not
575 # have ever been initialized in the first place.
576 # Not really sure what the heck is supposed to be going on here.
578 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
580 return $this->mUniqPrefix
;
584 * Set the context title
588 function setTitle( $t ) {
589 if ( !$t ||
$t instanceof FakeTitle
) {
590 $t = Title
::newFromText( 'NO TITLE' );
593 if ( strval( $t->getFragment() ) !== '' ) {
594 # Strip the fragment to avoid various odd effects
595 $this->mTitle
= clone $t;
596 $this->mTitle
->setFragment( '' );
603 * Accessor for the Title object
605 * @return Title object
607 function getTitle() {
608 return $this->mTitle
;
612 * Accessor/mutator for the Title object
614 * @param $x New Title object or null to just get the current one
615 * @return Title object
617 function Title( $x = null ) {
618 return wfSetVar( $this->mTitle
, $x );
622 * Set the output type
624 * @param $ot Integer: new value
626 function setOutputType( $ot ) {
627 $this->mOutputType
= $ot;
630 'html' => $ot == self
::OT_HTML
,
631 'wiki' => $ot == self
::OT_WIKI
,
632 'pre' => $ot == self
::OT_PREPROCESS
,
633 'plain' => $ot == self
::OT_PLAIN
,
638 * Accessor/mutator for the output type
640 * @param $x New value or null to just get the current one
643 function OutputType( $x = null ) {
644 return wfSetVar( $this->mOutputType
, $x );
648 * Get the ParserOutput object
650 * @return ParserOutput object
652 function getOutput() {
653 return $this->mOutput
;
657 * Get the ParserOptions object
659 * @return ParserOptions object
661 function getOptions() {
662 return $this->mOptions
;
666 * Accessor/mutator for the ParserOptions object
668 * @param $x New value or null to just get the current one
669 * @return Current ParserOptions object
671 function Options( $x = null ) {
672 return wfSetVar( $this->mOptions
, $x );
678 function nextLinkID() {
679 return $this->mLinkID++
;
685 function setLinkID( $id ) {
686 $this->mLinkID
= $id;
692 function getFunctionLang() {
695 $target = $this->mOptions
->getTargetLanguage();
696 if ( $target !== null ) {
699 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $this->mTitle
->getPageLanguage();
704 * Get a User object either from $this->mUser, if set, or from the
705 * ParserOptions object otherwise
707 * @return User object
710 if ( !is_null( $this->mUser
) ) {
713 return $this->mOptions
->getUser();
717 * Get a preprocessor object
719 * @return Preprocessor instance
721 function getPreprocessor() {
722 if ( !isset( $this->mPreprocessor
) ) {
723 $class = $this->mPreprocessorClass
;
724 $this->mPreprocessor
= new $class( $this );
726 return $this->mPreprocessor
;
730 * Replaces all occurrences of HTML-style comments and the given tags
731 * in the text with a random marker and returns the next text. The output
732 * parameter $matches will be an associative array filled with data in
734 * 'UNIQ-xxxxx' => array(
737 * array( 'param' => 'x' ),
738 * '<element param="x">tag content</element>' ) )
740 * @param $elements array list of element names. Comments are always extracted.
741 * @param $text string Source text string.
742 * @param $matches array Out parameter, Array: extracted tags
743 * @param $uniq_prefix string
744 * @return String: stripped text
746 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
751 $taglist = implode( '|', $elements );
752 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
754 while ( $text != '' ) {
755 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
757 if ( count( $p ) < 5 ) {
760 if ( count( $p ) > 5 ) {
774 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
775 $stripped .= $marker;
777 if ( $close === '/>' ) {
778 # Empty element tag, <tag />
783 if ( $element === '!--' ) {
786 $end = "/(<\\/$element\\s*>)/i";
788 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
790 if ( count( $q ) < 3 ) {
791 # No end tag -- let it run out to the end of the text.
800 $matches[$marker] = array( $element,
802 Sanitizer
::decodeTagAttributes( $attributes ),
803 "<$element$attributes$close$content$tail" );
809 * Get a list of strippable XML-like elements
813 function getStripList() {
814 return $this->mStripList
;
818 * Add an item to the strip state
819 * Returns the unique tag which must be inserted into the stripped text
820 * The tag will be replaced with the original text in unstrip()
822 * @param $text string
826 function insertStripItem( $text ) {
827 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
828 $this->mMarkerIndex++
;
829 $this->mStripState
->addGeneral( $rnd, $text );
834 * parse the wiki syntax used to render tables
838 * @param $text string
842 function doTableStuff( $text ) {
843 wfProfileIn( __METHOD__
);
845 $lines = StringUtils
::explode( "\n", $text );
849 foreach ( $lines as $outLine ) {
850 $line = trim( $outLine );
852 # empty line, go to next line,
853 # but only append \n if outside of table
855 $output .= $outLine . "\n";
858 $firstChars = $line[0];
859 if ( strlen( $line ) > 1 ) {
860 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
864 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
866 $table =& $this->last( $tables );
867 $table[0] = array(); // first row
868 $currentRow =& $table[0];
869 $table['indent'] = strlen( $matches[1] );
871 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
872 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
874 if ( $attributes !== '' ) {
875 $table['attributes'] = $attributes;
877 } elseif ( !isset( $tables[0] ) ) {
878 // we're outside the table
880 $out .= $outLine . "\n";
881 } elseif ( $firstChars === '|}' ) {
882 // trim the |} code from the line
883 $line = substr ( $line , 2 );
885 // Shorthand for last row
886 $lastRow =& $this->last( $table );
888 // a thead at the end becomes a tfoot, unless there is only one row
889 // Do this before deleting empty last lines to allow headers at the bottom of tables
890 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
891 $lastRow['type'] = 'tfoot';
892 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
893 $lastRow[$i]['type'] = 'th';
897 // Delete empty last lines
898 if ( empty( $lastRow ) ) {
902 $curtable = array_pop( $tables );
904 #Add a line-ending before the table, but only if there isn't one already
905 if ( substr( $out, -1 ) !== "\n" ) {
908 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
910 if ( count( $tables ) > 0 ) {
911 $table =& $this->last( $tables );
912 $currentRow =& $this->last( $table );
913 $currentElement =& $this->last( $currentRow );
915 $output =& $currentElement['content'];
922 } elseif ( $firstChars === '|-' ) {
923 // start a new row element
924 // but only when we haven't started one already
925 if ( count( $currentRow ) != 0 ) {
927 $currentRow =& $this->last( $table );
929 // Get the attributes, there's nothing else useful in $line now
930 $line = substr ( $line , 2 );
931 $attributes = $this->mStripState
->unstripBoth( $line );
932 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
933 if ( $attributes !== '' ) {
934 $currentRow['attributes'] = $attributes;
937 } elseif ( $firstChars === '|+' ) {
938 // a table caption, but only proceed if there isn't one already
939 if ( !isset ( $table['caption'] ) ) {
940 $line = substr ( $line , 2 );
942 $c = $this->getCellAttr( $line , 'caption' );
943 $table['caption'] = array();
944 $table['caption']['content'] = $c[0];
945 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
947 $output =& $table['caption']['content'];
949 } elseif ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
950 // Which kind of cells are we dealing with
952 $line = substr ( $line , 1 );
954 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
955 $line = str_replace ( '!!' , '||' , $line );
959 // Split up multiple cells on the same line.
960 $cells = StringUtils
::explodeMarkup( '||' , $line );
961 $line = ''; // save memory
963 // decide whether thead to tbody
964 if ( !array_key_exists( 'type', $currentRow ) ) {
965 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
966 } elseif ( $firstChars === '|' ) {
967 $currentRow['type'] = 'tbody';
970 // Loop through each table cell
971 foreach ( $cells as $cell ) {
973 $currentRow[] = array();
974 $currentElement =& $this->last( $currentRow );
976 $currentElement['type'] = $currentTag;
978 $c = $this->getCellAttr( $cell , $currentTag );
979 $currentElement['content'] = $c[0];
980 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
983 $output =& $currentElement['content'];
986 $output .= "\n$outLine";
990 # Remove trailing line-ending (b/c)
991 if ( substr( $out, -1 ) === "\n" ) {
992 $out = substr( $out, 0, -1 );
995 # Close any unclosed tables
996 if ( isset( $tables ) && count( $tables ) > 0 ) {
997 for ( $i = 0; $i < count( $tables ); $i++
) {
998 $curtable = array_pop( $tables );
999 $curtable = $this->generateTableHTML( $curtable );
1000 #Add a line-ending before the table, but only if there isn't one already
1001 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
1008 wfProfileOut( __METHOD__
);
1014 * Helper function for doTableStuff() separating the contents of cells from
1015 * attributes. Particularly useful as there's a possible bug and this action
1016 * is repeated twice.
1023 function getCellAttr ( $cell, $tagName ) {
1026 $cell = trim ( $cell );
1028 // A cell could contain both parameters and data
1029 $cellData = explode ( '|' , $cell , 2 );
1031 // Bug 553: Note that a '|' inside an invalid link should not
1032 // be mistaken as delimiting cell parameters
1033 if ( strpos( $cellData[0], '[[' ) !== false ) {
1034 $content = trim ( $cell );
1036 elseif ( count ( $cellData ) == 1 ) {
1037 $content = trim ( $cellData[0] );
1039 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
1040 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
1042 $content = trim ( $cellData[1] );
1044 return array( $content, $attributes );
1049 * Helper function for doTableStuff(). This converts the structured array into html.
1053 * @param $table array
1057 function generateTableHTML( &$table ) {
1058 $return = str_repeat( '<dl><dd>' , $table['indent'] );
1059 $return .= '<table';
1060 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1062 unset( $table['attributes'] );
1064 if ( isset( $table['caption'] ) ) {
1065 $return .= "\n<caption";
1066 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1068 $return .= $table['caption']['content'];
1069 $return .= "\n</caption>";
1075 // If we only have tbodies, mark table as simple
1076 for ( $i = 0; isset( $table[$i] ); $i++
) {
1077 if ( !count( $table[$i] ) ) continue;
1078 if ( !isset( $table[$i]['type'] ) ) {
1079 $table[$i]['type'] = 'tbody';
1081 if ( !$lastSection ) {
1082 $lastSection = $table[$i]['type'];
1083 } elseif ( $lastSection != $table[$i]['type'] ) {
1088 for ( $i = 0; isset( $table[$i] ); $i++
) {
1089 if ( !count( $table[$i] ) ) continue;
1090 $empty = false; // check for empty tables
1092 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1093 $return .= "\n<" . $table[$i]['type'] . '>';
1097 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1099 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1100 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1101 $return .= "\n<" . $table[$i][$j]['type'];
1102 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1105 $return .= $table[$i][$j]['content'];
1106 if ( $table[$i][$j]['content'] != '' )
1109 $return .= '</' . $table[$i][$j]['type'] . '>';
1110 unset( $table[$i][$j] );
1112 $return .= "\n</tr>";
1114 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && isset( $table[$i +
1]['type'] ) && $table[$i]['type'] != $table[$i +
1]['type'] ) ) {
1115 $return .= '</' . $table[$i]['type'] . '>';
1117 $lastSection = $table[$i]['type'];
1118 unset( $table[$i] );
1121 if ( isset( $table['caption'] ) ) {
1122 $return .= "\n<tr><td></td></tr>";
1127 $return .= "\n</table>";
1128 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1134 * like end() but only works on the numeric array index and php's internal pointers
1135 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1136 * ignores associative elements and will create a 0 key will a NULL value if there were
1137 * no numric elements and an array itself if not previously defined.
1143 function &last ( &$arr ) {
1144 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1149 * Helper function for parse() that transforms wiki markup into
1150 * HTML. Only called for $mOutputType == self::OT_HTML.
1154 * @param $text string
1155 * @param $isMain bool
1156 * @param $frame bool
1160 function internalParse( $text, $isMain = true, $frame = false ) {
1161 wfProfileIn( __METHOD__
);
1165 # Hook to suspend the parser in this state
1166 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1167 wfProfileOut( __METHOD__
);
1171 # if $frame is provided, then use $frame for replacing any variables
1173 # use frame depth to infer how include/noinclude tags should be handled
1174 # depth=0 means this is the top-level document; otherwise it's an included document
1175 if ( !$frame->depth
) {
1178 $flag = Parser
::PTD_FOR_INCLUSION
;
1180 $dom = $this->preprocessToDom( $text, $flag );
1181 $text = $frame->expand( $dom );
1183 # if $frame is not provided, then use old-style replaceVariables
1184 $text = $this->replaceVariables( $text );
1187 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1188 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1190 # Tables need to come after variable replacement for things to work
1191 # properly; putting them before other transformations should keep
1192 # exciting things like link expansions from showing up in surprising
1194 $text = $this->doTableStuff( $text );
1196 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1198 $text = $this->doDoubleUnderscore( $text );
1200 $text = $this->doHeadings( $text );
1201 if ( $this->mOptions
->getUseDynamicDates() ) {
1202 $df = DateFormatter
::getInstance();
1203 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1205 $text = $this->replaceInternalLinks( $text );
1206 $text = $this->doAllQuotes( $text );
1207 $text = $this->replaceExternalLinks( $text );
1209 # replaceInternalLinks may sometimes leave behind
1210 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1211 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1213 $text = $this->doMagicLinks( $text );
1214 $text = $this->formatHeadings( $text, $origText, $isMain );
1216 wfProfileOut( __METHOD__
);
1221 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1222 * magic external links.
1227 * @param $text string
1231 function doMagicLinks( $text ) {
1232 wfProfileIn( __METHOD__
);
1233 $prots = wfUrlProtocolsWithoutProtRel();
1234 $urlChar = self
::EXT_LINK_URL_CLASS
;
1235 $text = preg_replace_callback(
1237 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1238 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1239 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1240 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1241 ISBN\s+(\b # m[5]: ISBN, capture number
1242 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1243 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1244 [0-9Xx] # check digit
1246 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1247 wfProfileOut( __METHOD__
);
1252 * @throws MWException
1254 * @return HTML|string
1256 function magicLinkCallback( $m ) {
1257 if ( isset( $m[1] ) && $m[1] !== '' ) {
1260 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1263 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1264 # Free external link
1265 return $this->makeFreeExternalLink( $m[0] );
1266 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1268 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1271 $CssClass = 'mw-magiclink-rfc';
1273 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1275 $urlmsg = 'pubmedurl';
1276 $CssClass = 'mw-magiclink-pmid';
1279 throw new MWException( __METHOD__
.': unrecognised match type "' .
1280 substr( $m[0], 0, 20 ) . '"' );
1282 $url = wfMsgForContent( $urlmsg, $id );
1283 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1284 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1287 $num = strtr( $isbn, array(
1292 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1294 $titleObj->escapeLocalUrl() .
1295 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1302 * Make a free external link, given a user-supplied URL
1304 * @param $url string
1306 * @return string HTML
1309 function makeFreeExternalLink( $url ) {
1311 wfProfileIn( __METHOD__
);
1315 # The characters '<' and '>' (which were escaped by
1316 # removeHTMLtags()) should not be included in
1317 # URLs, per RFC 2396.
1319 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1320 $trail = substr( $url, $m2[0][1] ) . $trail;
1321 $url = substr( $url, 0, $m2[0][1] );
1324 # Move trailing punctuation to $trail
1326 # If there is no left bracket, then consider right brackets fair game too
1327 if ( strpos( $url, '(' ) === false ) {
1331 $numSepChars = strspn( strrev( $url ), $sep );
1332 if ( $numSepChars ) {
1333 $trail = substr( $url, -$numSepChars ) . $trail;
1334 $url = substr( $url, 0, -$numSepChars );
1337 $url = Sanitizer
::cleanUrl( $url );
1339 # Is this an external image?
1340 $text = $this->maybeMakeExternalImage( $url );
1341 if ( $text === false ) {
1342 # Not an image, make a link
1343 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1344 $this->getExternalLinkAttribs( $url ) );
1345 # Register it in the output object...
1346 # Replace unnecessary URL escape codes with their equivalent characters
1347 $pasteurized = self
::replaceUnusualEscapes( $url );
1348 $this->mOutput
->addExternalLink( $pasteurized );
1350 wfProfileOut( __METHOD__
);
1351 return $text . $trail;
1356 * Parse headers and return html
1360 * @param $text string
1364 function doHeadings( $text ) {
1365 wfProfileIn( __METHOD__
);
1366 for ( $i = 6; $i >= 1; --$i ) {
1367 $h = str_repeat( '=', $i );
1368 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1369 "<h$i>\\1</h$i>", $text );
1371 wfProfileOut( __METHOD__
);
1376 * Replace single quotes with HTML markup
1379 * @param $text string
1381 * @return string the altered text
1383 function doAllQuotes( $text ) {
1384 wfProfileIn( __METHOD__
);
1386 $lines = StringUtils
::explode( "\n", $text );
1387 foreach ( $lines as $line ) {
1388 $outtext .= $this->doQuotes( $line ) . "\n";
1390 $outtext = substr( $outtext, 0,-1 );
1391 wfProfileOut( __METHOD__
);
1396 * Helper function for doAllQuotes()
1398 * @param $text string
1402 public function doQuotes( $text ) {
1403 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1404 if ( count( $arr ) == 1 ) {
1407 # First, do some preliminary work. This may shift some apostrophes from
1408 # being mark-up to being text. It also counts the number of occurrences
1409 # of bold and italics mark-ups.
1412 for ( $i = 0; $i < count( $arr ); $i++
) {
1413 if ( ( $i %
2 ) == 1 ) {
1414 # If there are ever four apostrophes, assume the first is supposed to
1415 # be text, and the remaining three constitute mark-up for bold text.
1416 if ( strlen( $arr[$i] ) == 4 ) {
1419 } elseif ( strlen( $arr[$i] ) > 5 ) {
1420 # If there are more than 5 apostrophes in a row, assume they're all
1421 # text except for the last 5.
1422 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1425 # Count the number of occurrences of bold and italics mark-ups.
1426 # We are not counting sequences of five apostrophes.
1427 if ( strlen( $arr[$i] ) == 2 ) {
1429 } elseif ( strlen( $arr[$i] ) == 3 ) {
1431 } elseif ( strlen( $arr[$i] ) == 5 ) {
1438 # If there is an odd number of both bold and italics, it is likely
1439 # that one of the bold ones was meant to be an apostrophe followed
1440 # by italics. Which one we cannot know for certain, but it is more
1441 # likely to be one that has a single-letter word before it.
1442 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1444 $firstsingleletterword = -1;
1445 $firstmultiletterword = -1;
1447 foreach ( $arr as $r ) {
1448 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1449 $x1 = substr( $arr[$i-1], -1 );
1450 $x2 = substr( $arr[$i-1], -2, 1 );
1451 if ( $x1 === ' ' ) {
1452 if ( $firstspace == -1 ) {
1455 } elseif ( $x2 === ' ') {
1456 if ( $firstsingleletterword == -1 ) {
1457 $firstsingleletterword = $i;
1460 if ( $firstmultiletterword == -1 ) {
1461 $firstmultiletterword = $i;
1468 # If there is a single-letter word, use it!
1469 if ( $firstsingleletterword > -1 ) {
1470 $arr[$firstsingleletterword] = "''";
1471 $arr[$firstsingleletterword-1] .= "'";
1472 } elseif ( $firstmultiletterword > -1 ) {
1473 # If not, but there's a multi-letter word, use that one.
1474 $arr[$firstmultiletterword] = "''";
1475 $arr[$firstmultiletterword-1] .= "'";
1476 } elseif ( $firstspace > -1 ) {
1477 # ... otherwise use the first one that has neither.
1478 # (notice that it is possible for all three to be -1 if, for example,
1479 # there is only one pentuple-apostrophe in the line)
1480 $arr[$firstspace] = "''";
1481 $arr[$firstspace-1] .= "'";
1485 # Now let's actually convert our apostrophic mush to HTML!
1490 foreach ( $arr as $r ) {
1491 if ( ( $i %
2 ) == 0 ) {
1492 if ( $state === 'both' ) {
1498 if ( strlen( $r ) == 2 ) {
1499 if ( $state === 'i' ) {
1500 $output .= '</i>'; $state = '';
1501 } elseif ( $state === 'bi' ) {
1502 $output .= '</i>'; $state = 'b';
1503 } elseif ( $state === 'ib' ) {
1504 $output .= '</b></i><b>'; $state = 'b';
1505 } elseif ( $state === 'both' ) {
1506 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1507 } else { # $state can be 'b' or ''
1508 $output .= '<i>'; $state .= 'i';
1510 } elseif ( strlen( $r ) == 3 ) {
1511 if ( $state === 'b' ) {
1512 $output .= '</b>'; $state = '';
1513 } elseif ( $state === 'bi' ) {
1514 $output .= '</i></b><i>'; $state = 'i';
1515 } elseif ( $state === 'ib' ) {
1516 $output .= '</b>'; $state = 'i';
1517 } elseif ( $state === 'both' ) {
1518 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1519 } else { # $state can be 'i' or ''
1520 $output .= '<b>'; $state .= 'b';
1522 } elseif ( strlen( $r ) == 5 ) {
1523 if ( $state === 'b' ) {
1524 $output .= '</b><i>'; $state = 'i';
1525 } elseif ( $state === 'i' ) {
1526 $output .= '</i><b>'; $state = 'b';
1527 } elseif ( $state === 'bi' ) {
1528 $output .= '</i></b>'; $state = '';
1529 } elseif ( $state === 'ib' ) {
1530 $output .= '</b></i>'; $state = '';
1531 } elseif ( $state === 'both' ) {
1532 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1533 } else { # ($state == '')
1534 $buffer = ''; $state = 'both';
1540 # Now close all remaining tags. Notice that the order is important.
1541 if ( $state === 'b' ||
$state === 'ib' ) {
1544 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1547 if ( $state === 'bi' ) {
1550 # There might be lonely ''''', so make sure we have a buffer
1551 if ( $state === 'both' && $buffer ) {
1552 $output .= '<b><i>'.$buffer.'</i></b>';
1559 * Replace external links (REL)
1561 * Note: this is all very hackish and the order of execution matters a lot.
1562 * Make sure to run maintenance/parserTests.php if you change this code.
1566 * @param $text string
1570 function replaceExternalLinks( $text ) {
1572 wfProfileIn( __METHOD__
);
1574 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1575 $s = array_shift( $bits );
1578 while ( $i<count( $bits ) ) {
1580 $protocol = $bits[$i++
];
1581 $text = $bits[$i++
];
1582 $trail = $bits[$i++
];
1584 # The characters '<' and '>' (which were escaped by
1585 # removeHTMLtags()) should not be included in
1586 # URLs, per RFC 2396.
1588 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1589 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1590 $url = substr( $url, 0, $m2[0][1] );
1593 # If the link text is an image URL, replace it with an <img> tag
1594 # This happened by accident in the original parser, but some people used it extensively
1595 $img = $this->maybeMakeExternalImage( $text );
1596 if ( $img !== false ) {
1602 # Set linktype for CSS - if URL==text, link is essentially free
1603 $linktype = ( $text === $url ) ?
'free' : 'text';
1605 # No link text, e.g. [http://domain.tld/some.link]
1606 if ( $text == '' ) {
1608 $langObj = $this->getFunctionLang();
1609 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1610 $linktype = 'autonumber';
1612 # Have link text, e.g. [http://domain.tld/some.link text]s
1614 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1617 $text = $wgContLang->markNoConversion( $text );
1619 $url = Sanitizer
::cleanUrl( $url );
1621 # Use the encoded URL
1622 # This means that users can paste URLs directly into the text
1623 # Funny characters like ö aren't valid in URLs anyway
1624 # This was changed in August 2004
1625 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1626 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1628 # Register link in the output object.
1629 # Replace unnecessary URL escape codes with the referenced character
1630 # This prevents spammers from hiding links from the filters
1631 $pasteurized = self
::replaceUnusualEscapes( $url );
1632 $this->mOutput
->addExternalLink( $pasteurized );
1635 wfProfileOut( __METHOD__
);
1640 * Get an associative array of additional HTML attributes appropriate for a
1641 * particular external link. This currently may include rel => nofollow
1642 * (depending on configuration, namespace, and the URL's domain) and/or a
1643 * target attribute (depending on configuration).
1645 * @param $url String|bool optional URL, to extract the domain from for rel =>
1646 * nofollow if appropriate
1647 * @return Array associative array of HTML attributes
1649 function getExternalLinkAttribs( $url = false ) {
1651 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1652 $ns = $this->mTitle
->getNamespace();
1653 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1654 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1656 $attribs['rel'] = 'nofollow';
1658 if ( $this->mOptions
->getExternalLinkTarget() ) {
1659 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1665 * Replace unusual URL escape codes with their equivalent characters
1667 * @param $url String
1670 * @todo This can merge genuinely required bits in the path or query string,
1671 * breaking legit URLs. A proper fix would treat the various parts of
1672 * the URL differently; as a workaround, just use the output for
1673 * statistical records, not for actual linking/output.
1675 static function replaceUnusualEscapes( $url ) {
1676 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1677 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1681 * Callback function used in replaceUnusualEscapes().
1682 * Replaces unusual URL escape codes with their equivalent character
1684 * @param $matches array
1688 private static function replaceUnusualEscapesCallback( $matches ) {
1689 $char = urldecode( $matches[0] );
1690 $ord = ord( $char );
1691 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1692 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1693 # No, shouldn't be escaped
1696 # Yes, leave it escaped
1702 * make an image if it's allowed, either through the global
1703 * option, through the exception, or through the on-wiki whitelist
1706 * $param $url string
1710 function maybeMakeExternalImage( $url ) {
1711 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1712 $imagesexception = !empty( $imagesfrom );
1714 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1715 if ( $imagesexception && is_array( $imagesfrom ) ) {
1716 $imagematch = false;
1717 foreach ( $imagesfrom as $match ) {
1718 if ( strpos( $url, $match ) === 0 ) {
1723 } elseif ( $imagesexception ) {
1724 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1726 $imagematch = false;
1728 if ( $this->mOptions
->getAllowExternalImages()
1729 ||
( $imagesexception && $imagematch ) ) {
1730 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1732 $text = Linker
::makeExternalImage( $url );
1735 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1736 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1737 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1738 foreach ( $whitelist as $entry ) {
1739 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1740 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1743 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1744 # Image matches a whitelist entry
1745 $text = Linker
::makeExternalImage( $url );
1754 * Process [[ ]] wikilinks
1758 * @return String: processed text
1762 function replaceInternalLinks( $s ) {
1763 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1768 * Process [[ ]] wikilinks (RIL)
1769 * @return LinkHolderArray
1773 function replaceInternalLinks2( &$s ) {
1776 wfProfileIn( __METHOD__
);
1778 wfProfileIn( __METHOD__
.'-setup' );
1779 static $tc = FALSE, $e1, $e1_img;
1780 # the % is needed to support urlencoded titles as well
1782 $tc = Title
::legalChars() . '#%';
1783 # Match a link having the form [[namespace:link|alternate]]trail
1784 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1785 # Match cases where there is no "]]", which might still be images
1786 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1789 $holders = new LinkHolderArray( $this );
1791 # split the entire text string on occurences of [[
1792 $a = StringUtils
::explode( '[[', ' ' . $s );
1793 # get the first element (all text up to first [[), and remove the space we added
1796 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1797 $s = substr( $s, 1 );
1799 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1801 if ( $useLinkPrefixExtension ) {
1802 # Match the end of a line for a word that's not followed by whitespace,
1803 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1804 $e2 = wfMsgForContent( 'linkprefix' );
1807 if ( is_null( $this->mTitle
) ) {
1808 wfProfileOut( __METHOD__
.'-setup' );
1809 wfProfileOut( __METHOD__
);
1810 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1812 $nottalk = !$this->mTitle
->isTalkPage();
1814 if ( $useLinkPrefixExtension ) {
1816 if ( preg_match( $e2, $s, $m ) ) {
1817 $first_prefix = $m[2];
1819 $first_prefix = false;
1825 if ( $wgContLang->hasVariants() ) {
1826 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1828 $selflink = array( $this->mTitle
->getPrefixedText() );
1830 $useSubpages = $this->areSubpagesAllowed();
1831 wfProfileOut( __METHOD__
.'-setup' );
1833 # Loop for each link
1834 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1835 # Check for excessive memory usage
1836 if ( $holders->isBig() ) {
1838 # Do the existence check, replace the link holders and clear the array
1839 $holders->replace( $s );
1843 if ( $useLinkPrefixExtension ) {
1844 wfProfileIn( __METHOD__
.'-prefixhandling' );
1845 if ( preg_match( $e2, $s, $m ) ) {
1852 if ( $first_prefix ) {
1853 $prefix = $first_prefix;
1854 $first_prefix = false;
1856 wfProfileOut( __METHOD__
.'-prefixhandling' );
1859 $might_be_img = false;
1861 wfProfileIn( __METHOD__
."-e1" );
1862 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1864 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1865 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1866 # the real problem is with the $e1 regex
1869 # Still some problems for cases where the ] is meant to be outside punctuation,
1870 # and no image is in sight. See bug 2095.
1872 if ( $text !== '' &&
1873 substr( $m[3], 0, 1 ) === ']' &&
1874 strpos( $text, '[' ) !== false
1877 $text .= ']'; # so that replaceExternalLinks($text) works later
1878 $m[3] = substr( $m[3], 1 );
1880 # fix up urlencoded title texts
1881 if ( strpos( $m[1], '%' ) !== false ) {
1882 # Should anchors '#' also be rejected?
1883 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1886 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1887 $might_be_img = true;
1889 if ( strpos( $m[1], '%' ) !== false ) {
1890 $m[1] = rawurldecode( $m[1] );
1893 } else { # Invalid form; output directly
1894 $s .= $prefix . '[[' . $line ;
1895 wfProfileOut( __METHOD__
."-e1" );
1898 wfProfileOut( __METHOD__
."-e1" );
1899 wfProfileIn( __METHOD__
."-misc" );
1901 # Don't allow internal links to pages containing
1902 # PROTO: where PROTO is a valid URL protocol; these
1903 # should be external links.
1904 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1905 $s .= $prefix . '[[' . $line ;
1906 wfProfileOut( __METHOD__
."-misc" );
1910 # Make subpage if necessary
1911 if ( $useSubpages ) {
1912 $link = $this->maybeDoSubpageLink( $m[1], $text );
1917 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1919 # Strip off leading ':'
1920 $link = substr( $link, 1 );
1923 wfProfileOut( __METHOD__
."-misc" );
1924 wfProfileIn( __METHOD__
."-title" );
1925 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1926 if ( $nt === null ) {
1927 $s .= $prefix . '[[' . $line;
1928 wfProfileOut( __METHOD__
."-title" );
1932 $ns = $nt->getNamespace();
1933 $iw = $nt->getInterWiki();
1934 wfProfileOut( __METHOD__
."-title" );
1936 if ( $might_be_img ) { # if this is actually an invalid link
1937 wfProfileIn( __METHOD__
."-might_be_img" );
1938 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1941 # look at the next 'line' to see if we can close it there
1943 $next_line = $a->current();
1944 if ( $next_line === false ||
$next_line === null ) {
1947 $m = explode( ']]', $next_line, 3 );
1948 if ( count( $m ) == 3 ) {
1949 # the first ]] closes the inner link, the second the image
1951 $text .= "[[{$m[0]}]]{$m[1]}";
1954 } elseif ( count( $m ) == 2 ) {
1955 # if there's exactly one ]] that's fine, we'll keep looking
1956 $text .= "[[{$m[0]}]]{$m[1]}";
1958 # if $next_line is invalid too, we need look no further
1959 $text .= '[[' . $next_line;
1964 # we couldn't find the end of this imageLink, so output it raw
1965 # but don't ignore what might be perfectly normal links in the text we've examined
1966 $holders->merge( $this->replaceInternalLinks2( $text ) );
1967 $s .= "{$prefix}[[$link|$text";
1968 # note: no $trail, because without an end, there *is* no trail
1969 wfProfileOut( __METHOD__
."-might_be_img" );
1972 } else { # it's not an image, so output it raw
1973 $s .= "{$prefix}[[$link|$text";
1974 # note: no $trail, because without an end, there *is* no trail
1975 wfProfileOut( __METHOD__
."-might_be_img" );
1978 wfProfileOut( __METHOD__
."-might_be_img" );
1981 $wasblank = ( $text == '' );
1985 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1986 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1987 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1988 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1989 $text = $this->doQuotes( $text );
1992 # Link not escaped by : , create the various objects
1996 wfProfileIn( __METHOD__
."-interwiki" );
1997 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1998 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1999 $s = rtrim( $s . $prefix );
2000 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2001 wfProfileOut( __METHOD__
."-interwiki" );
2004 wfProfileOut( __METHOD__
."-interwiki" );
2006 if ( $ns == NS_FILE
) {
2007 wfProfileIn( __METHOD__
."-image" );
2008 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2010 # if no parameters were passed, $text
2011 # becomes something like "File:Foo.png",
2012 # which we don't want to pass on to the
2016 # recursively parse links inside the image caption
2017 # actually, this will parse them in any other parameters, too,
2018 # but it might be hard to fix that, and it doesn't matter ATM
2019 $text = $this->replaceExternalLinks( $text );
2020 $holders->merge( $this->replaceInternalLinks2( $text ) );
2022 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2023 $s .= $prefix . $this->armorLinks(
2024 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2026 $s .= $prefix . $trail;
2028 wfProfileOut( __METHOD__
."-image" );
2032 if ( $ns == NS_CATEGORY
) {
2033 wfProfileIn( __METHOD__
."-category" );
2034 $s = rtrim( $s . "\n" ); # bug 87
2037 $sortkey = $this->getDefaultSort();
2041 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2042 $sortkey = str_replace( "\n", '', $sortkey );
2043 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
2044 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2047 * Strip the whitespace Category links produce, see bug 87
2048 * @todo We might want to use trim($tmp, "\n") here.
2050 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2052 wfProfileOut( __METHOD__
."-category" );
2057 # Self-link checking
2058 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2059 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2060 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2065 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2066 # @todo FIXME: Should do batch file existence checks, see comment below
2067 if ( $ns == NS_MEDIA
) {
2068 wfProfileIn( __METHOD__
."-media" );
2069 # Give extensions a chance to select the file revision for us
2072 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2073 array( $this, $nt, &$options, &$descQuery ) );
2074 # Fetch and register the file (file title may be different via hooks)
2075 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2076 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2077 $s .= $prefix . $this->armorLinks(
2078 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2079 wfProfileOut( __METHOD__
."-media" );
2083 wfProfileIn( __METHOD__
."-always_known" );
2084 # Some titles, such as valid special pages or files in foreign repos, should
2085 # be shown as bluelinks even though they're not included in the page table
2087 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2088 # batch file existence checks for NS_FILE and NS_MEDIA
2089 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2090 $this->mOutput
->addLink( $nt );
2091 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2093 # Links will be added to the output link list after checking
2094 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2096 wfProfileOut( __METHOD__
."-always_known" );
2098 wfProfileOut( __METHOD__
);
2103 * Render a forced-blue link inline; protect against double expansion of
2104 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2105 * Since this little disaster has to split off the trail text to avoid
2106 * breaking URLs in the following text without breaking trails on the
2107 * wiki links, it's been made into a horrible function.
2110 * @param $text String
2111 * @param $query Array or String
2112 * @param $trail String
2113 * @param $prefix String
2114 * @return String: HTML-wikitext mix oh yuck
2116 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2117 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2119 if ( is_string( $query ) ) {
2120 $query = wfCgiToArray( $query );
2122 if ( $text == '' ) {
2123 $text = htmlspecialchars( $nt->getPrefixedText() );
2126 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2128 return $this->armorLinks( $link ) . $trail;
2132 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2133 * going to go through further parsing steps before inline URL expansion.
2135 * Not needed quite as much as it used to be since free links are a bit
2136 * more sensible these days. But bracketed links are still an issue.
2138 * @param $text String: more-or-less HTML
2139 * @return String: less-or-more HTML with NOPARSE bits
2141 function armorLinks( $text ) {
2142 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2143 "{$this->mUniqPrefix}NOPARSE$1", $text );
2147 * Return true if subpage links should be expanded on this page.
2150 function areSubpagesAllowed() {
2151 # Some namespaces don't allow subpages
2152 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2156 * Handle link to subpage if necessary
2158 * @param $target String: the source of the link
2159 * @param &$text String: the link text, modified as necessary
2160 * @return string the full name of the link
2163 function maybeDoSubpageLink( $target, &$text ) {
2164 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2168 * Used by doBlockLevels()
2173 function closeParagraph() {
2175 if ( $this->mLastSection
!= '' ) {
2176 $result = '</' . $this->mLastSection
. ">\n";
2178 $this->mInPre
= false;
2179 $this->mLastSection
= '';
2184 * getCommon() returns the length of the longest common substring
2185 * of both arguments, starting at the beginning of both.
2188 * @param $st1 string
2189 * @param $st2 string
2193 function getCommon( $st1, $st2 ) {
2194 $fl = strlen( $st1 );
2195 $shorter = strlen( $st2 );
2196 if ( $fl < $shorter ) {
2200 for ( $i = 0; $i < $shorter; ++
$i ) {
2201 if ( $st1[$i] != $st2[$i] ) {
2209 * These next three functions open, continue, and close the list
2210 * element appropriate to the prefix character passed into them.
2217 function openList( $char ) {
2218 $result = $this->closeParagraph();
2220 if ( '*' === $char ) {
2221 $result .= '<ul><li>';
2222 } elseif ( '#' === $char ) {
2223 $result .= '<ol><li>';
2224 } elseif ( ':' === $char ) {
2225 $result .= '<dl><dd>';
2226 } elseif ( ';' === $char ) {
2227 $result .= '<dl><dt>';
2228 $this->mDTopen
= true;
2230 $result = '<!-- ERR 1 -->';
2238 * @param $char String
2243 function nextItem( $char ) {
2244 if ( '*' === $char ||
'#' === $char ) {
2246 } elseif ( ':' === $char ||
';' === $char ) {
2248 if ( $this->mDTopen
) {
2251 if ( ';' === $char ) {
2252 $this->mDTopen
= true;
2253 return $close . '<dt>';
2255 $this->mDTopen
= false;
2256 return $close . '<dd>';
2259 return '<!-- ERR 2 -->';
2264 * @param $char String
2269 function closeList( $char ) {
2270 if ( '*' === $char ) {
2271 $text = '</li></ul>';
2272 } elseif ( '#' === $char ) {
2273 $text = '</li></ol>';
2274 } elseif ( ':' === $char ) {
2275 if ( $this->mDTopen
) {
2276 $this->mDTopen
= false;
2277 $text = '</dt></dl>';
2279 $text = '</dd></dl>';
2282 return '<!-- ERR 3 -->';
2289 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2291 * @param $text String
2292 * @param $linestart Boolean: whether or not this is at the start of a line.
2294 * @return string the lists rendered as HTML
2296 function doBlockLevels( $text, $linestart ) {
2297 wfProfileIn( __METHOD__
);
2299 # Parsing through the text line by line. The main thing
2300 # happening here is handling of block-level elements p, pre,
2301 # and making lists from lines starting with * # : etc.
2303 $textLines = StringUtils
::explode( "\n", $text );
2305 $lastPrefix = $output = '';
2306 $this->mDTopen
= $inBlockElem = false;
2308 $paragraphStack = false;
2310 foreach ( $textLines as $oLine ) {
2312 if ( !$linestart ) {
2322 $lastPrefixLength = strlen( $lastPrefix );
2323 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2324 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2325 # If not in a <pre> element, scan for and figure out what prefixes are there.
2326 if ( !$this->mInPre
) {
2327 # Multiple prefixes may abut each other for nested lists.
2328 $prefixLength = strspn( $oLine, '*#:;' );
2329 $prefix = substr( $oLine, 0, $prefixLength );
2332 # ; and : are both from definition-lists, so they're equivalent
2333 # for the purposes of determining whether or not we need to open/close
2335 $prefix2 = str_replace( ';', ':', $prefix );
2336 $t = substr( $oLine, $prefixLength );
2337 $this->mInPre
= (bool)$preOpenMatch;
2339 # Don't interpret any other prefixes in preformatted text
2341 $prefix = $prefix2 = '';
2346 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2347 # Same as the last item, so no need to deal with nesting or opening stuff
2348 $output .= $this->nextItem( substr( $prefix, -1 ) );
2349 $paragraphStack = false;
2351 if ( substr( $prefix, -1 ) === ';') {
2352 # The one nasty exception: definition lists work like this:
2353 # ; title : definition text
2354 # So we check for : in the remainder text to split up the
2355 # title and definition, without b0rking links.
2357 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2359 $output .= $term . $this->nextItem( ':' );
2362 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2363 # We need to open or close prefixes, or both.
2365 # Either open or close a level...
2366 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2367 $paragraphStack = false;
2369 # Close all the prefixes which aren't shared.
2370 while ( $commonPrefixLength < $lastPrefixLength ) {
2371 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2372 --$lastPrefixLength;
2375 # Continue the current prefix if appropriate.
2376 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2377 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2380 # Open prefixes where appropriate.
2381 while ( $prefixLength > $commonPrefixLength ) {
2382 $char = substr( $prefix, $commonPrefixLength, 1 );
2383 $output .= $this->openList( $char );
2385 if ( ';' === $char ) {
2386 # @todo FIXME: This is dupe of code above
2387 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2389 $output .= $term . $this->nextItem( ':' );
2392 ++
$commonPrefixLength;
2394 $lastPrefix = $prefix2;
2397 # If we have no prefixes, go to paragraph mode.
2398 if ( 0 == $prefixLength ) {
2399 wfProfileIn( __METHOD__
."-paragraph" );
2400 # No prefix (not in list)--go to paragraph mode
2401 # XXX: use a stack for nestable elements like span, table and div
2402 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2403 $closematch = preg_match(
2404 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2405 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2406 if ( $openmatch or $closematch ) {
2407 $paragraphStack = false;
2408 # TODO bug 5718: paragraph closed
2409 $output .= $this->closeParagraph();
2410 if ( $preOpenMatch and !$preCloseMatch ) {
2411 $this->mInPre
= true;
2413 $inBlockElem = !$closematch;
2414 } elseif ( !$inBlockElem && !$this->mInPre
) {
2415 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2417 if ( $this->mLastSection
!== 'pre' ) {
2418 $paragraphStack = false;
2419 $output .= $this->closeParagraph().'<pre>';
2420 $this->mLastSection
= 'pre';
2422 $t = substr( $t, 1 );
2425 if ( trim( $t ) === '' ) {
2426 if ( $paragraphStack ) {
2427 $output .= $paragraphStack.'<br />';
2428 $paragraphStack = false;
2429 $this->mLastSection
= 'p';
2431 if ( $this->mLastSection
!== 'p' ) {
2432 $output .= $this->closeParagraph();
2433 $this->mLastSection
= '';
2434 $paragraphStack = '<p>';
2436 $paragraphStack = '</p><p>';
2440 if ( $paragraphStack ) {
2441 $output .= $paragraphStack;
2442 $paragraphStack = false;
2443 $this->mLastSection
= 'p';
2444 } elseif ( $this->mLastSection
!== 'p' ) {
2445 $output .= $this->closeParagraph().'<p>';
2446 $this->mLastSection
= 'p';
2451 wfProfileOut( __METHOD__
."-paragraph" );
2453 # somewhere above we forget to get out of pre block (bug 785)
2454 if ( $preCloseMatch && $this->mInPre
) {
2455 $this->mInPre
= false;
2457 if ( $paragraphStack === false ) {
2461 while ( $prefixLength ) {
2462 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2465 if ( $this->mLastSection
!= '' ) {
2466 $output .= '</' . $this->mLastSection
. '>';
2467 $this->mLastSection
= '';
2470 wfProfileOut( __METHOD__
);
2475 * Split up a string on ':', ignoring any occurences inside tags
2476 * to prevent illegal overlapping.
2478 * @param $str String the string to split
2479 * @param &$before String set to everything before the ':'
2480 * @param &$after String set to everything after the ':'
2481 * @return String the position of the ':', or false if none found
2483 function findColonNoLinks( $str, &$before, &$after ) {
2484 wfProfileIn( __METHOD__
);
2486 $pos = strpos( $str, ':' );
2487 if ( $pos === false ) {
2489 wfProfileOut( __METHOD__
);
2493 $lt = strpos( $str, '<' );
2494 if ( $lt === false ||
$lt > $pos ) {
2495 # Easy; no tag nesting to worry about
2496 $before = substr( $str, 0, $pos );
2497 $after = substr( $str, $pos+
1 );
2498 wfProfileOut( __METHOD__
);
2502 # Ugly state machine to walk through avoiding tags.
2503 $state = self
::COLON_STATE_TEXT
;
2505 $len = strlen( $str );
2506 for( $i = 0; $i < $len; $i++
) {
2510 # (Using the number is a performance hack for common cases)
2511 case 0: # self::COLON_STATE_TEXT:
2514 # Could be either a <start> tag or an </end> tag
2515 $state = self
::COLON_STATE_TAGSTART
;
2518 if ( $stack == 0 ) {
2520 $before = substr( $str, 0, $i );
2521 $after = substr( $str, $i +
1 );
2522 wfProfileOut( __METHOD__
);
2525 # Embedded in a tag; don't break it.
2528 # Skip ahead looking for something interesting
2529 $colon = strpos( $str, ':', $i );
2530 if ( $colon === false ) {
2531 # Nothing else interesting
2532 wfProfileOut( __METHOD__
);
2535 $lt = strpos( $str, '<', $i );
2536 if ( $stack === 0 ) {
2537 if ( $lt === false ||
$colon < $lt ) {
2539 $before = substr( $str, 0, $colon );
2540 $after = substr( $str, $colon +
1 );
2541 wfProfileOut( __METHOD__
);
2545 if ( $lt === false ) {
2546 # Nothing else interesting to find; abort!
2547 # We're nested, but there's no close tags left. Abort!
2550 # Skip ahead to next tag start
2552 $state = self
::COLON_STATE_TAGSTART
;
2555 case 1: # self::COLON_STATE_TAG:
2560 $state = self
::COLON_STATE_TEXT
;
2563 # Slash may be followed by >?
2564 $state = self
::COLON_STATE_TAGSLASH
;
2570 case 2: # self::COLON_STATE_TAGSTART:
2573 $state = self
::COLON_STATE_CLOSETAG
;
2576 $state = self
::COLON_STATE_COMMENT
;
2579 # Illegal early close? This shouldn't happen D:
2580 $state = self
::COLON_STATE_TEXT
;
2583 $state = self
::COLON_STATE_TAG
;
2586 case 3: # self::COLON_STATE_CLOSETAG:
2591 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2592 wfProfileOut( __METHOD__
);
2595 $state = self
::COLON_STATE_TEXT
;
2598 case self
::COLON_STATE_TAGSLASH
:
2600 # Yes, a self-closed tag <blah/>
2601 $state = self
::COLON_STATE_TEXT
;
2603 # Probably we're jumping the gun, and this is an attribute
2604 $state = self
::COLON_STATE_TAG
;
2607 case 5: # self::COLON_STATE_COMMENT:
2609 $state = self
::COLON_STATE_COMMENTDASH
;
2612 case self
::COLON_STATE_COMMENTDASH
:
2614 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2616 $state = self
::COLON_STATE_COMMENT
;
2619 case self
::COLON_STATE_COMMENTDASHDASH
:
2621 $state = self
::COLON_STATE_TEXT
;
2623 $state = self
::COLON_STATE_COMMENT
;
2627 throw new MWException( "State machine error in " . __METHOD__
);
2631 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2632 wfProfileOut( __METHOD__
);
2635 wfProfileOut( __METHOD__
);
2640 * Return value of a magic variable (like PAGENAME)
2644 * @param $index integer
2645 * @param $frame PPFrame
2649 function getVariableValue( $index, $frame = false ) {
2650 global $wgContLang, $wgSitename, $wgServer;
2651 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2653 if ( is_null( $this->mTitle
) ) {
2654 // If no title set, bad things are going to happen
2655 // later. Title should always be set since this
2656 // should only be called in the middle of a parse
2657 // operation (but the unit-tests do funky stuff)
2658 throw new MWException( __METHOD__
. ' Should only be '
2659 . ' called while parsing (no title set)' );
2663 * Some of these require message or data lookups and can be
2664 * expensive to check many times.
2666 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2667 if ( isset( $this->mVarCache
[$index] ) ) {
2668 return $this->mVarCache
[$index];
2672 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2673 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2676 global $wgLocaltimezone;
2677 if ( isset( $wgLocaltimezone ) ) {
2678 $oldtz = date_default_timezone_get();
2679 date_default_timezone_set( $wgLocaltimezone );
2682 $localTimestamp = date( 'YmdHis', $ts );
2683 $localMonth = date( 'm', $ts );
2684 $localMonth1 = date( 'n', $ts );
2685 $localMonthName = date( 'n', $ts );
2686 $localDay = date( 'j', $ts );
2687 $localDay2 = date( 'd', $ts );
2688 $localDayOfWeek = date( 'w', $ts );
2689 $localWeek = date( 'W', $ts );
2690 $localYear = date( 'Y', $ts );
2691 $localHour = date( 'H', $ts );
2692 if ( isset( $wgLocaltimezone ) ) {
2693 date_default_timezone_set( $oldtz );
2696 $pageLang = $this->getFunctionLang();
2699 case 'currentmonth':
2700 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2702 case 'currentmonth1':
2703 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2705 case 'currentmonthname':
2706 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2708 case 'currentmonthnamegen':
2709 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2711 case 'currentmonthabbrev':
2712 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2715 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2718 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2721 $value = $pageLang->formatNum( $localMonth );
2724 $value = $pageLang->formatNum( $localMonth1 );
2726 case 'localmonthname':
2727 $value = $pageLang->getMonthName( $localMonthName );
2729 case 'localmonthnamegen':
2730 $value = $pageLang->getMonthNameGen( $localMonthName );
2732 case 'localmonthabbrev':
2733 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2736 $value = $pageLang->formatNum( $localDay );
2739 $value = $pageLang->formatNum( $localDay2 );
2742 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2745 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2747 case 'fullpagename':
2748 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2750 case 'fullpagenamee':
2751 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2754 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2756 case 'subpagenamee':
2757 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2759 case 'basepagename':
2760 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2762 case 'basepagenamee':
2763 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2765 case 'talkpagename':
2766 if ( $this->mTitle
->canTalk() ) {
2767 $talkPage = $this->mTitle
->getTalkPage();
2768 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2773 case 'talkpagenamee':
2774 if ( $this->mTitle
->canTalk() ) {
2775 $talkPage = $this->mTitle
->getTalkPage();
2776 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2781 case 'subjectpagename':
2782 $subjPage = $this->mTitle
->getSubjectPage();
2783 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2785 case 'subjectpagenamee':
2786 $subjPage = $this->mTitle
->getSubjectPage();
2787 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2790 # Let the edit saving system know we should parse the page
2791 # *after* a revision ID has been assigned.
2792 $this->mOutput
->setFlag( 'vary-revision' );
2793 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2794 $value = $this->mRevisionId
;
2797 # Let the edit saving system know we should parse the page
2798 # *after* a revision ID has been assigned. This is for null edits.
2799 $this->mOutput
->setFlag( 'vary-revision' );
2800 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2801 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2803 case 'revisionday2':
2804 # Let the edit saving system know we should parse the page
2805 # *after* a revision ID has been assigned. This is for null edits.
2806 $this->mOutput
->setFlag( 'vary-revision' );
2807 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2808 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2810 case 'revisionmonth':
2811 # Let the edit saving system know we should parse the page
2812 # *after* a revision ID has been assigned. This is for null edits.
2813 $this->mOutput
->setFlag( 'vary-revision' );
2814 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2815 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2817 case 'revisionmonth1':
2818 # Let the edit saving system know we should parse the page
2819 # *after* a revision ID has been assigned. This is for null edits.
2820 $this->mOutput
->setFlag( 'vary-revision' );
2821 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2822 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2824 case 'revisionyear':
2825 # Let the edit saving system know we should parse the page
2826 # *after* a revision ID has been assigned. This is for null edits.
2827 $this->mOutput
->setFlag( 'vary-revision' );
2828 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2829 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2831 case 'revisiontimestamp':
2832 # Let the edit saving system know we should parse the page
2833 # *after* a revision ID has been assigned. This is for null edits.
2834 $this->mOutput
->setFlag( 'vary-revision' );
2835 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2836 $value = $this->getRevisionTimestamp();
2838 case 'revisionuser':
2839 # Let the edit saving system know we should parse the page
2840 # *after* a revision ID has been assigned. This is for null edits.
2841 $this->mOutput
->setFlag( 'vary-revision' );
2842 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2843 $value = $this->getRevisionUser();
2846 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2849 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2852 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2855 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2857 case 'subjectspace':
2858 $value = $this->mTitle
->getSubjectNsText();
2860 case 'subjectspacee':
2861 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2863 case 'currentdayname':
2864 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2867 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2870 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2873 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2876 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2877 # int to remove the padding
2878 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2881 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2883 case 'localdayname':
2884 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2887 $value = $pageLang->formatNum( $localYear, true );
2890 $value = $pageLang->time( $localTimestamp, false, false );
2893 $value = $pageLang->formatNum( $localHour, true );
2896 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2897 # int to remove the padding
2898 $value = $pageLang->formatNum( (int)$localWeek );
2901 $value = $pageLang->formatNum( $localDayOfWeek );
2903 case 'numberofarticles':
2904 $value = $pageLang->formatNum( SiteStats
::articles() );
2906 case 'numberoffiles':
2907 $value = $pageLang->formatNum( SiteStats
::images() );
2909 case 'numberofusers':
2910 $value = $pageLang->formatNum( SiteStats
::users() );
2912 case 'numberofactiveusers':
2913 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2915 case 'numberofpages':
2916 $value = $pageLang->formatNum( SiteStats
::pages() );
2918 case 'numberofadmins':
2919 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2921 case 'numberofedits':
2922 $value = $pageLang->formatNum( SiteStats
::edits() );
2924 case 'numberofviews':
2925 $value = $pageLang->formatNum( SiteStats
::views() );
2927 case 'currenttimestamp':
2928 $value = wfTimestamp( TS_MW
, $ts );
2930 case 'localtimestamp':
2931 $value = $localTimestamp;
2933 case 'currentversion':
2934 $value = SpecialVersion
::getVersion();
2937 return $wgArticlePath;
2943 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2944 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2945 wfRestoreWarnings();
2946 return $serverName ?
$serverName : $wgServer;
2948 return $wgScriptPath;
2950 return $wgStylePath;
2951 case 'directionmark':
2952 return $pageLang->getDirMark();
2953 case 'contentlanguage':
2954 global $wgLanguageCode;
2955 return $wgLanguageCode;
2958 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2966 $this->mVarCache
[$index] = $value;
2973 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2977 function initialiseVariables() {
2978 wfProfileIn( __METHOD__
);
2979 $variableIDs = MagicWord
::getVariableIDs();
2980 $substIDs = MagicWord
::getSubstIDs();
2982 $this->mVariables
= new MagicWordArray( $variableIDs );
2983 $this->mSubstWords
= new MagicWordArray( $substIDs );
2984 wfProfileOut( __METHOD__
);
2988 * Preprocess some wikitext and return the document tree.
2989 * This is the ghost of replace_variables().
2991 * @param $text String: The text to parse
2992 * @param $flags Integer: bitwise combination of:
2993 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2994 * included. Default is to assume a direct page view.
2996 * The generated DOM tree must depend only on the input text and the flags.
2997 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2999 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3000 * change in the DOM tree for a given text, must be passed through the section identifier
3001 * in the section edit link and thus back to extractSections().
3003 * The output of this function is currently only cached in process memory, but a persistent
3004 * cache may be implemented at a later date which takes further advantage of these strict
3005 * dependency requirements.
3011 function preprocessToDom( $text, $flags = 0 ) {
3012 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3017 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3023 public static function splitWhitespace( $s ) {
3024 $ltrimmed = ltrim( $s );
3025 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3026 $trimmed = rtrim( $ltrimmed );
3027 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3029 $w2 = substr( $ltrimmed, -$diff );
3033 return array( $w1, $trimmed, $w2 );
3037 * Replace magic variables, templates, and template arguments
3038 * with the appropriate text. Templates are substituted recursively,
3039 * taking care to avoid infinite loops.
3041 * Note that the substitution depends on value of $mOutputType:
3042 * self::OT_WIKI: only {{subst:}} templates
3043 * self::OT_PREPROCESS: templates but not extension tags
3044 * self::OT_HTML: all templates and extension tags
3046 * @param $text String the text to transform
3047 * @param $frame PPFrame Object describing the arguments passed to the template.
3048 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3049 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3050 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3055 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3056 # Is there any text? Also, Prevent too big inclusions!
3057 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3060 wfProfileIn( __METHOD__
);
3062 if ( $frame === false ) {
3063 $frame = $this->getPreprocessor()->newFrame();
3064 } elseif ( !( $frame instanceof PPFrame
) ) {
3065 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3066 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3069 $dom = $this->preprocessToDom( $text );
3070 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3071 $text = $frame->expand( $dom, $flags );
3073 wfProfileOut( __METHOD__
);
3078 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3080 * @param $args array
3084 static function createAssocArgs( $args ) {
3085 $assocArgs = array();
3087 foreach ( $args as $arg ) {
3088 $eqpos = strpos( $arg, '=' );
3089 if ( $eqpos === false ) {
3090 $assocArgs[$index++
] = $arg;
3092 $name = trim( substr( $arg, 0, $eqpos ) );
3093 $value = trim( substr( $arg, $eqpos+
1 ) );
3094 if ( $value === false ) {
3097 if ( $name !== false ) {
3098 $assocArgs[$name] = $value;
3107 * Warn the user when a parser limitation is reached
3108 * Will warn at most once the user per limitation type
3110 * @param $limitationType String: should be one of:
3111 * 'expensive-parserfunction' (corresponding messages:
3112 * 'expensive-parserfunction-warning',
3113 * 'expensive-parserfunction-category')
3114 * 'post-expand-template-argument' (corresponding messages:
3115 * 'post-expand-template-argument-warning',
3116 * 'post-expand-template-argument-category')
3117 * 'post-expand-template-inclusion' (corresponding messages:
3118 * 'post-expand-template-inclusion-warning',
3119 * 'post-expand-template-inclusion-category')
3120 * @param $current Current value
3121 * @param $max Maximum allowed, when an explicit limit has been
3122 * exceeded, provide the values (optional)
3124 function limitationWarn( $limitationType, $current=null, $max=null) {
3125 # does no harm if $current and $max are present but are unnecessary for the message
3126 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3127 $this->mOutput
->addWarning( $warning );
3128 $this->addTrackingCategory( "$limitationType-category" );
3132 * Return the text of a template, after recursively
3133 * replacing any variables or templates within the template.
3135 * @param $piece Array: the parts of the template
3136 * $piece['title']: the title, i.e. the part before the |
3137 * $piece['parts']: the parameter array
3138 * $piece['lineStart']: whether the brace was at the start of a line
3139 * @param $frame PPFrame The current frame, contains template arguments
3140 * @return String: the text of the template
3143 function braceSubstitution( $piece, $frame ) {
3144 global $wgContLang, $wgNonincludableNamespaces, $wgEnableInterwikiTranscluding, $wgEnableInterwikiTemplatesTracking;
3145 wfProfileIn( __METHOD__
);
3146 wfProfileIn( __METHOD__
.'-setup' );
3149 $found = false; # $text has been filled
3150 $nowiki = false; # wiki markup in $text should be escaped
3151 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3152 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3153 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3155 # Title object, where $text came from
3158 # $part1 is the bit before the first |, and must contain only title characters.
3159 # Various prefixes will be stripped from it later.
3160 $titleWithSpaces = $frame->expand( $piece['title'] );
3161 $part1 = trim( $titleWithSpaces );
3164 # Original title text preserved for various purposes
3165 $originalTitle = $part1;
3167 # $args is a list of argument nodes, starting from index 0, not including $part1
3168 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3169 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3170 wfProfileOut( __METHOD__
.'-setup' );
3171 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3174 wfProfileIn( __METHOD__
.'-modifiers' );
3177 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3179 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3180 # Decide whether to expand template or keep wikitext as-is.
3181 if ( $this->ot
['wiki'] ) {
3182 if ( $substMatch === false ) {
3183 $literal = true; # literal when in PST with no prefix
3185 $literal = false; # expand when in PST with subst: or safesubst:
3188 if ( $substMatch == 'subst' ) {
3189 $literal = true; # literal when not in PST with plain subst:
3191 $literal = false; # expand when not in PST with safesubst: or no prefix
3195 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3202 if ( !$found && $args->getLength() == 0 ) {
3203 $id = $this->mVariables
->matchStartToEnd( $part1 );
3204 if ( $id !== false ) {
3205 $text = $this->getVariableValue( $id, $frame );
3206 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3207 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3213 # MSG, MSGNW and RAW
3216 $mwMsgnw = MagicWord
::get( 'msgnw' );
3217 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3220 # Remove obsolete MSG:
3221 $mwMsg = MagicWord
::get( 'msg' );
3222 $mwMsg->matchStartAndRemove( $part1 );
3226 $mwRaw = MagicWord
::get( 'raw' );
3227 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3228 $forceRawInterwiki = true;
3231 wfProfileOut( __METHOD__
.'-modifiers' );
3235 wfProfileIn( __METHOD__
. '-pfunc' );
3237 $colonPos = strpos( $part1, ':' );
3238 if ( $colonPos !== false ) {
3239 # Case sensitive functions
3240 $function = substr( $part1, 0, $colonPos );
3241 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3242 $function = $this->mFunctionSynonyms
[1][$function];
3244 # Case insensitive functions
3245 $function = $wgContLang->lc( $function );
3246 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3247 $function = $this->mFunctionSynonyms
[0][$function];
3253 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3254 $initialArgs = array( &$this );
3255 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3256 if ( $flags & SFH_OBJECT_ARGS
) {
3257 # Add a frame parameter, and pass the arguments as an array
3258 $allArgs = $initialArgs;
3259 $allArgs[] = $frame;
3260 for ( $i = 0; $i < $args->getLength(); $i++
) {
3261 $funcArgs[] = $args->item( $i );
3263 $allArgs[] = $funcArgs;
3265 # Convert arguments to plain text
3266 for ( $i = 0; $i < $args->getLength(); $i++
) {
3267 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3269 $allArgs = array_merge( $initialArgs, $funcArgs );
3272 # Workaround for PHP bug 35229 and similar
3273 if ( !is_callable( $callback ) ) {
3274 wfProfileOut( __METHOD__
. '-pfunc' );
3275 wfProfileOut( __METHOD__
);
3276 throw new MWException( "Tag hook for $function is not callable\n" );
3278 $result = call_user_func_array( $callback, $allArgs );
3281 $preprocessFlags = 0;
3283 if ( is_array( $result ) ) {
3284 if ( isset( $result[0] ) ) {
3286 unset( $result[0] );
3289 # Extract flags into the local scope
3290 # This allows callers to set flags such as nowiki, found, etc.
3296 $text = $this->preprocessToDom( $text, $preprocessFlags );
3301 wfProfileOut( __METHOD__
. '-pfunc' );
3304 # Finish mangling title and then check for loops.
3305 # Set $title to a Title object and $titleText to the PDBK
3308 # Split the title into page and subpage
3310 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3311 if ( $subpage !== '' ) {
3312 $ns = $this->mTitle
->getNamespace();
3314 $title = Title
::newFromText( $part1, $ns );
3316 if ( !$title->isExternal() && $piece['interwiki'] !== '' ) {
3317 $title->setInterwiki( $piece['interwiki'] );
3319 $titleText = $title->getPrefixedText();
3320 # Check for language variants if the template is not found
3321 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3322 $wgContLang->findVariantLink( $part1, $title, true );
3324 # Do recursion depth check
3325 $limit = $this->mOptions
->getMaxTemplateDepth();
3326 if ( $frame->depth
>= $limit ) {
3328 $text = '<span class="error">'
3329 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3335 # Load from database
3336 if ( !$found && $title ) {
3337 wfProfileIn( __METHOD__
. '-loadtpl' );
3338 if ( !$title->isExternal() ) {
3339 if ( $title->getNamespace() == NS_SPECIAL
3340 && $this->mOptions
->getAllowSpecialInclusion()
3341 && $this->ot
['html'] )
3343 $pageArgs = array();
3344 for ( $i = 0; $i < $args->getLength(); $i++
) {
3345 $bits = $args->item( $i )->splitArg();
3346 if ( strval( $bits['index'] ) === '' ) {
3347 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3348 $value = trim( $frame->expand( $bits['value'] ) );
3349 $pageArgs[$name] = $value;
3352 $context = new RequestContext
;
3353 $context->setTitle( $title );
3354 $context->setRequest( new FauxRequest( $pageArgs ) );
3355 $context->setUser( $this->getUser() );
3356 $context->setLang( Language
::factory( $this->mOptions
->getUserLang() ) );
3357 $ret = SpecialPageFactory
::capturePath( $title, $context );
3359 $text = $context->getOutput()->getHTML();
3360 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3363 $this->disableCache();
3365 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3366 $found = false; # access denied
3367 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3369 list( $text, $title ) = $this->getTemplateDom( $title );
3370 if ( $text !== false ) {
3376 # If the title is valid but undisplayable, make a link to it
3377 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3378 $text = "[[:$titleText]]";
3381 } elseif ( $wgEnableInterwikiTranscluding && $title->isTrans() ) {
3383 $text = Interwiki
::interwikiTransclude( $title );
3384 $this->registerDistantTemplate( $title );
3386 if ( $wgEnableInterwikiTemplatesTracking ) {
3387 $this->registerDistantTemplate( $title );
3390 if ( $text !== false ) {
3391 # Preprocess it like a template
3392 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3399 # Do infinite loop check
3400 # This has to be done after redirect resolution to avoid infinite loops via redirects
3401 if ( !$frame->loopCheck( $title ) ) {
3403 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3404 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3406 wfProfileOut( __METHOD__
. '-loadtpl' );
3409 # If we haven't found text to substitute by now, we're done
3410 # Recover the source wikitext and return it
3412 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3413 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3414 wfProfileOut( __METHOD__
);
3415 return array( 'object' => $text );
3418 # Expand DOM-style return values in a child frame
3419 if ( $isChildObj ) {
3420 # Clean up argument array
3421 $newFrame = $frame->newChild( $args, $title );
3424 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3425 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3426 # Expansion is eligible for the empty-frame cache
3427 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3428 $text = $this->mTplExpandCache
[$titleText];
3430 $text = $newFrame->expand( $text );
3431 $this->mTplExpandCache
[$titleText] = $text;
3434 # Uncached expansion
3435 $text = $newFrame->expand( $text );
3438 if ( $isLocalObj && $nowiki ) {
3439 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3440 $isLocalObj = false;
3443 # Replace raw HTML by a placeholder
3444 # Add a blank line preceding, to prevent it from mucking up
3445 # immediately preceding headings
3447 $text = "\n\n" . $this->insertStripItem( $text );
3448 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3449 # Escape nowiki-style return values
3450 $text = wfEscapeWikiText( $text );
3451 } elseif ( is_string( $text )
3452 && !$piece['lineStart']
3453 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3455 # Bug 529: if the template begins with a table or block-level
3456 # element, it should be treated as beginning a new line.
3457 # This behaviour is somewhat controversial.
3458 $text = "\n" . $text;
3461 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3462 # Error, oversize inclusion
3463 if ( $titleText !== false ) {
3464 # Make a working, properly escaped link if possible (bug 23588)
3465 $text = "[[:$titleText]]";
3467 # This will probably not be a working link, but at least it may
3468 # provide some hint of where the problem is
3469 preg_replace( '/^:/', '', $originalTitle );
3470 $text = "[[:$originalTitle]]";
3472 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3473 $this->limitationWarn( 'post-expand-template-inclusion' );
3476 if ( $isLocalObj ) {
3477 $ret = array( 'object' => $text );
3479 $ret = array( 'text' => $text );
3482 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3483 wfProfileOut( __METHOD__
);
3488 * Get the semi-parsed DOM representation of a template with a given title,
3489 * and its redirect destination title. Cached.
3491 * @param $title Title
3495 function getTemplateDom( $title ) {
3496 $cacheTitle = $title;
3497 $titleText = $title->getPrefixedDBkey();
3499 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3500 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3501 $title = Title
::makeTitle( $ns, $dbk );
3502 $titleText = $title->getPrefixedDBkey();
3504 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3505 return array( $this->mTplDomCache
[$titleText], $title );
3508 # Cache miss, go to the database
3509 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3511 if ( $text === false ) {
3512 $this->mTplDomCache
[$titleText] = false;
3513 return array( false, $title );
3516 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3517 $this->mTplDomCache
[ $titleText ] = $dom;
3519 if ( !$title->equals( $cacheTitle ) ) {
3520 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3521 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3524 return array( $dom, $title );
3528 * Fetch the unparsed text of a template and register a reference to it.
3529 * @param Title $title
3530 * @return Array ( string or false, Title )
3532 function fetchTemplateAndTitle( $title ) {
3533 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3534 $stuff = call_user_func( $templateCb, $title, $this );
3535 $text = $stuff['text'];
3536 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3537 if ( isset( $stuff['deps'] ) ) {
3538 foreach ( $stuff['deps'] as $dep ) {
3539 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3542 return array( $text, $finalTitle );
3546 * Register a distant template as used
3548 function registerDistantTemplate( $title ) {
3549 $stuff = Parser
::distantTemplateCallback( $title, $this );
3550 $text = $stuff['text'];
3551 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3552 if ( isset( $stuff['deps'] ) ) {
3553 foreach ( $stuff['deps'] as $dep ) {
3554 $this->mOutput
->addDistantTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3559 function fetchTemplate( $title ) {
3560 $rv = $this->fetchTemplateAndTitle( $title );
3565 * Static function to get a template
3566 * Can be overridden via ParserOptions::setTemplateCallback().
3568 * @parma $title Title
3569 * @param $parser Parser
3573 static function statelessFetchTemplate( $title, $parser = false ) {
3574 $text = $skip = false;
3575 $finalTitle = $title;
3578 # Loop to fetch the article, with up to 1 redirect
3579 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3580 # Give extensions a chance to select the revision instead
3581 $id = false; # Assume current
3582 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3583 array( $parser, $title, &$skip, &$id ) );
3589 'page_id' => $title->getArticleID(),
3596 ? Revision
::newFromId( $id )
3597 : Revision
::newFromTitle( $title );
3598 $rev_id = $rev ?
$rev->getId() : 0;
3599 # If there is no current revision, there is no page
3600 if ( $id === false && !$rev ) {
3601 $linkCache = LinkCache
::singleton();
3602 $linkCache->addBadLinkObj( $title );
3607 'page_id' => $title->getArticleID(),
3608 'rev_id' => $rev_id );
3609 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3610 # We fetched a rev from a different title; register it too...
3612 'title' => $rev->getTitle(),
3613 'page_id' => $rev->getPage(),
3614 'rev_id' => $rev_id );
3618 $text = $rev->getText();
3619 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3621 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3622 if ( !$message->exists() ) {
3626 $text = $message->plain();
3630 if ( $text === false ) {
3634 $finalTitle = $title;
3635 $title = Title
::newFromRedirect( $text );
3639 'finalTitle' => $finalTitle,
3644 * Fetch a file and its title and register a reference to it.
3645 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3646 * @param Title $title
3647 * @param Array $options Array of options to RepoGroup::findFile
3648 * @return File|false
3650 function fetchFile( $title, $options = array() ) {
3651 $res = $this->fetchFileAndTitle( $title, $options );
3656 * Fetch a file and its title and register a reference to it.
3657 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3658 * @param Title $title
3659 * @param Array $options Array of options to RepoGroup::findFile
3660 * @return Array ( File or false, Title of file )
3662 function fetchFileAndTitle( $title, $options = array() ) {
3663 if ( isset( $options['broken'] ) ) {
3664 $file = false; // broken thumbnail forced by hook
3665 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3666 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3667 } else { // get by (name,timestamp)
3668 $file = wfFindFile( $title, $options );
3670 $time = $file ?
$file->getTimestamp() : false;
3671 $sha1 = $file ?
$file->getSha1() : false;
3672 # Register the file as a dependency...
3673 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3674 if ( $file && !$title->equals( $file->getTitle() ) ) {
3675 # Update fetched file title
3676 $title = $file->getTitle();
3677 if ( is_null( $file->getRedirectedTitle() ) ) {
3678 # This file was not a redirect, but the title does not match.
3679 # Register under the new name because otherwise the link will
3681 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3684 return array( $file, $title );
3687 static function distantTemplateCallback( $title, $parser=false ) {
3692 'page_id' => $title->getArticleID(),
3693 'rev_id' => $rev_id );
3695 $finalTitle = $title;
3699 'finalTitle' => $finalTitle,
3704 * Triple brace replacement -- used for template arguments
3707 * @param $peice array
3708 * @param $frame PPFrame
3712 function argSubstitution( $piece, $frame ) {
3713 wfProfileIn( __METHOD__
);
3716 $parts = $piece['parts'];
3717 $nameWithSpaces = $frame->expand( $piece['title'] );
3718 $argName = trim( $nameWithSpaces );
3720 $text = $frame->getArgument( $argName );
3721 if ( $text === false && $parts->getLength() > 0
3725 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3728 # No match in frame, use the supplied default
3729 $object = $parts->item( 0 )->getChildren();
3731 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3732 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3733 $this->limitationWarn( 'post-expand-template-argument' );
3736 if ( $text === false && $object === false ) {
3738 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3740 if ( $error !== false ) {
3743 if ( $object !== false ) {
3744 $ret = array( 'object' => $object );
3746 $ret = array( 'text' => $text );
3749 wfProfileOut( __METHOD__
);
3754 * Return the text to be used for a given extension tag.
3755 * This is the ghost of strip().
3757 * @param $params Associative array of parameters:
3758 * name PPNode for the tag name
3759 * attr PPNode for unparsed text where tag attributes are thought to be
3760 * attributes Optional associative array of parsed attributes
3761 * inner Contents of extension element
3762 * noClose Original text did not have a close tag
3763 * @param $frame PPFrame
3767 function extensionSubstitution( $params, $frame ) {
3768 $name = $frame->expand( $params['name'] );
3769 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3770 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3771 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3773 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3774 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3775 if ( $isFunctionTag ) {
3776 $markerType = 'none';
3778 $markerType = 'general';
3780 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3781 $name = strtolower( $name );
3782 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3783 if ( isset( $params['attributes'] ) ) {
3784 $attributes = $attributes +
$params['attributes'];
3787 if ( isset( $this->mTagHooks
[$name] ) ) {
3788 # Workaround for PHP bug 35229 and similar
3789 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3790 throw new MWException( "Tag hook for $name is not callable\n" );
3792 $output = call_user_func_array( $this->mTagHooks
[$name],
3793 array( $content, $attributes, $this, $frame ) );
3794 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3795 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3796 if ( !is_callable( $callback ) ) {
3797 throw new MWException( "Tag hook for $name is not callable\n" );
3800 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3802 $output = '<span class="error">Invalid tag extension name: ' .
3803 htmlspecialchars( $name ) . '</span>';
3806 if ( is_array( $output ) ) {
3807 # Extract flags to local scope (to override $markerType)
3809 $output = $flags[0];
3814 if ( is_null( $attrText ) ) {
3817 if ( isset( $params['attributes'] ) ) {
3818 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3819 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3820 htmlspecialchars( $attrValue ) . '"';
3823 if ( $content === null ) {
3824 $output = "<$name$attrText/>";
3826 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3827 $output = "<$name$attrText>$content$close";
3831 if ( $markerType === 'none' ) {
3833 } elseif ( $markerType === 'nowiki' ) {
3834 $this->mStripState
->addNoWiki( $marker, $output );
3835 } elseif ( $markerType === 'general' ) {
3836 $this->mStripState
->addGeneral( $marker, $output );
3838 throw new MWException( __METHOD__
.': invalid marker type' );
3844 * Increment an include size counter
3846 * @param $type String: the type of expansion
3847 * @param $size Integer: the size of the text
3848 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3850 function incrementIncludeSize( $type, $size ) {
3851 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3854 $this->mIncludeSizes
[$type] +
= $size;
3860 * Increment the expensive function count
3862 * @return Boolean: false if the limit has been exceeded
3864 function incrementExpensiveFunctionCount() {
3865 global $wgExpensiveParserFunctionLimit;
3866 $this->mExpensiveFunctionCount++
;
3867 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3874 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3875 * Fills $this->mDoubleUnderscores, returns the modified text
3877 * @param $text string
3881 function doDoubleUnderscore( $text ) {
3882 wfProfileIn( __METHOD__
);
3884 # The position of __TOC__ needs to be recorded
3885 $mw = MagicWord
::get( 'toc' );
3886 if ( $mw->match( $text ) ) {
3887 $this->mShowToc
= true;
3888 $this->mForceTocPosition
= true;
3890 # Set a placeholder. At the end we'll fill it in with the TOC.
3891 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3893 # Only keep the first one.
3894 $text = $mw->replace( '', $text );
3897 # Now match and remove the rest of them
3898 $mwa = MagicWord
::getDoubleUnderscoreArray();
3899 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3901 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3902 $this->mOutput
->mNoGallery
= true;
3904 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3905 $this->mShowToc
= false;
3907 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3908 $this->addTrackingCategory( 'hidden-category-category' );
3910 # (bug 8068) Allow control over whether robots index a page.
3912 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3913 # is not desirable, the last one on the page should win.
3914 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3915 $this->mOutput
->setIndexPolicy( 'noindex' );
3916 $this->addTrackingCategory( 'noindex-category' );
3918 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3919 $this->mOutput
->setIndexPolicy( 'index' );
3920 $this->addTrackingCategory( 'index-category' );
3923 # Cache all double underscores in the database
3924 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3925 $this->mOutput
->setProperty( $key, '' );
3928 wfProfileOut( __METHOD__
);
3933 * Add a tracking category, getting the title from a system message,
3934 * or print a debug message if the title is invalid.
3936 * @param $msg String: message key
3937 * @return Boolean: whether the addition was successful
3939 protected function addTrackingCategory( $msg ) {
3940 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3941 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3944 $cat = wfMsgForContent( $msg );
3946 # Allow tracking categories to be disabled by setting them to "-"
3947 if ( $cat === '-' ) {
3951 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3952 if ( $containerCategory ) {
3953 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3956 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3962 * This function accomplishes several tasks:
3963 * 1) Auto-number headings if that option is enabled
3964 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3965 * 3) Add a Table of contents on the top for users who have enabled the option
3966 * 4) Auto-anchor headings
3968 * It loops through all headlines, collects the necessary data, then splits up the
3969 * string and re-inserts the newly formatted headlines.
3971 * @param $text String
3972 * @param $origText String: original, untouched wikitext
3973 * @param $isMain Boolean
3976 function formatHeadings( $text, $origText, $isMain=true ) {
3977 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3979 # Inhibit editsection links if requested in the page
3980 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3983 $showEditLink = $this->mOptions
->getEditSection();
3985 if ( $showEditLink ) {
3986 $this->mOutput
->setEditSectionTokens( true );
3989 # Get all headlines for numbering them and adding funky stuff like [edit]
3990 # links - this is for later, but we need the number of headlines right now
3992 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3994 # if there are fewer than 4 headlines in the article, do not show TOC
3995 # unless it's been explicitly enabled.
3996 $enoughToc = $this->mShowToc
&&
3997 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3999 # Allow user to stipulate that a page should have a "new section"
4000 # link added via __NEWSECTIONLINK__
4001 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4002 $this->mOutput
->setNewSection( true );
4005 # Allow user to remove the "new section"
4006 # link via __NONEWSECTIONLINK__
4007 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4008 $this->mOutput
->hideNewSection( true );
4011 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4012 # override above conditions and always show TOC above first header
4013 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4014 $this->mShowToc
= true;
4022 # Ugh .. the TOC should have neat indentation levels which can be
4023 # passed to the skin functions. These are determined here
4027 $sublevelCount = array();
4028 $levelCount = array();
4033 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4034 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4035 $oldType = $this->mOutputType
;
4036 $this->setOutputType( self
::OT_WIKI
);
4037 $frame = $this->getPreprocessor()->newFrame();
4038 $root = $this->preprocessToDom( $origText );
4039 $node = $root->getFirstChild();
4044 foreach ( $matches[3] as $headline ) {
4045 $isTemplate = false;
4047 $sectionIndex = false;
4049 $markerMatches = array();
4050 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4051 $serial = $markerMatches[1];
4052 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4053 $isTemplate = ( $titleText != $baseTitleText );
4054 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4058 $prevlevel = $level;
4060 $level = $matches[1][$headlineCount];
4062 if ( $level > $prevlevel ) {
4063 # Increase TOC level
4065 $sublevelCount[$toclevel] = 0;
4066 if ( $toclevel<$wgMaxTocLevel ) {
4067 $prevtoclevel = $toclevel;
4068 $toc .= Linker
::tocIndent();
4071 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4072 # Decrease TOC level, find level to jump to
4074 for ( $i = $toclevel; $i > 0; $i-- ) {
4075 if ( $levelCount[$i] == $level ) {
4076 # Found last matching level
4079 } elseif ( $levelCount[$i] < $level ) {
4080 # Found first matching level below current level
4088 if ( $toclevel<$wgMaxTocLevel ) {
4089 if ( $prevtoclevel < $wgMaxTocLevel ) {
4090 # Unindent only if the previous toc level was shown :p
4091 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4092 $prevtoclevel = $toclevel;
4094 $toc .= Linker
::tocLineEnd();
4098 # No change in level, end TOC line
4099 if ( $toclevel<$wgMaxTocLevel ) {
4100 $toc .= Linker
::tocLineEnd();
4104 $levelCount[$toclevel] = $level;
4106 # count number of headlines for each level
4107 @$sublevelCount[$toclevel]++
;
4109 for( $i = 1; $i <= $toclevel; $i++
) {
4110 if ( !empty( $sublevelCount[$i] ) ) {
4114 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4119 # The safe header is a version of the header text safe to use for links
4120 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4121 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4123 # Remove link placeholders by the link text.
4124 # <!--LINK number-->
4126 # link text with suffix
4127 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4129 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4130 $tocline = preg_replace(
4131 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4132 array( '', '<$1>' ),
4135 $tocline = trim( $tocline );
4137 # For the anchor, strip out HTML-y stuff period
4138 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4139 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4141 # Save headline for section edit hint before it's escaped
4142 $headlineHint = $safeHeadline;
4144 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4145 # For reverse compatibility, provide an id that's
4146 # HTML4-compatible, like we used to.
4148 # It may be worth noting, academically, that it's possible for
4149 # the legacy anchor to conflict with a non-legacy headline
4150 # anchor on the page. In this case likely the "correct" thing
4151 # would be to either drop the legacy anchors or make sure
4152 # they're numbered first. However, this would require people
4153 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4154 # manually, so let's not bother worrying about it.
4155 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4156 array( 'noninitial', 'legacy' ) );
4157 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4159 if ( $legacyHeadline == $safeHeadline ) {
4160 # No reason to have both (in fact, we can't)
4161 $legacyHeadline = false;
4164 $legacyHeadline = false;
4165 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4169 # HTML names must be case-insensitively unique (bug 10721).
4170 # This does not apply to Unicode characters per
4171 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4172 # @todo FIXME: We may be changing them depending on the current locale.
4173 $arrayKey = strtolower( $safeHeadline );
4174 if ( $legacyHeadline === false ) {
4175 $legacyArrayKey = false;
4177 $legacyArrayKey = strtolower( $legacyHeadline );
4180 # count how many in assoc. array so we can track dupes in anchors
4181 if ( isset( $refers[$arrayKey] ) ) {
4182 $refers[$arrayKey]++
;
4184 $refers[$arrayKey] = 1;
4186 if ( isset( $refers[$legacyArrayKey] ) ) {
4187 $refers[$legacyArrayKey]++
;
4189 $refers[$legacyArrayKey] = 1;
4192 # Don't number the heading if it is the only one (looks silly)
4193 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4194 # the two are different if the line contains a link
4195 $headline = $numbering . ' ' . $headline;
4198 # Create the anchor for linking from the TOC to the section
4199 $anchor = $safeHeadline;
4200 $legacyAnchor = $legacyHeadline;
4201 if ( $refers[$arrayKey] > 1 ) {
4202 $anchor .= '_' . $refers[$arrayKey];
4204 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4205 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4207 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4208 $toc .= Linker
::tocLine( $anchor, $tocline,
4209 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4212 # Add the section to the section tree
4213 # Find the DOM node for this header
4214 while ( $node && !$isTemplate ) {
4215 if ( $node->getName() === 'h' ) {
4216 $bits = $node->splitHeading();
4217 if ( $bits['i'] == $sectionIndex ) {
4221 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4222 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4223 $node = $node->getNextSibling();
4226 'toclevel' => $toclevel,
4229 'number' => $numbering,
4230 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4231 'fromtitle' => $titleText,
4232 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4233 'anchor' => $anchor,
4236 # give headline the correct <h#> tag
4237 if ( $showEditLink && $sectionIndex !== false ) {
4238 // Output edit section links as markers with styles that can be customized by skins
4239 if ( $isTemplate ) {
4240 # Put a T flag in the section identifier, to indicate to extractSections()
4241 # that sections inside <includeonly> should be counted.
4242 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4244 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4246 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4247 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4248 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4249 // so we don't have to worry about a user trying to input one of these markers directly.
4250 // We use a page and section attribute to stop the language converter from converting these important bits
4251 // of data, but put the headline hint inside a content block because the language converter is supposed to
4252 // be able to convert that piece of data.
4253 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4254 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4255 if ( isset($editlinkArgs[2]) ) {
4256 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4263 $head[$headlineCount] = Linker
::makeHeadline( $level,
4264 $matches['attrib'][$headlineCount], $anchor, $headline,
4265 $editlink, $legacyAnchor );
4270 $this->setOutputType( $oldType );
4272 # Never ever show TOC if no headers
4273 if ( $numVisible < 1 ) {
4278 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4279 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4281 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4282 $this->mOutput
->setTOCHTML( $toc );
4286 $this->mOutput
->setSections( $tocraw );
4289 # split up and insert constructed headlines
4290 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4293 // build an array of document sections
4294 $sections = array();
4295 foreach ( $blocks as $block ) {
4296 // $head is zero-based, sections aren't.
4297 if ( empty( $head[$i - 1] ) ) {
4298 $sections[$i] = $block;
4300 $sections[$i] = $head[$i - 1] . $block;
4304 * Send a hook, one per section.
4305 * The idea here is to be able to make section-level DIVs, but to do so in a
4306 * lower-impact, more correct way than r50769
4309 * $section : the section number
4310 * &$sectionContent : ref to the content of the section
4311 * $showEditLinks : boolean describing whether this section has an edit link
4313 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4318 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4319 // append the TOC at the beginning
4320 // Top anchor now in skin
4321 $sections[0] = $sections[0] . $toc . "\n";
4324 $full .= join( '', $sections );
4326 if ( $this->mForceTocPosition
) {
4327 return str_replace( '<!--MWTOC-->', $toc, $full );
4334 * Transform wiki markup when saving a page by doing \r\n -> \n
4335 * conversion, substitting signatures, {{subst:}} templates, etc.
4337 * @param $text String: the text to transform
4338 * @param $title Title: the Title object for the current article
4339 * @param $user User: the User object describing the current user
4340 * @param $options ParserOptions: parsing options
4341 * @param $clearState Boolean: whether to clear the parser state first
4342 * @return String: the altered wiki markup
4344 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4345 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4346 $this->setUser( $user );
4351 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4352 if( $options->getPreSaveTransform() ) {
4353 $text = $this->pstPass2( $text, $user );
4355 $text = $this->mStripState
->unstripBoth( $text );
4357 $this->setUser( null ); #Reset
4363 * Pre-save transform helper function
4366 * @param $text string
4371 function pstPass2( $text, $user ) {
4372 global $wgContLang, $wgLocaltimezone;
4374 # Note: This is the timestamp saved as hardcoded wikitext to
4375 # the database, we use $wgContLang here in order to give
4376 # everyone the same signature and use the default one rather
4377 # than the one selected in each user's preferences.
4378 # (see also bug 12815)
4379 $ts = $this->mOptions
->getTimestamp();
4380 if ( isset( $wgLocaltimezone ) ) {
4381 $tz = $wgLocaltimezone;
4383 $tz = date_default_timezone_get();
4386 $unixts = wfTimestamp( TS_UNIX
, $ts );
4387 $oldtz = date_default_timezone_get();
4388 date_default_timezone_set( $tz );
4389 $ts = date( 'YmdHis', $unixts );
4390 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4392 # Allow translation of timezones through wiki. date() can return
4393 # whatever crap the system uses, localised or not, so we cannot
4394 # ship premade translations.
4395 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4396 $msg = wfMessage( $key )->inContentLanguage();
4397 if ( $msg->exists() ) {
4398 $tzMsg = $msg->text();
4401 date_default_timezone_set( $oldtz );
4403 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4405 # Variable replacement
4406 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4407 $text = $this->replaceVariables( $text );
4409 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4410 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4413 $sigText = $this->getUserSig( $user );
4414 $text = strtr( $text, array(
4416 '~~~~' => "$sigText $d",
4420 # Context links: [[|name]] and [[name (context)|]]
4421 global $wgLegalTitleChars;
4422 $tc = "[$wgLegalTitleChars]";
4423 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4425 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4426 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4427 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4428 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4430 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4431 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4432 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4433 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4435 $t = $this->mTitle
->getText();
4437 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4438 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4439 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4440 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4442 # if there's no context, don't bother duplicating the title
4443 $text = preg_replace( $p2, '[[\\1]]', $text );
4446 # Trim trailing whitespace
4447 $text = rtrim( $text );
4453 * Fetch the user's signature text, if any, and normalize to
4454 * validated, ready-to-insert wikitext.
4455 * If you have pre-fetched the nickname or the fancySig option, you can
4456 * specify them here to save a database query.
4457 * Do not reuse this parser instance after calling getUserSig(),
4458 * as it may have changed if it's the $wgParser.
4461 * @param $nickname String|bool nickname to use or false to use user's default nickname
4462 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4463 * or null to use default value
4466 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4467 global $wgMaxSigChars;
4469 $username = $user->getName();
4471 # If not given, retrieve from the user object.
4472 if ( $nickname === false )
4473 $nickname = $user->getOption( 'nickname' );
4475 if ( is_null( $fancySig ) ) {
4476 $fancySig = $user->getBoolOption( 'fancysig' );
4479 $nickname = $nickname == null ?
$username : $nickname;
4481 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4482 $nickname = $username;
4483 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4484 } elseif ( $fancySig !== false ) {
4485 # Sig. might contain markup; validate this
4486 if ( $this->validateSig( $nickname ) !== false ) {
4487 # Validated; clean up (if needed) and return it
4488 return $this->cleanSig( $nickname, true );
4490 # Failed to validate; fall back to the default
4491 $nickname = $username;
4492 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4496 # Make sure nickname doesnt get a sig in a sig
4497 $nickname = $this->cleanSigInSig( $nickname );
4499 # If we're still here, make it a link to the user page
4500 $userText = wfEscapeWikiText( $username );
4501 $nickText = wfEscapeWikiText( $nickname );
4502 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4504 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4508 * Check that the user's signature contains no bad XML
4510 * @param $text String
4511 * @return mixed An expanded string, or false if invalid.
4513 function validateSig( $text ) {
4514 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4518 * Clean up signature text
4520 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4521 * 2) Substitute all transclusions
4523 * @param $text String
4524 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4525 * @return String: signature text
4527 function cleanSig( $text, $parsing = false ) {
4530 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4533 # Option to disable this feature
4534 if ( !$this->mOptions
->getCleanSignatures() ) {
4538 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4539 # => Move this logic to braceSubstitution()
4540 $substWord = MagicWord
::get( 'subst' );
4541 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4542 $substText = '{{' . $substWord->getSynonym( 0 );
4544 $text = preg_replace( $substRegex, $substText, $text );
4545 $text = $this->cleanSigInSig( $text );
4546 $dom = $this->preprocessToDom( $text );
4547 $frame = $this->getPreprocessor()->newFrame();
4548 $text = $frame->expand( $dom );
4551 $text = $this->mStripState
->unstripBoth( $text );
4558 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4560 * @param $text String
4561 * @return String: signature text with /~{3,5}/ removed
4563 function cleanSigInSig( $text ) {
4564 $text = preg_replace( '/~{3,5}/', '', $text );
4569 * Set up some variables which are usually set up in parse()
4570 * so that an external function can call some class members with confidence
4572 * @param $title Title|null
4573 * @param $options ParserOptions
4574 * @param $outputType
4575 * @param $clearState bool
4577 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4578 $this->startParse( $title, $options, $outputType, $clearState );
4582 * @param $title Title|null
4583 * @param $options ParserOptions
4584 * @param $outputType
4585 * @param $clearState bool
4587 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4588 $this->setTitle( $title );
4589 $this->mOptions
= $options;
4590 $this->setOutputType( $outputType );
4591 if ( $clearState ) {
4592 $this->clearState();
4597 * Wrapper for preprocess()
4599 * @param $text String: the text to preprocess
4600 * @param $options ParserOptions: options
4601 * @param $title Title object or null to use $wgTitle
4604 public function transformMsg( $text, $options, $title = null ) {
4605 static $executing = false;
4607 # Guard against infinite recursion
4613 wfProfileIn( __METHOD__
);
4619 # It's not uncommon having a null $wgTitle in scripts. See r80898
4620 # Create a ghost title in such case
4621 $title = Title
::newFromText( 'Dwimmerlaik' );
4623 $text = $this->preprocess( $text, $title, $options );
4626 wfProfileOut( __METHOD__
);
4631 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4632 * The callback should have the following form:
4633 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4635 * Transform and return $text. Use $parser for any required context, e.g. use
4636 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4638 * Hooks may return extended information by returning an array, of which the
4639 * first numbered element (index 0) must be the return string, and all other
4640 * entries are extracted into local variables within an internal function
4641 * in the Parser class.
4643 * This interface (introduced r61913) appears to be undocumented, but
4644 * 'markerName' is used by some core tag hooks to override which strip
4645 * array their results are placed in. **Use great caution if attempting
4646 * this interface, as it is not documented and injudicious use could smash
4647 * private variables.**
4649 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4650 * @param $callback Mixed: the callback function (and object) to use for the tag
4651 * @return The old value of the mTagHooks array associated with the hook
4653 public function setHook( $tag, $callback ) {
4654 $tag = strtolower( $tag );
4655 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4656 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4657 $this->mTagHooks
[$tag] = $callback;
4658 if ( !in_array( $tag, $this->mStripList
) ) {
4659 $this->mStripList
[] = $tag;
4666 * As setHook(), but letting the contents be parsed.
4668 * Transparent tag hooks are like regular XML-style tag hooks, except they
4669 * operate late in the transformation sequence, on HTML instead of wikitext.
4671 * This is probably obsoleted by things dealing with parser frames?
4672 * The only extension currently using it is geoserver.
4675 * @todo better document or deprecate this
4677 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4678 * @param $callback Mixed: the callback function (and object) to use for the tag
4679 * @return The old value of the mTagHooks array associated with the hook
4681 function setTransparentTagHook( $tag, $callback ) {
4682 $tag = strtolower( $tag );
4683 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4684 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4685 $this->mTransparentTagHooks
[$tag] = $callback;
4691 * Remove all tag hooks
4693 function clearTagHooks() {
4694 $this->mTagHooks
= array();
4695 $this->mStripList
= $this->mDefaultStripList
;
4699 * Remove a specific tag hook. Should not be called on $wgParser.
4700 * Does not change the strip list.
4702 * @param string $tag
4705 function clearTagHook( $tag ) {
4706 if ( isset( $this->mTagHooks
[$tag] ) ) {
4707 unset( $this->mTagHooks
[$tag] );
4712 * Create a function, e.g. {{sum:1|2|3}}
4713 * The callback function should have the form:
4714 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4716 * Or with SFH_OBJECT_ARGS:
4717 * function myParserFunction( $parser, $frame, $args ) { ... }
4719 * The callback may either return the text result of the function, or an array with the text
4720 * in element 0, and a number of flags in the other elements. The names of the flags are
4721 * specified in the keys. Valid flags are:
4722 * found The text returned is valid, stop processing the template. This
4724 * nowiki Wiki markup in the return value should be escaped
4725 * isHTML The returned text is HTML, armour it against wikitext transformation
4727 * @param $id String: The magic word ID
4728 * @param $callback Mixed: the callback function (and object) to use
4729 * @param $flags Integer: a combination of the following flags:
4730 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4732 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4733 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4734 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4735 * the arguments, and to control the way they are expanded.
4737 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4738 * arguments, for instance:
4739 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4741 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4742 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4743 * working if/when this is changed.
4745 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4748 * Please read the documentation in includes/parser/Preprocessor.php for more information
4749 * about the methods available in PPFrame and PPNode.
4751 * @return The old callback function for this name, if any
4753 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4756 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4757 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4759 # Add to function cache
4760 $mw = MagicWord
::get( $id );
4762 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4764 $synonyms = $mw->getSynonyms();
4765 $sensitive = intval( $mw->isCaseSensitive() );
4767 foreach ( $synonyms as $syn ) {
4769 if ( !$sensitive ) {
4770 $syn = $wgContLang->lc( $syn );
4773 if ( !( $flags & SFH_NO_HASH
) ) {
4776 # Remove trailing colon
4777 if ( substr( $syn, -1, 1 ) === ':' ) {
4778 $syn = substr( $syn, 0, -1 );
4780 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4786 * Get all registered function hook identifiers
4790 function getFunctionHooks() {
4791 return array_keys( $this->mFunctionHooks
);
4795 * Create a tag function, e.g. <test>some stuff</test>.
4796 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4797 * Unlike parser functions, their content is not preprocessed.
4799 function setFunctionTagHook( $tag, $callback, $flags ) {
4800 $tag = strtolower( $tag );
4801 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4802 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4803 $this->mFunctionTagHooks
[$tag] : null;
4804 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4806 if ( !in_array( $tag, $this->mStripList
) ) {
4807 $this->mStripList
[] = $tag;
4814 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4815 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4816 * Placeholders created in Skin::makeLinkObj()
4818 * @param $text string
4819 * @param $options int
4821 * @return array of link CSS classes, indexed by PDBK.
4823 function replaceLinkHolders( &$text, $options = 0 ) {
4824 return $this->mLinkHolders
->replace( $text );
4828 * Replace <!--LINK--> link placeholders with plain text of links
4829 * (not HTML-formatted).
4831 * @param $text String
4834 function replaceLinkHoldersText( $text ) {
4835 return $this->mLinkHolders
->replaceText( $text );
4839 * Renders an image gallery from a text with one line per image.
4840 * text labels may be given by using |-style alternative text. E.g.
4841 * Image:one.jpg|The number "1"
4842 * Image:tree.jpg|A tree
4843 * given as text will return the HTML of a gallery with two images,
4844 * labeled 'The number "1"' and
4847 * @param string $text
4848 * @param array $params
4849 * @return string HTML
4851 function renderImageGallery( $text, $params ) {
4852 $ig = new ImageGallery();
4853 $ig->setContextTitle( $this->mTitle
);
4854 $ig->setShowBytes( false );
4855 $ig->setShowFilename( false );
4856 $ig->setParser( $this );
4857 $ig->setHideBadImages();
4858 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4860 if ( isset( $params['showfilename'] ) ) {
4861 $ig->setShowFilename( true );
4863 $ig->setShowFilename( false );
4865 if ( isset( $params['caption'] ) ) {
4866 $caption = $params['caption'];
4867 $caption = htmlspecialchars( $caption );
4868 $caption = $this->replaceInternalLinks( $caption );
4869 $ig->setCaptionHtml( $caption );
4871 if ( isset( $params['perrow'] ) ) {
4872 $ig->setPerRow( $params['perrow'] );
4874 if ( isset( $params['widths'] ) ) {
4875 $ig->setWidths( $params['widths'] );
4877 if ( isset( $params['heights'] ) ) {
4878 $ig->setHeights( $params['heights'] );
4881 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4883 $lines = StringUtils
::explode( "\n", $text );
4884 foreach ( $lines as $line ) {
4885 # match lines like these:
4886 # Image:someimage.jpg|This is some image
4888 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4890 if ( count( $matches ) == 0 ) {
4894 if ( strpos( $matches[0], '%' ) !== false ) {
4895 $matches[1] = rawurldecode( $matches[1] );
4897 $title = Title
::newFromText( $matches[1], NS_FILE
);
4898 if ( is_null( $title ) ) {
4899 # Bogus title. Ignore these so we don't bomb out later.
4905 if ( isset( $matches[3] ) ) {
4906 // look for an |alt= definition while trying not to break existing
4907 // captions with multiple pipes (|) in it, until a more sensible grammar
4908 // is defined for images in galleries
4910 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4911 $altmatches = StringUtils
::explode('|', $matches[3]);
4912 $magicWordAlt = MagicWord
::get( 'img_alt' );
4914 foreach ( $altmatches as $altmatch ) {
4915 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4917 $alt = $this->stripAltText( $match, false );
4920 // concatenate all other pipes
4921 $label .= '|' . $altmatch;
4924 // remove the first pipe
4925 $label = substr( $label, 1 );
4928 $ig->add( $title, $label, $alt );
4930 return $ig->toHTML();
4937 function getImageParams( $handler ) {
4939 $handlerClass = get_class( $handler );
4943 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4944 # Initialise static lists
4945 static $internalParamNames = array(
4946 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4947 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4948 'bottom', 'text-bottom' ),
4949 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4950 'upright', 'border', 'link', 'alt' ),
4952 static $internalParamMap;
4953 if ( !$internalParamMap ) {
4954 $internalParamMap = array();
4955 foreach ( $internalParamNames as $type => $names ) {
4956 foreach ( $names as $name ) {
4957 $magicName = str_replace( '-', '_', "img_$name" );
4958 $internalParamMap[$magicName] = array( $type, $name );
4963 # Add handler params
4964 $paramMap = $internalParamMap;
4966 $handlerParamMap = $handler->getParamMap();
4967 foreach ( $handlerParamMap as $magic => $paramName ) {
4968 $paramMap[$magic] = array( 'handler', $paramName );
4971 $this->mImageParams
[$handlerClass] = $paramMap;
4972 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4974 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4978 * Parse image options text and use it to make an image
4980 * @param $title Title
4981 * @param $options String
4982 * @param $holders LinkHolderArray|false
4983 * @return string HTML
4985 function makeImage( $title, $options, $holders = false ) {
4986 # Check if the options text is of the form "options|alt text"
4988 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4989 # * left no resizing, just left align. label is used for alt= only
4990 # * right same, but right aligned
4991 # * none same, but not aligned
4992 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4993 # * center center the image
4994 # * frame Keep original image size, no magnify-button.
4995 # * framed Same as "frame"
4996 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4997 # * upright reduce width for upright images, rounded to full __0 px
4998 # * border draw a 1px border around the image
4999 # * alt Text for HTML alt attribute (defaults to empty)
5000 # * link Set the target of the image link. Can be external, interwiki, or local
5001 # vertical-align values (no % or length right now):
5011 $parts = StringUtils
::explode( "|", $options );
5013 # Give extensions a chance to select the file revision for us
5016 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5017 array( $this, $title, &$options, &$descQuery ) );
5018 # Fetch and register the file (file title may be different via hooks)
5019 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5022 $handler = $file ?
$file->getHandler() : false;
5024 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5027 $this->addTrackingCategory( 'broken-file-category' );
5030 # Process the input parameters
5032 $params = array( 'frame' => array(), 'handler' => array(),
5033 'horizAlign' => array(), 'vertAlign' => array() );
5034 foreach ( $parts as $part ) {
5035 $part = trim( $part );
5036 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5038 if ( isset( $paramMap[$magicName] ) ) {
5039 list( $type, $paramName ) = $paramMap[$magicName];
5041 # Special case; width and height come in one variable together
5042 if ( $type === 'handler' && $paramName === 'width' ) {
5044 # (bug 13500) In both cases (width/height and width only),
5045 # permit trailing "px" for backward compatibility.
5046 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5047 $width = intval( $m[1] );
5048 $height = intval( $m[2] );
5049 if ( $handler->validateParam( 'width', $width ) ) {
5050 $params[$type]['width'] = $width;
5053 if ( $handler->validateParam( 'height', $height ) ) {
5054 $params[$type]['height'] = $height;
5057 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5058 $width = intval( $value );
5059 if ( $handler->validateParam( 'width', $width ) ) {
5060 $params[$type]['width'] = $width;
5063 } # else no validation -- bug 13436
5065 if ( $type === 'handler' ) {
5066 # Validate handler parameter
5067 $validated = $handler->validateParam( $paramName, $value );
5069 # Validate internal parameters
5070 switch( $paramName ) {
5073 # @todo FIXME: Possibly check validity here for
5074 # manualthumb? downstream behavior seems odd with
5075 # missing manual thumbs.
5077 $value = $this->stripAltText( $value, $holders );
5080 $chars = self
::EXT_LINK_URL_CLASS
;
5081 $prots = $this->mUrlProtocols
;
5082 if ( $value === '' ) {
5083 $paramName = 'no-link';
5086 } elseif ( preg_match( "/^$prots/", $value ) ) {
5087 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5088 $paramName = 'link-url';
5089 $this->mOutput
->addExternalLink( $value );
5090 if ( $this->mOptions
->getExternalLinkTarget() ) {
5091 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5096 $linkTitle = Title
::newFromText( $value );
5098 $paramName = 'link-title';
5099 $value = $linkTitle;
5100 $this->mOutput
->addLink( $linkTitle );
5106 # Most other things appear to be empty or numeric...
5107 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5112 $params[$type][$paramName] = $value;
5116 if ( !$validated ) {
5121 # Process alignment parameters
5122 if ( $params['horizAlign'] ) {
5123 $params['frame']['align'] = key( $params['horizAlign'] );
5125 if ( $params['vertAlign'] ) {
5126 $params['frame']['valign'] = key( $params['vertAlign'] );
5129 $params['frame']['caption'] = $caption;
5131 # Will the image be presented in a frame, with the caption below?
5132 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5133 isset( $params['frame']['framed'] ) ||
5134 isset( $params['frame']['thumbnail'] ) ||
5135 isset( $params['frame']['manualthumb'] );
5137 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5138 # came to also set the caption, ordinary text after the image -- which
5139 # makes no sense, because that just repeats the text multiple times in
5140 # screen readers. It *also* came to set the title attribute.
5142 # Now that we have an alt attribute, we should not set the alt text to
5143 # equal the caption: that's worse than useless, it just repeats the
5144 # text. This is the framed/thumbnail case. If there's no caption, we
5145 # use the unnamed parameter for alt text as well, just for the time be-
5146 # ing, if the unnamed param is set and the alt param is not.
5148 # For the future, we need to figure out if we want to tweak this more,
5149 # e.g., introducing a title= parameter for the title; ignoring the un-
5150 # named parameter entirely for images without a caption; adding an ex-
5151 # plicit caption= parameter and preserving the old magic unnamed para-
5153 if ( $imageIsFramed ) { # Framed image
5154 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5155 # No caption or alt text, add the filename as the alt text so
5156 # that screen readers at least get some description of the image
5157 $params['frame']['alt'] = $title->getText();
5159 # Do not set $params['frame']['title'] because tooltips don't make sense
5161 } else { # Inline image
5162 if ( !isset( $params['frame']['alt'] ) ) {
5163 # No alt text, use the "caption" for the alt text
5164 if ( $caption !== '') {
5165 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5167 # No caption, fall back to using the filename for the
5169 $params['frame']['alt'] = $title->getText();
5172 # Use the "caption" for the tooltip text
5173 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5176 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5178 # Linker does the rest
5179 $time = isset( $options['time'] ) ?
$options['time'] : false;
5180 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5181 $time, $descQuery, $this->mOptions
->getThumbSize() );
5183 # Give the handler a chance to modify the parser object
5185 $handler->parserTransformHook( $this, $file );
5193 * @param $holders LinkHolderArray
5194 * @return mixed|String
5196 protected function stripAltText( $caption, $holders ) {
5197 # Strip bad stuff out of the title (tooltip). We can't just use
5198 # replaceLinkHoldersText() here, because if this function is called
5199 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5201 $tooltip = $holders->replaceText( $caption );
5203 $tooltip = $this->replaceLinkHoldersText( $caption );
5206 # make sure there are no placeholders in thumbnail attributes
5207 # that are later expanded to html- so expand them now and
5209 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5210 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5216 * Set a flag in the output object indicating that the content is dynamic and
5217 * shouldn't be cached.
5219 function disableCache() {
5220 wfDebug( "Parser output marked as uncacheable.\n" );
5221 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5222 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5226 * Callback from the Sanitizer for expanding items found in HTML attribute
5227 * values, so they can be safely tested and escaped.
5229 * @param $text String
5230 * @param $frame PPFrame
5233 function attributeStripCallback( &$text, $frame = false ) {
5234 $text = $this->replaceVariables( $text, $frame );
5235 $text = $this->mStripState
->unstripBoth( $text );
5244 function getTags() {
5245 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5249 * Replace transparent tags in $text with the values given by the callbacks.
5251 * Transparent tag hooks are like regular XML-style tag hooks, except they
5252 * operate late in the transformation sequence, on HTML instead of wikitext.
5254 * @param $text string
5258 function replaceTransparentTags( $text ) {
5260 $elements = array_keys( $this->mTransparentTagHooks
);
5261 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5262 $replacements = array();
5264 foreach ( $matches as $marker => $data ) {
5265 list( $element, $content, $params, $tag ) = $data;
5266 $tagName = strtolower( $element );
5267 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5268 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5272 $replacements[$marker] = $output;
5274 return strtr( $text, $replacements );
5278 * Break wikitext input into sections, and either pull or replace
5279 * some particular section's text.
5281 * External callers should use the getSection and replaceSection methods.
5283 * @param $text String: Page wikitext
5284 * @param $section String: a section identifier string of the form:
5285 * <flag1> - <flag2> - ... - <section number>
5287 * Currently the only recognised flag is "T", which means the target section number
5288 * was derived during a template inclusion parse, in other words this is a template
5289 * section edit link. If no flags are given, it was an ordinary section edit link.
5290 * This flag is required to avoid a section numbering mismatch when a section is
5291 * enclosed by <includeonly> (bug 6563).
5293 * The section number 0 pulls the text before the first heading; other numbers will
5294 * pull the given section along with its lower-level subsections. If the section is
5295 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5297 * Section 0 is always considered to exist, even if it only contains the empty
5298 * string. If $text is the empty string and section 0 is replaced, $newText is
5301 * @param $mode String: one of "get" or "replace"
5302 * @param $newText String: replacement text for section data.
5303 * @return String: for "get", the extracted section text.
5304 * for "replace", the whole page with the section replaced.
5306 private function extractSections( $text, $section, $mode, $newText='' ) {
5307 global $wgTitle; # not generally used but removes an ugly failure mode
5308 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5310 $frame = $this->getPreprocessor()->newFrame();
5312 # Process section extraction flags
5314 $sectionParts = explode( '-', $section );
5315 $sectionIndex = array_pop( $sectionParts );
5316 foreach ( $sectionParts as $part ) {
5317 if ( $part === 'T' ) {
5318 $flags |
= self
::PTD_FOR_INCLUSION
;
5322 # Check for empty input
5323 if ( strval( $text ) === '' ) {
5324 # Only sections 0 and T-0 exist in an empty document
5325 if ( $sectionIndex == 0 ) {
5326 if ( $mode === 'get' ) {
5332 if ( $mode === 'get' ) {
5340 # Preprocess the text
5341 $root = $this->preprocessToDom( $text, $flags );
5343 # <h> nodes indicate section breaks
5344 # They can only occur at the top level, so we can find them by iterating the root's children
5345 $node = $root->getFirstChild();
5347 # Find the target section
5348 if ( $sectionIndex == 0 ) {
5349 # Section zero doesn't nest, level=big
5350 $targetLevel = 1000;
5353 if ( $node->getName() === 'h' ) {
5354 $bits = $node->splitHeading();
5355 if ( $bits['i'] == $sectionIndex ) {
5356 $targetLevel = $bits['level'];
5360 if ( $mode === 'replace' ) {
5361 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5363 $node = $node->getNextSibling();
5369 if ( $mode === 'get' ) {
5376 # Find the end of the section, including nested sections
5378 if ( $node->getName() === 'h' ) {
5379 $bits = $node->splitHeading();
5380 $curLevel = $bits['level'];
5381 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5385 if ( $mode === 'get' ) {
5386 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5388 $node = $node->getNextSibling();
5391 # Write out the remainder (in replace mode only)
5392 if ( $mode === 'replace' ) {
5393 # Output the replacement text
5394 # Add two newlines on -- trailing whitespace in $newText is conventionally
5395 # stripped by the editor, so we need both newlines to restore the paragraph gap
5396 # Only add trailing whitespace if there is newText
5397 if ( $newText != "" ) {
5398 $outText .= $newText . "\n\n";
5402 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5403 $node = $node->getNextSibling();
5407 if ( is_string( $outText ) ) {
5408 # Re-insert stripped tags
5409 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5416 * This function returns the text of a section, specified by a number ($section).
5417 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5418 * the first section before any such heading (section 0).
5420 * If a section contains subsections, these are also returned.
5422 * @param $text String: text to look in
5423 * @param $section String: section identifier
5424 * @param $deftext String: default to return if section is not found
5425 * @return string text of the requested section
5427 public function getSection( $text, $section, $deftext='' ) {
5428 return $this->extractSections( $text, $section, "get", $deftext );
5432 * This function returns $oldtext after the content of the section
5433 * specified by $section has been replaced with $text. If the target
5434 * section does not exist, $oldtext is returned unchanged.
5436 * @param $oldtext String: former text of the article
5437 * @param $section Numeric: section identifier
5438 * @param $text String: replacing text
5439 * @return String: modified text
5441 public function replaceSection( $oldtext, $section, $text ) {
5442 return $this->extractSections( $oldtext, $section, "replace", $text );
5446 * Get the ID of the revision we are parsing
5448 * @return Mixed: integer or null
5450 function getRevisionId() {
5451 return $this->mRevisionId
;
5455 * Get the revision object for $this->mRevisionId
5457 * @return Revision|null either a Revision object or null
5459 protected function getRevisionObject() {
5460 if ( !is_null( $this->mRevisionObject
) ) {
5461 return $this->mRevisionObject
;
5463 if ( is_null( $this->mRevisionId
) ) {
5467 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5468 return $this->mRevisionObject
;
5472 * Get the timestamp associated with the current revision, adjusted for
5473 * the default server-local timestamp
5475 function getRevisionTimestamp() {
5476 if ( is_null( $this->mRevisionTimestamp
) ) {
5477 wfProfileIn( __METHOD__
);
5479 $revObject = $this->getRevisionObject();
5480 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5482 if( $timestamp !== false ) {
5485 # The cryptic '' timezone parameter tells to use the site-default
5486 # timezone offset instead of the user settings.
5488 # Since this value will be saved into the parser cache, served
5489 # to other users, and potentially even used inside links and such,
5490 # it needs to be consistent for all visitors.
5491 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5494 wfProfileOut( __METHOD__
);
5496 return $this->mRevisionTimestamp
;
5500 * Get the name of the user that edited the last revision
5502 * @return String: user name
5504 function getRevisionUser() {
5505 if( is_null( $this->mRevisionUser
) ) {
5506 $revObject = $this->getRevisionObject();
5508 # if this template is subst: the revision id will be blank,
5509 # so just use the current user's name
5511 $this->mRevisionUser
= $revObject->getUserText();
5512 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5513 $this->mRevisionUser
= $this->getUser()->getName();
5516 return $this->mRevisionUser
;
5520 * Mutator for $mDefaultSort
5522 * @param $sort New value
5524 public function setDefaultSort( $sort ) {
5525 $this->mDefaultSort
= $sort;
5526 $this->mOutput
->setProperty( 'defaultsort', $sort );
5530 * Accessor for $mDefaultSort
5531 * Will use the empty string if none is set.
5533 * This value is treated as a prefix, so the
5534 * empty string is equivalent to sorting by
5539 public function getDefaultSort() {
5540 if ( $this->mDefaultSort
!== false ) {
5541 return $this->mDefaultSort
;
5548 * Accessor for $mDefaultSort
5549 * Unlike getDefaultSort(), will return false if none is set
5551 * @return string or false
5553 public function getCustomDefaultSort() {
5554 return $this->mDefaultSort
;
5558 * Try to guess the section anchor name based on a wikitext fragment
5559 * presumably extracted from a heading, for example "Header" from
5562 * @param $text string
5566 public function guessSectionNameFromWikiText( $text ) {
5567 # Strip out wikitext links(they break the anchor)
5568 $text = $this->stripSectionName( $text );
5569 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5570 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5574 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5575 * instead. For use in redirects, since IE6 interprets Redirect: headers
5576 * as something other than UTF-8 (apparently?), resulting in breakage.
5578 * @param $text String: The section name
5579 * @return string An anchor
5581 public function guessLegacySectionNameFromWikiText( $text ) {
5582 # Strip out wikitext links(they break the anchor)
5583 $text = $this->stripSectionName( $text );
5584 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5585 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5589 * Strips a text string of wikitext for use in a section anchor
5591 * Accepts a text string and then removes all wikitext from the
5592 * string and leaves only the resultant text (i.e. the result of
5593 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5594 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5595 * to create valid section anchors by mimicing the output of the
5596 * parser when headings are parsed.
5598 * @param $text String: text string to be stripped of wikitext
5599 * for use in a Section anchor
5600 * @return Filtered text string
5602 public function stripSectionName( $text ) {
5603 # Strip internal link markup
5604 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5605 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5607 # Strip external link markup
5608 # @todo FIXME: Not tolerant to blank link text
5609 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5610 # on how many empty links there are on the page - need to figure that out.
5611 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5613 # Parse wikitext quotes (italics & bold)
5614 $text = $this->doQuotes( $text );
5617 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5622 * strip/replaceVariables/unstrip for preprocessor regression testing
5624 * @param $text string
5625 * @param $title Title
5626 * @param $options ParserOptions
5627 * @param $outputType int
5631 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5632 $this->startParse( $title, $options, $outputType, true );
5634 $text = $this->replaceVariables( $text );
5635 $text = $this->mStripState
->unstripBoth( $text );
5636 $text = Sanitizer
::removeHTMLtags( $text );
5641 * @param $text string
5642 * @param $title Title
5643 * @param $options ParserOptions
5646 function testPst( $text, Title
$title, ParserOptions
$options ) {
5647 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5652 * @param $title Title
5653 * @param $options ParserOptions
5656 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5657 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5661 * Call a callback function on all regions of the given text that are not
5662 * inside strip markers, and replace those regions with the return value
5663 * of the callback. For example, with input:
5667 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5668 * two strings will be replaced with the value returned by the callback in
5676 function markerSkipCallback( $s, $callback ) {
5679 while ( $i < strlen( $s ) ) {
5680 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5681 if ( $markerStart === false ) {
5682 $out .= call_user_func( $callback, substr( $s, $i ) );
5685 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5686 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5687 if ( $markerEnd === false ) {
5688 $out .= substr( $s, $markerStart );
5691 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5692 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5701 * Save the parser state required to convert the given half-parsed text to
5702 * HTML. "Half-parsed" in this context means the output of
5703 * recursiveTagParse() or internalParse(). This output has strip markers
5704 * from replaceVariables (extensionSubstitution() etc.), and link
5705 * placeholders from replaceLinkHolders().
5707 * Returns an array which can be serialized and stored persistently. This
5708 * array can later be loaded into another parser instance with
5709 * unserializeHalfParsedText(). The text can then be safely incorporated into
5710 * the return value of a parser hook.
5712 * @param $text string
5716 function serializeHalfParsedText( $text ) {
5717 wfProfileIn( __METHOD__
);
5720 'version' => self
::HALF_PARSED_VERSION
,
5721 'stripState' => $this->mStripState
->getSubState( $text ),
5722 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5724 wfProfileOut( __METHOD__
);
5729 * Load the parser state given in the $data array, which is assumed to
5730 * have been generated by serializeHalfParsedText(). The text contents is
5731 * extracted from the array, and its markers are transformed into markers
5732 * appropriate for the current Parser instance. This transformed text is
5733 * returned, and can be safely included in the return value of a parser
5736 * If the $data array has been stored persistently, the caller should first
5737 * check whether it is still valid, by calling isValidHalfParsedText().
5739 * @param $data Serialized data
5742 function unserializeHalfParsedText( $data ) {
5743 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5744 throw new MWException( __METHOD__
.': invalid version' );
5747 # First, extract the strip state.
5748 $texts = array( $data['text'] );
5749 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5751 # Now renumber links
5752 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5754 # Should be good to go.
5759 * Returns true if the given array, presumed to be generated by
5760 * serializeHalfParsedText(), is compatible with the current version of the
5763 * @param $data Array
5767 function isValidHalfParsedText( $data ) {
5768 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;