3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into XHTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
58 * $wgNamespacesWithSubpages
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
71 * Update this version number when the ParserOutput format
72 * changes in an incompatible way, so the parser cache
73 * can automatically discard old data.
75 const VERSION
= '1.6.4';
78 * Update this version number when the output of serialiseHalfParsedText()
79 * changes in an incompatible way
81 const HALF_PARSED_VERSION
= 2;
83 # Flags for Parser::setFunctionHook
84 # Also available as global constants from Defines.php
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
92 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
93 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
94 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
121 var $mTagHooks = array();
122 var $mTransparentTagHooks = array();
123 var $mFunctionHooks = array();
124 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
125 var $mFunctionTagHooks = array();
126 var $mStripList = array();
127 var $mDefaultStripList = array();
128 var $mVarCache = array();
129 var $mImageParams = array();
130 var $mImageParamsMagicArray = array();
131 var $mMarkerIndex = 0;
132 var $mFirstCall = true;
134 # Initialised by initialiseVariables()
137 * @var MagicWordArray
142 * @var MagicWordArray
145 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
147 # Cleared with clearState():
152 var $mAutonumber, $mDTopen;
159 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
161 * @var LinkHolderArray
166 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
168 var $mTplExpandCache; # empty-frame expansion cache
169 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
170 var $mExpensiveFunctionCount; # number of expensive parser function calls
171 var $mShowToc, $mForceTocPosition;
176 var $mUser; # User object; only used when doing pre-save transform
179 # These are variables reset at least once per parse regardless of $clearState
189 var $mTitle; # Title context, used for self-link rendering and similar things
190 var $mOutputType; # Output type, one of the OT_xxx constants
191 var $ot; # Shortcut alias, see setOutputType()
192 var $mRevisionObject; # The revision object of the specified revision ID
193 var $mRevisionId; # ID to display in {{REVISIONID}} tags
194 var $mRevisionTimestamp; # The timestamp of the specified revision ID
195 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
196 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
208 public function __construct( $conf = array() ) {
209 $this->mConf
= $conf;
210 $this->mUrlProtocols
= wfUrlProtocols();
211 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')'.
212 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
213 if ( isset( $conf['preprocessorClass'] ) ) {
214 $this->mPreprocessorClass
= $conf['preprocessorClass'];
215 } elseif ( defined( 'MW_COMPILED' ) ) {
216 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
217 $this->mPreprocessorClass
= 'Preprocessor_Hash';
218 } elseif ( extension_loaded( 'domxml' ) ) {
219 # PECL extension that conflicts with the core DOM extension (bug 13770)
220 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
221 $this->mPreprocessorClass
= 'Preprocessor_Hash';
222 } elseif ( extension_loaded( 'dom' ) ) {
223 $this->mPreprocessorClass
= 'Preprocessor_DOM';
225 $this->mPreprocessorClass
= 'Preprocessor_Hash';
227 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
231 * Reduce memory usage to reduce the impact of circular references
233 function __destruct() {
234 if ( isset( $this->mLinkHolders
) ) {
235 unset( $this->mLinkHolders
);
237 foreach ( $this as $name => $value ) {
238 unset( $this->$name );
243 * Do various kinds of initialisation on the first call of the parser
245 function firstCallInit() {
246 if ( !$this->mFirstCall
) {
249 $this->mFirstCall
= false;
251 wfProfileIn( __METHOD__
);
253 CoreParserFunctions
::register( $this );
254 CoreTagHooks
::register( $this );
255 $this->initialiseVariables();
257 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
258 wfProfileOut( __METHOD__
);
266 function clearState() {
267 wfProfileIn( __METHOD__
);
268 if ( $this->mFirstCall
) {
269 $this->firstCallInit();
271 $this->mOutput
= new ParserOutput
;
272 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
273 $this->mAutonumber
= 0;
274 $this->mLastSection
= '';
275 $this->mDTopen
= false;
276 $this->mIncludeCount
= array();
277 $this->mArgStack
= false;
278 $this->mInPre
= false;
279 $this->mLinkHolders
= new LinkHolderArray( $this );
281 $this->mRevisionObject
= $this->mRevisionTimestamp
=
282 $this->mRevisionId
= $this->mRevisionUser
= null;
283 $this->mVarCache
= array();
287 * Prefix for temporary replacement strings for the multipass parser.
288 * \x07 should never appear in input as it's disallowed in XML.
289 * Using it at the front also gives us a little extra robustness
290 * since it shouldn't match when butted up against identifier-like
293 * Must not consist of all title characters, or else it will change
294 * the behaviour of <nowiki> in a link.
296 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
297 $this->mStripState
= new StripState( $this->mUniqPrefix
);
300 # Clear these on every parse, bug 4549
301 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
303 $this->mShowToc
= true;
304 $this->mForceTocPosition
= false;
305 $this->mIncludeSizes
= array(
309 $this->mPPNodeCount
= 0;
310 $this->mGeneratedPPNodeCount
= 0;
311 $this->mHighestExpansionDepth
= 0;
312 $this->mDefaultSort
= false;
313 $this->mHeadings
= array();
314 $this->mDoubleUnderscores
= array();
315 $this->mExpensiveFunctionCount
= 0;
318 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
319 $this->mPreprocessor
= null;
322 wfRunHooks( 'ParserClearState', array( &$this ) );
323 wfProfileOut( __METHOD__
);
327 * Convert wikitext to HTML
328 * Do not call this function recursively.
330 * @param $text String: text we want to parse
331 * @param $title Title object
332 * @param $options ParserOptions
333 * @param $linestart boolean
334 * @param $clearState boolean
335 * @param $revid Int: number to pass in {{REVISIONID}}
336 * @return ParserOutput a ParserOutput
338 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
340 * First pass--just handle <nowiki> sections, pass the rest off
341 * to internalParse() which does all the real work.
344 global $wgUseTidy, $wgAlwaysUseTidy;
345 $fname = __METHOD__
.'-' . wfGetCaller();
346 wfProfileIn( __METHOD__
);
347 wfProfileIn( $fname );
349 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
351 # Remove the strip marker tag prefix from the input, if present.
353 $text = str_replace( $this->mUniqPrefix
, '', $text );
356 $oldRevisionId = $this->mRevisionId
;
357 $oldRevisionObject = $this->mRevisionObject
;
358 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
359 $oldRevisionUser = $this->mRevisionUser
;
360 if ( $revid !== null ) {
361 $this->mRevisionId
= $revid;
362 $this->mRevisionObject
= null;
363 $this->mRevisionTimestamp
= null;
364 $this->mRevisionUser
= null;
367 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
369 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
370 $text = $this->internalParse( $text );
371 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 # Clean up special characters, only run once, next-to-last before doBlockLevels
377 # french spaces, last one Guillemet-left
378 # only if there is something before the space
379 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
380 # french spaces, Guillemet-right
381 '/(\\302\\253) /' => '\\1 ',
382 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
384 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
386 $text = $this->doBlockLevels( $text, $linestart );
388 $this->replaceLinkHolders( $text );
391 * The input doesn't get language converted if
393 * b) Content isn't converted
394 * c) It's a conversion table
395 * d) it is an interface message (which is in the user language)
397 if ( !( $options->getDisableContentConversion()
398 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
400 # Run convert unconditionally in 1.18-compatible mode
401 global $wgBug34832TransitionalRollback;
402 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
403 # The position of the convert() call should not be changed. it
404 # assumes that the links are all replaced and the only thing left
405 # is the <nowiki> mark.
406 $text = $this->getConverterLanguage()->convert( $text );
411 * A converted title will be provided in the output object if title and
412 * content conversion are enabled, the article text does not contain
413 * a conversion-suppressing double-underscore tag, and no
414 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
415 * automatic link conversion.
417 if ( !( $options->getDisableTitleConversion()
418 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
419 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
420 ||
$this->mOutput
->getDisplayTitle() !== false ) )
422 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
423 if ( $convruletitle ) {
424 $this->mOutput
->setTitleText( $convruletitle );
426 $titleText = $this->getConverterLanguage()->convertTitle( $title );
427 $this->mOutput
->setTitleText( $titleText );
431 $text = $this->mStripState
->unstripNoWiki( $text );
433 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
435 $text = $this->replaceTransparentTags( $text );
436 $text = $this->mStripState
->unstripGeneral( $text );
438 $text = Sanitizer
::normalizeCharReferences( $text );
440 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
441 $text = MWTidy
::tidy( $text );
443 # attempt to sanitize at least some nesting problems
444 # (bug #2702 and quite a few others)
446 # ''Something [http://www.cool.com cool''] -->
447 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
448 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
449 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
450 # fix up an anchor inside another anchor, only
451 # at least for a single single nested link (bug 3695)
452 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
453 '\\1\\2</a>\\3</a>\\1\\4</a>',
454 # fix div inside inline elements- doBlockLevels won't wrap a line which
455 # contains a div, so fix it up here; replace
456 # div with escaped text
457 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
458 '\\1\\3<div\\5>\\6</div>\\8\\9',
459 # remove empty italic or bold tag pairs, some
460 # introduced by rules above
461 '/<([bi])><\/\\1>/' => '',
464 $text = preg_replace(
465 array_keys( $tidyregs ),
466 array_values( $tidyregs ),
470 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
471 $this->limitationWarn( 'expensive-parserfunction',
472 $this->mExpensiveFunctionCount
,
473 $this->mOptions
->getExpensiveParserFunctionLimit()
477 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
479 # Information on include size limits, for the benefit of users who try to skirt them
480 if ( $this->mOptions
->getEnableLimitReport() ) {
481 $max = $this->mOptions
->getMaxIncludeSize();
482 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
484 "NewPP limit report\n" .
485 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
486 "Preprocessor generated node count: " .
487 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
488 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
489 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
490 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
492 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
493 $text .= "\n<!-- \n$limitReport-->\n";
495 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
496 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
497 $this->mTitle
->getPrefixedDBkey() );
500 $this->mOutput
->setText( $text );
502 $this->mRevisionId
= $oldRevisionId;
503 $this->mRevisionObject
= $oldRevisionObject;
504 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
505 $this->mRevisionUser
= $oldRevisionUser;
506 wfProfileOut( $fname );
507 wfProfileOut( __METHOD__
);
509 return $this->mOutput
;
513 * Recursive parser entry point that can be called from an extension tag
516 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
518 * @param $text String: text extension wants to have parsed
519 * @param $frame PPFrame: The frame to use for expanding any template variables
523 function recursiveTagParse( $text, $frame=false ) {
524 wfProfileIn( __METHOD__
);
525 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
526 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
527 $text = $this->internalParse( $text, false, $frame );
528 wfProfileOut( __METHOD__
);
533 * Expand templates and variables in the text, producing valid, static wikitext.
534 * Also removes comments.
535 * @return mixed|string
537 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
538 wfProfileIn( __METHOD__
);
539 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
540 if ( $revid !== null ) {
541 $this->mRevisionId
= $revid;
543 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
544 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
545 $text = $this->replaceVariables( $text );
546 $text = $this->mStripState
->unstripBoth( $text );
547 wfProfileOut( __METHOD__
);
552 * Recursive parser entry point that can be called from an extension tag
555 * @param $text String: text to be expanded
556 * @param $frame PPFrame: The frame to use for expanding any template variables
560 public function recursivePreprocess( $text, $frame = false ) {
561 wfProfileIn( __METHOD__
);
562 $text = $this->replaceVariables( $text, $frame );
563 $text = $this->mStripState
->unstripBoth( $text );
564 wfProfileOut( __METHOD__
);
569 * Process the wikitext for the "?preload=" feature. (bug 5210)
571 * "<noinclude>", "<includeonly>" etc. are parsed as for template
572 * transclusion, comments, templates, arguments, tags hooks and parser
573 * functions are untouched.
575 * @param $text String
576 * @param $title Title
577 * @param $options ParserOptions
580 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
581 # Parser (re)initialisation
582 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
584 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
585 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
586 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
587 $text = $this->mStripState
->unstripBoth( $text );
592 * Get a random string
596 static public function getRandomString() {
597 return wfRandomString( 16 );
601 * Set the current user.
602 * Should only be used when doing pre-save transform.
604 * @param $user Mixed: User object or null (to reset)
606 function setUser( $user ) {
607 $this->mUser
= $user;
611 * Accessor for mUniqPrefix.
615 public function uniqPrefix() {
616 if ( !isset( $this->mUniqPrefix
) ) {
617 # @todo FIXME: This is probably *horribly wrong*
618 # LanguageConverter seems to want $wgParser's uniqPrefix, however
619 # if this is called for a parser cache hit, the parser may not
620 # have ever been initialized in the first place.
621 # Not really sure what the heck is supposed to be going on here.
623 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
625 return $this->mUniqPrefix
;
629 * Set the context title
633 function setTitle( $t ) {
634 if ( !$t ||
$t instanceof FakeTitle
) {
635 $t = Title
::newFromText( 'NO TITLE' );
638 if ( strval( $t->getFragment() ) !== '' ) {
639 # Strip the fragment to avoid various odd effects
640 $this->mTitle
= clone $t;
641 $this->mTitle
->setFragment( '' );
648 * Accessor for the Title object
650 * @return Title object
652 function getTitle() {
653 return $this->mTitle
;
657 * Accessor/mutator for the Title object
659 * @param $x Title object or null to just get the current one
660 * @return Title object
662 function Title( $x = null ) {
663 return wfSetVar( $this->mTitle
, $x );
667 * Set the output type
669 * @param $ot Integer: new value
671 function setOutputType( $ot ) {
672 $this->mOutputType
= $ot;
675 'html' => $ot == self
::OT_HTML
,
676 'wiki' => $ot == self
::OT_WIKI
,
677 'pre' => $ot == self
::OT_PREPROCESS
,
678 'plain' => $ot == self
::OT_PLAIN
,
683 * Accessor/mutator for the output type
685 * @param $x int|null New value or null to just get the current one
688 function OutputType( $x = null ) {
689 return wfSetVar( $this->mOutputType
, $x );
693 * Get the ParserOutput object
695 * @return ParserOutput object
697 function getOutput() {
698 return $this->mOutput
;
702 * Get the ParserOptions object
704 * @return ParserOptions object
706 function getOptions() {
707 return $this->mOptions
;
711 * Accessor/mutator for the ParserOptions object
713 * @param $x ParserOptions New value or null to just get the current one
714 * @return ParserOptions Current ParserOptions object
716 function Options( $x = null ) {
717 return wfSetVar( $this->mOptions
, $x );
723 function nextLinkID() {
724 return $this->mLinkID++
;
730 function setLinkID( $id ) {
731 $this->mLinkID
= $id;
735 * Get a language object for use in parser functions such as {{FORMATNUM:}}
738 function getFunctionLang() {
739 return $this->getTargetLanguage();
743 * Get the target language for the content being parsed. This is usually the
744 * language that the content is in.
748 * @return Language|null
750 public function getTargetLanguage() {
751 $target = $this->mOptions
->getTargetLanguage();
753 if ( $target !== null ) {
755 } elseif( $this->mOptions
->getInterfaceMessage() ) {
756 return $this->mOptions
->getUserLangObj();
757 } elseif( is_null( $this->mTitle
) ) {
758 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
761 return $this->mTitle
->getPageLanguage();
765 * Get the language object for language conversion
767 function getConverterLanguage() {
768 global $wgBug34832TransitionalRollback, $wgContLang;
769 if ( $wgBug34832TransitionalRollback ) {
772 return $this->getTargetLanguage();
777 * Get a User object either from $this->mUser, if set, or from the
778 * ParserOptions object otherwise
780 * @return User object
783 if ( !is_null( $this->mUser
) ) {
786 return $this->mOptions
->getUser();
790 * Get a preprocessor object
792 * @return Preprocessor instance
794 function getPreprocessor() {
795 if ( !isset( $this->mPreprocessor
) ) {
796 $class = $this->mPreprocessorClass
;
797 $this->mPreprocessor
= new $class( $this );
799 return $this->mPreprocessor
;
803 * Replaces all occurrences of HTML-style comments and the given tags
804 * in the text with a random marker and returns the next text. The output
805 * parameter $matches will be an associative array filled with data in
809 * 'UNIQ-xxxxx' => array(
812 * array( 'param' => 'x' ),
813 * '<element param="x">tag content</element>' ) )
816 * @param $elements array list of element names. Comments are always extracted.
817 * @param $text string Source text string.
818 * @param $matches array Out parameter, Array: extracted tags
819 * @param $uniq_prefix string
820 * @return String: stripped text
822 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
827 $taglist = implode( '|', $elements );
828 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
830 while ( $text != '' ) {
831 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
833 if ( count( $p ) < 5 ) {
836 if ( count( $p ) > 5 ) {
850 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
851 $stripped .= $marker;
853 if ( $close === '/>' ) {
854 # Empty element tag, <tag />
859 if ( $element === '!--' ) {
862 $end = "/(<\\/$element\\s*>)/i";
864 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
866 if ( count( $q ) < 3 ) {
867 # No end tag -- let it run out to the end of the text.
876 $matches[$marker] = array( $element,
878 Sanitizer
::decodeTagAttributes( $attributes ),
879 "<$element$attributes$close$content$tail" );
885 * Get a list of strippable XML-like elements
889 function getStripList() {
890 return $this->mStripList
;
894 * Add an item to the strip state
895 * Returns the unique tag which must be inserted into the stripped text
896 * The tag will be replaced with the original text in unstrip()
898 * @param $text string
902 function insertStripItem( $text ) {
903 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
904 $this->mMarkerIndex++
;
905 $this->mStripState
->addGeneral( $rnd, $text );
910 * parse the wiki syntax used to render tables
915 function doTableStuff( $text ) {
916 wfProfileIn( __METHOD__
);
918 $lines = StringUtils
::explode( "\n", $text );
920 $td_history = array(); # Is currently a td tag open?
921 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
922 $tr_history = array(); # Is currently a tr tag open?
923 $tr_attributes = array(); # history of tr attributes
924 $has_opened_tr = array(); # Did this table open a <tr> element?
925 $indent_level = 0; # indent level of the table
927 foreach ( $lines as $outLine ) {
928 $line = trim( $outLine );
930 if ( $line === '' ) { # empty line, go to next line
931 $out .= $outLine."\n";
935 $first_character = $line[0];
938 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
939 # First check if we are starting a new table
940 $indent_level = strlen( $matches[1] );
942 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
943 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
945 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
946 array_push( $td_history , false );
947 array_push( $last_tag_history , '' );
948 array_push( $tr_history , false );
949 array_push( $tr_attributes , '' );
950 array_push( $has_opened_tr , false );
951 } elseif ( count( $td_history ) == 0 ) {
952 # Don't do any of the following
953 $out .= $outLine."\n";
955 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
956 # We are ending a table
957 $line = '</table>' . substr( $line , 2 );
958 $last_tag = array_pop( $last_tag_history );
960 if ( !array_pop( $has_opened_tr ) ) {
961 $line = "<tr><td></td></tr>{$line}";
964 if ( array_pop( $tr_history ) ) {
965 $line = "</tr>{$line}";
968 if ( array_pop( $td_history ) ) {
969 $line = "</{$last_tag}>{$line}";
971 array_pop( $tr_attributes );
972 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
973 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
974 # Now we have a table row
975 $line = preg_replace( '#^\|-+#', '', $line );
977 # Whats after the tag is now only attributes
978 $attributes = $this->mStripState
->unstripBoth( $line );
979 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
980 array_pop( $tr_attributes );
981 array_push( $tr_attributes, $attributes );
984 $last_tag = array_pop( $last_tag_history );
985 array_pop( $has_opened_tr );
986 array_push( $has_opened_tr , true );
988 if ( array_pop( $tr_history ) ) {
992 if ( array_pop( $td_history ) ) {
993 $line = "</{$last_tag}>{$line}";
997 array_push( $tr_history , false );
998 array_push( $td_history , false );
999 array_push( $last_tag_history , '' );
1000 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
1001 # This might be cell elements, td, th or captions
1002 if ( substr( $line , 0 , 2 ) === '|+' ) {
1003 $first_character = '+';
1004 $line = substr( $line , 1 );
1007 $line = substr( $line , 1 );
1009 if ( $first_character === '!' ) {
1010 $line = str_replace( '!!' , '||' , $line );
1013 # Split up multiple cells on the same line.
1014 # FIXME : This can result in improper nesting of tags processed
1015 # by earlier parser steps, but should avoid splitting up eg
1016 # attribute values containing literal "||".
1017 $cells = StringUtils
::explodeMarkup( '||' , $line );
1021 # Loop through each table cell
1022 foreach ( $cells as $cell ) {
1024 if ( $first_character !== '+' ) {
1025 $tr_after = array_pop( $tr_attributes );
1026 if ( !array_pop( $tr_history ) ) {
1027 $previous = "<tr{$tr_after}>\n";
1029 array_push( $tr_history , true );
1030 array_push( $tr_attributes , '' );
1031 array_pop( $has_opened_tr );
1032 array_push( $has_opened_tr , true );
1035 $last_tag = array_pop( $last_tag_history );
1037 if ( array_pop( $td_history ) ) {
1038 $previous = "</{$last_tag}>\n{$previous}";
1041 if ( $first_character === '|' ) {
1043 } elseif ( $first_character === '!' ) {
1045 } elseif ( $first_character === '+' ) {
1046 $last_tag = 'caption';
1051 array_push( $last_tag_history , $last_tag );
1053 # A cell could contain both parameters and data
1054 $cell_data = explode( '|' , $cell , 2 );
1056 # Bug 553: Note that a '|' inside an invalid link should not
1057 # be mistaken as delimiting cell parameters
1058 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1059 $cell = "{$previous}<{$last_tag}>{$cell}";
1060 } elseif ( count( $cell_data ) == 1 ) {
1061 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1063 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1064 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1065 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1069 array_push( $td_history , true );
1072 $out .= $outLine . "\n";
1075 # Closing open td, tr && table
1076 while ( count( $td_history ) > 0 ) {
1077 if ( array_pop( $td_history ) ) {
1080 if ( array_pop( $tr_history ) ) {
1083 if ( !array_pop( $has_opened_tr ) ) {
1084 $out .= "<tr><td></td></tr>\n" ;
1087 $out .= "</table>\n";
1090 # Remove trailing line-ending (b/c)
1091 if ( substr( $out, -1 ) === "\n" ) {
1092 $out = substr( $out, 0, -1 );
1095 # special case: don't return empty table
1096 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1100 wfProfileOut( __METHOD__
);
1106 * Helper function for parse() that transforms wiki markup into
1107 * HTML. Only called for $mOutputType == self::OT_HTML.
1111 * @param $text string
1112 * @param $isMain bool
1113 * @param $frame bool
1117 function internalParse( $text, $isMain = true, $frame = false ) {
1118 wfProfileIn( __METHOD__
);
1122 # Hook to suspend the parser in this state
1123 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1124 wfProfileOut( __METHOD__
);
1128 # if $frame is provided, then use $frame for replacing any variables
1130 # use frame depth to infer how include/noinclude tags should be handled
1131 # depth=0 means this is the top-level document; otherwise it's an included document
1132 if ( !$frame->depth
) {
1135 $flag = Parser
::PTD_FOR_INCLUSION
;
1137 $dom = $this->preprocessToDom( $text, $flag );
1138 $text = $frame->expand( $dom );
1140 # if $frame is not provided, then use old-style replaceVariables
1141 $text = $this->replaceVariables( $text );
1144 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1145 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1146 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1148 # Tables need to come after variable replacement for things to work
1149 # properly; putting them before other transformations should keep
1150 # exciting things like link expansions from showing up in surprising
1152 $text = $this->doTableStuff( $text );
1154 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1156 $text = $this->doDoubleUnderscore( $text );
1158 $text = $this->doHeadings( $text );
1159 if ( $this->mOptions
->getUseDynamicDates() ) {
1160 $df = DateFormatter
::getInstance();
1161 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1163 $text = $this->replaceInternalLinks( $text );
1164 $text = $this->doAllQuotes( $text );
1165 $text = $this->replaceExternalLinks( $text );
1167 # replaceInternalLinks may sometimes leave behind
1168 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1169 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1171 $text = $this->doMagicLinks( $text );
1172 $text = $this->formatHeadings( $text, $origText, $isMain );
1174 wfProfileOut( __METHOD__
);
1179 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1180 * magic external links.
1185 * @param $text string
1189 function doMagicLinks( $text ) {
1190 wfProfileIn( __METHOD__
);
1191 $prots = wfUrlProtocolsWithoutProtRel();
1192 $urlChar = self
::EXT_LINK_URL_CLASS
;
1193 $text = preg_replace_callback(
1195 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1196 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1197 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1198 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1199 ISBN\s+(\b # m[5]: ISBN, capture number
1200 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1201 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1202 [0-9Xx] # check digit
1204 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1205 wfProfileOut( __METHOD__
);
1210 * @throws MWException
1212 * @return HTML|string
1214 function magicLinkCallback( $m ) {
1215 if ( isset( $m[1] ) && $m[1] !== '' ) {
1218 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1221 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1222 # Free external link
1223 return $this->makeFreeExternalLink( $m[0] );
1224 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1226 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1229 $CssClass = 'mw-magiclink-rfc';
1231 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1233 $urlmsg = 'pubmedurl';
1234 $CssClass = 'mw-magiclink-pmid';
1237 throw new MWException( __METHOD__
.': unrecognised match type "' .
1238 substr( $m[0], 0, 20 ) . '"' );
1240 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1241 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1242 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1245 $num = strtr( $isbn, array(
1250 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1252 htmlspecialchars( $titleObj->getLocalUrl() ) .
1253 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1260 * Make a free external link, given a user-supplied URL
1262 * @param $url string
1264 * @return string HTML
1267 function makeFreeExternalLink( $url ) {
1268 wfProfileIn( __METHOD__
);
1272 # The characters '<' and '>' (which were escaped by
1273 # removeHTMLtags()) should not be included in
1274 # URLs, per RFC 2396.
1276 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1277 $trail = substr( $url, $m2[0][1] ) . $trail;
1278 $url = substr( $url, 0, $m2[0][1] );
1281 # Move trailing punctuation to $trail
1283 # If there is no left bracket, then consider right brackets fair game too
1284 if ( strpos( $url, '(' ) === false ) {
1288 $numSepChars = strspn( strrev( $url ), $sep );
1289 if ( $numSepChars ) {
1290 $trail = substr( $url, -$numSepChars ) . $trail;
1291 $url = substr( $url, 0, -$numSepChars );
1294 $url = Sanitizer
::cleanUrl( $url );
1296 # Is this an external image?
1297 $text = $this->maybeMakeExternalImage( $url );
1298 if ( $text === false ) {
1299 # Not an image, make a link
1300 $text = Linker
::makeExternalLink( $url,
1301 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1302 $this->getExternalLinkAttribs( $url ) );
1303 # Register it in the output object...
1304 # Replace unnecessary URL escape codes with their equivalent characters
1305 $pasteurized = self
::replaceUnusualEscapes( $url );
1306 $this->mOutput
->addExternalLink( $pasteurized );
1308 wfProfileOut( __METHOD__
);
1309 return $text . $trail;
1314 * Parse headers and return html
1318 * @param $text string
1322 function doHeadings( $text ) {
1323 wfProfileIn( __METHOD__
);
1324 for ( $i = 6; $i >= 1; --$i ) {
1325 $h = str_repeat( '=', $i );
1326 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1327 "<h$i>\\1</h$i>", $text );
1329 wfProfileOut( __METHOD__
);
1334 * Replace single quotes with HTML markup
1337 * @param $text string
1339 * @return string the altered text
1341 function doAllQuotes( $text ) {
1342 wfProfileIn( __METHOD__
);
1344 $lines = StringUtils
::explode( "\n", $text );
1345 foreach ( $lines as $line ) {
1346 $outtext .= $this->doQuotes( $line ) . "\n";
1348 $outtext = substr( $outtext, 0,-1 );
1349 wfProfileOut( __METHOD__
);
1354 * Helper function for doAllQuotes()
1356 * @param $text string
1360 public function doQuotes( $text ) {
1361 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1362 if ( count( $arr ) == 1 ) {
1365 # First, do some preliminary work. This may shift some apostrophes from
1366 # being mark-up to being text. It also counts the number of occurrences
1367 # of bold and italics mark-ups.
1370 for ( $i = 0; $i < count( $arr ); $i++
) {
1371 if ( ( $i %
2 ) == 1 ) {
1372 # If there are ever four apostrophes, assume the first is supposed to
1373 # be text, and the remaining three constitute mark-up for bold text.
1374 if ( strlen( $arr[$i] ) == 4 ) {
1377 } elseif ( strlen( $arr[$i] ) > 5 ) {
1378 # If there are more than 5 apostrophes in a row, assume they're all
1379 # text except for the last 5.
1380 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1383 # Count the number of occurrences of bold and italics mark-ups.
1384 # We are not counting sequences of five apostrophes.
1385 if ( strlen( $arr[$i] ) == 2 ) {
1387 } elseif ( strlen( $arr[$i] ) == 3 ) {
1389 } elseif ( strlen( $arr[$i] ) == 5 ) {
1396 # If there is an odd number of both bold and italics, it is likely
1397 # that one of the bold ones was meant to be an apostrophe followed
1398 # by italics. Which one we cannot know for certain, but it is more
1399 # likely to be one that has a single-letter word before it.
1400 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1402 $firstsingleletterword = -1;
1403 $firstmultiletterword = -1;
1405 foreach ( $arr as $r ) {
1406 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1407 $x1 = substr( $arr[$i-1], -1 );
1408 $x2 = substr( $arr[$i-1], -2, 1 );
1409 if ( $x1 === ' ' ) {
1410 if ( $firstspace == -1 ) {
1413 } elseif ( $x2 === ' ') {
1414 if ( $firstsingleletterword == -1 ) {
1415 $firstsingleletterword = $i;
1418 if ( $firstmultiletterword == -1 ) {
1419 $firstmultiletterword = $i;
1426 # If there is a single-letter word, use it!
1427 if ( $firstsingleletterword > -1 ) {
1428 $arr[$firstsingleletterword] = "''";
1429 $arr[$firstsingleletterword-1] .= "'";
1430 } elseif ( $firstmultiletterword > -1 ) {
1431 # If not, but there's a multi-letter word, use that one.
1432 $arr[$firstmultiletterword] = "''";
1433 $arr[$firstmultiletterword-1] .= "'";
1434 } elseif ( $firstspace > -1 ) {
1435 # ... otherwise use the first one that has neither.
1436 # (notice that it is possible for all three to be -1 if, for example,
1437 # there is only one pentuple-apostrophe in the line)
1438 $arr[$firstspace] = "''";
1439 $arr[$firstspace-1] .= "'";
1443 # Now let's actually convert our apostrophic mush to HTML!
1448 foreach ( $arr as $r ) {
1449 if ( ( $i %
2 ) == 0 ) {
1450 if ( $state === 'both' ) {
1456 if ( strlen( $r ) == 2 ) {
1457 if ( $state === 'i' ) {
1458 $output .= '</i>'; $state = '';
1459 } elseif ( $state === 'bi' ) {
1460 $output .= '</i>'; $state = 'b';
1461 } elseif ( $state === 'ib' ) {
1462 $output .= '</b></i><b>'; $state = 'b';
1463 } elseif ( $state === 'both' ) {
1464 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1465 } else { # $state can be 'b' or ''
1466 $output .= '<i>'; $state .= 'i';
1468 } elseif ( strlen( $r ) == 3 ) {
1469 if ( $state === 'b' ) {
1470 $output .= '</b>'; $state = '';
1471 } elseif ( $state === 'bi' ) {
1472 $output .= '</i></b><i>'; $state = 'i';
1473 } elseif ( $state === 'ib' ) {
1474 $output .= '</b>'; $state = 'i';
1475 } elseif ( $state === 'both' ) {
1476 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1477 } else { # $state can be 'i' or ''
1478 $output .= '<b>'; $state .= 'b';
1480 } elseif ( strlen( $r ) == 5 ) {
1481 if ( $state === 'b' ) {
1482 $output .= '</b><i>'; $state = 'i';
1483 } elseif ( $state === 'i' ) {
1484 $output .= '</i><b>'; $state = 'b';
1485 } elseif ( $state === 'bi' ) {
1486 $output .= '</i></b>'; $state = '';
1487 } elseif ( $state === 'ib' ) {
1488 $output .= '</b></i>'; $state = '';
1489 } elseif ( $state === 'both' ) {
1490 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1491 } else { # ($state == '')
1492 $buffer = ''; $state = 'both';
1498 # Now close all remaining tags. Notice that the order is important.
1499 if ( $state === 'b' ||
$state === 'ib' ) {
1502 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1505 if ( $state === 'bi' ) {
1508 # There might be lonely ''''', so make sure we have a buffer
1509 if ( $state === 'both' && $buffer ) {
1510 $output .= '<b><i>'.$buffer.'</i></b>';
1517 * Replace external links (REL)
1519 * Note: this is all very hackish and the order of execution matters a lot.
1520 * Make sure to run maintenance/parserTests.php if you change this code.
1524 * @param $text string
1528 function replaceExternalLinks( $text ) {
1529 wfProfileIn( __METHOD__
);
1531 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1532 if ( $bits === false ) {
1533 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1535 $s = array_shift( $bits );
1538 while ( $i<count( $bits ) ) {
1540 $protocol = $bits[$i++
];
1541 $text = $bits[$i++
];
1542 $trail = $bits[$i++
];
1544 # The characters '<' and '>' (which were escaped by
1545 # removeHTMLtags()) should not be included in
1546 # URLs, per RFC 2396.
1548 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1549 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1550 $url = substr( $url, 0, $m2[0][1] );
1553 # If the link text is an image URL, replace it with an <img> tag
1554 # This happened by accident in the original parser, but some people used it extensively
1555 $img = $this->maybeMakeExternalImage( $text );
1556 if ( $img !== false ) {
1562 # Set linktype for CSS - if URL==text, link is essentially free
1563 $linktype = ( $text === $url ) ?
'free' : 'text';
1565 # No link text, e.g. [http://domain.tld/some.link]
1566 if ( $text == '' ) {
1568 $langObj = $this->getTargetLanguage();
1569 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1570 $linktype = 'autonumber';
1572 # Have link text, e.g. [http://domain.tld/some.link text]s
1574 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1577 $text = $this->getConverterLanguage()->markNoConversion( $text );
1579 $url = Sanitizer
::cleanUrl( $url );
1581 # Use the encoded URL
1582 # This means that users can paste URLs directly into the text
1583 # Funny characters like ö aren't valid in URLs anyway
1584 # This was changed in August 2004
1585 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1586 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1588 # Register link in the output object.
1589 # Replace unnecessary URL escape codes with the referenced character
1590 # This prevents spammers from hiding links from the filters
1591 $pasteurized = self
::replaceUnusualEscapes( $url );
1592 $this->mOutput
->addExternalLink( $pasteurized );
1595 wfProfileOut( __METHOD__
);
1600 * Get an associative array of additional HTML attributes appropriate for a
1601 * particular external link. This currently may include rel => nofollow
1602 * (depending on configuration, namespace, and the URL's domain) and/or a
1603 * target attribute (depending on configuration).
1605 * @param $url String|bool optional URL, to extract the domain from for rel =>
1606 * nofollow if appropriate
1607 * @return Array associative array of HTML attributes
1609 function getExternalLinkAttribs( $url = false ) {
1611 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1612 $ns = $this->mTitle
->getNamespace();
1613 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1614 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1616 $attribs['rel'] = 'nofollow';
1618 if ( $this->mOptions
->getExternalLinkTarget() ) {
1619 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1625 * Replace unusual URL escape codes with their equivalent characters
1627 * @param $url String
1630 * @todo This can merge genuinely required bits in the path or query string,
1631 * breaking legit URLs. A proper fix would treat the various parts of
1632 * the URL differently; as a workaround, just use the output for
1633 * statistical records, not for actual linking/output.
1635 static function replaceUnusualEscapes( $url ) {
1636 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1637 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1641 * Callback function used in replaceUnusualEscapes().
1642 * Replaces unusual URL escape codes with their equivalent character
1644 * @param $matches array
1648 private static function replaceUnusualEscapesCallback( $matches ) {
1649 $char = urldecode( $matches[0] );
1650 $ord = ord( $char );
1651 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1652 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1653 # No, shouldn't be escaped
1656 # Yes, leave it escaped
1662 * make an image if it's allowed, either through the global
1663 * option, through the exception, or through the on-wiki whitelist
1666 * $param $url string
1670 function maybeMakeExternalImage( $url ) {
1671 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1672 $imagesexception = !empty( $imagesfrom );
1674 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1675 if ( $imagesexception && is_array( $imagesfrom ) ) {
1676 $imagematch = false;
1677 foreach ( $imagesfrom as $match ) {
1678 if ( strpos( $url, $match ) === 0 ) {
1683 } elseif ( $imagesexception ) {
1684 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1686 $imagematch = false;
1688 if ( $this->mOptions
->getAllowExternalImages()
1689 ||
( $imagesexception && $imagematch ) ) {
1690 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1692 $text = Linker
::makeExternalImage( $url );
1695 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1696 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1697 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1698 foreach ( $whitelist as $entry ) {
1699 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1700 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1703 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1704 # Image matches a whitelist entry
1705 $text = Linker
::makeExternalImage( $url );
1714 * Process [[ ]] wikilinks
1718 * @return String: processed text
1722 function replaceInternalLinks( $s ) {
1723 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1728 * Process [[ ]] wikilinks (RIL)
1729 * @return LinkHolderArray
1733 function replaceInternalLinks2( &$s ) {
1734 wfProfileIn( __METHOD__
);
1736 wfProfileIn( __METHOD__
.'-setup' );
1737 static $tc = FALSE, $e1, $e1_img;
1738 # the % is needed to support urlencoded titles as well
1740 $tc = Title
::legalChars() . '#%';
1741 # Match a link having the form [[namespace:link|alternate]]trail
1742 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1743 # Match cases where there is no "]]", which might still be images
1744 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1747 $holders = new LinkHolderArray( $this );
1749 # split the entire text string on occurrences of [[
1750 $a = StringUtils
::explode( '[[', ' ' . $s );
1751 # get the first element (all text up to first [[), and remove the space we added
1754 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1755 $s = substr( $s, 1 );
1757 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1759 if ( $useLinkPrefixExtension ) {
1760 # Match the end of a line for a word that's not followed by whitespace,
1761 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1762 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1765 if ( is_null( $this->mTitle
) ) {
1766 wfProfileOut( __METHOD__
.'-setup' );
1767 wfProfileOut( __METHOD__
);
1768 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1770 $nottalk = !$this->mTitle
->isTalkPage();
1772 if ( $useLinkPrefixExtension ) {
1774 if ( preg_match( $e2, $s, $m ) ) {
1775 $first_prefix = $m[2];
1777 $first_prefix = false;
1783 if ( $this->getConverterLanguage()->hasVariants() ) {
1784 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1785 $this->mTitle
->getPrefixedText() );
1787 $selflink = array( $this->mTitle
->getPrefixedText() );
1789 $useSubpages = $this->areSubpagesAllowed();
1790 wfProfileOut( __METHOD__
.'-setup' );
1792 # Loop for each link
1793 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1794 # Check for excessive memory usage
1795 if ( $holders->isBig() ) {
1797 # Do the existence check, replace the link holders and clear the array
1798 $holders->replace( $s );
1802 if ( $useLinkPrefixExtension ) {
1803 wfProfileIn( __METHOD__
.'-prefixhandling' );
1804 if ( preg_match( $e2, $s, $m ) ) {
1811 if ( $first_prefix ) {
1812 $prefix = $first_prefix;
1813 $first_prefix = false;
1815 wfProfileOut( __METHOD__
.'-prefixhandling' );
1818 $might_be_img = false;
1820 wfProfileIn( __METHOD__
."-e1" );
1821 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1823 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1824 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1825 # the real problem is with the $e1 regex
1828 # Still some problems for cases where the ] is meant to be outside punctuation,
1829 # and no image is in sight. See bug 2095.
1831 if ( $text !== '' &&
1832 substr( $m[3], 0, 1 ) === ']' &&
1833 strpos( $text, '[' ) !== false
1836 $text .= ']'; # so that replaceExternalLinks($text) works later
1837 $m[3] = substr( $m[3], 1 );
1839 # fix up urlencoded title texts
1840 if ( strpos( $m[1], '%' ) !== false ) {
1841 # Should anchors '#' also be rejected?
1842 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1845 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1846 $might_be_img = true;
1848 if ( strpos( $m[1], '%' ) !== false ) {
1849 $m[1] = rawurldecode( $m[1] );
1852 } else { # Invalid form; output directly
1853 $s .= $prefix . '[[' . $line ;
1854 wfProfileOut( __METHOD__
."-e1" );
1857 wfProfileOut( __METHOD__
."-e1" );
1858 wfProfileIn( __METHOD__
."-misc" );
1860 # Don't allow internal links to pages containing
1861 # PROTO: where PROTO is a valid URL protocol; these
1862 # should be external links.
1863 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1864 $s .= $prefix . '[[' . $line ;
1865 wfProfileOut( __METHOD__
."-misc" );
1869 # Make subpage if necessary
1870 if ( $useSubpages ) {
1871 $link = $this->maybeDoSubpageLink( $m[1], $text );
1876 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1878 # Strip off leading ':'
1879 $link = substr( $link, 1 );
1882 wfProfileOut( __METHOD__
."-misc" );
1883 wfProfileIn( __METHOD__
."-title" );
1884 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1885 if ( $nt === null ) {
1886 $s .= $prefix . '[[' . $line;
1887 wfProfileOut( __METHOD__
."-title" );
1891 $ns = $nt->getNamespace();
1892 $iw = $nt->getInterWiki();
1893 wfProfileOut( __METHOD__
."-title" );
1895 if ( $might_be_img ) { # if this is actually an invalid link
1896 wfProfileIn( __METHOD__
."-might_be_img" );
1897 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1900 # look at the next 'line' to see if we can close it there
1902 $next_line = $a->current();
1903 if ( $next_line === false ||
$next_line === null ) {
1906 $m = explode( ']]', $next_line, 3 );
1907 if ( count( $m ) == 3 ) {
1908 # the first ]] closes the inner link, the second the image
1910 $text .= "[[{$m[0]}]]{$m[1]}";
1913 } elseif ( count( $m ) == 2 ) {
1914 # if there's exactly one ]] that's fine, we'll keep looking
1915 $text .= "[[{$m[0]}]]{$m[1]}";
1917 # if $next_line is invalid too, we need look no further
1918 $text .= '[[' . $next_line;
1923 # we couldn't find the end of this imageLink, so output it raw
1924 # but don't ignore what might be perfectly normal links in the text we've examined
1925 $holders->merge( $this->replaceInternalLinks2( $text ) );
1926 $s .= "{$prefix}[[$link|$text";
1927 # note: no $trail, because without an end, there *is* no trail
1928 wfProfileOut( __METHOD__
."-might_be_img" );
1931 } else { # it's not an image, so output it raw
1932 $s .= "{$prefix}[[$link|$text";
1933 # note: no $trail, because without an end, there *is* no trail
1934 wfProfileOut( __METHOD__
."-might_be_img" );
1937 wfProfileOut( __METHOD__
."-might_be_img" );
1940 $wasblank = ( $text == '' );
1944 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1945 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1946 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1947 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1948 $text = $this->doQuotes( $text );
1951 # Link not escaped by : , create the various objects
1954 wfProfileIn( __METHOD__
."-interwiki" );
1955 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1956 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1957 $s = rtrim( $s . $prefix );
1958 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1959 wfProfileOut( __METHOD__
."-interwiki" );
1962 wfProfileOut( __METHOD__
."-interwiki" );
1964 if ( $ns == NS_FILE
) {
1965 wfProfileIn( __METHOD__
."-image" );
1966 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1968 # if no parameters were passed, $text
1969 # becomes something like "File:Foo.png",
1970 # which we don't want to pass on to the
1974 # recursively parse links inside the image caption
1975 # actually, this will parse them in any other parameters, too,
1976 # but it might be hard to fix that, and it doesn't matter ATM
1977 $text = $this->replaceExternalLinks( $text );
1978 $holders->merge( $this->replaceInternalLinks2( $text ) );
1980 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1981 $s .= $prefix . $this->armorLinks(
1982 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1984 $s .= $prefix . $trail;
1986 wfProfileOut( __METHOD__
."-image" );
1990 if ( $ns == NS_CATEGORY
) {
1991 wfProfileIn( __METHOD__
."-category" );
1992 $s = rtrim( $s . "\n" ); # bug 87
1995 $sortkey = $this->getDefaultSort();
1999 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2000 $sortkey = str_replace( "\n", '', $sortkey );
2001 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2002 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2005 * Strip the whitespace Category links produce, see bug 87
2006 * @todo We might want to use trim($tmp, "\n") here.
2008 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2010 wfProfileOut( __METHOD__
."-category" );
2015 # Self-link checking
2016 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2017 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2018 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2023 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2024 # @todo FIXME: Should do batch file existence checks, see comment below
2025 if ( $ns == NS_MEDIA
) {
2026 wfProfileIn( __METHOD__
."-media" );
2027 # Give extensions a chance to select the file revision for us
2030 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2031 array( $this, $nt, &$options, &$descQuery ) );
2032 # Fetch and register the file (file title may be different via hooks)
2033 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2034 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2035 $s .= $prefix . $this->armorLinks(
2036 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2037 wfProfileOut( __METHOD__
."-media" );
2041 wfProfileIn( __METHOD__
."-always_known" );
2042 # Some titles, such as valid special pages or files in foreign repos, should
2043 # be shown as bluelinks even though they're not included in the page table
2045 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2046 # batch file existence checks for NS_FILE and NS_MEDIA
2047 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2048 $this->mOutput
->addLink( $nt );
2049 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2051 # Links will be added to the output link list after checking
2052 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2054 wfProfileOut( __METHOD__
."-always_known" );
2056 wfProfileOut( __METHOD__
);
2061 * Render a forced-blue link inline; protect against double expansion of
2062 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2063 * Since this little disaster has to split off the trail text to avoid
2064 * breaking URLs in the following text without breaking trails on the
2065 * wiki links, it's been made into a horrible function.
2068 * @param $text String
2069 * @param $query Array or String
2070 * @param $trail String
2071 * @param $prefix String
2072 * @return String: HTML-wikitext mix oh yuck
2074 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2075 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2077 if ( is_string( $query ) ) {
2078 $query = wfCgiToArray( $query );
2080 if ( $text == '' ) {
2081 $text = htmlspecialchars( $nt->getPrefixedText() );
2084 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2086 return $this->armorLinks( $link ) . $trail;
2090 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2091 * going to go through further parsing steps before inline URL expansion.
2093 * Not needed quite as much as it used to be since free links are a bit
2094 * more sensible these days. But bracketed links are still an issue.
2096 * @param $text String: more-or-less HTML
2097 * @return String: less-or-more HTML with NOPARSE bits
2099 function armorLinks( $text ) {
2100 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2101 "{$this->mUniqPrefix}NOPARSE$1", $text );
2105 * Return true if subpage links should be expanded on this page.
2108 function areSubpagesAllowed() {
2109 # Some namespaces don't allow subpages
2110 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2114 * Handle link to subpage if necessary
2116 * @param $target String: the source of the link
2117 * @param &$text String: the link text, modified as necessary
2118 * @return string the full name of the link
2121 function maybeDoSubpageLink( $target, &$text ) {
2122 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2126 * Used by doBlockLevels()
2131 function closeParagraph() {
2133 if ( $this->mLastSection
!= '' ) {
2134 $result = '</' . $this->mLastSection
. ">\n";
2136 $this->mInPre
= false;
2137 $this->mLastSection
= '';
2142 * getCommon() returns the length of the longest common substring
2143 * of both arguments, starting at the beginning of both.
2146 * @param $st1 string
2147 * @param $st2 string
2151 function getCommon( $st1, $st2 ) {
2152 $fl = strlen( $st1 );
2153 $shorter = strlen( $st2 );
2154 if ( $fl < $shorter ) {
2158 for ( $i = 0; $i < $shorter; ++
$i ) {
2159 if ( $st1[$i] != $st2[$i] ) {
2167 * These next three functions open, continue, and close the list
2168 * element appropriate to the prefix character passed into them.
2171 * @param $char string
2175 function openList( $char ) {
2176 $result = $this->closeParagraph();
2178 if ( '*' === $char ) {
2179 $result .= '<ul><li>';
2180 } elseif ( '#' === $char ) {
2181 $result .= '<ol><li>';
2182 } elseif ( ':' === $char ) {
2183 $result .= '<dl><dd>';
2184 } elseif ( ';' === $char ) {
2185 $result .= '<dl><dt>';
2186 $this->mDTopen
= true;
2188 $result = '<!-- ERR 1 -->';
2196 * @param $char String
2201 function nextItem( $char ) {
2202 if ( '*' === $char ||
'#' === $char ) {
2204 } elseif ( ':' === $char ||
';' === $char ) {
2206 if ( $this->mDTopen
) {
2209 if ( ';' === $char ) {
2210 $this->mDTopen
= true;
2211 return $close . '<dt>';
2213 $this->mDTopen
= false;
2214 return $close . '<dd>';
2217 return '<!-- ERR 2 -->';
2222 * @param $char String
2227 function closeList( $char ) {
2228 if ( '*' === $char ) {
2229 $text = '</li></ul>';
2230 } elseif ( '#' === $char ) {
2231 $text = '</li></ol>';
2232 } elseif ( ':' === $char ) {
2233 if ( $this->mDTopen
) {
2234 $this->mDTopen
= false;
2235 $text = '</dt></dl>';
2237 $text = '</dd></dl>';
2240 return '<!-- ERR 3 -->';
2247 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2249 * @param $text String
2250 * @param $linestart Boolean: whether or not this is at the start of a line.
2252 * @return string the lists rendered as HTML
2254 function doBlockLevels( $text, $linestart ) {
2255 wfProfileIn( __METHOD__
);
2257 # Parsing through the text line by line. The main thing
2258 # happening here is handling of block-level elements p, pre,
2259 # and making lists from lines starting with * # : etc.
2261 $textLines = StringUtils
::explode( "\n", $text );
2263 $lastPrefix = $output = '';
2264 $this->mDTopen
= $inBlockElem = false;
2266 $paragraphStack = false;
2268 foreach ( $textLines as $oLine ) {
2270 if ( !$linestart ) {
2280 $lastPrefixLength = strlen( $lastPrefix );
2281 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2282 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2283 # If not in a <pre> element, scan for and figure out what prefixes are there.
2284 if ( !$this->mInPre
) {
2285 # Multiple prefixes may abut each other for nested lists.
2286 $prefixLength = strspn( $oLine, '*#:;' );
2287 $prefix = substr( $oLine, 0, $prefixLength );
2290 # ; and : are both from definition-lists, so they're equivalent
2291 # for the purposes of determining whether or not we need to open/close
2293 $prefix2 = str_replace( ';', ':', $prefix );
2294 $t = substr( $oLine, $prefixLength );
2295 $this->mInPre
= (bool)$preOpenMatch;
2297 # Don't interpret any other prefixes in preformatted text
2299 $prefix = $prefix2 = '';
2304 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2305 # Same as the last item, so no need to deal with nesting or opening stuff
2306 $output .= $this->nextItem( substr( $prefix, -1 ) );
2307 $paragraphStack = false;
2309 if ( substr( $prefix, -1 ) === ';') {
2310 # The one nasty exception: definition lists work like this:
2311 # ; title : definition text
2312 # So we check for : in the remainder text to split up the
2313 # title and definition, without b0rking links.
2315 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2317 $output .= $term . $this->nextItem( ':' );
2320 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2321 # We need to open or close prefixes, or both.
2323 # Either open or close a level...
2324 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2325 $paragraphStack = false;
2327 # Close all the prefixes which aren't shared.
2328 while ( $commonPrefixLength < $lastPrefixLength ) {
2329 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2330 --$lastPrefixLength;
2333 # Continue the current prefix if appropriate.
2334 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2335 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2338 # Open prefixes where appropriate.
2339 while ( $prefixLength > $commonPrefixLength ) {
2340 $char = substr( $prefix, $commonPrefixLength, 1 );
2341 $output .= $this->openList( $char );
2343 if ( ';' === $char ) {
2344 # @todo FIXME: This is dupe of code above
2345 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2347 $output .= $term . $this->nextItem( ':' );
2350 ++
$commonPrefixLength;
2352 $lastPrefix = $prefix2;
2355 # If we have no prefixes, go to paragraph mode.
2356 if ( 0 == $prefixLength ) {
2357 wfProfileIn( __METHOD__
."-paragraph" );
2358 # No prefix (not in list)--go to paragraph mode
2359 # XXX: use a stack for nestable elements like span, table and div
2360 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2361 $closematch = preg_match(
2362 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2363 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2364 if ( $openmatch or $closematch ) {
2365 $paragraphStack = false;
2366 # TODO bug 5718: paragraph closed
2367 $output .= $this->closeParagraph();
2368 if ( $preOpenMatch and !$preCloseMatch ) {
2369 $this->mInPre
= true;
2371 $inBlockElem = !$closematch;
2372 } elseif ( !$inBlockElem && !$this->mInPre
) {
2373 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2375 if ( $this->mLastSection
!== 'pre' ) {
2376 $paragraphStack = false;
2377 $output .= $this->closeParagraph().'<pre>';
2378 $this->mLastSection
= 'pre';
2380 $t = substr( $t, 1 );
2383 if ( trim( $t ) === '' ) {
2384 if ( $paragraphStack ) {
2385 $output .= $paragraphStack.'<br />';
2386 $paragraphStack = false;
2387 $this->mLastSection
= 'p';
2389 if ( $this->mLastSection
!== 'p' ) {
2390 $output .= $this->closeParagraph();
2391 $this->mLastSection
= '';
2392 $paragraphStack = '<p>';
2394 $paragraphStack = '</p><p>';
2398 if ( $paragraphStack ) {
2399 $output .= $paragraphStack;
2400 $paragraphStack = false;
2401 $this->mLastSection
= 'p';
2402 } elseif ( $this->mLastSection
!== 'p' ) {
2403 $output .= $this->closeParagraph().'<p>';
2404 $this->mLastSection
= 'p';
2409 wfProfileOut( __METHOD__
."-paragraph" );
2411 # somewhere above we forget to get out of pre block (bug 785)
2412 if ( $preCloseMatch && $this->mInPre
) {
2413 $this->mInPre
= false;
2415 if ( $paragraphStack === false ) {
2419 while ( $prefixLength ) {
2420 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2423 if ( $this->mLastSection
!= '' ) {
2424 $output .= '</' . $this->mLastSection
. '>';
2425 $this->mLastSection
= '';
2428 wfProfileOut( __METHOD__
);
2433 * Split up a string on ':', ignoring any occurrences inside tags
2434 * to prevent illegal overlapping.
2436 * @param $str String the string to split
2437 * @param &$before String set to everything before the ':'
2438 * @param &$after String set to everything after the ':'
2439 * @return String the position of the ':', or false if none found
2441 function findColonNoLinks( $str, &$before, &$after ) {
2442 wfProfileIn( __METHOD__
);
2444 $pos = strpos( $str, ':' );
2445 if ( $pos === false ) {
2447 wfProfileOut( __METHOD__
);
2451 $lt = strpos( $str, '<' );
2452 if ( $lt === false ||
$lt > $pos ) {
2453 # Easy; no tag nesting to worry about
2454 $before = substr( $str, 0, $pos );
2455 $after = substr( $str, $pos+
1 );
2456 wfProfileOut( __METHOD__
);
2460 # Ugly state machine to walk through avoiding tags.
2461 $state = self
::COLON_STATE_TEXT
;
2463 $len = strlen( $str );
2464 for( $i = 0; $i < $len; $i++
) {
2468 # (Using the number is a performance hack for common cases)
2469 case 0: # self::COLON_STATE_TEXT:
2472 # Could be either a <start> tag or an </end> tag
2473 $state = self
::COLON_STATE_TAGSTART
;
2476 if ( $stack == 0 ) {
2478 $before = substr( $str, 0, $i );
2479 $after = substr( $str, $i +
1 );
2480 wfProfileOut( __METHOD__
);
2483 # Embedded in a tag; don't break it.
2486 # Skip ahead looking for something interesting
2487 $colon = strpos( $str, ':', $i );
2488 if ( $colon === false ) {
2489 # Nothing else interesting
2490 wfProfileOut( __METHOD__
);
2493 $lt = strpos( $str, '<', $i );
2494 if ( $stack === 0 ) {
2495 if ( $lt === false ||
$colon < $lt ) {
2497 $before = substr( $str, 0, $colon );
2498 $after = substr( $str, $colon +
1 );
2499 wfProfileOut( __METHOD__
);
2503 if ( $lt === false ) {
2504 # Nothing else interesting to find; abort!
2505 # We're nested, but there's no close tags left. Abort!
2508 # Skip ahead to next tag start
2510 $state = self
::COLON_STATE_TAGSTART
;
2513 case 1: # self::COLON_STATE_TAG:
2518 $state = self
::COLON_STATE_TEXT
;
2521 # Slash may be followed by >?
2522 $state = self
::COLON_STATE_TAGSLASH
;
2528 case 2: # self::COLON_STATE_TAGSTART:
2531 $state = self
::COLON_STATE_CLOSETAG
;
2534 $state = self
::COLON_STATE_COMMENT
;
2537 # Illegal early close? This shouldn't happen D:
2538 $state = self
::COLON_STATE_TEXT
;
2541 $state = self
::COLON_STATE_TAG
;
2544 case 3: # self::COLON_STATE_CLOSETAG:
2549 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2550 wfProfileOut( __METHOD__
);
2553 $state = self
::COLON_STATE_TEXT
;
2556 case self
::COLON_STATE_TAGSLASH
:
2558 # Yes, a self-closed tag <blah/>
2559 $state = self
::COLON_STATE_TEXT
;
2561 # Probably we're jumping the gun, and this is an attribute
2562 $state = self
::COLON_STATE_TAG
;
2565 case 5: # self::COLON_STATE_COMMENT:
2567 $state = self
::COLON_STATE_COMMENTDASH
;
2570 case self
::COLON_STATE_COMMENTDASH
:
2572 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2574 $state = self
::COLON_STATE_COMMENT
;
2577 case self
::COLON_STATE_COMMENTDASHDASH
:
2579 $state = self
::COLON_STATE_TEXT
;
2581 $state = self
::COLON_STATE_COMMENT
;
2585 throw new MWException( "State machine error in " . __METHOD__
);
2589 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2590 wfProfileOut( __METHOD__
);
2593 wfProfileOut( __METHOD__
);
2598 * Return value of a magic variable (like PAGENAME)
2602 * @param $index integer
2603 * @param $frame PPFrame
2607 function getVariableValue( $index, $frame = false ) {
2608 global $wgContLang, $wgSitename, $wgServer;
2609 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2611 if ( is_null( $this->mTitle
) ) {
2612 // If no title set, bad things are going to happen
2613 // later. Title should always be set since this
2614 // should only be called in the middle of a parse
2615 // operation (but the unit-tests do funky stuff)
2616 throw new MWException( __METHOD__
. ' Should only be '
2617 . ' called while parsing (no title set)' );
2621 * Some of these require message or data lookups and can be
2622 * expensive to check many times.
2624 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2625 if ( isset( $this->mVarCache
[$index] ) ) {
2626 return $this->mVarCache
[$index];
2630 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2631 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2634 global $wgLocaltimezone;
2635 if ( isset( $wgLocaltimezone ) ) {
2636 $oldtz = date_default_timezone_get();
2637 date_default_timezone_set( $wgLocaltimezone );
2640 $localTimestamp = date( 'YmdHis', $ts );
2641 $localMonth = date( 'm', $ts );
2642 $localMonth1 = date( 'n', $ts );
2643 $localMonthName = date( 'n', $ts );
2644 $localDay = date( 'j', $ts );
2645 $localDay2 = date( 'd', $ts );
2646 $localDayOfWeek = date( 'w', $ts );
2647 $localWeek = date( 'W', $ts );
2648 $localYear = date( 'Y', $ts );
2649 $localHour = date( 'H', $ts );
2650 if ( isset( $wgLocaltimezone ) ) {
2651 date_default_timezone_set( $oldtz );
2654 $pageLang = $this->getFunctionLang();
2657 case 'currentmonth':
2658 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2660 case 'currentmonth1':
2661 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2663 case 'currentmonthname':
2664 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2666 case 'currentmonthnamegen':
2667 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2669 case 'currentmonthabbrev':
2670 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2673 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2676 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2679 $value = $pageLang->formatNum( $localMonth );
2682 $value = $pageLang->formatNum( $localMonth1 );
2684 case 'localmonthname':
2685 $value = $pageLang->getMonthName( $localMonthName );
2687 case 'localmonthnamegen':
2688 $value = $pageLang->getMonthNameGen( $localMonthName );
2690 case 'localmonthabbrev':
2691 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2694 $value = $pageLang->formatNum( $localDay );
2697 $value = $pageLang->formatNum( $localDay2 );
2700 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2703 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2705 case 'fullpagename':
2706 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2708 case 'fullpagenamee':
2709 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2712 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2714 case 'subpagenamee':
2715 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2717 case 'basepagename':
2718 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2720 case 'basepagenamee':
2721 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2723 case 'talkpagename':
2724 if ( $this->mTitle
->canTalk() ) {
2725 $talkPage = $this->mTitle
->getTalkPage();
2726 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2731 case 'talkpagenamee':
2732 if ( $this->mTitle
->canTalk() ) {
2733 $talkPage = $this->mTitle
->getTalkPage();
2734 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2739 case 'subjectpagename':
2740 $subjPage = $this->mTitle
->getSubjectPage();
2741 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2743 case 'subjectpagenamee':
2744 $subjPage = $this->mTitle
->getSubjectPage();
2745 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2747 case 'pageid': // requested in bug 23427
2748 $pageid = $this->getTitle()->getArticleId();
2749 if( $pageid == 0 ) {
2750 # 0 means the page doesn't exist in the database,
2751 # which means the user is previewing a new page.
2752 # The vary-revision flag must be set, because the magic word
2753 # will have a different value once the page is saved.
2754 $this->mOutput
->setFlag( 'vary-revision' );
2755 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2757 $value = $pageid ?
$pageid : null;
2760 # Let the edit saving system know we should parse the page
2761 # *after* a revision ID has been assigned.
2762 $this->mOutput
->setFlag( 'vary-revision' );
2763 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2764 $value = $this->mRevisionId
;
2767 # Let the edit saving system know we should parse the page
2768 # *after* a revision ID has been assigned. This is for null edits.
2769 $this->mOutput
->setFlag( 'vary-revision' );
2770 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2771 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2773 case 'revisionday2':
2774 # Let the edit saving system know we should parse the page
2775 # *after* a revision ID has been assigned. This is for null edits.
2776 $this->mOutput
->setFlag( 'vary-revision' );
2777 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2778 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2780 case 'revisionmonth':
2781 # Let the edit saving system know we should parse the page
2782 # *after* a revision ID has been assigned. This is for null edits.
2783 $this->mOutput
->setFlag( 'vary-revision' );
2784 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2785 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2787 case 'revisionmonth1':
2788 # Let the edit saving system know we should parse the page
2789 # *after* a revision ID has been assigned. This is for null edits.
2790 $this->mOutput
->setFlag( 'vary-revision' );
2791 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2792 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2794 case 'revisionyear':
2795 # Let the edit saving system know we should parse the page
2796 # *after* a revision ID has been assigned. This is for null edits.
2797 $this->mOutput
->setFlag( 'vary-revision' );
2798 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2799 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2801 case 'revisiontimestamp':
2802 # Let the edit saving system know we should parse the page
2803 # *after* a revision ID has been assigned. This is for null edits.
2804 $this->mOutput
->setFlag( 'vary-revision' );
2805 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2806 $value = $this->getRevisionTimestamp();
2808 case 'revisionuser':
2809 # Let the edit saving system know we should parse the page
2810 # *after* a revision ID has been assigned. This is for null edits.
2811 $this->mOutput
->setFlag( 'vary-revision' );
2812 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2813 $value = $this->getRevisionUser();
2816 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2819 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2821 case 'namespacenumber':
2822 $value = $this->mTitle
->getNamespace();
2825 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2828 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2830 case 'subjectspace':
2831 $value = $this->mTitle
->getSubjectNsText();
2833 case 'subjectspacee':
2834 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2836 case 'currentdayname':
2837 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2840 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2843 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2846 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2849 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2850 # int to remove the padding
2851 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2854 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2856 case 'localdayname':
2857 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2860 $value = $pageLang->formatNum( $localYear, true );
2863 $value = $pageLang->time( $localTimestamp, false, false );
2866 $value = $pageLang->formatNum( $localHour, true );
2869 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2870 # int to remove the padding
2871 $value = $pageLang->formatNum( (int)$localWeek );
2874 $value = $pageLang->formatNum( $localDayOfWeek );
2876 case 'numberofarticles':
2877 $value = $pageLang->formatNum( SiteStats
::articles() );
2879 case 'numberoffiles':
2880 $value = $pageLang->formatNum( SiteStats
::images() );
2882 case 'numberofusers':
2883 $value = $pageLang->formatNum( SiteStats
::users() );
2885 case 'numberofactiveusers':
2886 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2888 case 'numberofpages':
2889 $value = $pageLang->formatNum( SiteStats
::pages() );
2891 case 'numberofadmins':
2892 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2894 case 'numberofedits':
2895 $value = $pageLang->formatNum( SiteStats
::edits() );
2897 case 'numberofviews':
2898 global $wgDisableCounters;
2899 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2901 case 'currenttimestamp':
2902 $value = wfTimestamp( TS_MW
, $ts );
2904 case 'localtimestamp':
2905 $value = $localTimestamp;
2907 case 'currentversion':
2908 $value = SpecialVersion
::getVersion();
2911 return $wgArticlePath;
2917 $serverParts = wfParseUrl( $wgServer );
2918 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2920 return $wgScriptPath;
2922 return $wgStylePath;
2923 case 'directionmark':
2924 return $pageLang->getDirMark();
2925 case 'contentlanguage':
2926 global $wgLanguageCode;
2927 return $wgLanguageCode;
2930 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2938 $this->mVarCache
[$index] = $value;
2945 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2949 function initialiseVariables() {
2950 wfProfileIn( __METHOD__
);
2951 $variableIDs = MagicWord
::getVariableIDs();
2952 $substIDs = MagicWord
::getSubstIDs();
2954 $this->mVariables
= new MagicWordArray( $variableIDs );
2955 $this->mSubstWords
= new MagicWordArray( $substIDs );
2956 wfProfileOut( __METHOD__
);
2960 * Preprocess some wikitext and return the document tree.
2961 * This is the ghost of replace_variables().
2963 * @param $text String: The text to parse
2964 * @param $flags Integer: bitwise combination of:
2965 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2966 * included. Default is to assume a direct page view.
2968 * The generated DOM tree must depend only on the input text and the flags.
2969 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2971 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2972 * change in the DOM tree for a given text, must be passed through the section identifier
2973 * in the section edit link and thus back to extractSections().
2975 * The output of this function is currently only cached in process memory, but a persistent
2976 * cache may be implemented at a later date which takes further advantage of these strict
2977 * dependency requirements.
2983 function preprocessToDom( $text, $flags = 0 ) {
2984 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2989 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2995 public static function splitWhitespace( $s ) {
2996 $ltrimmed = ltrim( $s );
2997 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2998 $trimmed = rtrim( $ltrimmed );
2999 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3001 $w2 = substr( $ltrimmed, -$diff );
3005 return array( $w1, $trimmed, $w2 );
3009 * Replace magic variables, templates, and template arguments
3010 * with the appropriate text. Templates are substituted recursively,
3011 * taking care to avoid infinite loops.
3013 * Note that the substitution depends on value of $mOutputType:
3014 * self::OT_WIKI: only {{subst:}} templates
3015 * self::OT_PREPROCESS: templates but not extension tags
3016 * self::OT_HTML: all templates and extension tags
3018 * @param $text String the text to transform
3019 * @param $frame PPFrame Object describing the arguments passed to the template.
3020 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3021 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3022 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3027 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3028 # Is there any text? Also, Prevent too big inclusions!
3029 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3032 wfProfileIn( __METHOD__
);
3034 if ( $frame === false ) {
3035 $frame = $this->getPreprocessor()->newFrame();
3036 } elseif ( !( $frame instanceof PPFrame
) ) {
3037 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3038 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3041 $dom = $this->preprocessToDom( $text );
3042 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3043 $text = $frame->expand( $dom, $flags );
3045 wfProfileOut( __METHOD__
);
3050 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3052 * @param $args array
3056 static function createAssocArgs( $args ) {
3057 $assocArgs = array();
3059 foreach ( $args as $arg ) {
3060 $eqpos = strpos( $arg, '=' );
3061 if ( $eqpos === false ) {
3062 $assocArgs[$index++
] = $arg;
3064 $name = trim( substr( $arg, 0, $eqpos ) );
3065 $value = trim( substr( $arg, $eqpos+
1 ) );
3066 if ( $value === false ) {
3069 if ( $name !== false ) {
3070 $assocArgs[$name] = $value;
3079 * Warn the user when a parser limitation is reached
3080 * Will warn at most once the user per limitation type
3082 * @param $limitationType String: should be one of:
3083 * 'expensive-parserfunction' (corresponding messages:
3084 * 'expensive-parserfunction-warning',
3085 * 'expensive-parserfunction-category')
3086 * 'post-expand-template-argument' (corresponding messages:
3087 * 'post-expand-template-argument-warning',
3088 * 'post-expand-template-argument-category')
3089 * 'post-expand-template-inclusion' (corresponding messages:
3090 * 'post-expand-template-inclusion-warning',
3091 * 'post-expand-template-inclusion-category')
3092 * @param $current int|null Current value
3093 * @param $max int|null Maximum allowed, when an explicit limit has been
3094 * exceeded, provide the values (optional)
3096 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3097 # does no harm if $current and $max are present but are unnecessary for the message
3098 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3099 ->inContentLanguage()->escaped();
3100 $this->mOutput
->addWarning( $warning );
3101 $this->addTrackingCategory( "$limitationType-category" );
3105 * Return the text of a template, after recursively
3106 * replacing any variables or templates within the template.
3108 * @param $piece Array: the parts of the template
3109 * $piece['title']: the title, i.e. the part before the |
3110 * $piece['parts']: the parameter array
3111 * $piece['lineStart']: whether the brace was at the start of a line
3112 * @param $frame PPFrame The current frame, contains template arguments
3113 * @return String: the text of the template
3116 function braceSubstitution( $piece, $frame ) {
3118 wfProfileIn( __METHOD__
);
3119 wfProfileIn( __METHOD__
.'-setup' );
3122 $found = false; # $text has been filled
3123 $nowiki = false; # wiki markup in $text should be escaped
3124 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3125 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3126 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3127 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3129 # Title object, where $text came from
3132 # $part1 is the bit before the first |, and must contain only title characters.
3133 # Various prefixes will be stripped from it later.
3134 $titleWithSpaces = $frame->expand( $piece['title'] );
3135 $part1 = trim( $titleWithSpaces );
3138 # Original title text preserved for various purposes
3139 $originalTitle = $part1;
3141 # $args is a list of argument nodes, starting from index 0, not including $part1
3142 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3143 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3144 wfProfileOut( __METHOD__
.'-setup' );
3146 $titleProfileIn = null; // profile templates
3149 wfProfileIn( __METHOD__
.'-modifiers' );
3152 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3154 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3155 # Decide whether to expand template or keep wikitext as-is.
3156 if ( $this->ot
['wiki'] ) {
3157 if ( $substMatch === false ) {
3158 $literal = true; # literal when in PST with no prefix
3160 $literal = false; # expand when in PST with subst: or safesubst:
3163 if ( $substMatch == 'subst' ) {
3164 $literal = true; # literal when not in PST with plain subst:
3166 $literal = false; # expand when not in PST with safesubst: or no prefix
3170 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3177 if ( !$found && $args->getLength() == 0 ) {
3178 $id = $this->mVariables
->matchStartToEnd( $part1 );
3179 if ( $id !== false ) {
3180 $text = $this->getVariableValue( $id, $frame );
3181 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3182 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3188 # MSG, MSGNW and RAW
3191 $mwMsgnw = MagicWord
::get( 'msgnw' );
3192 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3195 # Remove obsolete MSG:
3196 $mwMsg = MagicWord
::get( 'msg' );
3197 $mwMsg->matchStartAndRemove( $part1 );
3201 $mwRaw = MagicWord
::get( 'raw' );
3202 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3203 $forceRawInterwiki = true;
3206 wfProfileOut( __METHOD__
.'-modifiers' );
3210 wfProfileIn( __METHOD__
. '-pfunc' );
3212 $colonPos = strpos( $part1, ':' );
3213 if ( $colonPos !== false ) {
3214 # Case sensitive functions
3215 $function = substr( $part1, 0, $colonPos );
3216 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3217 $function = $this->mFunctionSynonyms
[1][$function];
3219 # Case insensitive functions
3220 $function = $wgContLang->lc( $function );
3221 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3222 $function = $this->mFunctionSynonyms
[0][$function];
3228 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3229 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3230 $initialArgs = array( &$this );
3231 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3232 if ( $flags & SFH_OBJECT_ARGS
) {
3233 # Add a frame parameter, and pass the arguments as an array
3234 $allArgs = $initialArgs;
3235 $allArgs[] = $frame;
3236 for ( $i = 0; $i < $args->getLength(); $i++
) {
3237 $funcArgs[] = $args->item( $i );
3239 $allArgs[] = $funcArgs;
3241 # Convert arguments to plain text
3242 for ( $i = 0; $i < $args->getLength(); $i++
) {
3243 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3245 $allArgs = array_merge( $initialArgs, $funcArgs );
3248 # Workaround for PHP bug 35229 and similar
3249 if ( !is_callable( $callback ) ) {
3250 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3251 wfProfileOut( __METHOD__
. '-pfunc' );
3252 wfProfileOut( __METHOD__
);
3253 throw new MWException( "Tag hook for $function is not callable\n" );
3255 $result = call_user_func_array( $callback, $allArgs );
3258 $preprocessFlags = 0;
3260 if ( is_array( $result ) ) {
3261 if ( isset( $result[0] ) ) {
3263 unset( $result[0] );
3266 # Extract flags into the local scope
3267 # This allows callers to set flags such as nowiki, found, etc.
3273 $text = $this->preprocessToDom( $text, $preprocessFlags );
3276 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3279 wfProfileOut( __METHOD__
. '-pfunc' );
3282 # Finish mangling title and then check for loops.
3283 # Set $title to a Title object and $titleText to the PDBK
3286 # Split the title into page and subpage
3288 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3289 if ( $subpage !== '' ) {
3290 $ns = $this->mTitle
->getNamespace();
3292 $title = Title
::newFromText( $part1, $ns );
3294 $titleText = $title->getPrefixedText();
3295 # Check for language variants if the template is not found
3296 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3297 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3299 # Do recursion depth check
3300 $limit = $this->mOptions
->getMaxTemplateDepth();
3301 if ( $frame->depth
>= $limit ) {
3303 $text = '<span class="error">'
3304 . wfMessage( 'parser-template-recursion-depth-warning' )
3305 ->numParams( $limit )->inContentLanguage()->text()
3311 # Load from database
3312 if ( !$found && $title ) {
3313 if ( !Profiler
::instance()->isPersistent() ) {
3314 # Too many unique items can kill profiling DBs/collectors
3315 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3316 wfProfileIn( $titleProfileIn ); // template in
3318 wfProfileIn( __METHOD__
. '-loadtpl' );
3319 if ( !$title->isExternal() ) {
3320 if ( $title->isSpecialPage()
3321 && $this->mOptions
->getAllowSpecialInclusion()
3322 && $this->ot
['html'] )
3324 // Pass the template arguments as URL parameters.
3325 // "uselang" will have no effect since the Language object
3326 // is forced to the one defined in ParserOptions.
3327 $pageArgs = array();
3328 for ( $i = 0; $i < $args->getLength(); $i++
) {
3329 $bits = $args->item( $i )->splitArg();
3330 if ( strval( $bits['index'] ) === '' ) {
3331 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3332 $value = trim( $frame->expand( $bits['value'] ) );
3333 $pageArgs[$name] = $value;
3337 // Create a new context to execute the special page
3338 $context = new RequestContext
;
3339 $context->setTitle( $title );
3340 $context->setRequest( new FauxRequest( $pageArgs ) );
3341 $context->setUser( $this->getUser() );
3342 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3343 $ret = SpecialPageFactory
::capturePath( $title, $context );
3345 $text = $context->getOutput()->getHTML();
3346 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3349 $this->disableCache();
3351 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3352 $found = false; # access denied
3353 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3355 list( $text, $title ) = $this->getTemplateDom( $title );
3356 if ( $text !== false ) {
3362 # If the title is valid but undisplayable, make a link to it
3363 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3364 $text = "[[:$titleText]]";
3367 } elseif ( $title->isTrans() ) {
3368 # Interwiki transclusion
3369 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3370 $text = $this->interwikiTransclude( $title, 'render' );
3373 $text = $this->interwikiTransclude( $title, 'raw' );
3374 # Preprocess it like a template
3375 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3381 # Do infinite loop check
3382 # This has to be done after redirect resolution to avoid infinite loops via redirects
3383 if ( !$frame->loopCheck( $title ) ) {
3385 $text = '<span class="error">'
3386 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3388 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3390 wfProfileOut( __METHOD__
. '-loadtpl' );
3393 # If we haven't found text to substitute by now, we're done
3394 # Recover the source wikitext and return it
3396 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3397 if ( $titleProfileIn ) {
3398 wfProfileOut( $titleProfileIn ); // template out
3400 wfProfileOut( __METHOD__
);
3401 return array( 'object' => $text );
3404 # Expand DOM-style return values in a child frame
3405 if ( $isChildObj ) {
3406 # Clean up argument array
3407 $newFrame = $frame->newChild( $args, $title );
3410 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3411 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3412 # Expansion is eligible for the empty-frame cache
3413 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3414 $text = $this->mTplExpandCache
[$titleText];
3416 $text = $newFrame->expand( $text );
3417 $this->mTplExpandCache
[$titleText] = $text;
3420 # Uncached expansion
3421 $text = $newFrame->expand( $text );
3424 if ( $isLocalObj && $nowiki ) {
3425 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3426 $isLocalObj = false;
3429 if ( $titleProfileIn ) {
3430 wfProfileOut( $titleProfileIn ); // template out
3433 # Replace raw HTML by a placeholder
3435 $text = $this->insertStripItem( $text );
3436 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3437 # Escape nowiki-style return values
3438 $text = wfEscapeWikiText( $text );
3439 } elseif ( is_string( $text )
3440 && !$piece['lineStart']
3441 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3443 # Bug 529: if the template begins with a table or block-level
3444 # element, it should be treated as beginning a new line.
3445 # This behaviour is somewhat controversial.
3446 $text = "\n" . $text;
3449 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3450 # Error, oversize inclusion
3451 if ( $titleText !== false ) {
3452 # Make a working, properly escaped link if possible (bug 23588)
3453 $text = "[[:$titleText]]";
3455 # This will probably not be a working link, but at least it may
3456 # provide some hint of where the problem is
3457 preg_replace( '/^:/', '', $originalTitle );
3458 $text = "[[:$originalTitle]]";
3460 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3461 $this->limitationWarn( 'post-expand-template-inclusion' );
3464 if ( $isLocalObj ) {
3465 $ret = array( 'object' => $text );
3467 $ret = array( 'text' => $text );
3470 wfProfileOut( __METHOD__
);
3475 * Get the semi-parsed DOM representation of a template with a given title,
3476 * and its redirect destination title. Cached.
3478 * @param $title Title
3482 function getTemplateDom( $title ) {
3483 $cacheTitle = $title;
3484 $titleText = $title->getPrefixedDBkey();
3486 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3487 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3488 $title = Title
::makeTitle( $ns, $dbk );
3489 $titleText = $title->getPrefixedDBkey();
3491 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3492 return array( $this->mTplDomCache
[$titleText], $title );
3495 # Cache miss, go to the database
3496 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3498 if ( $text === false ) {
3499 $this->mTplDomCache
[$titleText] = false;
3500 return array( false, $title );
3503 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3504 $this->mTplDomCache
[ $titleText ] = $dom;
3506 if ( !$title->equals( $cacheTitle ) ) {
3507 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3508 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3511 return array( $dom, $title );
3515 * Fetch the unparsed text of a template and register a reference to it.
3516 * @param Title $title
3517 * @return Array ( string or false, Title )
3519 function fetchTemplateAndTitle( $title ) {
3520 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3521 $stuff = call_user_func( $templateCb, $title, $this );
3522 $text = $stuff['text'];
3523 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3524 if ( isset( $stuff['deps'] ) ) {
3525 foreach ( $stuff['deps'] as $dep ) {
3526 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3529 return array( $text, $finalTitle );
3533 * Fetch the unparsed text of a template and register a reference to it.
3534 * @param Title $title
3535 * @return mixed string or false
3537 function fetchTemplate( $title ) {
3538 $rv = $this->fetchTemplateAndTitle( $title );
3543 * Static function to get a template
3544 * Can be overridden via ParserOptions::setTemplateCallback().
3546 * @param $title Title
3547 * @param $parser Parser
3551 static function statelessFetchTemplate( $title, $parser = false ) {
3552 $text = $skip = false;
3553 $finalTitle = $title;
3556 # Loop to fetch the article, with up to 1 redirect
3557 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3558 # Give extensions a chance to select the revision instead
3559 $id = false; # Assume current
3560 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3561 array( $parser, $title, &$skip, &$id ) );
3567 'page_id' => $title->getArticleID(),
3574 ? Revision
::newFromId( $id )
3575 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3576 $rev_id = $rev ?
$rev->getId() : 0;
3577 # If there is no current revision, there is no page
3578 if ( $id === false && !$rev ) {
3579 $linkCache = LinkCache
::singleton();
3580 $linkCache->addBadLinkObj( $title );
3585 'page_id' => $title->getArticleID(),
3586 'rev_id' => $rev_id );
3587 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3588 # We fetched a rev from a different title; register it too...
3590 'title' => $rev->getTitle(),
3591 'page_id' => $rev->getPage(),
3592 'rev_id' => $rev_id );
3596 $text = $rev->getText();
3597 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3599 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3600 if ( !$message->exists() ) {
3604 $text = $message->plain();
3608 if ( $text === false ) {
3612 $finalTitle = $title;
3613 $title = Title
::newFromRedirect( $text );
3617 'finalTitle' => $finalTitle,
3622 * Fetch a file and its title and register a reference to it.
3623 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3624 * @param Title $title
3625 * @param Array $options Array of options to RepoGroup::findFile
3628 function fetchFile( $title, $options = array() ) {
3629 $res = $this->fetchFileAndTitle( $title, $options );
3634 * Fetch a file and its title and register a reference to it.
3635 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3636 * @param Title $title
3637 * @param Array $options Array of options to RepoGroup::findFile
3638 * @return Array ( File or false, Title of file )
3640 function fetchFileAndTitle( $title, $options = array() ) {
3641 if ( isset( $options['broken'] ) ) {
3642 $file = false; // broken thumbnail forced by hook
3643 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3644 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3645 } else { // get by (name,timestamp)
3646 $file = wfFindFile( $title, $options );
3648 $time = $file ?
$file->getTimestamp() : false;
3649 $sha1 = $file ?
$file->getSha1() : false;
3650 # Register the file as a dependency...
3651 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3652 if ( $file && !$title->equals( $file->getTitle() ) ) {
3653 # Update fetched file title
3654 $title = $file->getTitle();
3655 if ( is_null( $file->getRedirectedTitle() ) ) {
3656 # This file was not a redirect, but the title does not match.
3657 # Register under the new name because otherwise the link will
3659 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3662 return array( $file, $title );
3666 * Transclude an interwiki link.
3668 * @param $title Title
3673 function interwikiTransclude( $title, $action ) {
3674 global $wgEnableScaryTranscluding;
3676 if ( !$wgEnableScaryTranscluding ) {
3677 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3680 $url = $title->getFullUrl( "action=$action" );
3682 if ( strlen( $url ) > 255 ) {
3683 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3685 return $this->fetchScaryTemplateMaybeFromCache( $url );
3689 * @param $url string
3690 * @return Mixed|String
3692 function fetchScaryTemplateMaybeFromCache( $url ) {
3693 global $wgTranscludeCacheExpiry;
3694 $dbr = wfGetDB( DB_SLAVE
);
3695 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3696 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3697 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3699 return $obj->tc_contents
;
3702 $text = Http
::get( $url );
3704 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3707 $dbw = wfGetDB( DB_MASTER
);
3708 $dbw->replace( 'transcache', array('tc_url'), array(
3710 'tc_time' => $dbw->timestamp( time() ),
3711 'tc_contents' => $text)
3717 * Triple brace replacement -- used for template arguments
3720 * @param $piece array
3721 * @param $frame PPFrame
3725 function argSubstitution( $piece, $frame ) {
3726 wfProfileIn( __METHOD__
);
3729 $parts = $piece['parts'];
3730 $nameWithSpaces = $frame->expand( $piece['title'] );
3731 $argName = trim( $nameWithSpaces );
3733 $text = $frame->getArgument( $argName );
3734 if ( $text === false && $parts->getLength() > 0
3738 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3741 # No match in frame, use the supplied default
3742 $object = $parts->item( 0 )->getChildren();
3744 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3745 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3746 $this->limitationWarn( 'post-expand-template-argument' );
3749 if ( $text === false && $object === false ) {
3751 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3753 if ( $error !== false ) {
3756 if ( $object !== false ) {
3757 $ret = array( 'object' => $object );
3759 $ret = array( 'text' => $text );
3762 wfProfileOut( __METHOD__
);
3767 * Return the text to be used for a given extension tag.
3768 * This is the ghost of strip().
3770 * @param $params array Associative array of parameters:
3771 * name PPNode for the tag name
3772 * attr PPNode for unparsed text where tag attributes are thought to be
3773 * attributes Optional associative array of parsed attributes
3774 * inner Contents of extension element
3775 * noClose Original text did not have a close tag
3776 * @param $frame PPFrame
3780 function extensionSubstitution( $params, $frame ) {
3781 $name = $frame->expand( $params['name'] );
3782 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3783 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3784 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3786 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3787 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3788 if ( $isFunctionTag ) {
3789 $markerType = 'none';
3791 $markerType = 'general';
3793 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3794 $name = strtolower( $name );
3795 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3796 if ( isset( $params['attributes'] ) ) {
3797 $attributes = $attributes +
$params['attributes'];
3800 if ( isset( $this->mTagHooks
[$name] ) ) {
3801 # Workaround for PHP bug 35229 and similar
3802 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3803 throw new MWException( "Tag hook for $name is not callable\n" );
3805 $output = call_user_func_array( $this->mTagHooks
[$name],
3806 array( $content, $attributes, $this, $frame ) );
3807 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3808 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3809 if ( !is_callable( $callback ) ) {
3810 throw new MWException( "Tag hook for $name is not callable\n" );
3813 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3815 $output = '<span class="error">Invalid tag extension name: ' .
3816 htmlspecialchars( $name ) . '</span>';
3819 if ( is_array( $output ) ) {
3820 # Extract flags to local scope (to override $markerType)
3822 $output = $flags[0];
3827 if ( is_null( $attrText ) ) {
3830 if ( isset( $params['attributes'] ) ) {
3831 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3832 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3833 htmlspecialchars( $attrValue ) . '"';
3836 if ( $content === null ) {
3837 $output = "<$name$attrText/>";
3839 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3840 $output = "<$name$attrText>$content$close";
3844 if ( $markerType === 'none' ) {
3846 } elseif ( $markerType === 'nowiki' ) {
3847 $this->mStripState
->addNoWiki( $marker, $output );
3848 } elseif ( $markerType === 'general' ) {
3849 $this->mStripState
->addGeneral( $marker, $output );
3851 throw new MWException( __METHOD__
.': invalid marker type' );
3857 * Increment an include size counter
3859 * @param $type String: the type of expansion
3860 * @param $size Integer: the size of the text
3861 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3863 function incrementIncludeSize( $type, $size ) {
3864 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3867 $this->mIncludeSizes
[$type] +
= $size;
3873 * Increment the expensive function count
3875 * @return Boolean: false if the limit has been exceeded
3877 function incrementExpensiveFunctionCount() {
3878 $this->mExpensiveFunctionCount++
;
3879 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3883 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3884 * Fills $this->mDoubleUnderscores, returns the modified text
3886 * @param $text string
3890 function doDoubleUnderscore( $text ) {
3891 wfProfileIn( __METHOD__
);
3893 # The position of __TOC__ needs to be recorded
3894 $mw = MagicWord
::get( 'toc' );
3895 if ( $mw->match( $text ) ) {
3896 $this->mShowToc
= true;
3897 $this->mForceTocPosition
= true;
3899 # Set a placeholder. At the end we'll fill it in with the TOC.
3900 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3902 # Only keep the first one.
3903 $text = $mw->replace( '', $text );
3906 # Now match and remove the rest of them
3907 $mwa = MagicWord
::getDoubleUnderscoreArray();
3908 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3910 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3911 $this->mOutput
->mNoGallery
= true;
3913 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3914 $this->mShowToc
= false;
3916 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3917 $this->addTrackingCategory( 'hidden-category-category' );
3919 # (bug 8068) Allow control over whether robots index a page.
3921 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3922 # is not desirable, the last one on the page should win.
3923 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3924 $this->mOutput
->setIndexPolicy( 'noindex' );
3925 $this->addTrackingCategory( 'noindex-category' );
3927 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3928 $this->mOutput
->setIndexPolicy( 'index' );
3929 $this->addTrackingCategory( 'index-category' );
3932 # Cache all double underscores in the database
3933 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3934 $this->mOutput
->setProperty( $key, '' );
3937 wfProfileOut( __METHOD__
);
3942 * Add a tracking category, getting the title from a system message,
3943 * or print a debug message if the title is invalid.
3945 * @param $msg String: message key
3946 * @return Boolean: whether the addition was successful
3948 public function addTrackingCategory( $msg ) {
3949 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3950 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3953 // Important to parse with correct title (bug 31469)
3954 $cat = wfMessage( $msg )
3955 ->title( $this->getTitle() )
3956 ->inContentLanguage()
3959 # Allow tracking categories to be disabled by setting them to "-"
3960 if ( $cat === '-' ) {
3964 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3965 if ( $containerCategory ) {
3966 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3969 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3975 * This function accomplishes several tasks:
3976 * 1) Auto-number headings if that option is enabled
3977 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3978 * 3) Add a Table of contents on the top for users who have enabled the option
3979 * 4) Auto-anchor headings
3981 * It loops through all headlines, collects the necessary data, then splits up the
3982 * string and re-inserts the newly formatted headlines.
3984 * @param $text String
3985 * @param $origText String: original, untouched wikitext
3986 * @param $isMain Boolean
3987 * @return mixed|string
3990 function formatHeadings( $text, $origText, $isMain=true ) {
3991 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3993 # Inhibit editsection links if requested in the page
3994 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3995 $maybeShowEditLink = $showEditLink = false;
3997 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3998 $showEditLink = $this->mOptions
->getEditSection();
4000 if ( $showEditLink ) {
4001 $this->mOutput
->setEditSectionTokens( true );
4004 # Get all headlines for numbering them and adding funky stuff like [edit]
4005 # links - this is for later, but we need the number of headlines right now
4007 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4009 # if there are fewer than 4 headlines in the article, do not show TOC
4010 # unless it's been explicitly enabled.
4011 $enoughToc = $this->mShowToc
&&
4012 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4014 # Allow user to stipulate that a page should have a "new section"
4015 # link added via __NEWSECTIONLINK__
4016 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4017 $this->mOutput
->setNewSection( true );
4020 # Allow user to remove the "new section"
4021 # link via __NONEWSECTIONLINK__
4022 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4023 $this->mOutput
->hideNewSection( true );
4026 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4027 # override above conditions and always show TOC above first header
4028 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4029 $this->mShowToc
= true;
4037 # Ugh .. the TOC should have neat indentation levels which can be
4038 # passed to the skin functions. These are determined here
4042 $sublevelCount = array();
4043 $levelCount = array();
4048 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4049 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4050 $oldType = $this->mOutputType
;
4051 $this->setOutputType( self
::OT_WIKI
);
4052 $frame = $this->getPreprocessor()->newFrame();
4053 $root = $this->preprocessToDom( $origText );
4054 $node = $root->getFirstChild();
4059 foreach ( $matches[3] as $headline ) {
4060 $isTemplate = false;
4062 $sectionIndex = false;
4064 $markerMatches = array();
4065 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4066 $serial = $markerMatches[1];
4067 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4068 $isTemplate = ( $titleText != $baseTitleText );
4069 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4073 $prevlevel = $level;
4075 $level = $matches[1][$headlineCount];
4077 if ( $level > $prevlevel ) {
4078 # Increase TOC level
4080 $sublevelCount[$toclevel] = 0;
4081 if ( $toclevel<$wgMaxTocLevel ) {
4082 $prevtoclevel = $toclevel;
4083 $toc .= Linker
::tocIndent();
4086 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4087 # Decrease TOC level, find level to jump to
4089 for ( $i = $toclevel; $i > 0; $i-- ) {
4090 if ( $levelCount[$i] == $level ) {
4091 # Found last matching level
4094 } elseif ( $levelCount[$i] < $level ) {
4095 # Found first matching level below current level
4103 if ( $toclevel<$wgMaxTocLevel ) {
4104 if ( $prevtoclevel < $wgMaxTocLevel ) {
4105 # Unindent only if the previous toc level was shown :p
4106 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4107 $prevtoclevel = $toclevel;
4109 $toc .= Linker
::tocLineEnd();
4113 # No change in level, end TOC line
4114 if ( $toclevel<$wgMaxTocLevel ) {
4115 $toc .= Linker
::tocLineEnd();
4119 $levelCount[$toclevel] = $level;
4121 # count number of headlines for each level
4122 @$sublevelCount[$toclevel]++
;
4124 for( $i = 1; $i <= $toclevel; $i++
) {
4125 if ( !empty( $sublevelCount[$i] ) ) {
4129 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4134 # The safe header is a version of the header text safe to use for links
4136 # Remove link placeholders by the link text.
4137 # <!--LINK number-->
4139 # link text with suffix
4140 # Do this before unstrip since link text can contain strip markers
4141 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4143 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4144 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4146 # Strip out HTML (first regex removes any tag not allowed)
4148 # * <sup> and <sub> (bug 8393)
4151 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4153 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4154 # to allow setting directionality in toc items.
4155 $tocline = preg_replace(
4156 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4157 array( '', '<$1>' ),
4160 $tocline = trim( $tocline );
4162 # For the anchor, strip out HTML-y stuff period
4163 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4164 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4166 # Save headline for section edit hint before it's escaped
4167 $headlineHint = $safeHeadline;
4169 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4170 # For reverse compatibility, provide an id that's
4171 # HTML4-compatible, like we used to.
4173 # It may be worth noting, academically, that it's possible for
4174 # the legacy anchor to conflict with a non-legacy headline
4175 # anchor on the page. In this case likely the "correct" thing
4176 # would be to either drop the legacy anchors or make sure
4177 # they're numbered first. However, this would require people
4178 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4179 # manually, so let's not bother worrying about it.
4180 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4181 array( 'noninitial', 'legacy' ) );
4182 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4184 if ( $legacyHeadline == $safeHeadline ) {
4185 # No reason to have both (in fact, we can't)
4186 $legacyHeadline = false;
4189 $legacyHeadline = false;
4190 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4194 # HTML names must be case-insensitively unique (bug 10721).
4195 # This does not apply to Unicode characters per
4196 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4197 # @todo FIXME: We may be changing them depending on the current locale.
4198 $arrayKey = strtolower( $safeHeadline );
4199 if ( $legacyHeadline === false ) {
4200 $legacyArrayKey = false;
4202 $legacyArrayKey = strtolower( $legacyHeadline );
4205 # count how many in assoc. array so we can track dupes in anchors
4206 if ( isset( $refers[$arrayKey] ) ) {
4207 $refers[$arrayKey]++
;
4209 $refers[$arrayKey] = 1;
4211 if ( isset( $refers[$legacyArrayKey] ) ) {
4212 $refers[$legacyArrayKey]++
;
4214 $refers[$legacyArrayKey] = 1;
4217 # Don't number the heading if it is the only one (looks silly)
4218 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4219 # the two are different if the line contains a link
4220 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4223 # Create the anchor for linking from the TOC to the section
4224 $anchor = $safeHeadline;
4225 $legacyAnchor = $legacyHeadline;
4226 if ( $refers[$arrayKey] > 1 ) {
4227 $anchor .= '_' . $refers[$arrayKey];
4229 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4230 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4232 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4233 $toc .= Linker
::tocLine( $anchor, $tocline,
4234 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4237 # Add the section to the section tree
4238 # Find the DOM node for this header
4239 while ( $node && !$isTemplate ) {
4240 if ( $node->getName() === 'h' ) {
4241 $bits = $node->splitHeading();
4242 if ( $bits['i'] == $sectionIndex ) {
4246 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4247 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4248 $node = $node->getNextSibling();
4251 'toclevel' => $toclevel,
4254 'number' => $numbering,
4255 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4256 'fromtitle' => $titleText,
4257 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4258 'anchor' => $anchor,
4261 # give headline the correct <h#> tag
4262 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4263 // Output edit section links as markers with styles that can be customized by skins
4264 if ( $isTemplate ) {
4265 # Put a T flag in the section identifier, to indicate to extractSections()
4266 # that sections inside <includeonly> should be counted.
4267 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4269 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4271 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4272 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4273 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4274 // so we don't have to worry about a user trying to input one of these markers directly.
4275 // We use a page and section attribute to stop the language converter from converting these important bits
4276 // of data, but put the headline hint inside a content block because the language converter is supposed to
4277 // be able to convert that piece of data.
4278 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4279 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4280 if ( isset($editlinkArgs[2]) ) {
4281 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4288 $head[$headlineCount] = Linker
::makeHeadline( $level,
4289 $matches['attrib'][$headlineCount], $anchor, $headline,
4290 $editlink, $legacyAnchor );
4295 $this->setOutputType( $oldType );
4297 # Never ever show TOC if no headers
4298 if ( $numVisible < 1 ) {
4303 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4304 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4306 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4307 $this->mOutput
->setTOCHTML( $toc );
4311 $this->mOutput
->setSections( $tocraw );
4314 # split up and insert constructed headlines
4315 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4318 // build an array of document sections
4319 $sections = array();
4320 foreach ( $blocks as $block ) {
4321 // $head is zero-based, sections aren't.
4322 if ( empty( $head[$i - 1] ) ) {
4323 $sections[$i] = $block;
4325 $sections[$i] = $head[$i - 1] . $block;
4329 * Send a hook, one per section.
4330 * The idea here is to be able to make section-level DIVs, but to do so in a
4331 * lower-impact, more correct way than r50769
4334 * $section : the section number
4335 * &$sectionContent : ref to the content of the section
4336 * $showEditLinks : boolean describing whether this section has an edit link
4338 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4343 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4344 // append the TOC at the beginning
4345 // Top anchor now in skin
4346 $sections[0] = $sections[0] . $toc . "\n";
4349 $full .= join( '', $sections );
4351 if ( $this->mForceTocPosition
) {
4352 return str_replace( '<!--MWTOC-->', $toc, $full );
4359 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4360 * conversion, substitting signatures, {{subst:}} templates, etc.
4362 * @param $text String: the text to transform
4363 * @param $title Title: the Title object for the current article
4364 * @param $user User: the User object describing the current user
4365 * @param $options ParserOptions: parsing options
4366 * @param $clearState Boolean: whether to clear the parser state first
4367 * @return String: the altered wiki markup
4369 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4370 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4371 $this->setUser( $user );
4376 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4377 if( $options->getPreSaveTransform() ) {
4378 $text = $this->pstPass2( $text, $user );
4380 $text = $this->mStripState
->unstripBoth( $text );
4382 $this->setUser( null ); #Reset
4388 * Pre-save transform helper function
4391 * @param $text string
4396 function pstPass2( $text, $user ) {
4397 global $wgContLang, $wgLocaltimezone;
4399 # Note: This is the timestamp saved as hardcoded wikitext to
4400 # the database, we use $wgContLang here in order to give
4401 # everyone the same signature and use the default one rather
4402 # than the one selected in each user's preferences.
4403 # (see also bug 12815)
4404 $ts = $this->mOptions
->getTimestamp();
4405 if ( isset( $wgLocaltimezone ) ) {
4406 $tz = $wgLocaltimezone;
4408 $tz = date_default_timezone_get();
4411 $unixts = wfTimestamp( TS_UNIX
, $ts );
4412 $oldtz = date_default_timezone_get();
4413 date_default_timezone_set( $tz );
4414 $ts = date( 'YmdHis', $unixts );
4415 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4417 # Allow translation of timezones through wiki. date() can return
4418 # whatever crap the system uses, localised or not, so we cannot
4419 # ship premade translations.
4420 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4421 $msg = wfMessage( $key )->inContentLanguage();
4422 if ( $msg->exists() ) {
4423 $tzMsg = $msg->text();
4426 date_default_timezone_set( $oldtz );
4428 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4430 # Variable replacement
4431 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4432 $text = $this->replaceVariables( $text );
4434 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4435 # which may corrupt this parser instance via its wfMessage()->text() call-
4438 $sigText = $this->getUserSig( $user );
4439 $text = strtr( $text, array(
4441 '~~~~' => "$sigText $d",
4445 # Context links: [[|name]] and [[name (context)|]]
4446 $tc = '[' . Title
::legalChars() . ']';
4447 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4449 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4450 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4451 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4452 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4454 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4455 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4456 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4457 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4459 $t = $this->mTitle
->getText();
4461 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4462 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4463 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4464 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4466 # if there's no context, don't bother duplicating the title
4467 $text = preg_replace( $p2, '[[\\1]]', $text );
4470 # Trim trailing whitespace
4471 $text = rtrim( $text );
4477 * Fetch the user's signature text, if any, and normalize to
4478 * validated, ready-to-insert wikitext.
4479 * If you have pre-fetched the nickname or the fancySig option, you can
4480 * specify them here to save a database query.
4481 * Do not reuse this parser instance after calling getUserSig(),
4482 * as it may have changed if it's the $wgParser.
4485 * @param $nickname String|bool nickname to use or false to use user's default nickname
4486 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4487 * or null to use default value
4490 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4491 global $wgMaxSigChars;
4493 $username = $user->getName();
4495 # If not given, retrieve from the user object.
4496 if ( $nickname === false )
4497 $nickname = $user->getOption( 'nickname' );
4499 if ( is_null( $fancySig ) ) {
4500 $fancySig = $user->getBoolOption( 'fancysig' );
4503 $nickname = $nickname == null ?
$username : $nickname;
4505 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4506 $nickname = $username;
4507 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4508 } elseif ( $fancySig !== false ) {
4509 # Sig. might contain markup; validate this
4510 if ( $this->validateSig( $nickname ) !== false ) {
4511 # Validated; clean up (if needed) and return it
4512 return $this->cleanSig( $nickname, true );
4514 # Failed to validate; fall back to the default
4515 $nickname = $username;
4516 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4520 # Make sure nickname doesnt get a sig in a sig
4521 $nickname = self
::cleanSigInSig( $nickname );
4523 # If we're still here, make it a link to the user page
4524 $userText = wfEscapeWikiText( $username );
4525 $nickText = wfEscapeWikiText( $nickname );
4526 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4528 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4532 * Check that the user's signature contains no bad XML
4534 * @param $text String
4535 * @return mixed An expanded string, or false if invalid.
4537 function validateSig( $text ) {
4538 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4542 * Clean up signature text
4544 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4545 * 2) Substitute all transclusions
4547 * @param $text String
4548 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4549 * @return String: signature text
4551 public function cleanSig( $text, $parsing = false ) {
4554 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4557 # Option to disable this feature
4558 if ( !$this->mOptions
->getCleanSignatures() ) {
4562 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4563 # => Move this logic to braceSubstitution()
4564 $substWord = MagicWord
::get( 'subst' );
4565 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4566 $substText = '{{' . $substWord->getSynonym( 0 );
4568 $text = preg_replace( $substRegex, $substText, $text );
4569 $text = self
::cleanSigInSig( $text );
4570 $dom = $this->preprocessToDom( $text );
4571 $frame = $this->getPreprocessor()->newFrame();
4572 $text = $frame->expand( $dom );
4575 $text = $this->mStripState
->unstripBoth( $text );
4582 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4584 * @param $text String
4585 * @return String: signature text with /~{3,5}/ removed
4587 public static function cleanSigInSig( $text ) {
4588 $text = preg_replace( '/~{3,5}/', '', $text );
4593 * Set up some variables which are usually set up in parse()
4594 * so that an external function can call some class members with confidence
4596 * @param $title Title|null
4597 * @param $options ParserOptions
4598 * @param $outputType
4599 * @param $clearState bool
4601 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4602 $this->startParse( $title, $options, $outputType, $clearState );
4606 * @param $title Title|null
4607 * @param $options ParserOptions
4608 * @param $outputType
4609 * @param $clearState bool
4611 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4612 $this->setTitle( $title );
4613 $this->mOptions
= $options;
4614 $this->setOutputType( $outputType );
4615 if ( $clearState ) {
4616 $this->clearState();
4621 * Wrapper for preprocess()
4623 * @param $text String: the text to preprocess
4624 * @param $options ParserOptions: options
4625 * @param $title Title object or null to use $wgTitle
4628 public function transformMsg( $text, $options, $title = null ) {
4629 static $executing = false;
4631 # Guard against infinite recursion
4637 wfProfileIn( __METHOD__
);
4643 # It's not uncommon having a null $wgTitle in scripts. See r80898
4644 # Create a ghost title in such case
4645 $title = Title
::newFromText( 'Dwimmerlaik' );
4647 $text = $this->preprocess( $text, $title, $options );
4650 wfProfileOut( __METHOD__
);
4655 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4656 * The callback should have the following form:
4657 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4659 * Transform and return $text. Use $parser for any required context, e.g. use
4660 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4662 * Hooks may return extended information by returning an array, of which the
4663 * first numbered element (index 0) must be the return string, and all other
4664 * entries are extracted into local variables within an internal function
4665 * in the Parser class.
4667 * This interface (introduced r61913) appears to be undocumented, but
4668 * 'markerName' is used by some core tag hooks to override which strip
4669 * array their results are placed in. **Use great caution if attempting
4670 * this interface, as it is not documented and injudicious use could smash
4671 * private variables.**
4673 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4674 * @param $callback Mixed: the callback function (and object) to use for the tag
4675 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4677 public function setHook( $tag, $callback ) {
4678 $tag = strtolower( $tag );
4679 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4680 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4682 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4683 $this->mTagHooks
[$tag] = $callback;
4684 if ( !in_array( $tag, $this->mStripList
) ) {
4685 $this->mStripList
[] = $tag;
4692 * As setHook(), but letting the contents be parsed.
4694 * Transparent tag hooks are like regular XML-style tag hooks, except they
4695 * operate late in the transformation sequence, on HTML instead of wikitext.
4697 * This is probably obsoleted by things dealing with parser frames?
4698 * The only extension currently using it is geoserver.
4701 * @todo better document or deprecate this
4703 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4704 * @param $callback Mixed: the callback function (and object) to use for the tag
4705 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4707 function setTransparentTagHook( $tag, $callback ) {
4708 $tag = strtolower( $tag );
4709 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4710 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4712 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4713 $this->mTransparentTagHooks
[$tag] = $callback;
4719 * Remove all tag hooks
4721 function clearTagHooks() {
4722 $this->mTagHooks
= array();
4723 $this->mFunctionTagHooks
= array();
4724 $this->mStripList
= $this->mDefaultStripList
;
4728 * Create a function, e.g. {{sum:1|2|3}}
4729 * The callback function should have the form:
4730 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4732 * Or with SFH_OBJECT_ARGS:
4733 * function myParserFunction( $parser, $frame, $args ) { ... }
4735 * The callback may either return the text result of the function, or an array with the text
4736 * in element 0, and a number of flags in the other elements. The names of the flags are
4737 * specified in the keys. Valid flags are:
4738 * found The text returned is valid, stop processing the template. This
4740 * nowiki Wiki markup in the return value should be escaped
4741 * isHTML The returned text is HTML, armour it against wikitext transformation
4743 * @param $id String: The magic word ID
4744 * @param $callback Mixed: the callback function (and object) to use
4745 * @param $flags Integer: a combination of the following flags:
4746 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4748 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4749 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4750 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4751 * the arguments, and to control the way they are expanded.
4753 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4754 * arguments, for instance:
4755 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4757 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4758 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4759 * working if/when this is changed.
4761 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4764 * Please read the documentation in includes/parser/Preprocessor.php for more information
4765 * about the methods available in PPFrame and PPNode.
4767 * @return string|callback The old callback function for this name, if any
4769 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4772 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4773 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4775 # Add to function cache
4776 $mw = MagicWord
::get( $id );
4778 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4780 $synonyms = $mw->getSynonyms();
4781 $sensitive = intval( $mw->isCaseSensitive() );
4783 foreach ( $synonyms as $syn ) {
4785 if ( !$sensitive ) {
4786 $syn = $wgContLang->lc( $syn );
4789 if ( !( $flags & SFH_NO_HASH
) ) {
4792 # Remove trailing colon
4793 if ( substr( $syn, -1, 1 ) === ':' ) {
4794 $syn = substr( $syn, 0, -1 );
4796 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4802 * Get all registered function hook identifiers
4806 function getFunctionHooks() {
4807 return array_keys( $this->mFunctionHooks
);
4811 * Create a tag function, e.g. "<test>some stuff</test>".
4812 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4813 * Unlike parser functions, their content is not preprocessed.
4816 function setFunctionTagHook( $tag, $callback, $flags ) {
4817 $tag = strtolower( $tag );
4818 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4819 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4820 $this->mFunctionTagHooks
[$tag] : null;
4821 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4823 if ( !in_array( $tag, $this->mStripList
) ) {
4824 $this->mStripList
[] = $tag;
4831 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4832 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4833 * Placeholders created in Skin::makeLinkObj()
4835 * @param $text string
4836 * @param $options int
4838 * @return array of link CSS classes, indexed by PDBK.
4840 function replaceLinkHolders( &$text, $options = 0 ) {
4841 return $this->mLinkHolders
->replace( $text );
4845 * Replace "<!--LINK-->" link placeholders with plain text of links
4846 * (not HTML-formatted).
4848 * @param $text String
4851 function replaceLinkHoldersText( $text ) {
4852 return $this->mLinkHolders
->replaceText( $text );
4856 * Renders an image gallery from a text with one line per image.
4857 * text labels may be given by using |-style alternative text. E.g.
4858 * Image:one.jpg|The number "1"
4859 * Image:tree.jpg|A tree
4860 * given as text will return the HTML of a gallery with two images,
4861 * labeled 'The number "1"' and
4864 * @param string $text
4865 * @param array $params
4866 * @return string HTML
4868 function renderImageGallery( $text, $params ) {
4869 $ig = new ImageGallery();
4870 $ig->setContextTitle( $this->mTitle
);
4871 $ig->setShowBytes( false );
4872 $ig->setShowFilename( false );
4873 $ig->setParser( $this );
4874 $ig->setHideBadImages();
4875 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4877 if ( isset( $params['showfilename'] ) ) {
4878 $ig->setShowFilename( true );
4880 $ig->setShowFilename( false );
4882 if ( isset( $params['caption'] ) ) {
4883 $caption = $params['caption'];
4884 $caption = htmlspecialchars( $caption );
4885 $caption = $this->replaceInternalLinks( $caption );
4886 $ig->setCaptionHtml( $caption );
4888 if ( isset( $params['perrow'] ) ) {
4889 $ig->setPerRow( $params['perrow'] );
4891 if ( isset( $params['widths'] ) ) {
4892 $ig->setWidths( $params['widths'] );
4894 if ( isset( $params['heights'] ) ) {
4895 $ig->setHeights( $params['heights'] );
4898 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4900 $lines = StringUtils
::explode( "\n", $text );
4901 foreach ( $lines as $line ) {
4902 # match lines like these:
4903 # Image:someimage.jpg|This is some image
4905 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4907 if ( count( $matches ) == 0 ) {
4911 if ( strpos( $matches[0], '%' ) !== false ) {
4912 $matches[1] = rawurldecode( $matches[1] );
4914 $title = Title
::newFromText( $matches[1], NS_FILE
);
4915 if ( is_null( $title ) ) {
4916 # Bogus title. Ignore these so we don't bomb out later.
4923 if ( isset( $matches[3] ) ) {
4924 // look for an |alt= definition while trying not to break existing
4925 // captions with multiple pipes (|) in it, until a more sensible grammar
4926 // is defined for images in galleries
4928 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4929 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4930 $magicWordAlt = MagicWord
::get( 'img_alt' );
4931 $magicWordLink = MagicWord
::get( 'img_link' );
4933 foreach ( $parameterMatches as $parameterMatch ) {
4934 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4935 $alt = $this->stripAltText( $match, false );
4937 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4938 $link = strip_tags($this->replaceLinkHoldersText($match));
4939 $chars = self
::EXT_LINK_URL_CLASS
;
4940 $prots = $this->mUrlProtocols
;
4941 //check to see if link matches an absolute url, if not then it must be a wiki link.
4942 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4943 $localLinkTitle = Title
::newFromText($link);
4944 $link = $localLinkTitle->getLocalURL();
4948 // concatenate all other pipes
4949 $label .= '|' . $parameterMatch;
4952 // remove the first pipe
4953 $label = substr( $label, 1 );
4956 $ig->add( $title, $label, $alt ,$link);
4958 return $ig->toHTML();
4965 function getImageParams( $handler ) {
4967 $handlerClass = get_class( $handler );
4971 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4972 # Initialise static lists
4973 static $internalParamNames = array(
4974 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4975 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4976 'bottom', 'text-bottom' ),
4977 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4978 'upright', 'border', 'link', 'alt', 'class' ),
4980 static $internalParamMap;
4981 if ( !$internalParamMap ) {
4982 $internalParamMap = array();
4983 foreach ( $internalParamNames as $type => $names ) {
4984 foreach ( $names as $name ) {
4985 $magicName = str_replace( '-', '_', "img_$name" );
4986 $internalParamMap[$magicName] = array( $type, $name );
4991 # Add handler params
4992 $paramMap = $internalParamMap;
4994 $handlerParamMap = $handler->getParamMap();
4995 foreach ( $handlerParamMap as $magic => $paramName ) {
4996 $paramMap[$magic] = array( 'handler', $paramName );
4999 $this->mImageParams
[$handlerClass] = $paramMap;
5000 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5002 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5006 * Parse image options text and use it to make an image
5008 * @param $title Title
5009 * @param $options String
5010 * @param $holders LinkHolderArray|bool
5011 * @return string HTML
5013 function makeImage( $title, $options, $holders = false ) {
5014 # Check if the options text is of the form "options|alt text"
5016 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5017 # * left no resizing, just left align. label is used for alt= only
5018 # * right same, but right aligned
5019 # * none same, but not aligned
5020 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5021 # * center center the image
5022 # * frame Keep original image size, no magnify-button.
5023 # * framed Same as "frame"
5024 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5025 # * upright reduce width for upright images, rounded to full __0 px
5026 # * border draw a 1px border around the image
5027 # * alt Text for HTML alt attribute (defaults to empty)
5028 # * class Set a class for img node
5029 # * link Set the target of the image link. Can be external, interwiki, or local
5030 # vertical-align values (no % or length right now):
5040 $parts = StringUtils
::explode( "|", $options );
5042 # Give extensions a chance to select the file revision for us
5045 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5046 array( $this, $title, &$options, &$descQuery ) );
5047 # Fetch and register the file (file title may be different via hooks)
5048 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5051 $handler = $file ?
$file->getHandler() : false;
5053 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5056 $this->addTrackingCategory( 'broken-file-category' );
5059 # Process the input parameters
5061 $params = array( 'frame' => array(), 'handler' => array(),
5062 'horizAlign' => array(), 'vertAlign' => array() );
5063 foreach ( $parts as $part ) {
5064 $part = trim( $part );
5065 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5067 if ( isset( $paramMap[$magicName] ) ) {
5068 list( $type, $paramName ) = $paramMap[$magicName];
5070 # Special case; width and height come in one variable together
5071 if ( $type === 'handler' && $paramName === 'width' ) {
5072 $parsedWidthParam = $this->parseWidthParam( $value );
5073 if( isset( $parsedWidthParam['width'] ) ) {
5074 $width = $parsedWidthParam['width'];
5075 if ( $handler->validateParam( 'width', $width ) ) {
5076 $params[$type]['width'] = $width;
5080 if( isset( $parsedWidthParam['height'] ) ) {
5081 $height = $parsedWidthParam['height'];
5082 if ( $handler->validateParam( 'height', $height ) ) {
5083 $params[$type]['height'] = $height;
5087 # else no validation -- bug 13436
5089 if ( $type === 'handler' ) {
5090 # Validate handler parameter
5091 $validated = $handler->validateParam( $paramName, $value );
5093 # Validate internal parameters
5094 switch( $paramName ) {
5098 # @todo FIXME: Possibly check validity here for
5099 # manualthumb? downstream behavior seems odd with
5100 # missing manual thumbs.
5102 $value = $this->stripAltText( $value, $holders );
5105 $chars = self
::EXT_LINK_URL_CLASS
;
5106 $prots = $this->mUrlProtocols
;
5107 if ( $value === '' ) {
5108 $paramName = 'no-link';
5111 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5112 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5113 $paramName = 'link-url';
5114 $this->mOutput
->addExternalLink( $value );
5115 if ( $this->mOptions
->getExternalLinkTarget() ) {
5116 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5121 $linkTitle = Title
::newFromText( $value );
5123 $paramName = 'link-title';
5124 $value = $linkTitle;
5125 $this->mOutput
->addLink( $linkTitle );
5131 # Most other things appear to be empty or numeric...
5132 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5137 $params[$type][$paramName] = $value;
5141 if ( !$validated ) {
5146 # Process alignment parameters
5147 if ( $params['horizAlign'] ) {
5148 $params['frame']['align'] = key( $params['horizAlign'] );
5150 if ( $params['vertAlign'] ) {
5151 $params['frame']['valign'] = key( $params['vertAlign'] );
5154 $params['frame']['caption'] = $caption;
5156 # Will the image be presented in a frame, with the caption below?
5157 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5158 isset( $params['frame']['framed'] ) ||
5159 isset( $params['frame']['thumbnail'] ) ||
5160 isset( $params['frame']['manualthumb'] );
5162 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5163 # came to also set the caption, ordinary text after the image -- which
5164 # makes no sense, because that just repeats the text multiple times in
5165 # screen readers. It *also* came to set the title attribute.
5167 # Now that we have an alt attribute, we should not set the alt text to
5168 # equal the caption: that's worse than useless, it just repeats the
5169 # text. This is the framed/thumbnail case. If there's no caption, we
5170 # use the unnamed parameter for alt text as well, just for the time be-
5171 # ing, if the unnamed param is set and the alt param is not.
5173 # For the future, we need to figure out if we want to tweak this more,
5174 # e.g., introducing a title= parameter for the title; ignoring the un-
5175 # named parameter entirely for images without a caption; adding an ex-
5176 # plicit caption= parameter and preserving the old magic unnamed para-
5178 if ( $imageIsFramed ) { # Framed image
5179 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5180 # No caption or alt text, add the filename as the alt text so
5181 # that screen readers at least get some description of the image
5182 $params['frame']['alt'] = $title->getText();
5184 # Do not set $params['frame']['title'] because tooltips don't make sense
5186 } else { # Inline image
5187 if ( !isset( $params['frame']['alt'] ) ) {
5188 # No alt text, use the "caption" for the alt text
5189 if ( $caption !== '') {
5190 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5192 # No caption, fall back to using the filename for the
5194 $params['frame']['alt'] = $title->getText();
5197 # Use the "caption" for the tooltip text
5198 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5201 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5203 # Linker does the rest
5204 $time = isset( $options['time'] ) ?
$options['time'] : false;
5205 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5206 $time, $descQuery, $this->mOptions
->getThumbSize() );
5208 # Give the handler a chance to modify the parser object
5210 $handler->parserTransformHook( $this, $file );
5218 * @param $holders LinkHolderArray
5219 * @return mixed|String
5221 protected function stripAltText( $caption, $holders ) {
5222 # Strip bad stuff out of the title (tooltip). We can't just use
5223 # replaceLinkHoldersText() here, because if this function is called
5224 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5226 $tooltip = $holders->replaceText( $caption );
5228 $tooltip = $this->replaceLinkHoldersText( $caption );
5231 # make sure there are no placeholders in thumbnail attributes
5232 # that are later expanded to html- so expand them now and
5234 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5235 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5241 * Set a flag in the output object indicating that the content is dynamic and
5242 * shouldn't be cached.
5244 function disableCache() {
5245 wfDebug( "Parser output marked as uncacheable.\n" );
5246 if ( !$this->mOutput
) {
5247 throw new MWException( __METHOD__
.
5248 " can only be called when actually parsing something" );
5250 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5251 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5255 * Callback from the Sanitizer for expanding items found in HTML attribute
5256 * values, so they can be safely tested and escaped.
5258 * @param $text String
5259 * @param $frame PPFrame
5262 function attributeStripCallback( &$text, $frame = false ) {
5263 $text = $this->replaceVariables( $text, $frame );
5264 $text = $this->mStripState
->unstripBoth( $text );
5273 function getTags() {
5274 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5278 * Replace transparent tags in $text with the values given by the callbacks.
5280 * Transparent tag hooks are like regular XML-style tag hooks, except they
5281 * operate late in the transformation sequence, on HTML instead of wikitext.
5283 * @param $text string
5287 function replaceTransparentTags( $text ) {
5289 $elements = array_keys( $this->mTransparentTagHooks
);
5290 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5291 $replacements = array();
5293 foreach ( $matches as $marker => $data ) {
5294 list( $element, $content, $params, $tag ) = $data;
5295 $tagName = strtolower( $element );
5296 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5297 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5301 $replacements[$marker] = $output;
5303 return strtr( $text, $replacements );
5307 * Break wikitext input into sections, and either pull or replace
5308 * some particular section's text.
5310 * External callers should use the getSection and replaceSection methods.
5312 * @param $text String: Page wikitext
5313 * @param $section String: a section identifier string of the form:
5314 * "<flag1> - <flag2> - ... - <section number>"
5316 * Currently the only recognised flag is "T", which means the target section number
5317 * was derived during a template inclusion parse, in other words this is a template
5318 * section edit link. If no flags are given, it was an ordinary section edit link.
5319 * This flag is required to avoid a section numbering mismatch when a section is
5320 * enclosed by "<includeonly>" (bug 6563).
5322 * The section number 0 pulls the text before the first heading; other numbers will
5323 * pull the given section along with its lower-level subsections. If the section is
5324 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5326 * Section 0 is always considered to exist, even if it only contains the empty
5327 * string. If $text is the empty string and section 0 is replaced, $newText is
5330 * @param $mode String: one of "get" or "replace"
5331 * @param $newText String: replacement text for section data.
5332 * @return String: for "get", the extracted section text.
5333 * for "replace", the whole page with the section replaced.
5335 private function extractSections( $text, $section, $mode, $newText='' ) {
5336 global $wgTitle; # not generally used but removes an ugly failure mode
5337 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5339 $frame = $this->getPreprocessor()->newFrame();
5341 # Process section extraction flags
5343 $sectionParts = explode( '-', $section );
5344 $sectionIndex = array_pop( $sectionParts );
5345 foreach ( $sectionParts as $part ) {
5346 if ( $part === 'T' ) {
5347 $flags |
= self
::PTD_FOR_INCLUSION
;
5351 # Check for empty input
5352 if ( strval( $text ) === '' ) {
5353 # Only sections 0 and T-0 exist in an empty document
5354 if ( $sectionIndex == 0 ) {
5355 if ( $mode === 'get' ) {
5361 if ( $mode === 'get' ) {
5369 # Preprocess the text
5370 $root = $this->preprocessToDom( $text, $flags );
5372 # <h> nodes indicate section breaks
5373 # They can only occur at the top level, so we can find them by iterating the root's children
5374 $node = $root->getFirstChild();
5376 # Find the target section
5377 if ( $sectionIndex == 0 ) {
5378 # Section zero doesn't nest, level=big
5379 $targetLevel = 1000;
5382 if ( $node->getName() === 'h' ) {
5383 $bits = $node->splitHeading();
5384 if ( $bits['i'] == $sectionIndex ) {
5385 $targetLevel = $bits['level'];
5389 if ( $mode === 'replace' ) {
5390 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5392 $node = $node->getNextSibling();
5398 if ( $mode === 'get' ) {
5405 # Find the end of the section, including nested sections
5407 if ( $node->getName() === 'h' ) {
5408 $bits = $node->splitHeading();
5409 $curLevel = $bits['level'];
5410 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5414 if ( $mode === 'get' ) {
5415 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5417 $node = $node->getNextSibling();
5420 # Write out the remainder (in replace mode only)
5421 if ( $mode === 'replace' ) {
5422 # Output the replacement text
5423 # Add two newlines on -- trailing whitespace in $newText is conventionally
5424 # stripped by the editor, so we need both newlines to restore the paragraph gap
5425 # Only add trailing whitespace if there is newText
5426 if ( $newText != "" ) {
5427 $outText .= $newText . "\n\n";
5431 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5432 $node = $node->getNextSibling();
5436 if ( is_string( $outText ) ) {
5437 # Re-insert stripped tags
5438 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5445 * This function returns the text of a section, specified by a number ($section).
5446 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5447 * the first section before any such heading (section 0).
5449 * If a section contains subsections, these are also returned.
5451 * @param $text String: text to look in
5452 * @param $section String: section identifier
5453 * @param $deftext String: default to return if section is not found
5454 * @return string text of the requested section
5456 public function getSection( $text, $section, $deftext='' ) {
5457 return $this->extractSections( $text, $section, "get", $deftext );
5461 * This function returns $oldtext after the content of the section
5462 * specified by $section has been replaced with $text. If the target
5463 * section does not exist, $oldtext is returned unchanged.
5465 * @param $oldtext String: former text of the article
5466 * @param $section int section identifier
5467 * @param $text String: replacing text
5468 * @return String: modified text
5470 public function replaceSection( $oldtext, $section, $text ) {
5471 return $this->extractSections( $oldtext, $section, "replace", $text );
5475 * Get the ID of the revision we are parsing
5477 * @return Mixed: integer or null
5479 function getRevisionId() {
5480 return $this->mRevisionId
;
5484 * Get the revision object for $this->mRevisionId
5486 * @return Revision|null either a Revision object or null
5488 protected function getRevisionObject() {
5489 if ( !is_null( $this->mRevisionObject
) ) {
5490 return $this->mRevisionObject
;
5492 if ( is_null( $this->mRevisionId
) ) {
5496 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5497 return $this->mRevisionObject
;
5501 * Get the timestamp associated with the current revision, adjusted for
5502 * the default server-local timestamp
5504 function getRevisionTimestamp() {
5505 if ( is_null( $this->mRevisionTimestamp
) ) {
5506 wfProfileIn( __METHOD__
);
5510 $revObject = $this->getRevisionObject();
5511 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5513 # The cryptic '' timezone parameter tells to use the site-default
5514 # timezone offset instead of the user settings.
5516 # Since this value will be saved into the parser cache, served
5517 # to other users, and potentially even used inside links and such,
5518 # it needs to be consistent for all visitors.
5519 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5521 wfProfileOut( __METHOD__
);
5523 return $this->mRevisionTimestamp
;
5527 * Get the name of the user that edited the last revision
5529 * @return String: user name
5531 function getRevisionUser() {
5532 if( is_null( $this->mRevisionUser
) ) {
5533 $revObject = $this->getRevisionObject();
5535 # if this template is subst: the revision id will be blank,
5536 # so just use the current user's name
5538 $this->mRevisionUser
= $revObject->getUserText();
5539 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5540 $this->mRevisionUser
= $this->getUser()->getName();
5543 return $this->mRevisionUser
;
5547 * Mutator for $mDefaultSort
5549 * @param $sort string New value
5551 public function setDefaultSort( $sort ) {
5552 $this->mDefaultSort
= $sort;
5553 $this->mOutput
->setProperty( 'defaultsort', $sort );
5557 * Accessor for $mDefaultSort
5558 * Will use the empty string if none is set.
5560 * This value is treated as a prefix, so the
5561 * empty string is equivalent to sorting by
5566 public function getDefaultSort() {
5567 if ( $this->mDefaultSort
!== false ) {
5568 return $this->mDefaultSort
;
5575 * Accessor for $mDefaultSort
5576 * Unlike getDefaultSort(), will return false if none is set
5578 * @return string or false
5580 public function getCustomDefaultSort() {
5581 return $this->mDefaultSort
;
5585 * Try to guess the section anchor name based on a wikitext fragment
5586 * presumably extracted from a heading, for example "Header" from
5589 * @param $text string
5593 public function guessSectionNameFromWikiText( $text ) {
5594 # Strip out wikitext links(they break the anchor)
5595 $text = $this->stripSectionName( $text );
5596 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5597 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5601 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5602 * instead. For use in redirects, since IE6 interprets Redirect: headers
5603 * as something other than UTF-8 (apparently?), resulting in breakage.
5605 * @param $text String: The section name
5606 * @return string An anchor
5608 public function guessLegacySectionNameFromWikiText( $text ) {
5609 # Strip out wikitext links(they break the anchor)
5610 $text = $this->stripSectionName( $text );
5611 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5612 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5616 * Strips a text string of wikitext for use in a section anchor
5618 * Accepts a text string and then removes all wikitext from the
5619 * string and leaves only the resultant text (i.e. the result of
5620 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5621 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5622 * to create valid section anchors by mimicing the output of the
5623 * parser when headings are parsed.
5625 * @param $text String: text string to be stripped of wikitext
5626 * for use in a Section anchor
5627 * @return string Filtered text string
5629 public function stripSectionName( $text ) {
5630 # Strip internal link markup
5631 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5632 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5634 # Strip external link markup
5635 # @todo FIXME: Not tolerant to blank link text
5636 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5637 # on how many empty links there are on the page - need to figure that out.
5638 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5640 # Parse wikitext quotes (italics & bold)
5641 $text = $this->doQuotes( $text );
5644 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5649 * strip/replaceVariables/unstrip for preprocessor regression testing
5651 * @param $text string
5652 * @param $title Title
5653 * @param $options ParserOptions
5654 * @param $outputType int
5658 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5659 $this->startParse( $title, $options, $outputType, true );
5661 $text = $this->replaceVariables( $text );
5662 $text = $this->mStripState
->unstripBoth( $text );
5663 $text = Sanitizer
::removeHTMLtags( $text );
5668 * @param $text string
5669 * @param $title Title
5670 * @param $options ParserOptions
5673 function testPst( $text, Title
$title, ParserOptions
$options ) {
5674 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5679 * @param $title Title
5680 * @param $options ParserOptions
5683 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5684 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5688 * Call a callback function on all regions of the given text that are not
5689 * inside strip markers, and replace those regions with the return value
5690 * of the callback. For example, with input:
5694 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5695 * two strings will be replaced with the value returned by the callback in
5703 function markerSkipCallback( $s, $callback ) {
5706 while ( $i < strlen( $s ) ) {
5707 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5708 if ( $markerStart === false ) {
5709 $out .= call_user_func( $callback, substr( $s, $i ) );
5712 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5713 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5714 if ( $markerEnd === false ) {
5715 $out .= substr( $s, $markerStart );
5718 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5719 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5728 * Remove any strip markers found in the given text.
5730 * @param $text Input string
5733 function killMarkers( $text ) {
5734 return $this->mStripState
->killMarkers( $text );
5738 * Save the parser state required to convert the given half-parsed text to
5739 * HTML. "Half-parsed" in this context means the output of
5740 * recursiveTagParse() or internalParse(). This output has strip markers
5741 * from replaceVariables (extensionSubstitution() etc.), and link
5742 * placeholders from replaceLinkHolders().
5744 * Returns an array which can be serialized and stored persistently. This
5745 * array can later be loaded into another parser instance with
5746 * unserializeHalfParsedText(). The text can then be safely incorporated into
5747 * the return value of a parser hook.
5749 * @param $text string
5753 function serializeHalfParsedText( $text ) {
5754 wfProfileIn( __METHOD__
);
5757 'version' => self
::HALF_PARSED_VERSION
,
5758 'stripState' => $this->mStripState
->getSubState( $text ),
5759 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5761 wfProfileOut( __METHOD__
);
5766 * Load the parser state given in the $data array, which is assumed to
5767 * have been generated by serializeHalfParsedText(). The text contents is
5768 * extracted from the array, and its markers are transformed into markers
5769 * appropriate for the current Parser instance. This transformed text is
5770 * returned, and can be safely included in the return value of a parser
5773 * If the $data array has been stored persistently, the caller should first
5774 * check whether it is still valid, by calling isValidHalfParsedText().
5776 * @param $data array Serialized data
5779 function unserializeHalfParsedText( $data ) {
5780 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5781 throw new MWException( __METHOD__
.': invalid version' );
5784 # First, extract the strip state.
5785 $texts = array( $data['text'] );
5786 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5788 # Now renumber links
5789 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5791 # Should be good to go.
5796 * Returns true if the given array, presumed to be generated by
5797 * serializeHalfParsedText(), is compatible with the current version of the
5800 * @param $data Array
5804 function isValidHalfParsedText( $data ) {
5805 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5809 * Parsed a width param of imagelink like 300px or 200x300px
5811 * @param $value String
5816 public function parseWidthParam( $value ) {
5817 $parsedWidthParam = array();
5818 if( $value === '' ) {
5819 return $parsedWidthParam;
5822 # (bug 13500) In both cases (width/height and width only),
5823 # permit trailing "px" for backward compatibility.
5824 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5825 $width = intval( $m[1] );
5826 $height = intval( $m[2] );
5827 $parsedWidthParam['width'] = $width;
5828 $parsedWidthParam['height'] = $height;
5829 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5830 $width = intval( $value );
5831 $parsedWidthParam['width'] = $width;
5833 return $parsedWidthParam;