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.
37 * NOT $wgUser or $wgTitle or $wgRequest or $wgLang. 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, $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.
379 $text = $this->getFunctionLang()->convert( $text );
383 * A converted title will be provided in the output object if title and
384 * content conversion are enabled, the article text does not contain
385 * a conversion-suppressing double-underscore tag, and no
386 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
387 * automatic link conversion.
389 if ( !( $wgDisableLangConversion
390 ||
$wgDisableTitleConversion
391 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
392 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
393 ||
$this->mOutput
->getDisplayTitle() !== false ) )
395 $convruletitle = $this->getFunctionLang()->getConvRuleTitle();
396 if ( $convruletitle ) {
397 $this->mOutput
->setTitleText( $convruletitle );
399 $titleText = $this->getFunctionLang()->convertTitle( $title );
400 $this->mOutput
->setTitleText( $titleText );
404 $text = $this->mStripState
->unstripNoWiki( $text );
406 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
408 $text = $this->replaceTransparentTags( $text );
409 $text = $this->mStripState
->unstripGeneral( $text );
411 $text = Sanitizer
::normalizeCharReferences( $text );
413 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
414 $text = MWTidy
::tidy( $text );
416 # attempt to sanitize at least some nesting problems
417 # (bug #2702 and quite a few others)
419 # ''Something [http://www.cool.com cool''] -->
420 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
421 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
422 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
423 # fix up an anchor inside another anchor, only
424 # at least for a single single nested link (bug 3695)
425 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
426 '\\1\\2</a>\\3</a>\\1\\4</a>',
427 # fix div inside inline elements- doBlockLevels won't wrap a line which
428 # contains a div, so fix it up here; replace
429 # div with escaped text
430 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
431 '\\1\\3<div\\5>\\6</div>\\8\\9',
432 # remove empty italic or bold tag pairs, some
433 # introduced by rules above
434 '/<([bi])><\/\\1>/' => '',
437 $text = preg_replace(
438 array_keys( $tidyregs ),
439 array_values( $tidyregs ),
442 global $wgExpensiveParserFunctionLimit;
443 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
444 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
447 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
449 # Information on include size limits, for the benefit of users who try to skirt them
450 if ( $this->mOptions
->getEnableLimitReport() ) {
451 $max = $this->mOptions
->getMaxIncludeSize();
452 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
454 "NewPP limit report\n" .
455 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
456 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
457 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
459 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
460 $text .= "\n<!-- \n$limitReport-->\n";
462 $this->mOutput
->setText( $text );
464 $this->mRevisionId
= $oldRevisionId;
465 $this->mRevisionObject
= $oldRevisionObject;
466 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
467 $this->mRevisionUser
= $oldRevisionUser;
468 wfProfileOut( $fname );
469 wfProfileOut( __METHOD__
);
471 return $this->mOutput
;
475 * Recursive parser entry point that can be called from an extension tag
478 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
480 * @param $text String: text extension wants to have parsed
481 * @param $frame PPFrame: The frame to use for expanding any template variables
485 function recursiveTagParse( $text, $frame=false ) {
486 wfProfileIn( __METHOD__
);
487 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
488 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
489 $text = $this->internalParse( $text, false, $frame );
490 wfProfileOut( __METHOD__
);
495 * Expand templates and variables in the text, producing valid, static wikitext.
496 * Also removes comments.
498 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
499 wfProfileIn( __METHOD__
);
500 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
501 if ( $revid !== null ) {
502 $this->mRevisionId
= $revid;
504 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
505 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
506 $text = $this->replaceVariables( $text );
507 $text = $this->mStripState
->unstripBoth( $text );
508 wfProfileOut( __METHOD__
);
513 * Recursive parser entry point that can be called from an extension tag
516 * @param $text String: text to be expanded
517 * @param $frame PPFrame: The frame to use for expanding any template variables
520 public function recursivePreprocess( $text, $frame = false ) {
521 wfProfileIn( __METHOD__
);
522 $text = $this->replaceVariables( $text, $frame );
523 $text = $this->mStripState
->unstripBoth( $text );
524 wfProfileOut( __METHOD__
);
529 * Process the wikitext for the ?preload= feature. (bug 5210)
531 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
532 * comments, templates, arguments, tags hooks and parser functions are untouched.
534 * @param $text String
535 * @param $title Title
536 * @param $options ParserOptions
539 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
540 # Parser (re)initialisation
541 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
543 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
544 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
545 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
546 $text = $this->mStripState
->unstripBoth( $text );
551 * Get a random string
555 static public function getRandomString() {
556 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
560 * Set the current user.
561 * Should only be used when doing pre-save transform.
563 * @param $user Mixed: User object or null (to reset)
565 function setUser( $user ) {
566 $this->mUser
= $user;
570 * Accessor for mUniqPrefix.
574 public function uniqPrefix() {
575 if ( !isset( $this->mUniqPrefix
) ) {
576 # @todo FIXME: This is probably *horribly wrong*
577 # LanguageConverter seems to want $wgParser's uniqPrefix, however
578 # if this is called for a parser cache hit, the parser may not
579 # have ever been initialized in the first place.
580 # Not really sure what the heck is supposed to be going on here.
582 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
584 return $this->mUniqPrefix
;
588 * Set the context title
592 function setTitle( $t ) {
593 if ( !$t ||
$t instanceof FakeTitle
) {
594 $t = Title
::newFromText( 'NO TITLE' );
597 if ( strval( $t->getFragment() ) !== '' ) {
598 # Strip the fragment to avoid various odd effects
599 $this->mTitle
= clone $t;
600 $this->mTitle
->setFragment( '' );
607 * Accessor for the Title object
609 * @return Title object
611 function getTitle() {
612 return $this->mTitle
;
616 * Accessor/mutator for the Title object
618 * @param $x New Title object or null to just get the current one
619 * @return Title object
621 function Title( $x = null ) {
622 return wfSetVar( $this->mTitle
, $x );
626 * Set the output type
628 * @param $ot Integer: new value
630 function setOutputType( $ot ) {
631 $this->mOutputType
= $ot;
634 'html' => $ot == self
::OT_HTML
,
635 'wiki' => $ot == self
::OT_WIKI
,
636 'pre' => $ot == self
::OT_PREPROCESS
,
637 'plain' => $ot == self
::OT_PLAIN
,
642 * Accessor/mutator for the output type
644 * @param $x New value or null to just get the current one
647 function OutputType( $x = null ) {
648 return wfSetVar( $this->mOutputType
, $x );
652 * Get the ParserOutput object
654 * @return ParserOutput object
656 function getOutput() {
657 return $this->mOutput
;
661 * Get the ParserOptions object
663 * @return ParserOptions object
665 function getOptions() {
666 return $this->mOptions
;
670 * Accessor/mutator for the ParserOptions object
672 * @param $x New value or null to just get the current one
673 * @return Current ParserOptions object
675 function Options( $x = null ) {
676 return wfSetVar( $this->mOptions
, $x );
682 function nextLinkID() {
683 return $this->mLinkID++
;
689 function setLinkID( $id ) {
690 $this->mLinkID
= $id;
696 function getFunctionLang() {
697 $target = $this->mOptions
->getTargetLanguage();
698 if ( $target !== null ) {
700 } elseif( $this->mOptions
->getInterfaceMessage() ) {
701 return $this->mOptions
->getUserLangObj();
702 } elseif( is_null( $this->mTitle
) ) {
703 throw new MWException( __METHOD__
.': $this->mTitle is null' );
705 return $this->mTitle
->getPageLanguage();
709 * Get a User object either from $this->mUser, if set, or from the
710 * ParserOptions object otherwise
712 * @return User object
715 if ( !is_null( $this->mUser
) ) {
718 return $this->mOptions
->getUser();
722 * Get a preprocessor object
724 * @return Preprocessor instance
726 function getPreprocessor() {
727 if ( !isset( $this->mPreprocessor
) ) {
728 $class = $this->mPreprocessorClass
;
729 $this->mPreprocessor
= new $class( $this );
731 return $this->mPreprocessor
;
735 * Replaces all occurrences of HTML-style comments and the given tags
736 * in the text with a random marker and returns the next text. The output
737 * parameter $matches will be an associative array filled with data in
739 * 'UNIQ-xxxxx' => array(
742 * array( 'param' => 'x' ),
743 * '<element param="x">tag content</element>' ) )
745 * @param $elements array list of element names. Comments are always extracted.
746 * @param $text string Source text string.
747 * @param $matches array Out parameter, Array: extracted tags
748 * @param $uniq_prefix string
749 * @return String: stripped text
751 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
756 $taglist = implode( '|', $elements );
757 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
759 while ( $text != '' ) {
760 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
762 if ( count( $p ) < 5 ) {
765 if ( count( $p ) > 5 ) {
779 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
780 $stripped .= $marker;
782 if ( $close === '/>' ) {
783 # Empty element tag, <tag />
788 if ( $element === '!--' ) {
791 $end = "/(<\\/$element\\s*>)/i";
793 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
795 if ( count( $q ) < 3 ) {
796 # No end tag -- let it run out to the end of the text.
805 $matches[$marker] = array( $element,
807 Sanitizer
::decodeTagAttributes( $attributes ),
808 "<$element$attributes$close$content$tail" );
814 * Get a list of strippable XML-like elements
818 function getStripList() {
819 return $this->mStripList
;
823 * Add an item to the strip state
824 * Returns the unique tag which must be inserted into the stripped text
825 * The tag will be replaced with the original text in unstrip()
827 * @param $text string
831 function insertStripItem( $text ) {
832 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
833 $this->mMarkerIndex++
;
834 $this->mStripState
->addGeneral( $rnd, $text );
839 * parse the wiki syntax used to render tables
843 function doTableStuff( $text ) {
844 wfProfileIn( __METHOD__
);
846 $lines = StringUtils
::explode( "\n", $text );
848 $td_history = array(); # Is currently a td tag open?
849 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
850 $tr_history = array(); # Is currently a tr tag open?
851 $tr_attributes = array(); # history of tr attributes
852 $has_opened_tr = array(); # Did this table open a <tr> element?
853 $indent_level = 0; # indent level of the table
855 foreach ( $lines as $outLine ) {
856 $line = trim( $outLine );
858 if ( $line === '' ) { # empty line, go to next line
859 $out .= $outLine."\n";
863 $first_character = $line[0];
866 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
867 # First check if we are starting a new table
868 $indent_level = strlen( $matches[1] );
870 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
871 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
873 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
874 array_push( $td_history , false );
875 array_push( $last_tag_history , '' );
876 array_push( $tr_history , false );
877 array_push( $tr_attributes , '' );
878 array_push( $has_opened_tr , false );
879 } elseif ( count( $td_history ) == 0 ) {
880 # Don't do any of the following
881 $out .= $outLine."\n";
883 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
884 # We are ending a table
885 $line = '</table>' . substr( $line , 2 );
886 $last_tag = array_pop( $last_tag_history );
888 if ( !array_pop( $has_opened_tr ) ) {
889 $line = "<tr><td></td></tr>{$line}";
892 if ( array_pop( $tr_history ) ) {
893 $line = "</tr>{$line}";
896 if ( array_pop( $td_history ) ) {
897 $line = "</{$last_tag}>{$line}";
899 array_pop( $tr_attributes );
900 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
901 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
902 # Now we have a table row
903 $line = preg_replace( '#^\|-+#', '', $line );
905 # Whats after the tag is now only attributes
906 $attributes = $this->mStripState
->unstripBoth( $line );
907 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
908 array_pop( $tr_attributes );
909 array_push( $tr_attributes, $attributes );
912 $last_tag = array_pop( $last_tag_history );
913 array_pop( $has_opened_tr );
914 array_push( $has_opened_tr , true );
916 if ( array_pop( $tr_history ) ) {
920 if ( array_pop( $td_history ) ) {
921 $line = "</{$last_tag}>{$line}";
925 array_push( $tr_history , false );
926 array_push( $td_history , false );
927 array_push( $last_tag_history , '' );
928 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
929 # This might be cell elements, td, th or captions
930 if ( substr( $line , 0 , 2 ) === '|+' ) {
931 $first_character = '+';
932 $line = substr( $line , 1 );
935 $line = substr( $line , 1 );
937 if ( $first_character === '!' ) {
938 $line = str_replace( '!!' , '||' , $line );
941 # Split up multiple cells on the same line.
942 # FIXME : This can result in improper nesting of tags processed
943 # by earlier parser steps, but should avoid splitting up eg
944 # attribute values containing literal "||".
945 $cells = StringUtils
::explodeMarkup( '||' , $line );
949 # Loop through each table cell
950 foreach ( $cells as $cell ) {
952 if ( $first_character !== '+' ) {
953 $tr_after = array_pop( $tr_attributes );
954 if ( !array_pop( $tr_history ) ) {
955 $previous = "<tr{$tr_after}>\n";
957 array_push( $tr_history , true );
958 array_push( $tr_attributes , '' );
959 array_pop( $has_opened_tr );
960 array_push( $has_opened_tr , true );
963 $last_tag = array_pop( $last_tag_history );
965 if ( array_pop( $td_history ) ) {
966 $previous = "</{$last_tag}>\n{$previous}";
969 if ( $first_character === '|' ) {
971 } elseif ( $first_character === '!' ) {
973 } elseif ( $first_character === '+' ) {
974 $last_tag = 'caption';
979 array_push( $last_tag_history , $last_tag );
981 # A cell could contain both parameters and data
982 $cell_data = explode( '|' , $cell , 2 );
984 # Bug 553: Note that a '|' inside an invalid link should not
985 # be mistaken as delimiting cell parameters
986 if ( strpos( $cell_data[0], '[[' ) !== false ) {
987 $cell = "{$previous}<{$last_tag}>{$cell}";
988 } elseif ( count( $cell_data ) == 1 ) {
989 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
991 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
992 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
993 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
997 array_push( $td_history , true );
1000 $out .= $outLine . "\n";
1003 # Closing open td, tr && table
1004 while ( count( $td_history ) > 0 ) {
1005 if ( array_pop( $td_history ) ) {
1008 if ( array_pop( $tr_history ) ) {
1011 if ( !array_pop( $has_opened_tr ) ) {
1012 $out .= "<tr><td></td></tr>\n" ;
1015 $out .= "</table>\n";
1018 # Remove trailing line-ending (b/c)
1019 if ( substr( $out, -1 ) === "\n" ) {
1020 $out = substr( $out, 0, -1 );
1023 # special case: don't return empty table
1024 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1028 wfProfileOut( __METHOD__
);
1034 * Helper function for parse() that transforms wiki markup into
1035 * HTML. Only called for $mOutputType == self::OT_HTML.
1039 * @param $text string
1040 * @param $isMain bool
1041 * @param $frame bool
1045 function internalParse( $text, $isMain = true, $frame = false ) {
1046 wfProfileIn( __METHOD__
);
1050 # Hook to suspend the parser in this state
1051 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1052 wfProfileOut( __METHOD__
);
1056 # if $frame is provided, then use $frame for replacing any variables
1058 # use frame depth to infer how include/noinclude tags should be handled
1059 # depth=0 means this is the top-level document; otherwise it's an included document
1060 if ( !$frame->depth
) {
1063 $flag = Parser
::PTD_FOR_INCLUSION
;
1065 $dom = $this->preprocessToDom( $text, $flag );
1066 $text = $frame->expand( $dom );
1068 # if $frame is not provided, then use old-style replaceVariables
1069 $text = $this->replaceVariables( $text );
1072 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1073 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1075 # Tables need to come after variable replacement for things to work
1076 # properly; putting them before other transformations should keep
1077 # exciting things like link expansions from showing up in surprising
1079 $text = $this->doTableStuff( $text );
1081 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1083 $text = $this->doDoubleUnderscore( $text );
1085 $text = $this->doHeadings( $text );
1086 if ( $this->mOptions
->getUseDynamicDates() ) {
1087 $df = DateFormatter
::getInstance();
1088 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1090 $text = $this->replaceInternalLinks( $text );
1091 $text = $this->doAllQuotes( $text );
1092 $text = $this->replaceExternalLinks( $text );
1094 # replaceInternalLinks may sometimes leave behind
1095 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1096 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1098 $text = $this->doMagicLinks( $text );
1099 $text = $this->formatHeadings( $text, $origText, $isMain );
1101 wfProfileOut( __METHOD__
);
1106 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1107 * magic external links.
1112 * @param $text string
1116 function doMagicLinks( $text ) {
1117 wfProfileIn( __METHOD__
);
1118 $prots = wfUrlProtocolsWithoutProtRel();
1119 $urlChar = self
::EXT_LINK_URL_CLASS
;
1120 $text = preg_replace_callback(
1122 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1123 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1124 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1125 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1126 ISBN\s+(\b # m[5]: ISBN, capture number
1127 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1128 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1129 [0-9Xx] # check digit
1131 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1132 wfProfileOut( __METHOD__
);
1137 * @throws MWException
1139 * @return HTML|string
1141 function magicLinkCallback( $m ) {
1142 if ( isset( $m[1] ) && $m[1] !== '' ) {
1145 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1148 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1149 # Free external link
1150 return $this->makeFreeExternalLink( $m[0] );
1151 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1153 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1156 $CssClass = 'mw-magiclink-rfc';
1158 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1160 $urlmsg = 'pubmedurl';
1161 $CssClass = 'mw-magiclink-pmid';
1164 throw new MWException( __METHOD__
.': unrecognised match type "' .
1165 substr( $m[0], 0, 20 ) . '"' );
1167 $url = wfMsgForContent( $urlmsg, $id );
1168 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1169 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1172 $num = strtr( $isbn, array(
1177 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1179 $titleObj->escapeLocalUrl() .
1180 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1187 * Make a free external link, given a user-supplied URL
1189 * @param $url string
1191 * @return string HTML
1194 function makeFreeExternalLink( $url ) {
1195 wfProfileIn( __METHOD__
);
1199 # The characters '<' and '>' (which were escaped by
1200 # removeHTMLtags()) should not be included in
1201 # URLs, per RFC 2396.
1203 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1204 $trail = substr( $url, $m2[0][1] ) . $trail;
1205 $url = substr( $url, 0, $m2[0][1] );
1208 # Move trailing punctuation to $trail
1210 # If there is no left bracket, then consider right brackets fair game too
1211 if ( strpos( $url, '(' ) === false ) {
1215 $numSepChars = strspn( strrev( $url ), $sep );
1216 if ( $numSepChars ) {
1217 $trail = substr( $url, -$numSepChars ) . $trail;
1218 $url = substr( $url, 0, -$numSepChars );
1221 $url = Sanitizer
::cleanUrl( $url );
1223 # Is this an external image?
1224 $text = $this->maybeMakeExternalImage( $url );
1225 if ( $text === false ) {
1226 # Not an image, make a link
1227 $text = Linker
::makeExternalLink( $url, $this->getFunctionLang()->markNoConversion($url), true, 'free',
1228 $this->getExternalLinkAttribs( $url ) );
1229 # Register it in the output object...
1230 # Replace unnecessary URL escape codes with their equivalent characters
1231 $pasteurized = self
::replaceUnusualEscapes( $url );
1232 $this->mOutput
->addExternalLink( $pasteurized );
1234 wfProfileOut( __METHOD__
);
1235 return $text . $trail;
1240 * Parse headers and return html
1244 * @param $text string
1248 function doHeadings( $text ) {
1249 wfProfileIn( __METHOD__
);
1250 for ( $i = 6; $i >= 1; --$i ) {
1251 $h = str_repeat( '=', $i );
1252 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1253 "<h$i>\\1</h$i>", $text );
1255 wfProfileOut( __METHOD__
);
1260 * Replace single quotes with HTML markup
1263 * @param $text string
1265 * @return string the altered text
1267 function doAllQuotes( $text ) {
1268 wfProfileIn( __METHOD__
);
1270 $lines = StringUtils
::explode( "\n", $text );
1271 foreach ( $lines as $line ) {
1272 $outtext .= $this->doQuotes( $line ) . "\n";
1274 $outtext = substr( $outtext, 0,-1 );
1275 wfProfileOut( __METHOD__
);
1280 * Helper function for doAllQuotes()
1282 * @param $text string
1286 public function doQuotes( $text ) {
1287 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1288 if ( count( $arr ) == 1 ) {
1291 # First, do some preliminary work. This may shift some apostrophes from
1292 # being mark-up to being text. It also counts the number of occurrences
1293 # of bold and italics mark-ups.
1296 for ( $i = 0; $i < count( $arr ); $i++
) {
1297 if ( ( $i %
2 ) == 1 ) {
1298 # If there are ever four apostrophes, assume the first is supposed to
1299 # be text, and the remaining three constitute mark-up for bold text.
1300 if ( strlen( $arr[$i] ) == 4 ) {
1303 } elseif ( strlen( $arr[$i] ) > 5 ) {
1304 # If there are more than 5 apostrophes in a row, assume they're all
1305 # text except for the last 5.
1306 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1309 # Count the number of occurrences of bold and italics mark-ups.
1310 # We are not counting sequences of five apostrophes.
1311 if ( strlen( $arr[$i] ) == 2 ) {
1313 } elseif ( strlen( $arr[$i] ) == 3 ) {
1315 } elseif ( strlen( $arr[$i] ) == 5 ) {
1322 # If there is an odd number of both bold and italics, it is likely
1323 # that one of the bold ones was meant to be an apostrophe followed
1324 # by italics. Which one we cannot know for certain, but it is more
1325 # likely to be one that has a single-letter word before it.
1326 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1328 $firstsingleletterword = -1;
1329 $firstmultiletterword = -1;
1331 foreach ( $arr as $r ) {
1332 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1333 $x1 = substr( $arr[$i-1], -1 );
1334 $x2 = substr( $arr[$i-1], -2, 1 );
1335 if ( $x1 === ' ' ) {
1336 if ( $firstspace == -1 ) {
1339 } elseif ( $x2 === ' ') {
1340 if ( $firstsingleletterword == -1 ) {
1341 $firstsingleletterword = $i;
1344 if ( $firstmultiletterword == -1 ) {
1345 $firstmultiletterword = $i;
1352 # If there is a single-letter word, use it!
1353 if ( $firstsingleletterword > -1 ) {
1354 $arr[$firstsingleletterword] = "''";
1355 $arr[$firstsingleletterword-1] .= "'";
1356 } elseif ( $firstmultiletterword > -1 ) {
1357 # If not, but there's a multi-letter word, use that one.
1358 $arr[$firstmultiletterword] = "''";
1359 $arr[$firstmultiletterword-1] .= "'";
1360 } elseif ( $firstspace > -1 ) {
1361 # ... otherwise use the first one that has neither.
1362 # (notice that it is possible for all three to be -1 if, for example,
1363 # there is only one pentuple-apostrophe in the line)
1364 $arr[$firstspace] = "''";
1365 $arr[$firstspace-1] .= "'";
1369 # Now let's actually convert our apostrophic mush to HTML!
1374 foreach ( $arr as $r ) {
1375 if ( ( $i %
2 ) == 0 ) {
1376 if ( $state === 'both' ) {
1382 if ( strlen( $r ) == 2 ) {
1383 if ( $state === 'i' ) {
1384 $output .= '</i>'; $state = '';
1385 } elseif ( $state === 'bi' ) {
1386 $output .= '</i>'; $state = 'b';
1387 } elseif ( $state === 'ib' ) {
1388 $output .= '</b></i><b>'; $state = 'b';
1389 } elseif ( $state === 'both' ) {
1390 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1391 } else { # $state can be 'b' or ''
1392 $output .= '<i>'; $state .= 'i';
1394 } elseif ( strlen( $r ) == 3 ) {
1395 if ( $state === 'b' ) {
1396 $output .= '</b>'; $state = '';
1397 } elseif ( $state === 'bi' ) {
1398 $output .= '</i></b><i>'; $state = 'i';
1399 } elseif ( $state === 'ib' ) {
1400 $output .= '</b>'; $state = 'i';
1401 } elseif ( $state === 'both' ) {
1402 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1403 } else { # $state can be 'i' or ''
1404 $output .= '<b>'; $state .= 'b';
1406 } elseif ( strlen( $r ) == 5 ) {
1407 if ( $state === 'b' ) {
1408 $output .= '</b><i>'; $state = 'i';
1409 } elseif ( $state === 'i' ) {
1410 $output .= '</i><b>'; $state = 'b';
1411 } elseif ( $state === 'bi' ) {
1412 $output .= '</i></b>'; $state = '';
1413 } elseif ( $state === 'ib' ) {
1414 $output .= '</b></i>'; $state = '';
1415 } elseif ( $state === 'both' ) {
1416 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1417 } else { # ($state == '')
1418 $buffer = ''; $state = 'both';
1424 # Now close all remaining tags. Notice that the order is important.
1425 if ( $state === 'b' ||
$state === 'ib' ) {
1428 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1431 if ( $state === 'bi' ) {
1434 # There might be lonely ''''', so make sure we have a buffer
1435 if ( $state === 'both' && $buffer ) {
1436 $output .= '<b><i>'.$buffer.'</i></b>';
1443 * Replace external links (REL)
1445 * Note: this is all very hackish and the order of execution matters a lot.
1446 * Make sure to run maintenance/parserTests.php if you change this code.
1450 * @param $text string
1454 function replaceExternalLinks( $text ) {
1455 wfProfileIn( __METHOD__
);
1457 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1458 $s = array_shift( $bits );
1461 while ( $i<count( $bits ) ) {
1463 $protocol = $bits[$i++
];
1464 $text = $bits[$i++
];
1465 $trail = $bits[$i++
];
1467 # The characters '<' and '>' (which were escaped by
1468 # removeHTMLtags()) should not be included in
1469 # URLs, per RFC 2396.
1471 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1472 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1473 $url = substr( $url, 0, $m2[0][1] );
1476 # If the link text is an image URL, replace it with an <img> tag
1477 # This happened by accident in the original parser, but some people used it extensively
1478 $img = $this->maybeMakeExternalImage( $text );
1479 if ( $img !== false ) {
1485 # Set linktype for CSS - if URL==text, link is essentially free
1486 $linktype = ( $text === $url ) ?
'free' : 'text';
1488 # No link text, e.g. [http://domain.tld/some.link]
1489 if ( $text == '' ) {
1491 $langObj = $this->getFunctionLang();
1492 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1493 $linktype = 'autonumber';
1495 # Have link text, e.g. [http://domain.tld/some.link text]s
1497 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1500 $text = $this->getFunctionLang()->markNoConversion( $text );
1502 $url = Sanitizer
::cleanUrl( $url );
1504 # Use the encoded URL
1505 # This means that users can paste URLs directly into the text
1506 # Funny characters like ö aren't valid in URLs anyway
1507 # This was changed in August 2004
1508 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1509 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1511 # Register link in the output object.
1512 # Replace unnecessary URL escape codes with the referenced character
1513 # This prevents spammers from hiding links from the filters
1514 $pasteurized = self
::replaceUnusualEscapes( $url );
1515 $this->mOutput
->addExternalLink( $pasteurized );
1518 wfProfileOut( __METHOD__
);
1523 * Get an associative array of additional HTML attributes appropriate for a
1524 * particular external link. This currently may include rel => nofollow
1525 * (depending on configuration, namespace, and the URL's domain) and/or a
1526 * target attribute (depending on configuration).
1528 * @param $url String|bool optional URL, to extract the domain from for rel =>
1529 * nofollow if appropriate
1530 * @return Array associative array of HTML attributes
1532 function getExternalLinkAttribs( $url = false ) {
1534 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1535 $ns = $this->mTitle
->getNamespace();
1536 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1537 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1539 $attribs['rel'] = 'nofollow';
1541 if ( $this->mOptions
->getExternalLinkTarget() ) {
1542 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1548 * Replace unusual URL escape codes with their equivalent characters
1550 * @param $url String
1553 * @todo This can merge genuinely required bits in the path or query string,
1554 * breaking legit URLs. A proper fix would treat the various parts of
1555 * the URL differently; as a workaround, just use the output for
1556 * statistical records, not for actual linking/output.
1558 static function replaceUnusualEscapes( $url ) {
1559 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1560 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1564 * Callback function used in replaceUnusualEscapes().
1565 * Replaces unusual URL escape codes with their equivalent character
1567 * @param $matches array
1571 private static function replaceUnusualEscapesCallback( $matches ) {
1572 $char = urldecode( $matches[0] );
1573 $ord = ord( $char );
1574 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1575 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1576 # No, shouldn't be escaped
1579 # Yes, leave it escaped
1585 * make an image if it's allowed, either through the global
1586 * option, through the exception, or through the on-wiki whitelist
1589 * $param $url string
1593 function maybeMakeExternalImage( $url ) {
1594 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1595 $imagesexception = !empty( $imagesfrom );
1597 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1598 if ( $imagesexception && is_array( $imagesfrom ) ) {
1599 $imagematch = false;
1600 foreach ( $imagesfrom as $match ) {
1601 if ( strpos( $url, $match ) === 0 ) {
1606 } elseif ( $imagesexception ) {
1607 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1609 $imagematch = false;
1611 if ( $this->mOptions
->getAllowExternalImages()
1612 ||
( $imagesexception && $imagematch ) ) {
1613 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1615 $text = Linker
::makeExternalImage( $url );
1618 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1619 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1620 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1621 foreach ( $whitelist as $entry ) {
1622 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1623 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1626 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1627 # Image matches a whitelist entry
1628 $text = Linker
::makeExternalImage( $url );
1637 * Process [[ ]] wikilinks
1641 * @return String: processed text
1645 function replaceInternalLinks( $s ) {
1646 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1651 * Process [[ ]] wikilinks (RIL)
1652 * @return LinkHolderArray
1656 function replaceInternalLinks2( &$s ) {
1657 wfProfileIn( __METHOD__
);
1659 wfProfileIn( __METHOD__
.'-setup' );
1660 static $tc = FALSE, $e1, $e1_img;
1661 # the % is needed to support urlencoded titles as well
1663 $tc = Title
::legalChars() . '#%';
1664 # Match a link having the form [[namespace:link|alternate]]trail
1665 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1666 # Match cases where there is no "]]", which might still be images
1667 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1670 $holders = new LinkHolderArray( $this );
1672 # split the entire text string on occurences of [[
1673 $a = StringUtils
::explode( '[[', ' ' . $s );
1674 # get the first element (all text up to first [[), and remove the space we added
1677 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1678 $s = substr( $s, 1 );
1680 $useLinkPrefixExtension = $this->getFunctionLang()->linkPrefixExtension();
1682 if ( $useLinkPrefixExtension ) {
1683 # Match the end of a line for a word that's not followed by whitespace,
1684 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1685 $e2 = wfMsgForContent( 'linkprefix' );
1688 if ( is_null( $this->mTitle
) ) {
1689 wfProfileOut( __METHOD__
.'-setup' );
1690 wfProfileOut( __METHOD__
);
1691 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1693 $nottalk = !$this->mTitle
->isTalkPage();
1695 if ( $useLinkPrefixExtension ) {
1697 if ( preg_match( $e2, $s, $m ) ) {
1698 $first_prefix = $m[2];
1700 $first_prefix = false;
1706 if ( $this->getFunctionLang()->hasVariants() ) {
1707 $selflink = $this->getFunctionLang()->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1709 $selflink = array( $this->mTitle
->getPrefixedText() );
1711 $useSubpages = $this->areSubpagesAllowed();
1712 wfProfileOut( __METHOD__
.'-setup' );
1714 # Loop for each link
1715 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1716 # Check for excessive memory usage
1717 if ( $holders->isBig() ) {
1719 # Do the existence check, replace the link holders and clear the array
1720 $holders->replace( $s );
1724 if ( $useLinkPrefixExtension ) {
1725 wfProfileIn( __METHOD__
.'-prefixhandling' );
1726 if ( preg_match( $e2, $s, $m ) ) {
1733 if ( $first_prefix ) {
1734 $prefix = $first_prefix;
1735 $first_prefix = false;
1737 wfProfileOut( __METHOD__
.'-prefixhandling' );
1740 $might_be_img = false;
1742 wfProfileIn( __METHOD__
."-e1" );
1743 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1745 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1746 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1747 # the real problem is with the $e1 regex
1750 # Still some problems for cases where the ] is meant to be outside punctuation,
1751 # and no image is in sight. See bug 2095.
1753 if ( $text !== '' &&
1754 substr( $m[3], 0, 1 ) === ']' &&
1755 strpos( $text, '[' ) !== false
1758 $text .= ']'; # so that replaceExternalLinks($text) works later
1759 $m[3] = substr( $m[3], 1 );
1761 # fix up urlencoded title texts
1762 if ( strpos( $m[1], '%' ) !== false ) {
1763 # Should anchors '#' also be rejected?
1764 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1767 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1768 $might_be_img = true;
1770 if ( strpos( $m[1], '%' ) !== false ) {
1771 $m[1] = rawurldecode( $m[1] );
1774 } else { # Invalid form; output directly
1775 $s .= $prefix . '[[' . $line ;
1776 wfProfileOut( __METHOD__
."-e1" );
1779 wfProfileOut( __METHOD__
."-e1" );
1780 wfProfileIn( __METHOD__
."-misc" );
1782 # Don't allow internal links to pages containing
1783 # PROTO: where PROTO is a valid URL protocol; these
1784 # should be external links.
1785 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1786 $s .= $prefix . '[[' . $line ;
1787 wfProfileOut( __METHOD__
."-misc" );
1791 # Make subpage if necessary
1792 if ( $useSubpages ) {
1793 $link = $this->maybeDoSubpageLink( $m[1], $text );
1798 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1800 # Strip off leading ':'
1801 $link = substr( $link, 1 );
1804 wfProfileOut( __METHOD__
."-misc" );
1805 wfProfileIn( __METHOD__
."-title" );
1806 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1807 if ( $nt === null ) {
1808 $s .= $prefix . '[[' . $line;
1809 wfProfileOut( __METHOD__
."-title" );
1813 $ns = $nt->getNamespace();
1814 $iw = $nt->getInterWiki();
1815 wfProfileOut( __METHOD__
."-title" );
1817 if ( $might_be_img ) { # if this is actually an invalid link
1818 wfProfileIn( __METHOD__
."-might_be_img" );
1819 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1822 # look at the next 'line' to see if we can close it there
1824 $next_line = $a->current();
1825 if ( $next_line === false ||
$next_line === null ) {
1828 $m = explode( ']]', $next_line, 3 );
1829 if ( count( $m ) == 3 ) {
1830 # the first ]] closes the inner link, the second the image
1832 $text .= "[[{$m[0]}]]{$m[1]}";
1835 } elseif ( count( $m ) == 2 ) {
1836 # if there's exactly one ]] that's fine, we'll keep looking
1837 $text .= "[[{$m[0]}]]{$m[1]}";
1839 # if $next_line is invalid too, we need look no further
1840 $text .= '[[' . $next_line;
1845 # we couldn't find the end of this imageLink, so output it raw
1846 # but don't ignore what might be perfectly normal links in the text we've examined
1847 $holders->merge( $this->replaceInternalLinks2( $text ) );
1848 $s .= "{$prefix}[[$link|$text";
1849 # note: no $trail, because without an end, there *is* no trail
1850 wfProfileOut( __METHOD__
."-might_be_img" );
1853 } else { # it's not an image, so output it raw
1854 $s .= "{$prefix}[[$link|$text";
1855 # note: no $trail, because without an end, there *is* no trail
1856 wfProfileOut( __METHOD__
."-might_be_img" );
1859 wfProfileOut( __METHOD__
."-might_be_img" );
1862 $wasblank = ( $text == '' );
1866 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1867 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1868 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1869 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1870 $text = $this->doQuotes( $text );
1873 # Link not escaped by : , create the various objects
1878 wfProfileIn( __METHOD__
."-interwiki" );
1879 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1880 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1881 $s = rtrim( $s . $prefix );
1882 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1883 wfProfileOut( __METHOD__
."-interwiki" );
1886 wfProfileOut( __METHOD__
."-interwiki" );
1888 if ( $ns == NS_FILE
) {
1889 wfProfileIn( __METHOD__
."-image" );
1890 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1892 # if no parameters were passed, $text
1893 # becomes something like "File:Foo.png",
1894 # which we don't want to pass on to the
1898 # recursively parse links inside the image caption
1899 # actually, this will parse them in any other parameters, too,
1900 # but it might be hard to fix that, and it doesn't matter ATM
1901 $text = $this->replaceExternalLinks( $text );
1902 $holders->merge( $this->replaceInternalLinks2( $text ) );
1904 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1905 $s .= $prefix . $this->armorLinks(
1906 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1908 $s .= $prefix . $trail;
1910 wfProfileOut( __METHOD__
."-image" );
1914 if ( $ns == NS_CATEGORY
) {
1915 wfProfileIn( __METHOD__
."-category" );
1916 $s = rtrim( $s . "\n" ); # bug 87
1919 $sortkey = $this->getDefaultSort();
1923 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1924 $sortkey = str_replace( "\n", '', $sortkey );
1925 $sortkey = $this->getFunctionLang()->convertCategoryKey( $sortkey );
1926 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1929 * Strip the whitespace Category links produce, see bug 87
1930 * @todo We might want to use trim($tmp, "\n") here.
1932 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1934 wfProfileOut( __METHOD__
."-category" );
1939 # Self-link checking
1940 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1941 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1942 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
1947 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1948 # @todo FIXME: Should do batch file existence checks, see comment below
1949 if ( $ns == NS_MEDIA
) {
1950 wfProfileIn( __METHOD__
."-media" );
1951 # Give extensions a chance to select the file revision for us
1954 wfRunHooks( 'BeforeParserFetchFileAndTitle',
1955 array( $this, $nt, &$options, &$descQuery ) );
1956 # Fetch and register the file (file title may be different via hooks)
1957 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
1958 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1959 $s .= $prefix . $this->armorLinks(
1960 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
1961 wfProfileOut( __METHOD__
."-media" );
1965 wfProfileIn( __METHOD__
."-always_known" );
1966 # Some titles, such as valid special pages or files in foreign repos, should
1967 # be shown as bluelinks even though they're not included in the page table
1969 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1970 # batch file existence checks for NS_FILE and NS_MEDIA
1971 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1972 $this->mOutput
->addLink( $nt );
1973 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
1975 # Links will be added to the output link list after checking
1976 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
1978 wfProfileOut( __METHOD__
."-always_known" );
1980 wfProfileOut( __METHOD__
);
1985 * Render a forced-blue link inline; protect against double expansion of
1986 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1987 * Since this little disaster has to split off the trail text to avoid
1988 * breaking URLs in the following text without breaking trails on the
1989 * wiki links, it's been made into a horrible function.
1992 * @param $text String
1993 * @param $query Array or String
1994 * @param $trail String
1995 * @param $prefix String
1996 * @return String: HTML-wikitext mix oh yuck
1998 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
1999 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2001 if ( is_string( $query ) ) {
2002 $query = wfCgiToArray( $query );
2004 if ( $text == '' ) {
2005 $text = htmlspecialchars( $nt->getPrefixedText() );
2008 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2010 return $this->armorLinks( $link ) . $trail;
2014 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2015 * going to go through further parsing steps before inline URL expansion.
2017 * Not needed quite as much as it used to be since free links are a bit
2018 * more sensible these days. But bracketed links are still an issue.
2020 * @param $text String: more-or-less HTML
2021 * @return String: less-or-more HTML with NOPARSE bits
2023 function armorLinks( $text ) {
2024 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2025 "{$this->mUniqPrefix}NOPARSE$1", $text );
2029 * Return true if subpage links should be expanded on this page.
2032 function areSubpagesAllowed() {
2033 # Some namespaces don't allow subpages
2034 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2038 * Handle link to subpage if necessary
2040 * @param $target String: the source of the link
2041 * @param &$text String: the link text, modified as necessary
2042 * @return string the full name of the link
2045 function maybeDoSubpageLink( $target, &$text ) {
2046 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2050 * Used by doBlockLevels()
2055 function closeParagraph() {
2057 if ( $this->mLastSection
!= '' ) {
2058 $result = '</' . $this->mLastSection
. ">\n";
2060 $this->mInPre
= false;
2061 $this->mLastSection
= '';
2066 * getCommon() returns the length of the longest common substring
2067 * of both arguments, starting at the beginning of both.
2070 * @param $st1 string
2071 * @param $st2 string
2075 function getCommon( $st1, $st2 ) {
2076 $fl = strlen( $st1 );
2077 $shorter = strlen( $st2 );
2078 if ( $fl < $shorter ) {
2082 for ( $i = 0; $i < $shorter; ++
$i ) {
2083 if ( $st1[$i] != $st2[$i] ) {
2091 * These next three functions open, continue, and close the list
2092 * element appropriate to the prefix character passed into them.
2099 function openList( $char ) {
2100 $result = $this->closeParagraph();
2102 if ( '*' === $char ) {
2103 $result .= '<ul><li>';
2104 } elseif ( '#' === $char ) {
2105 $result .= '<ol><li>';
2106 } elseif ( ':' === $char ) {
2107 $result .= '<dl><dd>';
2108 } elseif ( ';' === $char ) {
2109 $result .= '<dl><dt>';
2110 $this->mDTopen
= true;
2112 $result = '<!-- ERR 1 -->';
2120 * @param $char String
2125 function nextItem( $char ) {
2126 if ( '*' === $char ||
'#' === $char ) {
2128 } elseif ( ':' === $char ||
';' === $char ) {
2130 if ( $this->mDTopen
) {
2133 if ( ';' === $char ) {
2134 $this->mDTopen
= true;
2135 return $close . '<dt>';
2137 $this->mDTopen
= false;
2138 return $close . '<dd>';
2141 return '<!-- ERR 2 -->';
2146 * @param $char String
2151 function closeList( $char ) {
2152 if ( '*' === $char ) {
2153 $text = '</li></ul>';
2154 } elseif ( '#' === $char ) {
2155 $text = '</li></ol>';
2156 } elseif ( ':' === $char ) {
2157 if ( $this->mDTopen
) {
2158 $this->mDTopen
= false;
2159 $text = '</dt></dl>';
2161 $text = '</dd></dl>';
2164 return '<!-- ERR 3 -->';
2171 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2173 * @param $text String
2174 * @param $linestart Boolean: whether or not this is at the start of a line.
2176 * @return string the lists rendered as HTML
2178 function doBlockLevels( $text, $linestart ) {
2179 wfProfileIn( __METHOD__
);
2181 # Parsing through the text line by line. The main thing
2182 # happening here is handling of block-level elements p, pre,
2183 # and making lists from lines starting with * # : etc.
2185 $textLines = StringUtils
::explode( "\n", $text );
2187 $lastPrefix = $output = '';
2188 $this->mDTopen
= $inBlockElem = false;
2190 $paragraphStack = false;
2192 foreach ( $textLines as $oLine ) {
2194 if ( !$linestart ) {
2204 $lastPrefixLength = strlen( $lastPrefix );
2205 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2206 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2207 # If not in a <pre> element, scan for and figure out what prefixes are there.
2208 if ( !$this->mInPre
) {
2209 # Multiple prefixes may abut each other for nested lists.
2210 $prefixLength = strspn( $oLine, '*#:;' );
2211 $prefix = substr( $oLine, 0, $prefixLength );
2214 # ; and : are both from definition-lists, so they're equivalent
2215 # for the purposes of determining whether or not we need to open/close
2217 $prefix2 = str_replace( ';', ':', $prefix );
2218 $t = substr( $oLine, $prefixLength );
2219 $this->mInPre
= (bool)$preOpenMatch;
2221 # Don't interpret any other prefixes in preformatted text
2223 $prefix = $prefix2 = '';
2228 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2229 # Same as the last item, so no need to deal with nesting or opening stuff
2230 $output .= $this->nextItem( substr( $prefix, -1 ) );
2231 $paragraphStack = false;
2233 if ( substr( $prefix, -1 ) === ';') {
2234 # The one nasty exception: definition lists work like this:
2235 # ; title : definition text
2236 # So we check for : in the remainder text to split up the
2237 # title and definition, without b0rking links.
2239 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2241 $output .= $term . $this->nextItem( ':' );
2244 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2245 # We need to open or close prefixes, or both.
2247 # Either open or close a level...
2248 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2249 $paragraphStack = false;
2251 # Close all the prefixes which aren't shared.
2252 while ( $commonPrefixLength < $lastPrefixLength ) {
2253 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2254 --$lastPrefixLength;
2257 # Continue the current prefix if appropriate.
2258 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2259 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2262 # Open prefixes where appropriate.
2263 while ( $prefixLength > $commonPrefixLength ) {
2264 $char = substr( $prefix, $commonPrefixLength, 1 );
2265 $output .= $this->openList( $char );
2267 if ( ';' === $char ) {
2268 # @todo FIXME: This is dupe of code above
2269 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2271 $output .= $term . $this->nextItem( ':' );
2274 ++
$commonPrefixLength;
2276 $lastPrefix = $prefix2;
2279 # If we have no prefixes, go to paragraph mode.
2280 if ( 0 == $prefixLength ) {
2281 wfProfileIn( __METHOD__
."-paragraph" );
2282 # No prefix (not in list)--go to paragraph mode
2283 # XXX: use a stack for nestable elements like span, table and div
2284 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2285 $closematch = preg_match(
2286 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2287 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2288 if ( $openmatch or $closematch ) {
2289 $paragraphStack = false;
2290 # TODO bug 5718: paragraph closed
2291 $output .= $this->closeParagraph();
2292 if ( $preOpenMatch and !$preCloseMatch ) {
2293 $this->mInPre
= true;
2295 $inBlockElem = !$closematch;
2296 } elseif ( !$inBlockElem && !$this->mInPre
) {
2297 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2299 if ( $this->mLastSection
!== 'pre' ) {
2300 $paragraphStack = false;
2301 $output .= $this->closeParagraph().'<pre>';
2302 $this->mLastSection
= 'pre';
2304 $t = substr( $t, 1 );
2307 if ( trim( $t ) === '' ) {
2308 if ( $paragraphStack ) {
2309 $output .= $paragraphStack.'<br />';
2310 $paragraphStack = false;
2311 $this->mLastSection
= 'p';
2313 if ( $this->mLastSection
!== 'p' ) {
2314 $output .= $this->closeParagraph();
2315 $this->mLastSection
= '';
2316 $paragraphStack = '<p>';
2318 $paragraphStack = '</p><p>';
2322 if ( $paragraphStack ) {
2323 $output .= $paragraphStack;
2324 $paragraphStack = false;
2325 $this->mLastSection
= 'p';
2326 } elseif ( $this->mLastSection
!== 'p' ) {
2327 $output .= $this->closeParagraph().'<p>';
2328 $this->mLastSection
= 'p';
2333 wfProfileOut( __METHOD__
."-paragraph" );
2335 # somewhere above we forget to get out of pre block (bug 785)
2336 if ( $preCloseMatch && $this->mInPre
) {
2337 $this->mInPre
= false;
2339 if ( $paragraphStack === false ) {
2343 while ( $prefixLength ) {
2344 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2347 if ( $this->mLastSection
!= '' ) {
2348 $output .= '</' . $this->mLastSection
. '>';
2349 $this->mLastSection
= '';
2352 wfProfileOut( __METHOD__
);
2357 * Split up a string on ':', ignoring any occurences inside tags
2358 * to prevent illegal overlapping.
2360 * @param $str String the string to split
2361 * @param &$before String set to everything before the ':'
2362 * @param &$after String set to everything after the ':'
2363 * @return String the position of the ':', or false if none found
2365 function findColonNoLinks( $str, &$before, &$after ) {
2366 wfProfileIn( __METHOD__
);
2368 $pos = strpos( $str, ':' );
2369 if ( $pos === false ) {
2371 wfProfileOut( __METHOD__
);
2375 $lt = strpos( $str, '<' );
2376 if ( $lt === false ||
$lt > $pos ) {
2377 # Easy; no tag nesting to worry about
2378 $before = substr( $str, 0, $pos );
2379 $after = substr( $str, $pos+
1 );
2380 wfProfileOut( __METHOD__
);
2384 # Ugly state machine to walk through avoiding tags.
2385 $state = self
::COLON_STATE_TEXT
;
2387 $len = strlen( $str );
2388 for( $i = 0; $i < $len; $i++
) {
2392 # (Using the number is a performance hack for common cases)
2393 case 0: # self::COLON_STATE_TEXT:
2396 # Could be either a <start> tag or an </end> tag
2397 $state = self
::COLON_STATE_TAGSTART
;
2400 if ( $stack == 0 ) {
2402 $before = substr( $str, 0, $i );
2403 $after = substr( $str, $i +
1 );
2404 wfProfileOut( __METHOD__
);
2407 # Embedded in a tag; don't break it.
2410 # Skip ahead looking for something interesting
2411 $colon = strpos( $str, ':', $i );
2412 if ( $colon === false ) {
2413 # Nothing else interesting
2414 wfProfileOut( __METHOD__
);
2417 $lt = strpos( $str, '<', $i );
2418 if ( $stack === 0 ) {
2419 if ( $lt === false ||
$colon < $lt ) {
2421 $before = substr( $str, 0, $colon );
2422 $after = substr( $str, $colon +
1 );
2423 wfProfileOut( __METHOD__
);
2427 if ( $lt === false ) {
2428 # Nothing else interesting to find; abort!
2429 # We're nested, but there's no close tags left. Abort!
2432 # Skip ahead to next tag start
2434 $state = self
::COLON_STATE_TAGSTART
;
2437 case 1: # self::COLON_STATE_TAG:
2442 $state = self
::COLON_STATE_TEXT
;
2445 # Slash may be followed by >?
2446 $state = self
::COLON_STATE_TAGSLASH
;
2452 case 2: # self::COLON_STATE_TAGSTART:
2455 $state = self
::COLON_STATE_CLOSETAG
;
2458 $state = self
::COLON_STATE_COMMENT
;
2461 # Illegal early close? This shouldn't happen D:
2462 $state = self
::COLON_STATE_TEXT
;
2465 $state = self
::COLON_STATE_TAG
;
2468 case 3: # self::COLON_STATE_CLOSETAG:
2473 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2474 wfProfileOut( __METHOD__
);
2477 $state = self
::COLON_STATE_TEXT
;
2480 case self
::COLON_STATE_TAGSLASH
:
2482 # Yes, a self-closed tag <blah/>
2483 $state = self
::COLON_STATE_TEXT
;
2485 # Probably we're jumping the gun, and this is an attribute
2486 $state = self
::COLON_STATE_TAG
;
2489 case 5: # self::COLON_STATE_COMMENT:
2491 $state = self
::COLON_STATE_COMMENTDASH
;
2494 case self
::COLON_STATE_COMMENTDASH
:
2496 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2498 $state = self
::COLON_STATE_COMMENT
;
2501 case self
::COLON_STATE_COMMENTDASHDASH
:
2503 $state = self
::COLON_STATE_TEXT
;
2505 $state = self
::COLON_STATE_COMMENT
;
2509 throw new MWException( "State machine error in " . __METHOD__
);
2513 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2514 wfProfileOut( __METHOD__
);
2517 wfProfileOut( __METHOD__
);
2522 * Return value of a magic variable (like PAGENAME)
2526 * @param $index integer
2527 * @param $frame PPFrame
2531 function getVariableValue( $index, $frame = false ) {
2532 global $wgContLang, $wgSitename, $wgServer;
2533 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2535 if ( is_null( $this->mTitle
) ) {
2536 // If no title set, bad things are going to happen
2537 // later. Title should always be set since this
2538 // should only be called in the middle of a parse
2539 // operation (but the unit-tests do funky stuff)
2540 throw new MWException( __METHOD__
. ' Should only be '
2541 . ' called while parsing (no title set)' );
2545 * Some of these require message or data lookups and can be
2546 * expensive to check many times.
2548 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2549 if ( isset( $this->mVarCache
[$index] ) ) {
2550 return $this->mVarCache
[$index];
2554 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2555 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2558 global $wgLocaltimezone;
2559 if ( isset( $wgLocaltimezone ) ) {
2560 $oldtz = date_default_timezone_get();
2561 date_default_timezone_set( $wgLocaltimezone );
2564 $localTimestamp = date( 'YmdHis', $ts );
2565 $localMonth = date( 'm', $ts );
2566 $localMonth1 = date( 'n', $ts );
2567 $localMonthName = date( 'n', $ts );
2568 $localDay = date( 'j', $ts );
2569 $localDay2 = date( 'd', $ts );
2570 $localDayOfWeek = date( 'w', $ts );
2571 $localWeek = date( 'W', $ts );
2572 $localYear = date( 'Y', $ts );
2573 $localHour = date( 'H', $ts );
2574 if ( isset( $wgLocaltimezone ) ) {
2575 date_default_timezone_set( $oldtz );
2578 $pageLang = $this->getFunctionLang();
2581 case 'currentmonth':
2582 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2584 case 'currentmonth1':
2585 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2587 case 'currentmonthname':
2588 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2590 case 'currentmonthnamegen':
2591 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2593 case 'currentmonthabbrev':
2594 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2597 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2600 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2603 $value = $pageLang->formatNum( $localMonth );
2606 $value = $pageLang->formatNum( $localMonth1 );
2608 case 'localmonthname':
2609 $value = $pageLang->getMonthName( $localMonthName );
2611 case 'localmonthnamegen':
2612 $value = $pageLang->getMonthNameGen( $localMonthName );
2614 case 'localmonthabbrev':
2615 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2618 $value = $pageLang->formatNum( $localDay );
2621 $value = $pageLang->formatNum( $localDay2 );
2624 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2627 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2629 case 'fullpagename':
2630 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2632 case 'fullpagenamee':
2633 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2636 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2638 case 'subpagenamee':
2639 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2641 case 'basepagename':
2642 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2644 case 'basepagenamee':
2645 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2647 case 'talkpagename':
2648 if ( $this->mTitle
->canTalk() ) {
2649 $talkPage = $this->mTitle
->getTalkPage();
2650 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2655 case 'talkpagenamee':
2656 if ( $this->mTitle
->canTalk() ) {
2657 $talkPage = $this->mTitle
->getTalkPage();
2658 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2663 case 'subjectpagename':
2664 $subjPage = $this->mTitle
->getSubjectPage();
2665 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2667 case 'subjectpagenamee':
2668 $subjPage = $this->mTitle
->getSubjectPage();
2669 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2672 # Let the edit saving system know we should parse the page
2673 # *after* a revision ID has been assigned.
2674 $this->mOutput
->setFlag( 'vary-revision' );
2675 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2676 $value = $this->mRevisionId
;
2679 # Let the edit saving system know we should parse the page
2680 # *after* a revision ID has been assigned. This is for null edits.
2681 $this->mOutput
->setFlag( 'vary-revision' );
2682 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2683 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2685 case 'revisionday2':
2686 # Let the edit saving system know we should parse the page
2687 # *after* a revision ID has been assigned. This is for null edits.
2688 $this->mOutput
->setFlag( 'vary-revision' );
2689 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2690 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2692 case 'revisionmonth':
2693 # Let the edit saving system know we should parse the page
2694 # *after* a revision ID has been assigned. This is for null edits.
2695 $this->mOutput
->setFlag( 'vary-revision' );
2696 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2697 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2699 case 'revisionmonth1':
2700 # Let the edit saving system know we should parse the page
2701 # *after* a revision ID has been assigned. This is for null edits.
2702 $this->mOutput
->setFlag( 'vary-revision' );
2703 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2704 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2706 case 'revisionyear':
2707 # Let the edit saving system know we should parse the page
2708 # *after* a revision ID has been assigned. This is for null edits.
2709 $this->mOutput
->setFlag( 'vary-revision' );
2710 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2711 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2713 case 'revisiontimestamp':
2714 # Let the edit saving system know we should parse the page
2715 # *after* a revision ID has been assigned. This is for null edits.
2716 $this->mOutput
->setFlag( 'vary-revision' );
2717 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2718 $value = $this->getRevisionTimestamp();
2720 case 'revisionuser':
2721 # Let the edit saving system know we should parse the page
2722 # *after* a revision ID has been assigned. This is for null edits.
2723 $this->mOutput
->setFlag( 'vary-revision' );
2724 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2725 $value = $this->getRevisionUser();
2728 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2731 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2734 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2737 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2739 case 'subjectspace':
2740 $value = $this->mTitle
->getSubjectNsText();
2742 case 'subjectspacee':
2743 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2745 case 'currentdayname':
2746 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2749 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2752 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2755 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2758 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2759 # int to remove the padding
2760 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2763 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2765 case 'localdayname':
2766 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2769 $value = $pageLang->formatNum( $localYear, true );
2772 $value = $pageLang->time( $localTimestamp, false, false );
2775 $value = $pageLang->formatNum( $localHour, true );
2778 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2779 # int to remove the padding
2780 $value = $pageLang->formatNum( (int)$localWeek );
2783 $value = $pageLang->formatNum( $localDayOfWeek );
2785 case 'numberofarticles':
2786 $value = $pageLang->formatNum( SiteStats
::articles() );
2788 case 'numberoffiles':
2789 $value = $pageLang->formatNum( SiteStats
::images() );
2791 case 'numberofusers':
2792 $value = $pageLang->formatNum( SiteStats
::users() );
2794 case 'numberofactiveusers':
2795 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2797 case 'numberofpages':
2798 $value = $pageLang->formatNum( SiteStats
::pages() );
2800 case 'numberofadmins':
2801 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2803 case 'numberofedits':
2804 $value = $pageLang->formatNum( SiteStats
::edits() );
2806 case 'numberofviews':
2807 $value = $pageLang->formatNum( SiteStats
::views() );
2809 case 'currenttimestamp':
2810 $value = wfTimestamp( TS_MW
, $ts );
2812 case 'localtimestamp':
2813 $value = $localTimestamp;
2815 case 'currentversion':
2816 $value = SpecialVersion
::getVersion();
2819 return $wgArticlePath;
2825 $serverParts = wfParseUrl( $wgServer );
2826 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2828 return $wgScriptPath;
2830 return $wgStylePath;
2831 case 'directionmark':
2832 return $pageLang->getDirMark();
2833 case 'contentlanguage':
2834 global $wgLanguageCode;
2835 return $wgLanguageCode;
2838 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2846 $this->mVarCache
[$index] = $value;
2853 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2857 function initialiseVariables() {
2858 wfProfileIn( __METHOD__
);
2859 $variableIDs = MagicWord
::getVariableIDs();
2860 $substIDs = MagicWord
::getSubstIDs();
2862 $this->mVariables
= new MagicWordArray( $variableIDs );
2863 $this->mSubstWords
= new MagicWordArray( $substIDs );
2864 wfProfileOut( __METHOD__
);
2868 * Preprocess some wikitext and return the document tree.
2869 * This is the ghost of replace_variables().
2871 * @param $text String: The text to parse
2872 * @param $flags Integer: bitwise combination of:
2873 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2874 * included. Default is to assume a direct page view.
2876 * The generated DOM tree must depend only on the input text and the flags.
2877 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2879 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2880 * change in the DOM tree for a given text, must be passed through the section identifier
2881 * in the section edit link and thus back to extractSections().
2883 * The output of this function is currently only cached in process memory, but a persistent
2884 * cache may be implemented at a later date which takes further advantage of these strict
2885 * dependency requirements.
2891 function preprocessToDom( $text, $flags = 0 ) {
2892 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2897 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2903 public static function splitWhitespace( $s ) {
2904 $ltrimmed = ltrim( $s );
2905 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2906 $trimmed = rtrim( $ltrimmed );
2907 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2909 $w2 = substr( $ltrimmed, -$diff );
2913 return array( $w1, $trimmed, $w2 );
2917 * Replace magic variables, templates, and template arguments
2918 * with the appropriate text. Templates are substituted recursively,
2919 * taking care to avoid infinite loops.
2921 * Note that the substitution depends on value of $mOutputType:
2922 * self::OT_WIKI: only {{subst:}} templates
2923 * self::OT_PREPROCESS: templates but not extension tags
2924 * self::OT_HTML: all templates and extension tags
2926 * @param $text String the text to transform
2927 * @param $frame PPFrame Object describing the arguments passed to the template.
2928 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2929 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2930 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
2935 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2936 # Is there any text? Also, Prevent too big inclusions!
2937 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2940 wfProfileIn( __METHOD__
);
2942 if ( $frame === false ) {
2943 $frame = $this->getPreprocessor()->newFrame();
2944 } elseif ( !( $frame instanceof PPFrame
) ) {
2945 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2946 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2949 $dom = $this->preprocessToDom( $text );
2950 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2951 $text = $frame->expand( $dom, $flags );
2953 wfProfileOut( __METHOD__
);
2958 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2960 * @param $args array
2964 static function createAssocArgs( $args ) {
2965 $assocArgs = array();
2967 foreach ( $args as $arg ) {
2968 $eqpos = strpos( $arg, '=' );
2969 if ( $eqpos === false ) {
2970 $assocArgs[$index++
] = $arg;
2972 $name = trim( substr( $arg, 0, $eqpos ) );
2973 $value = trim( substr( $arg, $eqpos+
1 ) );
2974 if ( $value === false ) {
2977 if ( $name !== false ) {
2978 $assocArgs[$name] = $value;
2987 * Warn the user when a parser limitation is reached
2988 * Will warn at most once the user per limitation type
2990 * @param $limitationType String: should be one of:
2991 * 'expensive-parserfunction' (corresponding messages:
2992 * 'expensive-parserfunction-warning',
2993 * 'expensive-parserfunction-category')
2994 * 'post-expand-template-argument' (corresponding messages:
2995 * 'post-expand-template-argument-warning',
2996 * 'post-expand-template-argument-category')
2997 * 'post-expand-template-inclusion' (corresponding messages:
2998 * 'post-expand-template-inclusion-warning',
2999 * 'post-expand-template-inclusion-category')
3000 * @param $current Current value
3001 * @param $max Maximum allowed, when an explicit limit has been
3002 * exceeded, provide the values (optional)
3004 function limitationWarn( $limitationType, $current=null, $max=null) {
3005 # does no harm if $current and $max are present but are unnecessary for the message
3006 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3007 $this->mOutput
->addWarning( $warning );
3008 $this->addTrackingCategory( "$limitationType-category" );
3012 * Return the text of a template, after recursively
3013 * replacing any variables or templates within the template.
3015 * @param $piece Array: the parts of the template
3016 * $piece['title']: the title, i.e. the part before the |
3017 * $piece['parts']: the parameter array
3018 * $piece['lineStart']: whether the brace was at the start of a line
3019 * @param $frame PPFrame The current frame, contains template arguments
3020 * @return String: the text of the template
3023 function braceSubstitution( $piece, $frame ) {
3024 global $wgContLang, $wgNonincludableNamespaces;
3025 wfProfileIn( __METHOD__
);
3026 wfProfileIn( __METHOD__
.'-setup' );
3029 $found = false; # $text has been filled
3030 $nowiki = false; # wiki markup in $text should be escaped
3031 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3032 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3033 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3034 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3036 # Title object, where $text came from
3039 # $part1 is the bit before the first |, and must contain only title characters.
3040 # Various prefixes will be stripped from it later.
3041 $titleWithSpaces = $frame->expand( $piece['title'] );
3042 $part1 = trim( $titleWithSpaces );
3045 # Original title text preserved for various purposes
3046 $originalTitle = $part1;
3048 # $args is a list of argument nodes, starting from index 0, not including $part1
3049 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3050 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3051 wfProfileOut( __METHOD__
.'-setup' );
3052 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3055 wfProfileIn( __METHOD__
.'-modifiers' );
3058 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3060 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3061 # Decide whether to expand template or keep wikitext as-is.
3062 if ( $this->ot
['wiki'] ) {
3063 if ( $substMatch === false ) {
3064 $literal = true; # literal when in PST with no prefix
3066 $literal = false; # expand when in PST with subst: or safesubst:
3069 if ( $substMatch == 'subst' ) {
3070 $literal = true; # literal when not in PST with plain subst:
3072 $literal = false; # expand when not in PST with safesubst: or no prefix
3076 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3083 if ( !$found && $args->getLength() == 0 ) {
3084 $id = $this->mVariables
->matchStartToEnd( $part1 );
3085 if ( $id !== false ) {
3086 $text = $this->getVariableValue( $id, $frame );
3087 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3088 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3094 # MSG, MSGNW and RAW
3097 $mwMsgnw = MagicWord
::get( 'msgnw' );
3098 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3101 # Remove obsolete MSG:
3102 $mwMsg = MagicWord
::get( 'msg' );
3103 $mwMsg->matchStartAndRemove( $part1 );
3107 $mwRaw = MagicWord
::get( 'raw' );
3108 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3109 $forceRawInterwiki = true;
3112 wfProfileOut( __METHOD__
.'-modifiers' );
3116 wfProfileIn( __METHOD__
. '-pfunc' );
3118 $colonPos = strpos( $part1, ':' );
3119 if ( $colonPos !== false ) {
3120 # Case sensitive functions
3121 $function = substr( $part1, 0, $colonPos );
3122 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3123 $function = $this->mFunctionSynonyms
[1][$function];
3125 # Case insensitive functions
3126 $function = $this->getFunctionLang()->lc( $function );
3127 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3128 $function = $this->mFunctionSynonyms
[0][$function];
3134 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3135 $initialArgs = array( &$this );
3136 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3137 if ( $flags & SFH_OBJECT_ARGS
) {
3138 # Add a frame parameter, and pass the arguments as an array
3139 $allArgs = $initialArgs;
3140 $allArgs[] = $frame;
3141 for ( $i = 0; $i < $args->getLength(); $i++
) {
3142 $funcArgs[] = $args->item( $i );
3144 $allArgs[] = $funcArgs;
3146 # Convert arguments to plain text
3147 for ( $i = 0; $i < $args->getLength(); $i++
) {
3148 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3150 $allArgs = array_merge( $initialArgs, $funcArgs );
3153 # Workaround for PHP bug 35229 and similar
3154 if ( !is_callable( $callback ) ) {
3155 wfProfileOut( __METHOD__
. '-pfunc' );
3156 wfProfileOut( __METHOD__
);
3157 throw new MWException( "Tag hook for $function is not callable\n" );
3159 $result = call_user_func_array( $callback, $allArgs );
3162 $preprocessFlags = 0;
3164 if ( is_array( $result ) ) {
3165 if ( isset( $result[0] ) ) {
3167 unset( $result[0] );
3170 # Extract flags into the local scope
3171 # This allows callers to set flags such as nowiki, found, etc.
3177 $text = $this->preprocessToDom( $text, $preprocessFlags );
3182 wfProfileOut( __METHOD__
. '-pfunc' );
3185 # Finish mangling title and then check for loops.
3186 # Set $title to a Title object and $titleText to the PDBK
3189 # Split the title into page and subpage
3191 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3192 if ( $subpage !== '' ) {
3193 $ns = $this->mTitle
->getNamespace();
3195 $title = Title
::newFromText( $part1, $ns );
3197 $titleText = $title->getPrefixedText();
3198 # Check for language variants if the template is not found
3199 if ( $this->getFunctionLang()->hasVariants() && $title->getArticleID() == 0 ) {
3200 $this->getFunctionLang()->findVariantLink( $part1, $title, true );
3202 # Do recursion depth check
3203 $limit = $this->mOptions
->getMaxTemplateDepth();
3204 if ( $frame->depth
>= $limit ) {
3206 $text = '<span class="error">'
3207 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3213 # Load from database
3214 if ( !$found && $title ) {
3215 wfProfileIn( __METHOD__
. '-loadtpl' );
3216 if ( !$title->isExternal() ) {
3217 if ( $title->getNamespace() == NS_SPECIAL
3218 && $this->mOptions
->getAllowSpecialInclusion()
3219 && $this->ot
['html'] )
3221 // Pass the template arguments as URL parameters.
3222 // "uselang" will have no effect since the Language object
3223 // is forced to the one defined in ParserOptions.
3224 $pageArgs = array();
3225 for ( $i = 0; $i < $args->getLength(); $i++
) {
3226 $bits = $args->item( $i )->splitArg();
3227 if ( strval( $bits['index'] ) === '' ) {
3228 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3229 $value = trim( $frame->expand( $bits['value'] ) );
3230 $pageArgs[$name] = $value;
3234 // Create a new context to execute the special page
3235 $context = new RequestContext
;
3236 $context->setTitle( $title );
3237 $context->setRequest( new FauxRequest( $pageArgs ) );
3238 $context->setUser( $this->getUser() );
3239 $context->setLang( $this->mOptions
->getUserLangObj() );
3240 $ret = SpecialPageFactory
::capturePath( $title, $context );
3242 $text = $context->getOutput()->getHTML();
3243 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3246 $this->disableCache();
3248 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3249 $found = false; # access denied
3250 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3252 list( $text, $title ) = $this->getTemplateDom( $title );
3253 if ( $text !== false ) {
3259 # If the title is valid but undisplayable, make a link to it
3260 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3261 $text = "[[:$titleText]]";
3264 } elseif ( $title->isTrans() ) {
3265 # Interwiki transclusion
3266 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3267 $text = $this->interwikiTransclude( $title, 'render' );
3270 $text = $this->interwikiTransclude( $title, 'raw' );
3271 # Preprocess it like a template
3272 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3278 # Do infinite loop check
3279 # This has to be done after redirect resolution to avoid infinite loops via redirects
3280 if ( !$frame->loopCheck( $title ) ) {
3282 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3283 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3285 wfProfileOut( __METHOD__
. '-loadtpl' );
3288 # If we haven't found text to substitute by now, we're done
3289 # Recover the source wikitext and return it
3291 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3292 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3293 wfProfileOut( __METHOD__
);
3294 return array( 'object' => $text );
3297 # Expand DOM-style return values in a child frame
3298 if ( $isChildObj ) {
3299 # Clean up argument array
3300 $newFrame = $frame->newChild( $args, $title );
3303 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3304 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3305 # Expansion is eligible for the empty-frame cache
3306 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3307 $text = $this->mTplExpandCache
[$titleText];
3309 $text = $newFrame->expand( $text );
3310 $this->mTplExpandCache
[$titleText] = $text;
3313 # Uncached expansion
3314 $text = $newFrame->expand( $text );
3317 if ( $isLocalObj && $nowiki ) {
3318 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3319 $isLocalObj = false;
3322 # Replace raw HTML by a placeholder
3323 # Add a blank line preceding, to prevent it from mucking up
3324 # immediately preceding headings
3326 $text = "\n\n" . $this->insertStripItem( $text );
3327 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3328 # Escape nowiki-style return values
3329 $text = wfEscapeWikiText( $text );
3330 } elseif ( is_string( $text )
3331 && !$piece['lineStart']
3332 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3334 # Bug 529: if the template begins with a table or block-level
3335 # element, it should be treated as beginning a new line.
3336 # This behaviour is somewhat controversial.
3337 $text = "\n" . $text;
3340 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3341 # Error, oversize inclusion
3342 if ( $titleText !== false ) {
3343 # Make a working, properly escaped link if possible (bug 23588)
3344 $text = "[[:$titleText]]";
3346 # This will probably not be a working link, but at least it may
3347 # provide some hint of where the problem is
3348 preg_replace( '/^:/', '', $originalTitle );
3349 $text = "[[:$originalTitle]]";
3351 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3352 $this->limitationWarn( 'post-expand-template-inclusion' );
3355 if ( $isLocalObj ) {
3356 $ret = array( 'object' => $text );
3358 $ret = array( 'text' => $text );
3361 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3362 wfProfileOut( __METHOD__
);
3367 * Get the semi-parsed DOM representation of a template with a given title,
3368 * and its redirect destination title. Cached.
3370 * @param $title Title
3374 function getTemplateDom( $title ) {
3375 $cacheTitle = $title;
3376 $titleText = $title->getPrefixedDBkey();
3378 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3379 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3380 $title = Title
::makeTitle( $ns, $dbk );
3381 $titleText = $title->getPrefixedDBkey();
3383 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3384 return array( $this->mTplDomCache
[$titleText], $title );
3387 # Cache miss, go to the database
3388 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3390 if ( $text === false ) {
3391 $this->mTplDomCache
[$titleText] = false;
3392 return array( false, $title );
3395 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3396 $this->mTplDomCache
[ $titleText ] = $dom;
3398 if ( !$title->equals( $cacheTitle ) ) {
3399 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3400 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3403 return array( $dom, $title );
3407 * Fetch the unparsed text of a template and register a reference to it.
3408 * @param Title $title
3409 * @return Array ( string or false, Title )
3411 function fetchTemplateAndTitle( $title ) {
3412 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3413 $stuff = call_user_func( $templateCb, $title, $this );
3414 $text = $stuff['text'];
3415 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3416 if ( isset( $stuff['deps'] ) ) {
3417 foreach ( $stuff['deps'] as $dep ) {
3418 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3421 return array( $text, $finalTitle );
3425 * Fetch the unparsed text of a template and register a reference to it.
3426 * @param Title $title
3427 * @return mixed string or false
3429 function fetchTemplate( $title ) {
3430 $rv = $this->fetchTemplateAndTitle( $title );
3435 * Static function to get a template
3436 * Can be overridden via ParserOptions::setTemplateCallback().
3438 * @parma $title Title
3439 * @param $parser Parser
3443 static function statelessFetchTemplate( $title, $parser = false ) {
3444 $text = $skip = false;
3445 $finalTitle = $title;
3448 # Loop to fetch the article, with up to 1 redirect
3449 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3450 # Give extensions a chance to select the revision instead
3451 $id = false; # Assume current
3452 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3453 array( $parser, $title, &$skip, &$id ) );
3459 'page_id' => $title->getArticleID(),
3466 ? Revision
::newFromId( $id )
3467 : Revision
::newFromTitle( $title );
3468 $rev_id = $rev ?
$rev->getId() : 0;
3469 # If there is no current revision, there is no page
3470 if ( $id === false && !$rev ) {
3471 $linkCache = LinkCache
::singleton();
3472 $linkCache->addBadLinkObj( $title );
3477 'page_id' => $title->getArticleID(),
3478 'rev_id' => $rev_id );
3479 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3480 # We fetched a rev from a different title; register it too...
3482 'title' => $rev->getTitle(),
3483 'page_id' => $rev->getPage(),
3484 'rev_id' => $rev_id );
3488 $text = $rev->getText();
3489 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3491 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3492 if ( !$message->exists() ) {
3496 $text = $message->plain();
3500 if ( $text === false ) {
3504 $finalTitle = $title;
3505 $title = Title
::newFromRedirect( $text );
3509 'finalTitle' => $finalTitle,
3514 * Fetch a file and its title and register a reference to it.
3515 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3516 * @param Title $title
3517 * @param Array $options Array of options to RepoGroup::findFile
3518 * @return File|false
3520 function fetchFile( $title, $options = array() ) {
3521 $res = $this->fetchFileAndTitle( $title, $options );
3526 * Fetch a file and its title and register a reference to it.
3527 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3528 * @param Title $title
3529 * @param Array $options Array of options to RepoGroup::findFile
3530 * @return Array ( File or false, Title of file )
3532 function fetchFileAndTitle( $title, $options = array() ) {
3533 if ( isset( $options['broken'] ) ) {
3534 $file = false; // broken thumbnail forced by hook
3535 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3536 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3537 } else { // get by (name,timestamp)
3538 $file = wfFindFile( $title, $options );
3540 $time = $file ?
$file->getTimestamp() : false;
3541 $sha1 = $file ?
$file->getSha1() : false;
3542 # Register the file as a dependency...
3543 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3544 if ( $file && !$title->equals( $file->getTitle() ) ) {
3545 # Update fetched file title
3546 $title = $file->getTitle();
3547 if ( is_null( $file->getRedirectedTitle() ) ) {
3548 # This file was not a redirect, but the title does not match.
3549 # Register under the new name because otherwise the link will
3551 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3554 return array( $file, $title );
3558 * Transclude an interwiki link.
3560 * @param $title Title
3565 function interwikiTransclude( $title, $action ) {
3566 global $wgEnableScaryTranscluding;
3568 if ( !$wgEnableScaryTranscluding ) {
3569 return wfMsgForContent('scarytranscludedisabled');
3572 $url = $title->getFullUrl( "action=$action" );
3574 if ( strlen( $url ) > 255 ) {
3575 return wfMsgForContent( 'scarytranscludetoolong' );
3577 return $this->fetchScaryTemplateMaybeFromCache( $url );
3581 * @param $url string
3582 * @return Mixed|String
3584 function fetchScaryTemplateMaybeFromCache( $url ) {
3585 global $wgTranscludeCacheExpiry;
3586 $dbr = wfGetDB( DB_SLAVE
);
3587 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3588 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3589 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3591 return $obj->tc_contents
;
3594 $text = Http
::get( $url );
3596 return wfMsgForContent( 'scarytranscludefailed', $url );
3599 $dbw = wfGetDB( DB_MASTER
);
3600 $dbw->replace( 'transcache', array('tc_url'), array(
3602 'tc_time' => $dbw->timestamp( time() ),
3603 'tc_contents' => $text)
3609 * Triple brace replacement -- used for template arguments
3612 * @param $peice array
3613 * @param $frame PPFrame
3617 function argSubstitution( $piece, $frame ) {
3618 wfProfileIn( __METHOD__
);
3621 $parts = $piece['parts'];
3622 $nameWithSpaces = $frame->expand( $piece['title'] );
3623 $argName = trim( $nameWithSpaces );
3625 $text = $frame->getArgument( $argName );
3626 if ( $text === false && $parts->getLength() > 0
3630 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3633 # No match in frame, use the supplied default
3634 $object = $parts->item( 0 )->getChildren();
3636 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3637 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3638 $this->limitationWarn( 'post-expand-template-argument' );
3641 if ( $text === false && $object === false ) {
3643 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3645 if ( $error !== false ) {
3648 if ( $object !== false ) {
3649 $ret = array( 'object' => $object );
3651 $ret = array( 'text' => $text );
3654 wfProfileOut( __METHOD__
);
3659 * Return the text to be used for a given extension tag.
3660 * This is the ghost of strip().
3662 * @param $params Associative array of parameters:
3663 * name PPNode for the tag name
3664 * attr PPNode for unparsed text where tag attributes are thought to be
3665 * attributes Optional associative array of parsed attributes
3666 * inner Contents of extension element
3667 * noClose Original text did not have a close tag
3668 * @param $frame PPFrame
3672 function extensionSubstitution( $params, $frame ) {
3673 $name = $frame->expand( $params['name'] );
3674 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3675 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3676 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3678 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3679 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3680 if ( $isFunctionTag ) {
3681 $markerType = 'none';
3683 $markerType = 'general';
3685 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3686 $name = strtolower( $name );
3687 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3688 if ( isset( $params['attributes'] ) ) {
3689 $attributes = $attributes +
$params['attributes'];
3692 if ( isset( $this->mTagHooks
[$name] ) ) {
3693 # Workaround for PHP bug 35229 and similar
3694 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3695 throw new MWException( "Tag hook for $name is not callable\n" );
3697 $output = call_user_func_array( $this->mTagHooks
[$name],
3698 array( $content, $attributes, $this, $frame ) );
3699 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3700 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3701 if ( !is_callable( $callback ) ) {
3702 throw new MWException( "Tag hook for $name is not callable\n" );
3705 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3707 $output = '<span class="error">Invalid tag extension name: ' .
3708 htmlspecialchars( $name ) . '</span>';
3711 if ( is_array( $output ) ) {
3712 # Extract flags to local scope (to override $markerType)
3714 $output = $flags[0];
3719 if ( is_null( $attrText ) ) {
3722 if ( isset( $params['attributes'] ) ) {
3723 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3724 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3725 htmlspecialchars( $attrValue ) . '"';
3728 if ( $content === null ) {
3729 $output = "<$name$attrText/>";
3731 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3732 $output = "<$name$attrText>$content$close";
3736 if ( $markerType === 'none' ) {
3738 } elseif ( $markerType === 'nowiki' ) {
3739 $this->mStripState
->addNoWiki( $marker, $output );
3740 } elseif ( $markerType === 'general' ) {
3741 $this->mStripState
->addGeneral( $marker, $output );
3743 throw new MWException( __METHOD__
.': invalid marker type' );
3749 * Increment an include size counter
3751 * @param $type String: the type of expansion
3752 * @param $size Integer: the size of the text
3753 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3755 function incrementIncludeSize( $type, $size ) {
3756 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3759 $this->mIncludeSizes
[$type] +
= $size;
3765 * Increment the expensive function count
3767 * @return Boolean: false if the limit has been exceeded
3769 function incrementExpensiveFunctionCount() {
3770 global $wgExpensiveParserFunctionLimit;
3771 $this->mExpensiveFunctionCount++
;
3772 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3779 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3780 * Fills $this->mDoubleUnderscores, returns the modified text
3782 * @param $text string
3786 function doDoubleUnderscore( $text ) {
3787 wfProfileIn( __METHOD__
);
3789 # The position of __TOC__ needs to be recorded
3790 $mw = MagicWord
::get( 'toc' );
3791 if ( $mw->match( $text ) ) {
3792 $this->mShowToc
= true;
3793 $this->mForceTocPosition
= true;
3795 # Set a placeholder. At the end we'll fill it in with the TOC.
3796 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3798 # Only keep the first one.
3799 $text = $mw->replace( '', $text );
3802 # Now match and remove the rest of them
3803 $mwa = MagicWord
::getDoubleUnderscoreArray();
3804 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3806 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3807 $this->mOutput
->mNoGallery
= true;
3809 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3810 $this->mShowToc
= false;
3812 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3813 $this->addTrackingCategory( 'hidden-category-category' );
3815 # (bug 8068) Allow control over whether robots index a page.
3817 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3818 # is not desirable, the last one on the page should win.
3819 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3820 $this->mOutput
->setIndexPolicy( 'noindex' );
3821 $this->addTrackingCategory( 'noindex-category' );
3823 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3824 $this->mOutput
->setIndexPolicy( 'index' );
3825 $this->addTrackingCategory( 'index-category' );
3828 # Cache all double underscores in the database
3829 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3830 $this->mOutput
->setProperty( $key, '' );
3833 wfProfileOut( __METHOD__
);
3838 * Add a tracking category, getting the title from a system message,
3839 * or print a debug message if the title is invalid.
3841 * @param $msg String: message key
3842 * @return Boolean: whether the addition was successful
3844 protected function addTrackingCategory( $msg ) {
3845 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3846 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3849 $cat = wfMsgForContent( $msg );
3851 # Allow tracking categories to be disabled by setting them to "-"
3852 if ( $cat === '-' ) {
3856 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3857 if ( $containerCategory ) {
3858 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3861 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3867 * This function accomplishes several tasks:
3868 * 1) Auto-number headings if that option is enabled
3869 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3870 * 3) Add a Table of contents on the top for users who have enabled the option
3871 * 4) Auto-anchor headings
3873 * It loops through all headlines, collects the necessary data, then splits up the
3874 * string and re-inserts the newly formatted headlines.
3876 * @param $text String
3877 * @param $origText String: original, untouched wikitext
3878 * @param $isMain Boolean
3881 function formatHeadings( $text, $origText, $isMain=true ) {
3882 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3884 # Inhibit editsection links if requested in the page
3885 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3886 $maybeShowEditLink = $showEditLink = false;
3888 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3889 $showEditLink = $this->mOptions
->getEditSection();
3891 if ( $showEditLink ) {
3892 $this->mOutput
->setEditSectionTokens( true );
3895 # Get all headlines for numbering them and adding funky stuff like [edit]
3896 # links - this is for later, but we need the number of headlines right now
3898 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3900 # if there are fewer than 4 headlines in the article, do not show TOC
3901 # unless it's been explicitly enabled.
3902 $enoughToc = $this->mShowToc
&&
3903 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3905 # Allow user to stipulate that a page should have a "new section"
3906 # link added via __NEWSECTIONLINK__
3907 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3908 $this->mOutput
->setNewSection( true );
3911 # Allow user to remove the "new section"
3912 # link via __NONEWSECTIONLINK__
3913 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3914 $this->mOutput
->hideNewSection( true );
3917 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3918 # override above conditions and always show TOC above first header
3919 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3920 $this->mShowToc
= true;
3928 # Ugh .. the TOC should have neat indentation levels which can be
3929 # passed to the skin functions. These are determined here
3933 $sublevelCount = array();
3934 $levelCount = array();
3939 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3940 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3941 $oldType = $this->mOutputType
;
3942 $this->setOutputType( self
::OT_WIKI
);
3943 $frame = $this->getPreprocessor()->newFrame();
3944 $root = $this->preprocessToDom( $origText );
3945 $node = $root->getFirstChild();
3950 foreach ( $matches[3] as $headline ) {
3951 $isTemplate = false;
3953 $sectionIndex = false;
3955 $markerMatches = array();
3956 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3957 $serial = $markerMatches[1];
3958 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3959 $isTemplate = ( $titleText != $baseTitleText );
3960 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3964 $prevlevel = $level;
3966 $level = $matches[1][$headlineCount];
3968 if ( $level > $prevlevel ) {
3969 # Increase TOC level
3971 $sublevelCount[$toclevel] = 0;
3972 if ( $toclevel<$wgMaxTocLevel ) {
3973 $prevtoclevel = $toclevel;
3974 $toc .= Linker
::tocIndent();
3977 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3978 # Decrease TOC level, find level to jump to
3980 for ( $i = $toclevel; $i > 0; $i-- ) {
3981 if ( $levelCount[$i] == $level ) {
3982 # Found last matching level
3985 } elseif ( $levelCount[$i] < $level ) {
3986 # Found first matching level below current level
3994 if ( $toclevel<$wgMaxTocLevel ) {
3995 if ( $prevtoclevel < $wgMaxTocLevel ) {
3996 # Unindent only if the previous toc level was shown :p
3997 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3998 $prevtoclevel = $toclevel;
4000 $toc .= Linker
::tocLineEnd();
4004 # No change in level, end TOC line
4005 if ( $toclevel<$wgMaxTocLevel ) {
4006 $toc .= Linker
::tocLineEnd();
4010 $levelCount[$toclevel] = $level;
4012 # count number of headlines for each level
4013 @$sublevelCount[$toclevel]++
;
4015 for( $i = 1; $i <= $toclevel; $i++
) {
4016 if ( !empty( $sublevelCount[$i] ) ) {
4020 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4025 # The safe header is a version of the header text safe to use for links
4026 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4027 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4029 # Remove link placeholders by the link text.
4030 # <!--LINK number-->
4032 # link text with suffix
4033 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4035 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4036 $tocline = preg_replace(
4037 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4038 array( '', '<$1>' ),
4041 $tocline = trim( $tocline );
4043 # For the anchor, strip out HTML-y stuff period
4044 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4045 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4047 # Save headline for section edit hint before it's escaped
4048 $headlineHint = $safeHeadline;
4050 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4051 # For reverse compatibility, provide an id that's
4052 # HTML4-compatible, like we used to.
4054 # It may be worth noting, academically, that it's possible for
4055 # the legacy anchor to conflict with a non-legacy headline
4056 # anchor on the page. In this case likely the "correct" thing
4057 # would be to either drop the legacy anchors or make sure
4058 # they're numbered first. However, this would require people
4059 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4060 # manually, so let's not bother worrying about it.
4061 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4062 array( 'noninitial', 'legacy' ) );
4063 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4065 if ( $legacyHeadline == $safeHeadline ) {
4066 # No reason to have both (in fact, we can't)
4067 $legacyHeadline = false;
4070 $legacyHeadline = false;
4071 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4075 # HTML names must be case-insensitively unique (bug 10721).
4076 # This does not apply to Unicode characters per
4077 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4078 # @todo FIXME: We may be changing them depending on the current locale.
4079 $arrayKey = strtolower( $safeHeadline );
4080 if ( $legacyHeadline === false ) {
4081 $legacyArrayKey = false;
4083 $legacyArrayKey = strtolower( $legacyHeadline );
4086 # count how many in assoc. array so we can track dupes in anchors
4087 if ( isset( $refers[$arrayKey] ) ) {
4088 $refers[$arrayKey]++
;
4090 $refers[$arrayKey] = 1;
4092 if ( isset( $refers[$legacyArrayKey] ) ) {
4093 $refers[$legacyArrayKey]++
;
4095 $refers[$legacyArrayKey] = 1;
4098 # Don't number the heading if it is the only one (looks silly)
4099 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4100 # the two are different if the line contains a link
4101 $headline = $numbering . ' ' . $headline;
4104 # Create the anchor for linking from the TOC to the section
4105 $anchor = $safeHeadline;
4106 $legacyAnchor = $legacyHeadline;
4107 if ( $refers[$arrayKey] > 1 ) {
4108 $anchor .= '_' . $refers[$arrayKey];
4110 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4111 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4113 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4114 $toc .= Linker
::tocLine( $anchor, $tocline,
4115 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4118 # Add the section to the section tree
4119 # Find the DOM node for this header
4120 while ( $node && !$isTemplate ) {
4121 if ( $node->getName() === 'h' ) {
4122 $bits = $node->splitHeading();
4123 if ( $bits['i'] == $sectionIndex ) {
4127 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4128 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4129 $node = $node->getNextSibling();
4132 'toclevel' => $toclevel,
4135 'number' => $numbering,
4136 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4137 'fromtitle' => $titleText,
4138 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4139 'anchor' => $anchor,
4142 # give headline the correct <h#> tag
4143 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4144 // Output edit section links as markers with styles that can be customized by skins
4145 if ( $isTemplate ) {
4146 # Put a T flag in the section identifier, to indicate to extractSections()
4147 # that sections inside <includeonly> should be counted.
4148 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4150 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4152 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4153 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4154 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4155 // so we don't have to worry about a user trying to input one of these markers directly.
4156 // We use a page and section attribute to stop the language converter from converting these important bits
4157 // of data, but put the headline hint inside a content block because the language converter is supposed to
4158 // be able to convert that piece of data.
4159 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4160 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4161 if ( isset($editlinkArgs[2]) ) {
4162 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4169 $head[$headlineCount] = Linker
::makeHeadline( $level,
4170 $matches['attrib'][$headlineCount], $anchor, $headline,
4171 $editlink, $legacyAnchor );
4176 $this->setOutputType( $oldType );
4178 # Never ever show TOC if no headers
4179 if ( $numVisible < 1 ) {
4184 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4185 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4187 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4188 $this->mOutput
->setTOCHTML( $toc );
4192 $this->mOutput
->setSections( $tocraw );
4195 # split up and insert constructed headlines
4196 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4199 // build an array of document sections
4200 $sections = array();
4201 foreach ( $blocks as $block ) {
4202 // $head is zero-based, sections aren't.
4203 if ( empty( $head[$i - 1] ) ) {
4204 $sections[$i] = $block;
4206 $sections[$i] = $head[$i - 1] . $block;
4210 * Send a hook, one per section.
4211 * The idea here is to be able to make section-level DIVs, but to do so in a
4212 * lower-impact, more correct way than r50769
4215 * $section : the section number
4216 * &$sectionContent : ref to the content of the section
4217 * $showEditLinks : boolean describing whether this section has an edit link
4219 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4224 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4225 // append the TOC at the beginning
4226 // Top anchor now in skin
4227 $sections[0] = $sections[0] . $toc . "\n";
4230 $full .= join( '', $sections );
4232 if ( $this->mForceTocPosition
) {
4233 return str_replace( '<!--MWTOC-->', $toc, $full );
4240 * Transform wiki markup when saving a page by doing \r\n -> \n
4241 * conversion, substitting signatures, {{subst:}} templates, etc.
4243 * @param $text String: the text to transform
4244 * @param $title Title: the Title object for the current article
4245 * @param $user User: the User object describing the current user
4246 * @param $options ParserOptions: parsing options
4247 * @param $clearState Boolean: whether to clear the parser state first
4248 * @return String: the altered wiki markup
4250 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4251 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4252 $this->setUser( $user );
4257 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4258 if( $options->getPreSaveTransform() ) {
4259 $text = $this->pstPass2( $text, $user );
4261 $text = $this->mStripState
->unstripBoth( $text );
4263 $this->setUser( null ); #Reset
4269 * Pre-save transform helper function
4272 * @param $text string
4277 function pstPass2( $text, $user ) {
4278 global $wgContLang, $wgLocaltimezone;
4280 # Note: This is the timestamp saved as hardcoded wikitext to
4281 # the database, we use $wgContLang here in order to give
4282 # everyone the same signature and use the default one rather
4283 # than the one selected in each user's preferences.
4284 # (see also bug 12815)
4285 $ts = $this->mOptions
->getTimestamp();
4286 if ( isset( $wgLocaltimezone ) ) {
4287 $tz = $wgLocaltimezone;
4289 $tz = date_default_timezone_get();
4292 $unixts = wfTimestamp( TS_UNIX
, $ts );
4293 $oldtz = date_default_timezone_get();
4294 date_default_timezone_set( $tz );
4295 $ts = date( 'YmdHis', $unixts );
4296 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4298 # Allow translation of timezones through wiki. date() can return
4299 # whatever crap the system uses, localised or not, so we cannot
4300 # ship premade translations.
4301 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4302 $msg = wfMessage( $key )->inContentLanguage();
4303 if ( $msg->exists() ) {
4304 $tzMsg = $msg->text();
4307 date_default_timezone_set( $oldtz );
4309 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4311 # Variable replacement
4312 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4313 $text = $this->replaceVariables( $text );
4315 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4316 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4319 $sigText = $this->getUserSig( $user );
4320 $text = strtr( $text, array(
4322 '~~~~' => "$sigText $d",
4326 # Context links: [[|name]] and [[name (context)|]]
4327 global $wgLegalTitleChars;
4328 $tc = "[$wgLegalTitleChars]";
4329 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4331 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4332 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4333 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4334 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4336 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4337 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4338 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4339 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4341 $t = $this->mTitle
->getText();
4343 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4344 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4345 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4346 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4348 # if there's no context, don't bother duplicating the title
4349 $text = preg_replace( $p2, '[[\\1]]', $text );
4352 # Trim trailing whitespace
4353 $text = rtrim( $text );
4359 * Fetch the user's signature text, if any, and normalize to
4360 * validated, ready-to-insert wikitext.
4361 * If you have pre-fetched the nickname or the fancySig option, you can
4362 * specify them here to save a database query.
4363 * Do not reuse this parser instance after calling getUserSig(),
4364 * as it may have changed if it's the $wgParser.
4367 * @param $nickname String|bool nickname to use or false to use user's default nickname
4368 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4369 * or null to use default value
4372 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4373 global $wgMaxSigChars;
4375 $username = $user->getName();
4377 # If not given, retrieve from the user object.
4378 if ( $nickname === false )
4379 $nickname = $user->getOption( 'nickname' );
4381 if ( is_null( $fancySig ) ) {
4382 $fancySig = $user->getBoolOption( 'fancysig' );
4385 $nickname = $nickname == null ?
$username : $nickname;
4387 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4388 $nickname = $username;
4389 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4390 } elseif ( $fancySig !== false ) {
4391 # Sig. might contain markup; validate this
4392 if ( $this->validateSig( $nickname ) !== false ) {
4393 # Validated; clean up (if needed) and return it
4394 return $this->cleanSig( $nickname, true );
4396 # Failed to validate; fall back to the default
4397 $nickname = $username;
4398 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4402 # Make sure nickname doesnt get a sig in a sig
4403 $nickname = $this->cleanSigInSig( $nickname );
4405 # If we're still here, make it a link to the user page
4406 $userText = wfEscapeWikiText( $username );
4407 $nickText = wfEscapeWikiText( $nickname );
4408 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4410 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4414 * Check that the user's signature contains no bad XML
4416 * @param $text String
4417 * @return mixed An expanded string, or false if invalid.
4419 function validateSig( $text ) {
4420 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4424 * Clean up signature text
4426 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4427 * 2) Substitute all transclusions
4429 * @param $text String
4430 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4431 * @return String: signature text
4433 function cleanSig( $text, $parsing = false ) {
4436 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4439 # Option to disable this feature
4440 if ( !$this->mOptions
->getCleanSignatures() ) {
4444 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4445 # => Move this logic to braceSubstitution()
4446 $substWord = MagicWord
::get( 'subst' );
4447 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4448 $substText = '{{' . $substWord->getSynonym( 0 );
4450 $text = preg_replace( $substRegex, $substText, $text );
4451 $text = $this->cleanSigInSig( $text );
4452 $dom = $this->preprocessToDom( $text );
4453 $frame = $this->getPreprocessor()->newFrame();
4454 $text = $frame->expand( $dom );
4457 $text = $this->mStripState
->unstripBoth( $text );
4464 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4466 * @param $text String
4467 * @return String: signature text with /~{3,5}/ removed
4469 function cleanSigInSig( $text ) {
4470 $text = preg_replace( '/~{3,5}/', '', $text );
4475 * Set up some variables which are usually set up in parse()
4476 * so that an external function can call some class members with confidence
4478 * @param $title Title|null
4479 * @param $options ParserOptions
4480 * @param $outputType
4481 * @param $clearState bool
4483 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4484 $this->startParse( $title, $options, $outputType, $clearState );
4488 * @param $title Title|null
4489 * @param $options ParserOptions
4490 * @param $outputType
4491 * @param $clearState bool
4493 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4494 $this->setTitle( $title );
4495 $this->mOptions
= $options;
4496 $this->setOutputType( $outputType );
4497 if ( $clearState ) {
4498 $this->clearState();
4503 * Wrapper for preprocess()
4505 * @param $text String: the text to preprocess
4506 * @param $options ParserOptions: options
4507 * @param $title Title object or null to use $wgTitle
4510 public function transformMsg( $text, $options, $title = null ) {
4511 static $executing = false;
4513 # Guard against infinite recursion
4519 wfProfileIn( __METHOD__
);
4525 # It's not uncommon having a null $wgTitle in scripts. See r80898
4526 # Create a ghost title in such case
4527 $title = Title
::newFromText( 'Dwimmerlaik' );
4529 $text = $this->preprocess( $text, $title, $options );
4532 wfProfileOut( __METHOD__
);
4537 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4538 * The callback should have the following form:
4539 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4541 * Transform and return $text. Use $parser for any required context, e.g. use
4542 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4544 * Hooks may return extended information by returning an array, of which the
4545 * first numbered element (index 0) must be the return string, and all other
4546 * entries are extracted into local variables within an internal function
4547 * in the Parser class.
4549 * This interface (introduced r61913) appears to be undocumented, but
4550 * 'markerName' is used by some core tag hooks to override which strip
4551 * array their results are placed in. **Use great caution if attempting
4552 * this interface, as it is not documented and injudicious use could smash
4553 * private variables.**
4555 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4556 * @param $callback Mixed: the callback function (and object) to use for the tag
4557 * @return The old value of the mTagHooks array associated with the hook
4559 public function setHook( $tag, $callback ) {
4560 $tag = strtolower( $tag );
4561 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4562 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4563 $this->mTagHooks
[$tag] = $callback;
4564 if ( !in_array( $tag, $this->mStripList
) ) {
4565 $this->mStripList
[] = $tag;
4572 * As setHook(), but letting the contents be parsed.
4574 * Transparent tag hooks are like regular XML-style tag hooks, except they
4575 * operate late in the transformation sequence, on HTML instead of wikitext.
4577 * This is probably obsoleted by things dealing with parser frames?
4578 * The only extension currently using it is geoserver.
4581 * @todo better document or deprecate this
4583 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4584 * @param $callback Mixed: the callback function (and object) to use for the tag
4585 * @return The old value of the mTagHooks array associated with the hook
4587 function setTransparentTagHook( $tag, $callback ) {
4588 $tag = strtolower( $tag );
4589 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4590 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4591 $this->mTransparentTagHooks
[$tag] = $callback;
4597 * Remove all tag hooks
4599 function clearTagHooks() {
4600 $this->mTagHooks
= array();
4601 $this->mStripList
= $this->mDefaultStripList
;
4605 * Create a function, e.g. {{sum:1|2|3}}
4606 * The callback function should have the form:
4607 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4609 * Or with SFH_OBJECT_ARGS:
4610 * function myParserFunction( $parser, $frame, $args ) { ... }
4612 * The callback may either return the text result of the function, or an array with the text
4613 * in element 0, and a number of flags in the other elements. The names of the flags are
4614 * specified in the keys. Valid flags are:
4615 * found The text returned is valid, stop processing the template. This
4617 * nowiki Wiki markup in the return value should be escaped
4618 * isHTML The returned text is HTML, armour it against wikitext transformation
4620 * @param $id String: The magic word ID
4621 * @param $callback Mixed: the callback function (and object) to use
4622 * @param $flags Integer: a combination of the following flags:
4623 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4625 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4626 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4627 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4628 * the arguments, and to control the way they are expanded.
4630 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4631 * arguments, for instance:
4632 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4634 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4635 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4636 * working if/when this is changed.
4638 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4641 * Please read the documentation in includes/parser/Preprocessor.php for more information
4642 * about the methods available in PPFrame and PPNode.
4644 * @return The old callback function for this name, if any
4646 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4649 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4650 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4652 # Add to function cache
4653 $mw = MagicWord
::get( $id );
4655 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4657 $synonyms = $mw->getSynonyms();
4658 $sensitive = intval( $mw->isCaseSensitive() );
4660 foreach ( $synonyms as $syn ) {
4662 if ( !$sensitive ) {
4663 $syn = $wgContLang->lc( $syn );
4666 if ( !( $flags & SFH_NO_HASH
) ) {
4669 # Remove trailing colon
4670 if ( substr( $syn, -1, 1 ) === ':' ) {
4671 $syn = substr( $syn, 0, -1 );
4673 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4679 * Get all registered function hook identifiers
4683 function getFunctionHooks() {
4684 return array_keys( $this->mFunctionHooks
);
4688 * Create a tag function, e.g. <test>some stuff</test>.
4689 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4690 * Unlike parser functions, their content is not preprocessed.
4692 function setFunctionTagHook( $tag, $callback, $flags ) {
4693 $tag = strtolower( $tag );
4694 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4695 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4696 $this->mFunctionTagHooks
[$tag] : null;
4697 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4699 if ( !in_array( $tag, $this->mStripList
) ) {
4700 $this->mStripList
[] = $tag;
4707 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4708 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4709 * Placeholders created in Skin::makeLinkObj()
4711 * @param $text string
4712 * @param $options int
4714 * @return array of link CSS classes, indexed by PDBK.
4716 function replaceLinkHolders( &$text, $options = 0 ) {
4717 return $this->mLinkHolders
->replace( $text );
4721 * Replace <!--LINK--> link placeholders with plain text of links
4722 * (not HTML-formatted).
4724 * @param $text String
4727 function replaceLinkHoldersText( $text ) {
4728 return $this->mLinkHolders
->replaceText( $text );
4732 * Renders an image gallery from a text with one line per image.
4733 * text labels may be given by using |-style alternative text. E.g.
4734 * Image:one.jpg|The number "1"
4735 * Image:tree.jpg|A tree
4736 * given as text will return the HTML of a gallery with two images,
4737 * labeled 'The number "1"' and
4740 * @param string $text
4741 * @param array $params
4742 * @return string HTML
4744 function renderImageGallery( $text, $params ) {
4745 $ig = new ImageGallery();
4746 $ig->setContextTitle( $this->mTitle
);
4747 $ig->setShowBytes( false );
4748 $ig->setShowFilename( false );
4749 $ig->setParser( $this );
4750 $ig->setHideBadImages();
4751 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4753 if ( isset( $params['showfilename'] ) ) {
4754 $ig->setShowFilename( true );
4756 $ig->setShowFilename( false );
4758 if ( isset( $params['caption'] ) ) {
4759 $caption = $params['caption'];
4760 $caption = htmlspecialchars( $caption );
4761 $caption = $this->replaceInternalLinks( $caption );
4762 $ig->setCaptionHtml( $caption );
4764 if ( isset( $params['perrow'] ) ) {
4765 $ig->setPerRow( $params['perrow'] );
4767 if ( isset( $params['widths'] ) ) {
4768 $ig->setWidths( $params['widths'] );
4770 if ( isset( $params['heights'] ) ) {
4771 $ig->setHeights( $params['heights'] );
4774 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4776 $lines = StringUtils
::explode( "\n", $text );
4777 foreach ( $lines as $line ) {
4778 # match lines like these:
4779 # Image:someimage.jpg|This is some image
4781 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4783 if ( count( $matches ) == 0 ) {
4787 if ( strpos( $matches[0], '%' ) !== false ) {
4788 $matches[1] = rawurldecode( $matches[1] );
4790 $title = Title
::newFromText( $matches[1], NS_FILE
);
4791 if ( is_null( $title ) ) {
4792 # Bogus title. Ignore these so we don't bomb out later.
4798 if ( isset( $matches[3] ) ) {
4799 // look for an |alt= definition while trying not to break existing
4800 // captions with multiple pipes (|) in it, until a more sensible grammar
4801 // is defined for images in galleries
4803 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4804 $altmatches = StringUtils
::explode('|', $matches[3]);
4805 $magicWordAlt = MagicWord
::get( 'img_alt' );
4807 foreach ( $altmatches as $altmatch ) {
4808 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4810 $alt = $this->stripAltText( $match, false );
4813 // concatenate all other pipes
4814 $label .= '|' . $altmatch;
4817 // remove the first pipe
4818 $label = substr( $label, 1 );
4821 $ig->add( $title, $label, $alt );
4823 return $ig->toHTML();
4830 function getImageParams( $handler ) {
4832 $handlerClass = get_class( $handler );
4836 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4837 # Initialise static lists
4838 static $internalParamNames = array(
4839 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4840 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4841 'bottom', 'text-bottom' ),
4842 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4843 'upright', 'border', 'link', 'alt' ),
4845 static $internalParamMap;
4846 if ( !$internalParamMap ) {
4847 $internalParamMap = array();
4848 foreach ( $internalParamNames as $type => $names ) {
4849 foreach ( $names as $name ) {
4850 $magicName = str_replace( '-', '_', "img_$name" );
4851 $internalParamMap[$magicName] = array( $type, $name );
4856 # Add handler params
4857 $paramMap = $internalParamMap;
4859 $handlerParamMap = $handler->getParamMap();
4860 foreach ( $handlerParamMap as $magic => $paramName ) {
4861 $paramMap[$magic] = array( 'handler', $paramName );
4864 $this->mImageParams
[$handlerClass] = $paramMap;
4865 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4867 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4871 * Parse image options text and use it to make an image
4873 * @param $title Title
4874 * @param $options String
4875 * @param $holders LinkHolderArray|false
4876 * @return string HTML
4878 function makeImage( $title, $options, $holders = false ) {
4879 # Check if the options text is of the form "options|alt text"
4881 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4882 # * left no resizing, just left align. label is used for alt= only
4883 # * right same, but right aligned
4884 # * none same, but not aligned
4885 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4886 # * center center the image
4887 # * frame Keep original image size, no magnify-button.
4888 # * framed Same as "frame"
4889 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4890 # * upright reduce width for upright images, rounded to full __0 px
4891 # * border draw a 1px border around the image
4892 # * alt Text for HTML alt attribute (defaults to empty)
4893 # * link Set the target of the image link. Can be external, interwiki, or local
4894 # vertical-align values (no % or length right now):
4904 $parts = StringUtils
::explode( "|", $options );
4906 # Give extensions a chance to select the file revision for us
4909 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4910 array( $this, $title, &$options, &$descQuery ) );
4911 # Fetch and register the file (file title may be different via hooks)
4912 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
4915 $handler = $file ?
$file->getHandler() : false;
4917 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4920 $this->addTrackingCategory( 'broken-file-category' );
4923 # Process the input parameters
4925 $params = array( 'frame' => array(), 'handler' => array(),
4926 'horizAlign' => array(), 'vertAlign' => array() );
4927 foreach ( $parts as $part ) {
4928 $part = trim( $part );
4929 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4931 if ( isset( $paramMap[$magicName] ) ) {
4932 list( $type, $paramName ) = $paramMap[$magicName];
4934 # Special case; width and height come in one variable together
4935 if ( $type === 'handler' && $paramName === 'width' ) {
4937 # (bug 13500) In both cases (width/height and width only),
4938 # permit trailing "px" for backward compatibility.
4939 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4940 $width = intval( $m[1] );
4941 $height = intval( $m[2] );
4942 if ( $handler->validateParam( 'width', $width ) ) {
4943 $params[$type]['width'] = $width;
4946 if ( $handler->validateParam( 'height', $height ) ) {
4947 $params[$type]['height'] = $height;
4950 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4951 $width = intval( $value );
4952 if ( $handler->validateParam( 'width', $width ) ) {
4953 $params[$type]['width'] = $width;
4956 } # else no validation -- bug 13436
4958 if ( $type === 'handler' ) {
4959 # Validate handler parameter
4960 $validated = $handler->validateParam( $paramName, $value );
4962 # Validate internal parameters
4963 switch( $paramName ) {
4966 # @todo FIXME: Possibly check validity here for
4967 # manualthumb? downstream behavior seems odd with
4968 # missing manual thumbs.
4970 $value = $this->stripAltText( $value, $holders );
4973 $chars = self
::EXT_LINK_URL_CLASS
;
4974 $prots = $this->mUrlProtocols
;
4975 if ( $value === '' ) {
4976 $paramName = 'no-link';
4979 } elseif ( preg_match( "/^$prots/", $value ) ) {
4980 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
4981 $paramName = 'link-url';
4982 $this->mOutput
->addExternalLink( $value );
4983 if ( $this->mOptions
->getExternalLinkTarget() ) {
4984 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4989 $linkTitle = Title
::newFromText( $value );
4991 $paramName = 'link-title';
4992 $value = $linkTitle;
4993 $this->mOutput
->addLink( $linkTitle );
4999 # Most other things appear to be empty or numeric...
5000 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5005 $params[$type][$paramName] = $value;
5009 if ( !$validated ) {
5014 # Process alignment parameters
5015 if ( $params['horizAlign'] ) {
5016 $params['frame']['align'] = key( $params['horizAlign'] );
5018 if ( $params['vertAlign'] ) {
5019 $params['frame']['valign'] = key( $params['vertAlign'] );
5022 $params['frame']['caption'] = $caption;
5024 # Will the image be presented in a frame, with the caption below?
5025 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5026 isset( $params['frame']['framed'] ) ||
5027 isset( $params['frame']['thumbnail'] ) ||
5028 isset( $params['frame']['manualthumb'] );
5030 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5031 # came to also set the caption, ordinary text after the image -- which
5032 # makes no sense, because that just repeats the text multiple times in
5033 # screen readers. It *also* came to set the title attribute.
5035 # Now that we have an alt attribute, we should not set the alt text to
5036 # equal the caption: that's worse than useless, it just repeats the
5037 # text. This is the framed/thumbnail case. If there's no caption, we
5038 # use the unnamed parameter for alt text as well, just for the time be-
5039 # ing, if the unnamed param is set and the alt param is not.
5041 # For the future, we need to figure out if we want to tweak this more,
5042 # e.g., introducing a title= parameter for the title; ignoring the un-
5043 # named parameter entirely for images without a caption; adding an ex-
5044 # plicit caption= parameter and preserving the old magic unnamed para-
5046 if ( $imageIsFramed ) { # Framed image
5047 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5048 # No caption or alt text, add the filename as the alt text so
5049 # that screen readers at least get some description of the image
5050 $params['frame']['alt'] = $title->getText();
5052 # Do not set $params['frame']['title'] because tooltips don't make sense
5054 } else { # Inline image
5055 if ( !isset( $params['frame']['alt'] ) ) {
5056 # No alt text, use the "caption" for the alt text
5057 if ( $caption !== '') {
5058 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5060 # No caption, fall back to using the filename for the
5062 $params['frame']['alt'] = $title->getText();
5065 # Use the "caption" for the tooltip text
5066 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5069 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5071 # Linker does the rest
5072 $time = isset( $options['time'] ) ?
$options['time'] : false;
5073 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5074 $time, $descQuery, $this->mOptions
->getThumbSize() );
5076 # Give the handler a chance to modify the parser object
5078 $handler->parserTransformHook( $this, $file );
5086 * @param $holders LinkHolderArray
5087 * @return mixed|String
5089 protected function stripAltText( $caption, $holders ) {
5090 # Strip bad stuff out of the title (tooltip). We can't just use
5091 # replaceLinkHoldersText() here, because if this function is called
5092 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5094 $tooltip = $holders->replaceText( $caption );
5096 $tooltip = $this->replaceLinkHoldersText( $caption );
5099 # make sure there are no placeholders in thumbnail attributes
5100 # that are later expanded to html- so expand them now and
5102 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5103 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5109 * Set a flag in the output object indicating that the content is dynamic and
5110 * shouldn't be cached.
5112 function disableCache() {
5113 wfDebug( "Parser output marked as uncacheable.\n" );
5114 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5115 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5119 * Callback from the Sanitizer for expanding items found in HTML attribute
5120 * values, so they can be safely tested and escaped.
5122 * @param $text String
5123 * @param $frame PPFrame
5126 function attributeStripCallback( &$text, $frame = false ) {
5127 $text = $this->replaceVariables( $text, $frame );
5128 $text = $this->mStripState
->unstripBoth( $text );
5137 function getTags() {
5138 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5142 * Replace transparent tags in $text with the values given by the callbacks.
5144 * Transparent tag hooks are like regular XML-style tag hooks, except they
5145 * operate late in the transformation sequence, on HTML instead of wikitext.
5147 * @param $text string
5151 function replaceTransparentTags( $text ) {
5153 $elements = array_keys( $this->mTransparentTagHooks
);
5154 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5155 $replacements = array();
5157 foreach ( $matches as $marker => $data ) {
5158 list( $element, $content, $params, $tag ) = $data;
5159 $tagName = strtolower( $element );
5160 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5161 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5165 $replacements[$marker] = $output;
5167 return strtr( $text, $replacements );
5171 * Break wikitext input into sections, and either pull or replace
5172 * some particular section's text.
5174 * External callers should use the getSection and replaceSection methods.
5176 * @param $text String: Page wikitext
5177 * @param $section String: a section identifier string of the form:
5178 * <flag1> - <flag2> - ... - <section number>
5180 * Currently the only recognised flag is "T", which means the target section number
5181 * was derived during a template inclusion parse, in other words this is a template
5182 * section edit link. If no flags are given, it was an ordinary section edit link.
5183 * This flag is required to avoid a section numbering mismatch when a section is
5184 * enclosed by <includeonly> (bug 6563).
5186 * The section number 0 pulls the text before the first heading; other numbers will
5187 * pull the given section along with its lower-level subsections. If the section is
5188 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5190 * Section 0 is always considered to exist, even if it only contains the empty
5191 * string. If $text is the empty string and section 0 is replaced, $newText is
5194 * @param $mode String: one of "get" or "replace"
5195 * @param $newText String: replacement text for section data.
5196 * @return String: for "get", the extracted section text.
5197 * for "replace", the whole page with the section replaced.
5199 private function extractSections( $text, $section, $mode, $newText='' ) {
5200 global $wgTitle; # not generally used but removes an ugly failure mode
5201 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5203 $frame = $this->getPreprocessor()->newFrame();
5205 # Process section extraction flags
5207 $sectionParts = explode( '-', $section );
5208 $sectionIndex = array_pop( $sectionParts );
5209 foreach ( $sectionParts as $part ) {
5210 if ( $part === 'T' ) {
5211 $flags |
= self
::PTD_FOR_INCLUSION
;
5215 # Check for empty input
5216 if ( strval( $text ) === '' ) {
5217 # Only sections 0 and T-0 exist in an empty document
5218 if ( $sectionIndex == 0 ) {
5219 if ( $mode === 'get' ) {
5225 if ( $mode === 'get' ) {
5233 # Preprocess the text
5234 $root = $this->preprocessToDom( $text, $flags );
5236 # <h> nodes indicate section breaks
5237 # They can only occur at the top level, so we can find them by iterating the root's children
5238 $node = $root->getFirstChild();
5240 # Find the target section
5241 if ( $sectionIndex == 0 ) {
5242 # Section zero doesn't nest, level=big
5243 $targetLevel = 1000;
5246 if ( $node->getName() === 'h' ) {
5247 $bits = $node->splitHeading();
5248 if ( $bits['i'] == $sectionIndex ) {
5249 $targetLevel = $bits['level'];
5253 if ( $mode === 'replace' ) {
5254 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5256 $node = $node->getNextSibling();
5262 if ( $mode === 'get' ) {
5269 # Find the end of the section, including nested sections
5271 if ( $node->getName() === 'h' ) {
5272 $bits = $node->splitHeading();
5273 $curLevel = $bits['level'];
5274 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5278 if ( $mode === 'get' ) {
5279 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5281 $node = $node->getNextSibling();
5284 # Write out the remainder (in replace mode only)
5285 if ( $mode === 'replace' ) {
5286 # Output the replacement text
5287 # Add two newlines on -- trailing whitespace in $newText is conventionally
5288 # stripped by the editor, so we need both newlines to restore the paragraph gap
5289 # Only add trailing whitespace if there is newText
5290 if ( $newText != "" ) {
5291 $outText .= $newText . "\n\n";
5295 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5296 $node = $node->getNextSibling();
5300 if ( is_string( $outText ) ) {
5301 # Re-insert stripped tags
5302 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5309 * This function returns the text of a section, specified by a number ($section).
5310 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5311 * the first section before any such heading (section 0).
5313 * If a section contains subsections, these are also returned.
5315 * @param $text String: text to look in
5316 * @param $section String: section identifier
5317 * @param $deftext String: default to return if section is not found
5318 * @return string text of the requested section
5320 public function getSection( $text, $section, $deftext='' ) {
5321 return $this->extractSections( $text, $section, "get", $deftext );
5325 * This function returns $oldtext after the content of the section
5326 * specified by $section has been replaced with $text. If the target
5327 * section does not exist, $oldtext is returned unchanged.
5329 * @param $oldtext String: former text of the article
5330 * @param $section Numeric: section identifier
5331 * @param $text String: replacing text
5332 * @return String: modified text
5334 public function replaceSection( $oldtext, $section, $text ) {
5335 return $this->extractSections( $oldtext, $section, "replace", $text );
5339 * Get the ID of the revision we are parsing
5341 * @return Mixed: integer or null
5343 function getRevisionId() {
5344 return $this->mRevisionId
;
5348 * Get the revision object for $this->mRevisionId
5350 * @return Revision|null either a Revision object or null
5352 protected function getRevisionObject() {
5353 if ( !is_null( $this->mRevisionObject
) ) {
5354 return $this->mRevisionObject
;
5356 if ( is_null( $this->mRevisionId
) ) {
5360 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5361 return $this->mRevisionObject
;
5365 * Get the timestamp associated with the current revision, adjusted for
5366 * the default server-local timestamp
5368 function getRevisionTimestamp() {
5369 if ( is_null( $this->mRevisionTimestamp
) ) {
5370 wfProfileIn( __METHOD__
);
5374 $revObject = $this->getRevisionObject();
5375 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5377 # The cryptic '' timezone parameter tells to use the site-default
5378 # timezone offset instead of the user settings.
5380 # Since this value will be saved into the parser cache, served
5381 # to other users, and potentially even used inside links and such,
5382 # it needs to be consistent for all visitors.
5383 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5385 wfProfileOut( __METHOD__
);
5387 return $this->mRevisionTimestamp
;
5391 * Get the name of the user that edited the last revision
5393 * @return String: user name
5395 function getRevisionUser() {
5396 if( is_null( $this->mRevisionUser
) ) {
5397 $revObject = $this->getRevisionObject();
5399 # if this template is subst: the revision id will be blank,
5400 # so just use the current user's name
5402 $this->mRevisionUser
= $revObject->getUserText();
5403 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5404 $this->mRevisionUser
= $this->getUser()->getName();
5407 return $this->mRevisionUser
;
5411 * Mutator for $mDefaultSort
5413 * @param $sort New value
5415 public function setDefaultSort( $sort ) {
5416 $this->mDefaultSort
= $sort;
5417 $this->mOutput
->setProperty( 'defaultsort', $sort );
5421 * Accessor for $mDefaultSort
5422 * Will use the empty string if none is set.
5424 * This value is treated as a prefix, so the
5425 * empty string is equivalent to sorting by
5430 public function getDefaultSort() {
5431 if ( $this->mDefaultSort
!== false ) {
5432 return $this->mDefaultSort
;
5439 * Accessor for $mDefaultSort
5440 * Unlike getDefaultSort(), will return false if none is set
5442 * @return string or false
5444 public function getCustomDefaultSort() {
5445 return $this->mDefaultSort
;
5449 * Try to guess the section anchor name based on a wikitext fragment
5450 * presumably extracted from a heading, for example "Header" from
5453 * @param $text string
5457 public function guessSectionNameFromWikiText( $text ) {
5458 # Strip out wikitext links(they break the anchor)
5459 $text = $this->stripSectionName( $text );
5460 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5461 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5465 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5466 * instead. For use in redirects, since IE6 interprets Redirect: headers
5467 * as something other than UTF-8 (apparently?), resulting in breakage.
5469 * @param $text String: The section name
5470 * @return string An anchor
5472 public function guessLegacySectionNameFromWikiText( $text ) {
5473 # Strip out wikitext links(they break the anchor)
5474 $text = $this->stripSectionName( $text );
5475 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5476 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5480 * Strips a text string of wikitext for use in a section anchor
5482 * Accepts a text string and then removes all wikitext from the
5483 * string and leaves only the resultant text (i.e. the result of
5484 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5485 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5486 * to create valid section anchors by mimicing the output of the
5487 * parser when headings are parsed.
5489 * @param $text String: text string to be stripped of wikitext
5490 * for use in a Section anchor
5491 * @return Filtered text string
5493 public function stripSectionName( $text ) {
5494 # Strip internal link markup
5495 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5496 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5498 # Strip external link markup
5499 # @todo FIXME: Not tolerant to blank link text
5500 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5501 # on how many empty links there are on the page - need to figure that out.
5502 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5504 # Parse wikitext quotes (italics & bold)
5505 $text = $this->doQuotes( $text );
5508 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5513 * strip/replaceVariables/unstrip for preprocessor regression testing
5515 * @param $text string
5516 * @param $title Title
5517 * @param $options ParserOptions
5518 * @param $outputType int
5522 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5523 $this->startParse( $title, $options, $outputType, true );
5525 $text = $this->replaceVariables( $text );
5526 $text = $this->mStripState
->unstripBoth( $text );
5527 $text = Sanitizer
::removeHTMLtags( $text );
5532 * @param $text string
5533 * @param $title Title
5534 * @param $options ParserOptions
5537 function testPst( $text, Title
$title, ParserOptions
$options ) {
5538 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5543 * @param $title Title
5544 * @param $options ParserOptions
5547 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5548 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5552 * Call a callback function on all regions of the given text that are not
5553 * inside strip markers, and replace those regions with the return value
5554 * of the callback. For example, with input:
5558 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5559 * two strings will be replaced with the value returned by the callback in
5567 function markerSkipCallback( $s, $callback ) {
5570 while ( $i < strlen( $s ) ) {
5571 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5572 if ( $markerStart === false ) {
5573 $out .= call_user_func( $callback, substr( $s, $i ) );
5576 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5577 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5578 if ( $markerEnd === false ) {
5579 $out .= substr( $s, $markerStart );
5582 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5583 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5592 * Save the parser state required to convert the given half-parsed text to
5593 * HTML. "Half-parsed" in this context means the output of
5594 * recursiveTagParse() or internalParse(). This output has strip markers
5595 * from replaceVariables (extensionSubstitution() etc.), and link
5596 * placeholders from replaceLinkHolders().
5598 * Returns an array which can be serialized and stored persistently. This
5599 * array can later be loaded into another parser instance with
5600 * unserializeHalfParsedText(). The text can then be safely incorporated into
5601 * the return value of a parser hook.
5603 * @param $text string
5607 function serializeHalfParsedText( $text ) {
5608 wfProfileIn( __METHOD__
);
5611 'version' => self
::HALF_PARSED_VERSION
,
5612 'stripState' => $this->mStripState
->getSubState( $text ),
5613 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5615 wfProfileOut( __METHOD__
);
5620 * Load the parser state given in the $data array, which is assumed to
5621 * have been generated by serializeHalfParsedText(). The text contents is
5622 * extracted from the array, and its markers are transformed into markers
5623 * appropriate for the current Parser instance. This transformed text is
5624 * returned, and can be safely included in the return value of a parser
5627 * If the $data array has been stored persistently, the caller should first
5628 * check whether it is still valid, by calling isValidHalfParsedText().
5630 * @param $data Serialized data
5633 function unserializeHalfParsedText( $data ) {
5634 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5635 throw new MWException( __METHOD__
.': invalid version' );
5638 # First, extract the strip state.
5639 $texts = array( $data['text'] );
5640 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5642 # Now renumber links
5643 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5645 # Should be good to go.
5650 * Returns true if the given array, presumed to be generated by
5651 * serializeHalfParsedText(), is compatible with the current version of the
5654 * @param $data Array
5658 function isValidHalfParsedText( $data ) {
5659 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;