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
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
208 var $mLangLinkLanguages;
215 public function __construct( $conf = array() ) {
216 $this->mConf
= $conf;
217 $this->mUrlProtocols
= wfUrlProtocols();
218 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')'.
219 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass
= $conf['preprocessorClass'];
222 } elseif ( defined( 'MW_COMPILED' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass
= 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass
= 'Preprocessor_DOM';
232 $this->mPreprocessorClass
= 'Preprocessor_Hash';
234 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
238 * Reduce memory usage to reduce the impact of circular references
240 function __destruct() {
241 if ( isset( $this->mLinkHolders
) ) {
242 unset( $this->mLinkHolders
);
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
250 * Do various kinds of initialisation on the first call of the parser
252 function firstCallInit() {
253 if ( !$this->mFirstCall
) {
256 $this->mFirstCall
= false;
258 wfProfileIn( __METHOD__
);
260 CoreParserFunctions
::register( $this );
261 CoreTagHooks
::register( $this );
262 $this->initialiseVariables();
264 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
265 wfProfileOut( __METHOD__
);
273 function clearState() {
274 wfProfileIn( __METHOD__
);
275 if ( $this->mFirstCall
) {
276 $this->firstCallInit();
278 $this->mOutput
= new ParserOutput
;
279 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
280 $this->mAutonumber
= 0;
281 $this->mLastSection
= '';
282 $this->mDTopen
= false;
283 $this->mIncludeCount
= array();
284 $this->mArgStack
= false;
285 $this->mInPre
= false;
286 $this->mLinkHolders
= new LinkHolderArray( $this );
288 $this->mRevisionObject
= $this->mRevisionTimestamp
=
289 $this->mRevisionId
= $this->mRevisionUser
= null;
290 $this->mVarCache
= array();
292 $this->mLangLinkLanguages
= array();
295 * Prefix for temporary replacement strings for the multipass parser.
296 * \x07 should never appear in input as it's disallowed in XML.
297 * Using it at the front also gives us a little extra robustness
298 * since it shouldn't match when butted up against identifier-like
301 * Must not consist of all title characters, or else it will change
302 * the behaviour of <nowiki> in a link.
304 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
305 $this->mStripState
= new StripState( $this->mUniqPrefix
);
308 # Clear these on every parse, bug 4549
309 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
311 $this->mShowToc
= true;
312 $this->mForceTocPosition
= false;
313 $this->mIncludeSizes
= array(
317 $this->mPPNodeCount
= 0;
318 $this->mGeneratedPPNodeCount
= 0;
319 $this->mHighestExpansionDepth
= 0;
320 $this->mDefaultSort
= false;
321 $this->mHeadings
= array();
322 $this->mDoubleUnderscores
= array();
323 $this->mExpensiveFunctionCount
= 0;
326 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
327 $this->mPreprocessor
= null;
330 wfRunHooks( 'ParserClearState', array( &$this ) );
331 wfProfileOut( __METHOD__
);
335 * Convert wikitext to HTML
336 * Do not call this function recursively.
338 * @param $text String: text we want to parse
339 * @param $title Title object
340 * @param $options ParserOptions
341 * @param $linestart boolean
342 * @param $clearState boolean
343 * @param $revid Int: number to pass in {{REVISIONID}}
344 * @return ParserOutput a ParserOutput
346 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
348 * First pass--just handle <nowiki> sections, pass the rest off
349 * to internalParse() which does all the real work.
352 global $wgUseTidy, $wgAlwaysUseTidy;
353 $fname = __METHOD__
.'-' . wfGetCaller();
354 wfProfileIn( __METHOD__
);
355 wfProfileIn( $fname );
357 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
359 # Remove the strip marker tag prefix from the input, if present.
361 $text = str_replace( $this->mUniqPrefix
, '', $text );
364 $oldRevisionId = $this->mRevisionId
;
365 $oldRevisionObject = $this->mRevisionObject
;
366 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
367 $oldRevisionUser = $this->mRevisionUser
;
368 if ( $revid !== null ) {
369 $this->mRevisionId
= $revid;
370 $this->mRevisionObject
= null;
371 $this->mRevisionTimestamp
= null;
372 $this->mRevisionUser
= null;
375 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
377 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
378 $text = $this->internalParse( $text );
379 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
381 $text = $this->mStripState
->unstripGeneral( $text );
383 # Clean up special characters, only run once, next-to-last before doBlockLevels
385 # french spaces, last one Guillemet-left
386 # only if there is something before the space
387 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
388 # french spaces, Guillemet-right
389 '/(\\302\\253) /' => '\\1 ',
390 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
392 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
394 $text = $this->doBlockLevels( $text, $linestart );
396 $this->replaceLinkHolders( $text );
399 * The input doesn't get language converted if
401 * b) Content isn't converted
402 * c) It's a conversion table
403 * d) it is an interface message (which is in the user language)
405 if ( !( $options->getDisableContentConversion()
406 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
408 # Run convert unconditionally in 1.18-compatible mode
409 global $wgBug34832TransitionalRollback;
410 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
411 # The position of the convert() call should not be changed. it
412 # assumes that the links are all replaced and the only thing left
413 # is the <nowiki> mark.
414 $text = $this->getConverterLanguage()->convert( $text );
419 * A converted title will be provided in the output object if title and
420 * content conversion are enabled, the article text does not contain
421 * a conversion-suppressing double-underscore tag, and no
422 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
423 * automatic link conversion.
425 if ( !( $options->getDisableTitleConversion()
426 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
427 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
428 ||
$this->mOutput
->getDisplayTitle() !== false ) )
430 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
431 if ( $convruletitle ) {
432 $this->mOutput
->setTitleText( $convruletitle );
434 $titleText = $this->getConverterLanguage()->convertTitle( $title );
435 $this->mOutput
->setTitleText( $titleText );
439 $text = $this->mStripState
->unstripNoWiki( $text );
441 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
443 $text = $this->replaceTransparentTags( $text );
444 $text = $this->mStripState
->unstripGeneral( $text );
446 $text = Sanitizer
::normalizeCharReferences( $text );
448 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
449 $text = MWTidy
::tidy( $text );
451 # attempt to sanitize at least some nesting problems
452 # (bug #2702 and quite a few others)
454 # ''Something [http://www.cool.com cool''] -->
455 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
456 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
457 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
458 # fix up an anchor inside another anchor, only
459 # at least for a single single nested link (bug 3695)
460 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
461 '\\1\\2</a>\\3</a>\\1\\4</a>',
462 # fix div inside inline elements- doBlockLevels won't wrap a line which
463 # contains a div, so fix it up here; replace
464 # div with escaped text
465 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
466 '\\1\\3<div\\5>\\6</div>\\8\\9',
467 # remove empty italic or bold tag pairs, some
468 # introduced by rules above
469 '/<([bi])><\/\\1>/' => '',
472 $text = preg_replace(
473 array_keys( $tidyregs ),
474 array_values( $tidyregs ),
478 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
479 $this->limitationWarn( 'expensive-parserfunction',
480 $this->mExpensiveFunctionCount
,
481 $this->mOptions
->getExpensiveParserFunctionLimit()
485 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
487 # Information on include size limits, for the benefit of users who try to skirt them
488 if ( $this->mOptions
->getEnableLimitReport() ) {
489 $max = $this->mOptions
->getMaxIncludeSize();
490 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
492 "NewPP limit report\n" .
493 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
494 "Preprocessor generated node count: " .
495 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
496 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
497 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
498 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
500 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
501 $text .= "\n<!-- \n$limitReport-->\n";
503 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
504 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
505 $this->mTitle
->getPrefixedDBkey() );
508 $this->mOutput
->setText( $text );
510 $this->mRevisionId
= $oldRevisionId;
511 $this->mRevisionObject
= $oldRevisionObject;
512 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
513 $this->mRevisionUser
= $oldRevisionUser;
514 wfProfileOut( $fname );
515 wfProfileOut( __METHOD__
);
517 return $this->mOutput
;
521 * Recursive parser entry point that can be called from an extension tag
524 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
526 * @param $text String: text extension wants to have parsed
527 * @param $frame PPFrame: The frame to use for expanding any template variables
531 function recursiveTagParse( $text, $frame=false ) {
532 wfProfileIn( __METHOD__
);
533 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
534 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
535 $text = $this->internalParse( $text, false, $frame );
536 wfProfileOut( __METHOD__
);
541 * Expand templates and variables in the text, producing valid, static wikitext.
542 * Also removes comments.
543 * @return mixed|string
545 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
546 wfProfileIn( __METHOD__
);
547 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
548 if ( $revid !== null ) {
549 $this->mRevisionId
= $revid;
551 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
552 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
553 $text = $this->replaceVariables( $text );
554 $text = $this->mStripState
->unstripBoth( $text );
555 wfProfileOut( __METHOD__
);
560 * Recursive parser entry point that can be called from an extension tag
563 * @param $text String: text to be expanded
564 * @param $frame PPFrame: The frame to use for expanding any template variables
568 public function recursivePreprocess( $text, $frame = false ) {
569 wfProfileIn( __METHOD__
);
570 $text = $this->replaceVariables( $text, $frame );
571 $text = $this->mStripState
->unstripBoth( $text );
572 wfProfileOut( __METHOD__
);
577 * Process the wikitext for the "?preload=" feature. (bug 5210)
579 * "<noinclude>", "<includeonly>" etc. are parsed as for template
580 * transclusion, comments, templates, arguments, tags hooks and parser
581 * functions are untouched.
583 * @param $text String
584 * @param $title Title
585 * @param $options ParserOptions
588 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
589 # Parser (re)initialisation
590 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
592 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
593 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
594 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
595 $text = $this->mStripState
->unstripBoth( $text );
600 * Get a random string
604 static public function getRandomString() {
605 return wfRandomString( 16 );
609 * Set the current user.
610 * Should only be used when doing pre-save transform.
612 * @param $user Mixed: User object or null (to reset)
614 function setUser( $user ) {
615 $this->mUser
= $user;
619 * Accessor for mUniqPrefix.
623 public function uniqPrefix() {
624 if ( !isset( $this->mUniqPrefix
) ) {
625 # @todo FIXME: This is probably *horribly wrong*
626 # LanguageConverter seems to want $wgParser's uniqPrefix, however
627 # if this is called for a parser cache hit, the parser may not
628 # have ever been initialized in the first place.
629 # Not really sure what the heck is supposed to be going on here.
631 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
633 return $this->mUniqPrefix
;
637 * Set the context title
641 function setTitle( $t ) {
642 if ( !$t ||
$t instanceof FakeTitle
) {
643 $t = Title
::newFromText( 'NO TITLE' );
646 if ( strval( $t->getFragment() ) !== '' ) {
647 # Strip the fragment to avoid various odd effects
648 $this->mTitle
= clone $t;
649 $this->mTitle
->setFragment( '' );
656 * Accessor for the Title object
658 * @return Title object
660 function getTitle() {
661 return $this->mTitle
;
665 * Accessor/mutator for the Title object
667 * @param $x Title object or null to just get the current one
668 * @return Title object
670 function Title( $x = null ) {
671 return wfSetVar( $this->mTitle
, $x );
675 * Set the output type
677 * @param $ot Integer: new value
679 function setOutputType( $ot ) {
680 $this->mOutputType
= $ot;
683 'html' => $ot == self
::OT_HTML
,
684 'wiki' => $ot == self
::OT_WIKI
,
685 'pre' => $ot == self
::OT_PREPROCESS
,
686 'plain' => $ot == self
::OT_PLAIN
,
691 * Accessor/mutator for the output type
693 * @param $x int|null New value or null to just get the current one
696 function OutputType( $x = null ) {
697 return wfSetVar( $this->mOutputType
, $x );
701 * Get the ParserOutput object
703 * @return ParserOutput object
705 function getOutput() {
706 return $this->mOutput
;
710 * Get the ParserOptions object
712 * @return ParserOptions object
714 function getOptions() {
715 return $this->mOptions
;
719 * Accessor/mutator for the ParserOptions object
721 * @param $x ParserOptions New value or null to just get the current one
722 * @return ParserOptions Current ParserOptions object
724 function Options( $x = null ) {
725 return wfSetVar( $this->mOptions
, $x );
731 function nextLinkID() {
732 return $this->mLinkID++
;
738 function setLinkID( $id ) {
739 $this->mLinkID
= $id;
743 * Get a language object for use in parser functions such as {{FORMATNUM:}}
746 function getFunctionLang() {
747 return $this->getTargetLanguage();
751 * Get the target language for the content being parsed. This is usually the
752 * language that the content is in.
756 * @throws MWException
757 * @return Language|null
759 public function getTargetLanguage() {
760 $target = $this->mOptions
->getTargetLanguage();
762 if ( $target !== null ) {
764 } elseif( $this->mOptions
->getInterfaceMessage() ) {
765 return $this->mOptions
->getUserLangObj();
766 } elseif( is_null( $this->mTitle
) ) {
767 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
770 return $this->mTitle
->getPageLanguage();
774 * Get the language object for language conversion
776 function getConverterLanguage() {
777 global $wgBug34832TransitionalRollback, $wgContLang;
778 if ( $wgBug34832TransitionalRollback ) {
781 return $this->getTargetLanguage();
786 * Get a User object either from $this->mUser, if set, or from the
787 * ParserOptions object otherwise
789 * @return User object
792 if ( !is_null( $this->mUser
) ) {
795 return $this->mOptions
->getUser();
799 * Get a preprocessor object
801 * @return Preprocessor instance
803 function getPreprocessor() {
804 if ( !isset( $this->mPreprocessor
) ) {
805 $class = $this->mPreprocessorClass
;
806 $this->mPreprocessor
= new $class( $this );
808 return $this->mPreprocessor
;
812 * Replaces all occurrences of HTML-style comments and the given tags
813 * in the text with a random marker and returns the next text. The output
814 * parameter $matches will be an associative array filled with data in
818 * 'UNIQ-xxxxx' => array(
821 * array( 'param' => 'x' ),
822 * '<element param="x">tag content</element>' ) )
825 * @param $elements array list of element names. Comments are always extracted.
826 * @param $text string Source text string.
827 * @param $matches array Out parameter, Array: extracted tags
828 * @param $uniq_prefix string
829 * @return String: stripped text
831 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
836 $taglist = implode( '|', $elements );
837 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
839 while ( $text != '' ) {
840 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
842 if ( count( $p ) < 5 ) {
845 if ( count( $p ) > 5 ) {
859 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
860 $stripped .= $marker;
862 if ( $close === '/>' ) {
863 # Empty element tag, <tag />
868 if ( $element === '!--' ) {
871 $end = "/(<\\/$element\\s*>)/i";
873 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
875 if ( count( $q ) < 3 ) {
876 # No end tag -- let it run out to the end of the text.
885 $matches[$marker] = array( $element,
887 Sanitizer
::decodeTagAttributes( $attributes ),
888 "<$element$attributes$close$content$tail" );
894 * Get a list of strippable XML-like elements
898 function getStripList() {
899 return $this->mStripList
;
903 * Add an item to the strip state
904 * Returns the unique tag which must be inserted into the stripped text
905 * The tag will be replaced with the original text in unstrip()
907 * @param $text string
911 function insertStripItem( $text ) {
912 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
913 $this->mMarkerIndex++
;
914 $this->mStripState
->addGeneral( $rnd, $text );
919 * parse the wiki syntax used to render tables
924 function doTableStuff( $text ) {
925 wfProfileIn( __METHOD__
);
927 $lines = StringUtils
::explode( "\n", $text );
929 $td_history = array(); # Is currently a td tag open?
930 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
931 $tr_history = array(); # Is currently a tr tag open?
932 $tr_attributes = array(); # history of tr attributes
933 $has_opened_tr = array(); # Did this table open a <tr> element?
934 $indent_level = 0; # indent level of the table
936 foreach ( $lines as $outLine ) {
937 $line = trim( $outLine );
939 if ( $line === '' ) { # empty line, go to next line
940 $out .= $outLine."\n";
944 $first_character = $line[0];
947 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
948 # First check if we are starting a new table
949 $indent_level = strlen( $matches[1] );
951 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
952 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
954 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
955 array_push( $td_history , false );
956 array_push( $last_tag_history , '' );
957 array_push( $tr_history , false );
958 array_push( $tr_attributes , '' );
959 array_push( $has_opened_tr , false );
960 } elseif ( count( $td_history ) == 0 ) {
961 # Don't do any of the following
962 $out .= $outLine."\n";
964 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
965 # We are ending a table
966 $line = '</table>' . substr( $line , 2 );
967 $last_tag = array_pop( $last_tag_history );
969 if ( !array_pop( $has_opened_tr ) ) {
970 $line = "<tr><td></td></tr>{$line}";
973 if ( array_pop( $tr_history ) ) {
974 $line = "</tr>{$line}";
977 if ( array_pop( $td_history ) ) {
978 $line = "</{$last_tag}>{$line}";
980 array_pop( $tr_attributes );
981 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
982 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
983 # Now we have a table row
984 $line = preg_replace( '#^\|-+#', '', $line );
986 # Whats after the tag is now only attributes
987 $attributes = $this->mStripState
->unstripBoth( $line );
988 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
989 array_pop( $tr_attributes );
990 array_push( $tr_attributes, $attributes );
993 $last_tag = array_pop( $last_tag_history );
994 array_pop( $has_opened_tr );
995 array_push( $has_opened_tr , true );
997 if ( array_pop( $tr_history ) ) {
1001 if ( array_pop( $td_history ) ) {
1002 $line = "</{$last_tag}>{$line}";
1006 array_push( $tr_history , false );
1007 array_push( $td_history , false );
1008 array_push( $last_tag_history , '' );
1009 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
1010 # This might be cell elements, td, th or captions
1011 if ( substr( $line , 0 , 2 ) === '|+' ) {
1012 $first_character = '+';
1013 $line = substr( $line , 1 );
1016 $line = substr( $line , 1 );
1018 if ( $first_character === '!' ) {
1019 $line = str_replace( '!!' , '||' , $line );
1022 # Split up multiple cells on the same line.
1023 # FIXME : This can result in improper nesting of tags processed
1024 # by earlier parser steps, but should avoid splitting up eg
1025 # attribute values containing literal "||".
1026 $cells = StringUtils
::explodeMarkup( '||' , $line );
1030 # Loop through each table cell
1031 foreach ( $cells as $cell ) {
1033 if ( $first_character !== '+' ) {
1034 $tr_after = array_pop( $tr_attributes );
1035 if ( !array_pop( $tr_history ) ) {
1036 $previous = "<tr{$tr_after}>\n";
1038 array_push( $tr_history , true );
1039 array_push( $tr_attributes , '' );
1040 array_pop( $has_opened_tr );
1041 array_push( $has_opened_tr , true );
1044 $last_tag = array_pop( $last_tag_history );
1046 if ( array_pop( $td_history ) ) {
1047 $previous = "</{$last_tag}>\n{$previous}";
1050 if ( $first_character === '|' ) {
1052 } elseif ( $first_character === '!' ) {
1054 } elseif ( $first_character === '+' ) {
1055 $last_tag = 'caption';
1060 array_push( $last_tag_history , $last_tag );
1062 # A cell could contain both parameters and data
1063 $cell_data = explode( '|' , $cell , 2 );
1065 # Bug 553: Note that a '|' inside an invalid link should not
1066 # be mistaken as delimiting cell parameters
1067 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1068 $cell = "{$previous}<{$last_tag}>{$cell}";
1069 } elseif ( count( $cell_data ) == 1 ) {
1070 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1072 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1073 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1074 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1078 array_push( $td_history , true );
1081 $out .= $outLine . "\n";
1084 # Closing open td, tr && table
1085 while ( count( $td_history ) > 0 ) {
1086 if ( array_pop( $td_history ) ) {
1089 if ( array_pop( $tr_history ) ) {
1092 if ( !array_pop( $has_opened_tr ) ) {
1093 $out .= "<tr><td></td></tr>\n" ;
1096 $out .= "</table>\n";
1099 # Remove trailing line-ending (b/c)
1100 if ( substr( $out, -1 ) === "\n" ) {
1101 $out = substr( $out, 0, -1 );
1104 # special case: don't return empty table
1105 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1109 wfProfileOut( __METHOD__
);
1115 * Helper function for parse() that transforms wiki markup into
1116 * HTML. Only called for $mOutputType == self::OT_HTML.
1120 * @param $text string
1121 * @param $isMain bool
1122 * @param $frame bool
1126 function internalParse( $text, $isMain = true, $frame = false ) {
1127 wfProfileIn( __METHOD__
);
1131 # Hook to suspend the parser in this state
1132 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1133 wfProfileOut( __METHOD__
);
1137 # if $frame is provided, then use $frame for replacing any variables
1139 # use frame depth to infer how include/noinclude tags should be handled
1140 # depth=0 means this is the top-level document; otherwise it's an included document
1141 if ( !$frame->depth
) {
1144 $flag = Parser
::PTD_FOR_INCLUSION
;
1146 $dom = $this->preprocessToDom( $text, $flag );
1147 $text = $frame->expand( $dom );
1149 # if $frame is not provided, then use old-style replaceVariables
1150 $text = $this->replaceVariables( $text );
1153 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1154 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1155 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1157 # Tables need to come after variable replacement for things to work
1158 # properly; putting them before other transformations should keep
1159 # exciting things like link expansions from showing up in surprising
1161 $text = $this->doTableStuff( $text );
1163 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1165 $text = $this->doDoubleUnderscore( $text );
1167 $text = $this->doHeadings( $text );
1168 if ( $this->mOptions
->getUseDynamicDates() ) {
1169 $df = DateFormatter
::getInstance();
1170 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1172 $text = $this->replaceInternalLinks( $text );
1173 $text = $this->doAllQuotes( $text );
1174 $text = $this->replaceExternalLinks( $text );
1176 # replaceInternalLinks may sometimes leave behind
1177 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1178 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1180 $text = $this->doMagicLinks( $text );
1181 $text = $this->formatHeadings( $text, $origText, $isMain );
1183 wfProfileOut( __METHOD__
);
1188 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1189 * magic external links.
1194 * @param $text string
1198 function doMagicLinks( $text ) {
1199 wfProfileIn( __METHOD__
);
1200 $prots = wfUrlProtocolsWithoutProtRel();
1201 $urlChar = self
::EXT_LINK_URL_CLASS
;
1202 $text = preg_replace_callback(
1204 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1205 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1206 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1207 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1208 ISBN\s+(\b # m[5]: ISBN, capture number
1209 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1210 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1211 [0-9Xx] # check digit
1213 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1214 wfProfileOut( __METHOD__
);
1219 * @throws MWException
1221 * @return HTML|string
1223 function magicLinkCallback( $m ) {
1224 if ( isset( $m[1] ) && $m[1] !== '' ) {
1227 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1230 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1231 # Free external link
1232 return $this->makeFreeExternalLink( $m[0] );
1233 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1235 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1238 $CssClass = 'mw-magiclink-rfc';
1240 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1242 $urlmsg = 'pubmedurl';
1243 $CssClass = 'mw-magiclink-pmid';
1246 throw new MWException( __METHOD__
.': unrecognised match type "' .
1247 substr( $m[0], 0, 20 ) . '"' );
1249 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1250 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1251 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1254 $num = strtr( $isbn, array(
1259 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1261 htmlspecialchars( $titleObj->getLocalUrl() ) .
1262 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1269 * Make a free external link, given a user-supplied URL
1271 * @param $url string
1273 * @return string HTML
1276 function makeFreeExternalLink( $url ) {
1277 wfProfileIn( __METHOD__
);
1281 # The characters '<' and '>' (which were escaped by
1282 # removeHTMLtags()) should not be included in
1283 # URLs, per RFC 2396.
1285 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1286 $trail = substr( $url, $m2[0][1] ) . $trail;
1287 $url = substr( $url, 0, $m2[0][1] );
1290 # Move trailing punctuation to $trail
1292 # If there is no left bracket, then consider right brackets fair game too
1293 if ( strpos( $url, '(' ) === false ) {
1297 $numSepChars = strspn( strrev( $url ), $sep );
1298 if ( $numSepChars ) {
1299 $trail = substr( $url, -$numSepChars ) . $trail;
1300 $url = substr( $url, 0, -$numSepChars );
1303 $url = Sanitizer
::cleanUrl( $url );
1305 # Is this an external image?
1306 $text = $this->maybeMakeExternalImage( $url );
1307 if ( $text === false ) {
1308 # Not an image, make a link
1309 $text = Linker
::makeExternalLink( $url,
1310 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1311 $this->getExternalLinkAttribs( $url ) );
1312 # Register it in the output object...
1313 # Replace unnecessary URL escape codes with their equivalent characters
1314 $pasteurized = self
::replaceUnusualEscapes( $url );
1315 $this->mOutput
->addExternalLink( $pasteurized );
1317 wfProfileOut( __METHOD__
);
1318 return $text . $trail;
1323 * Parse headers and return html
1327 * @param $text string
1331 function doHeadings( $text ) {
1332 wfProfileIn( __METHOD__
);
1333 for ( $i = 6; $i >= 1; --$i ) {
1334 $h = str_repeat( '=', $i );
1335 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1336 "<h$i>\\1</h$i>", $text );
1338 wfProfileOut( __METHOD__
);
1343 * Replace single quotes with HTML markup
1346 * @param $text string
1348 * @return string the altered text
1350 function doAllQuotes( $text ) {
1351 wfProfileIn( __METHOD__
);
1353 $lines = StringUtils
::explode( "\n", $text );
1354 foreach ( $lines as $line ) {
1355 $outtext .= $this->doQuotes( $line ) . "\n";
1357 $outtext = substr( $outtext, 0,-1 );
1358 wfProfileOut( __METHOD__
);
1363 * Helper function for doAllQuotes()
1365 * @param $text string
1369 public function doQuotes( $text ) {
1370 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1371 if ( count( $arr ) == 1 ) {
1374 # First, do some preliminary work. This may shift some apostrophes from
1375 # being mark-up to being text. It also counts the number of occurrences
1376 # of bold and italics mark-ups.
1379 for ( $i = 0; $i < count( $arr ); $i++
) {
1380 if ( ( $i %
2 ) == 1 ) {
1381 # If there are ever four apostrophes, assume the first is supposed to
1382 # be text, and the remaining three constitute mark-up for bold text.
1383 if ( strlen( $arr[$i] ) == 4 ) {
1386 } elseif ( strlen( $arr[$i] ) > 5 ) {
1387 # If there are more than 5 apostrophes in a row, assume they're all
1388 # text except for the last 5.
1389 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1392 # Count the number of occurrences of bold and italics mark-ups.
1393 # We are not counting sequences of five apostrophes.
1394 if ( strlen( $arr[$i] ) == 2 ) {
1396 } elseif ( strlen( $arr[$i] ) == 3 ) {
1398 } elseif ( strlen( $arr[$i] ) == 5 ) {
1405 # If there is an odd number of both bold and italics, it is likely
1406 # that one of the bold ones was meant to be an apostrophe followed
1407 # by italics. Which one we cannot know for certain, but it is more
1408 # likely to be one that has a single-letter word before it.
1409 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1411 $firstsingleletterword = -1;
1412 $firstmultiletterword = -1;
1414 foreach ( $arr as $r ) {
1415 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1416 $x1 = substr( $arr[$i-1], -1 );
1417 $x2 = substr( $arr[$i-1], -2, 1 );
1418 if ( $x1 === ' ' ) {
1419 if ( $firstspace == -1 ) {
1422 } elseif ( $x2 === ' ') {
1423 if ( $firstsingleletterword == -1 ) {
1424 $firstsingleletterword = $i;
1427 if ( $firstmultiletterword == -1 ) {
1428 $firstmultiletterword = $i;
1435 # If there is a single-letter word, use it!
1436 if ( $firstsingleletterword > -1 ) {
1437 $arr[$firstsingleletterword] = "''";
1438 $arr[$firstsingleletterword-1] .= "'";
1439 } elseif ( $firstmultiletterword > -1 ) {
1440 # If not, but there's a multi-letter word, use that one.
1441 $arr[$firstmultiletterword] = "''";
1442 $arr[$firstmultiletterword-1] .= "'";
1443 } elseif ( $firstspace > -1 ) {
1444 # ... otherwise use the first one that has neither.
1445 # (notice that it is possible for all three to be -1 if, for example,
1446 # there is only one pentuple-apostrophe in the line)
1447 $arr[$firstspace] = "''";
1448 $arr[$firstspace-1] .= "'";
1452 # Now let's actually convert our apostrophic mush to HTML!
1457 foreach ( $arr as $r ) {
1458 if ( ( $i %
2 ) == 0 ) {
1459 if ( $state === 'both' ) {
1465 if ( strlen( $r ) == 2 ) {
1466 if ( $state === 'i' ) {
1467 $output .= '</i>'; $state = '';
1468 } elseif ( $state === 'bi' ) {
1469 $output .= '</i>'; $state = 'b';
1470 } elseif ( $state === 'ib' ) {
1471 $output .= '</b></i><b>'; $state = 'b';
1472 } elseif ( $state === 'both' ) {
1473 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1474 } else { # $state can be 'b' or ''
1475 $output .= '<i>'; $state .= 'i';
1477 } elseif ( strlen( $r ) == 3 ) {
1478 if ( $state === 'b' ) {
1479 $output .= '</b>'; $state = '';
1480 } elseif ( $state === 'bi' ) {
1481 $output .= '</i></b><i>'; $state = 'i';
1482 } elseif ( $state === 'ib' ) {
1483 $output .= '</b>'; $state = 'i';
1484 } elseif ( $state === 'both' ) {
1485 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1486 } else { # $state can be 'i' or ''
1487 $output .= '<b>'; $state .= 'b';
1489 } elseif ( strlen( $r ) == 5 ) {
1490 if ( $state === 'b' ) {
1491 $output .= '</b><i>'; $state = 'i';
1492 } elseif ( $state === 'i' ) {
1493 $output .= '</i><b>'; $state = 'b';
1494 } elseif ( $state === 'bi' ) {
1495 $output .= '</i></b>'; $state = '';
1496 } elseif ( $state === 'ib' ) {
1497 $output .= '</b></i>'; $state = '';
1498 } elseif ( $state === 'both' ) {
1499 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1500 } else { # ($state == '')
1501 $buffer = ''; $state = 'both';
1507 # Now close all remaining tags. Notice that the order is important.
1508 if ( $state === 'b' ||
$state === 'ib' ) {
1511 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1514 if ( $state === 'bi' ) {
1517 # There might be lonely ''''', so make sure we have a buffer
1518 if ( $state === 'both' && $buffer ) {
1519 $output .= '<b><i>'.$buffer.'</i></b>';
1526 * Replace external links (REL)
1528 * Note: this is all very hackish and the order of execution matters a lot.
1529 * Make sure to run maintenance/parserTests.php if you change this code.
1533 * @param $text string
1535 * @throws MWException
1538 function replaceExternalLinks( $text ) {
1539 wfProfileIn( __METHOD__
);
1541 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1542 if ( $bits === false ) {
1543 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1545 $s = array_shift( $bits );
1548 while ( $i<count( $bits ) ) {
1550 $protocol = $bits[$i++
];
1551 $text = $bits[$i++
];
1552 $trail = $bits[$i++
];
1554 # The characters '<' and '>' (which were escaped by
1555 # removeHTMLtags()) should not be included in
1556 # URLs, per RFC 2396.
1558 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1559 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1560 $url = substr( $url, 0, $m2[0][1] );
1563 # If the link text is an image URL, replace it with an <img> tag
1564 # This happened by accident in the original parser, but some people used it extensively
1565 $img = $this->maybeMakeExternalImage( $text );
1566 if ( $img !== false ) {
1572 # Set linktype for CSS - if URL==text, link is essentially free
1573 $linktype = ( $text === $url ) ?
'free' : 'text';
1575 # No link text, e.g. [http://domain.tld/some.link]
1576 if ( $text == '' ) {
1578 $langObj = $this->getTargetLanguage();
1579 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1580 $linktype = 'autonumber';
1582 # Have link text, e.g. [http://domain.tld/some.link text]s
1584 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1587 $text = $this->getConverterLanguage()->markNoConversion( $text );
1589 $url = Sanitizer
::cleanUrl( $url );
1591 # Use the encoded URL
1592 # This means that users can paste URLs directly into the text
1593 # Funny characters like ö aren't valid in URLs anyway
1594 # This was changed in August 2004
1595 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1596 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1598 # Register link in the output object.
1599 # Replace unnecessary URL escape codes with the referenced character
1600 # This prevents spammers from hiding links from the filters
1601 $pasteurized = self
::replaceUnusualEscapes( $url );
1602 $this->mOutput
->addExternalLink( $pasteurized );
1605 wfProfileOut( __METHOD__
);
1610 * Get an associative array of additional HTML attributes appropriate for a
1611 * particular external link. This currently may include rel => nofollow
1612 * (depending on configuration, namespace, and the URL's domain) and/or a
1613 * target attribute (depending on configuration).
1615 * @param $url String|bool optional URL, to extract the domain from for rel =>
1616 * nofollow if appropriate
1617 * @return Array associative array of HTML attributes
1619 function getExternalLinkAttribs( $url = false ) {
1621 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1622 $ns = $this->mTitle
->getNamespace();
1623 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1624 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1626 $attribs['rel'] = 'nofollow';
1628 if ( $this->mOptions
->getExternalLinkTarget() ) {
1629 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1635 * Replace unusual URL escape codes with their equivalent characters
1637 * @param $url String
1640 * @todo This can merge genuinely required bits in the path or query string,
1641 * breaking legit URLs. A proper fix would treat the various parts of
1642 * the URL differently; as a workaround, just use the output for
1643 * statistical records, not for actual linking/output.
1645 static function replaceUnusualEscapes( $url ) {
1646 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1647 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1651 * Callback function used in replaceUnusualEscapes().
1652 * Replaces unusual URL escape codes with their equivalent character
1654 * @param $matches array
1658 private static function replaceUnusualEscapesCallback( $matches ) {
1659 $char = urldecode( $matches[0] );
1660 $ord = ord( $char );
1661 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1662 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1663 # No, shouldn't be escaped
1666 # Yes, leave it escaped
1672 * make an image if it's allowed, either through the global
1673 * option, through the exception, or through the on-wiki whitelist
1676 * $param $url string
1680 function maybeMakeExternalImage( $url ) {
1681 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1682 $imagesexception = !empty( $imagesfrom );
1684 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1685 if ( $imagesexception && is_array( $imagesfrom ) ) {
1686 $imagematch = false;
1687 foreach ( $imagesfrom as $match ) {
1688 if ( strpos( $url, $match ) === 0 ) {
1693 } elseif ( $imagesexception ) {
1694 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1696 $imagematch = false;
1698 if ( $this->mOptions
->getAllowExternalImages()
1699 ||
( $imagesexception && $imagematch ) ) {
1700 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1702 $text = Linker
::makeExternalImage( $url );
1705 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1706 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1707 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1708 foreach ( $whitelist as $entry ) {
1709 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1710 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1713 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1714 # Image matches a whitelist entry
1715 $text = Linker
::makeExternalImage( $url );
1724 * Process [[ ]] wikilinks
1728 * @return String: processed text
1732 function replaceInternalLinks( $s ) {
1733 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1738 * Process [[ ]] wikilinks (RIL)
1740 * @throws MWException
1741 * @return LinkHolderArray
1745 function replaceInternalLinks2( &$s ) {
1746 wfProfileIn( __METHOD__
);
1748 wfProfileIn( __METHOD__
.'-setup' );
1749 static $tc = FALSE, $e1, $e1_img;
1750 # the % is needed to support urlencoded titles as well
1752 $tc = Title
::legalChars() . '#%';
1753 # Match a link having the form [[namespace:link|alternate]]trail
1754 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1755 # Match cases where there is no "]]", which might still be images
1756 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1759 $holders = new LinkHolderArray( $this );
1761 # split the entire text string on occurrences of [[
1762 $a = StringUtils
::explode( '[[', ' ' . $s );
1763 # get the first element (all text up to first [[), and remove the space we added
1766 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1767 $s = substr( $s, 1 );
1769 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1771 if ( $useLinkPrefixExtension ) {
1772 # Match the end of a line for a word that's not followed by whitespace,
1773 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1774 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1777 if ( is_null( $this->mTitle
) ) {
1778 wfProfileOut( __METHOD__
.'-setup' );
1779 wfProfileOut( __METHOD__
);
1780 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1782 $nottalk = !$this->mTitle
->isTalkPage();
1784 if ( $useLinkPrefixExtension ) {
1786 if ( preg_match( $e2, $s, $m ) ) {
1787 $first_prefix = $m[2];
1789 $first_prefix = false;
1795 if ( $this->getConverterLanguage()->hasVariants() ) {
1796 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1797 $this->mTitle
->getPrefixedText() );
1799 $selflink = array( $this->mTitle
->getPrefixedText() );
1801 $useSubpages = $this->areSubpagesAllowed();
1802 wfProfileOut( __METHOD__
.'-setup' );
1804 # Loop for each link
1805 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1806 # Check for excessive memory usage
1807 if ( $holders->isBig() ) {
1809 # Do the existence check, replace the link holders and clear the array
1810 $holders->replace( $s );
1814 if ( $useLinkPrefixExtension ) {
1815 wfProfileIn( __METHOD__
.'-prefixhandling' );
1816 if ( preg_match( $e2, $s, $m ) ) {
1823 if ( $first_prefix ) {
1824 $prefix = $first_prefix;
1825 $first_prefix = false;
1827 wfProfileOut( __METHOD__
.'-prefixhandling' );
1830 $might_be_img = false;
1832 wfProfileIn( __METHOD__
."-e1" );
1833 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1835 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1836 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1837 # the real problem is with the $e1 regex
1840 # Still some problems for cases where the ] is meant to be outside punctuation,
1841 # and no image is in sight. See bug 2095.
1843 if ( $text !== '' &&
1844 substr( $m[3], 0, 1 ) === ']' &&
1845 strpos( $text, '[' ) !== false
1848 $text .= ']'; # so that replaceExternalLinks($text) works later
1849 $m[3] = substr( $m[3], 1 );
1851 # fix up urlencoded title texts
1852 if ( strpos( $m[1], '%' ) !== false ) {
1853 # Should anchors '#' also be rejected?
1854 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1857 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1858 $might_be_img = true;
1860 if ( strpos( $m[1], '%' ) !== false ) {
1861 $m[1] = rawurldecode( $m[1] );
1864 } else { # Invalid form; output directly
1865 $s .= $prefix . '[[' . $line ;
1866 wfProfileOut( __METHOD__
."-e1" );
1869 wfProfileOut( __METHOD__
."-e1" );
1870 wfProfileIn( __METHOD__
."-misc" );
1872 # Don't allow internal links to pages containing
1873 # PROTO: where PROTO is a valid URL protocol; these
1874 # should be external links.
1875 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1876 $s .= $prefix . '[[' . $line ;
1877 wfProfileOut( __METHOD__
."-misc" );
1881 # Make subpage if necessary
1882 if ( $useSubpages ) {
1883 $link = $this->maybeDoSubpageLink( $m[1], $text );
1888 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1890 # Strip off leading ':'
1891 $link = substr( $link, 1 );
1894 wfProfileOut( __METHOD__
."-misc" );
1895 wfProfileIn( __METHOD__
."-title" );
1896 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1897 if ( $nt === null ) {
1898 $s .= $prefix . '[[' . $line;
1899 wfProfileOut( __METHOD__
."-title" );
1903 $ns = $nt->getNamespace();
1904 $iw = $nt->getInterWiki();
1905 wfProfileOut( __METHOD__
."-title" );
1907 if ( $might_be_img ) { # if this is actually an invalid link
1908 wfProfileIn( __METHOD__
."-might_be_img" );
1909 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1912 # look at the next 'line' to see if we can close it there
1914 $next_line = $a->current();
1915 if ( $next_line === false ||
$next_line === null ) {
1918 $m = explode( ']]', $next_line, 3 );
1919 if ( count( $m ) == 3 ) {
1920 # the first ]] closes the inner link, the second the image
1922 $text .= "[[{$m[0]}]]{$m[1]}";
1925 } elseif ( count( $m ) == 2 ) {
1926 # if there's exactly one ]] that's fine, we'll keep looking
1927 $text .= "[[{$m[0]}]]{$m[1]}";
1929 # if $next_line is invalid too, we need look no further
1930 $text .= '[[' . $next_line;
1935 # we couldn't find the end of this imageLink, so output it raw
1936 # but don't ignore what might be perfectly normal links in the text we've examined
1937 $holders->merge( $this->replaceInternalLinks2( $text ) );
1938 $s .= "{$prefix}[[$link|$text";
1939 # note: no $trail, because without an end, there *is* no trail
1940 wfProfileOut( __METHOD__
."-might_be_img" );
1943 } else { # it's not an image, so output it raw
1944 $s .= "{$prefix}[[$link|$text";
1945 # note: no $trail, because without an end, there *is* no trail
1946 wfProfileOut( __METHOD__
."-might_be_img" );
1949 wfProfileOut( __METHOD__
."-might_be_img" );
1952 $wasblank = ( $text == '' );
1956 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1957 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1958 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1959 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1960 $text = $this->doQuotes( $text );
1963 # Link not escaped by : , create the various objects
1966 wfProfileIn( __METHOD__
."-interwiki" );
1967 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1968 // XXX: the above check prevents links to sites with identifiers that are not language codes
1970 # Bug 24502: filter duplicates
1971 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1972 $this->mLangLinkLanguages
[$iw] = true;
1973 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1976 $s = rtrim( $s . $prefix );
1977 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1978 wfProfileOut( __METHOD__
."-interwiki" );
1981 wfProfileOut( __METHOD__
."-interwiki" );
1983 if ( $ns == NS_FILE
) {
1984 wfProfileIn( __METHOD__
."-image" );
1985 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1987 # if no parameters were passed, $text
1988 # becomes something like "File:Foo.png",
1989 # which we don't want to pass on to the
1993 # recursively parse links inside the image caption
1994 # actually, this will parse them in any other parameters, too,
1995 # but it might be hard to fix that, and it doesn't matter ATM
1996 $text = $this->replaceExternalLinks( $text );
1997 $holders->merge( $this->replaceInternalLinks2( $text ) );
1999 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2000 $s .= $prefix . $this->armorLinks(
2001 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2003 $s .= $prefix . $trail;
2005 wfProfileOut( __METHOD__
."-image" );
2009 if ( $ns == NS_CATEGORY
) {
2010 wfProfileIn( __METHOD__
."-category" );
2011 $s = rtrim( $s . "\n" ); # bug 87
2014 $sortkey = $this->getDefaultSort();
2018 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2019 $sortkey = str_replace( "\n", '', $sortkey );
2020 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2021 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2024 * Strip the whitespace Category links produce, see bug 87
2025 * @todo We might want to use trim($tmp, "\n") here.
2027 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2029 wfProfileOut( __METHOD__
."-category" );
2034 # Self-link checking
2035 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2036 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2037 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2042 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2043 # @todo FIXME: Should do batch file existence checks, see comment below
2044 if ( $ns == NS_MEDIA
) {
2045 wfProfileIn( __METHOD__
."-media" );
2046 # Give extensions a chance to select the file revision for us
2049 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2050 array( $this, $nt, &$options, &$descQuery ) );
2051 # Fetch and register the file (file title may be different via hooks)
2052 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2053 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2054 $s .= $prefix . $this->armorLinks(
2055 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2056 wfProfileOut( __METHOD__
."-media" );
2060 wfProfileIn( __METHOD__
."-always_known" );
2061 # Some titles, such as valid special pages or files in foreign repos, should
2062 # be shown as bluelinks even though they're not included in the page table
2064 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2065 # batch file existence checks for NS_FILE and NS_MEDIA
2066 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2067 $this->mOutput
->addLink( $nt );
2068 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2070 # Links will be added to the output link list after checking
2071 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2073 wfProfileOut( __METHOD__
."-always_known" );
2075 wfProfileOut( __METHOD__
);
2080 * Render a forced-blue link inline; protect against double expansion of
2081 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2082 * Since this little disaster has to split off the trail text to avoid
2083 * breaking URLs in the following text without breaking trails on the
2084 * wiki links, it's been made into a horrible function.
2087 * @param $text String
2088 * @param $query Array or String
2089 * @param $trail String
2090 * @param $prefix String
2091 * @return String: HTML-wikitext mix oh yuck
2093 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2094 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2096 if ( is_string( $query ) ) {
2097 $query = wfCgiToArray( $query );
2099 if ( $text == '' ) {
2100 $text = htmlspecialchars( $nt->getPrefixedText() );
2103 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2105 return $this->armorLinks( $link ) . $trail;
2109 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2110 * going to go through further parsing steps before inline URL expansion.
2112 * Not needed quite as much as it used to be since free links are a bit
2113 * more sensible these days. But bracketed links are still an issue.
2115 * @param $text String: more-or-less HTML
2116 * @return String: less-or-more HTML with NOPARSE bits
2118 function armorLinks( $text ) {
2119 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2120 "{$this->mUniqPrefix}NOPARSE$1", $text );
2124 * Return true if subpage links should be expanded on this page.
2127 function areSubpagesAllowed() {
2128 # Some namespaces don't allow subpages
2129 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2133 * Handle link to subpage if necessary
2135 * @param $target String: the source of the link
2136 * @param &$text String: the link text, modified as necessary
2137 * @return string the full name of the link
2140 function maybeDoSubpageLink( $target, &$text ) {
2141 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2145 * Used by doBlockLevels()
2150 function closeParagraph() {
2152 if ( $this->mLastSection
!= '' ) {
2153 $result = '</' . $this->mLastSection
. ">\n";
2155 $this->mInPre
= false;
2156 $this->mLastSection
= '';
2161 * getCommon() returns the length of the longest common substring
2162 * of both arguments, starting at the beginning of both.
2165 * @param $st1 string
2166 * @param $st2 string
2170 function getCommon( $st1, $st2 ) {
2171 $fl = strlen( $st1 );
2172 $shorter = strlen( $st2 );
2173 if ( $fl < $shorter ) {
2177 for ( $i = 0; $i < $shorter; ++
$i ) {
2178 if ( $st1[$i] != $st2[$i] ) {
2186 * These next three functions open, continue, and close the list
2187 * element appropriate to the prefix character passed into them.
2190 * @param $char string
2194 function openList( $char ) {
2195 $result = $this->closeParagraph();
2197 if ( '*' === $char ) {
2198 $result .= '<ul><li>';
2199 } elseif ( '#' === $char ) {
2200 $result .= '<ol><li>';
2201 } elseif ( ':' === $char ) {
2202 $result .= '<dl><dd>';
2203 } elseif ( ';' === $char ) {
2204 $result .= '<dl><dt>';
2205 $this->mDTopen
= true;
2207 $result = '<!-- ERR 1 -->';
2215 * @param $char String
2220 function nextItem( $char ) {
2221 if ( '*' === $char ||
'#' === $char ) {
2223 } elseif ( ':' === $char ||
';' === $char ) {
2225 if ( $this->mDTopen
) {
2228 if ( ';' === $char ) {
2229 $this->mDTopen
= true;
2230 return $close . '<dt>';
2232 $this->mDTopen
= false;
2233 return $close . '<dd>';
2236 return '<!-- ERR 2 -->';
2241 * @param $char String
2246 function closeList( $char ) {
2247 if ( '*' === $char ) {
2248 $text = '</li></ul>';
2249 } elseif ( '#' === $char ) {
2250 $text = '</li></ol>';
2251 } elseif ( ':' === $char ) {
2252 if ( $this->mDTopen
) {
2253 $this->mDTopen
= false;
2254 $text = '</dt></dl>';
2256 $text = '</dd></dl>';
2259 return '<!-- ERR 3 -->';
2266 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2268 * @param $text String
2269 * @param $linestart Boolean: whether or not this is at the start of a line.
2271 * @return string the lists rendered as HTML
2273 function doBlockLevels( $text, $linestart ) {
2274 wfProfileIn( __METHOD__
);
2276 # Parsing through the text line by line. The main thing
2277 # happening here is handling of block-level elements p, pre,
2278 # and making lists from lines starting with * # : etc.
2280 $textLines = StringUtils
::explode( "\n", $text );
2282 $lastPrefix = $output = '';
2283 $this->mDTopen
= $inBlockElem = false;
2285 $paragraphStack = false;
2287 foreach ( $textLines as $oLine ) {
2289 if ( !$linestart ) {
2299 $lastPrefixLength = strlen( $lastPrefix );
2300 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2301 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2302 # If not in a <pre> element, scan for and figure out what prefixes are there.
2303 if ( !$this->mInPre
) {
2304 # Multiple prefixes may abut each other for nested lists.
2305 $prefixLength = strspn( $oLine, '*#:;' );
2306 $prefix = substr( $oLine, 0, $prefixLength );
2309 # ; and : are both from definition-lists, so they're equivalent
2310 # for the purposes of determining whether or not we need to open/close
2312 $prefix2 = str_replace( ';', ':', $prefix );
2313 $t = substr( $oLine, $prefixLength );
2314 $this->mInPre
= (bool)$preOpenMatch;
2316 # Don't interpret any other prefixes in preformatted text
2318 $prefix = $prefix2 = '';
2323 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2324 # Same as the last item, so no need to deal with nesting or opening stuff
2325 $output .= $this->nextItem( substr( $prefix, -1 ) );
2326 $paragraphStack = false;
2328 if ( substr( $prefix, -1 ) === ';') {
2329 # The one nasty exception: definition lists work like this:
2330 # ; title : definition text
2331 # So we check for : in the remainder text to split up the
2332 # title and definition, without b0rking links.
2334 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2336 $output .= $term . $this->nextItem( ':' );
2339 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2340 # We need to open or close prefixes, or both.
2342 # Either open or close a level...
2343 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2344 $paragraphStack = false;
2346 # Close all the prefixes which aren't shared.
2347 while ( $commonPrefixLength < $lastPrefixLength ) {
2348 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2349 --$lastPrefixLength;
2352 # Continue the current prefix if appropriate.
2353 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2354 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2357 # Open prefixes where appropriate.
2358 while ( $prefixLength > $commonPrefixLength ) {
2359 $char = substr( $prefix, $commonPrefixLength, 1 );
2360 $output .= $this->openList( $char );
2362 if ( ';' === $char ) {
2363 # @todo FIXME: This is dupe of code above
2364 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2366 $output .= $term . $this->nextItem( ':' );
2369 ++
$commonPrefixLength;
2371 $lastPrefix = $prefix2;
2374 # If we have no prefixes, go to paragraph mode.
2375 if ( 0 == $prefixLength ) {
2376 wfProfileIn( __METHOD__
."-paragraph" );
2377 # No prefix (not in list)--go to paragraph mode
2378 # XXX: use a stack for nestable elements like span, table and div
2379 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2380 $closematch = preg_match(
2381 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2382 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2383 if ( $openmatch or $closematch ) {
2384 $paragraphStack = false;
2385 # TODO bug 5718: paragraph closed
2386 $output .= $this->closeParagraph();
2387 if ( $preOpenMatch and !$preCloseMatch ) {
2388 $this->mInPre
= true;
2390 $inBlockElem = !$closematch;
2391 } elseif ( !$inBlockElem && !$this->mInPre
) {
2392 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2394 if ( $this->mLastSection
!== 'pre' ) {
2395 $paragraphStack = false;
2396 $output .= $this->closeParagraph().'<pre>';
2397 $this->mLastSection
= 'pre';
2399 $t = substr( $t, 1 );
2402 if ( trim( $t ) === '' ) {
2403 if ( $paragraphStack ) {
2404 $output .= $paragraphStack.'<br />';
2405 $paragraphStack = false;
2406 $this->mLastSection
= 'p';
2408 if ( $this->mLastSection
!== 'p' ) {
2409 $output .= $this->closeParagraph();
2410 $this->mLastSection
= '';
2411 $paragraphStack = '<p>';
2413 $paragraphStack = '</p><p>';
2417 if ( $paragraphStack ) {
2418 $output .= $paragraphStack;
2419 $paragraphStack = false;
2420 $this->mLastSection
= 'p';
2421 } elseif ( $this->mLastSection
!== 'p' ) {
2422 $output .= $this->closeParagraph().'<p>';
2423 $this->mLastSection
= 'p';
2428 wfProfileOut( __METHOD__
."-paragraph" );
2430 # somewhere above we forget to get out of pre block (bug 785)
2431 if ( $preCloseMatch && $this->mInPre
) {
2432 $this->mInPre
= false;
2434 if ( $paragraphStack === false ) {
2438 while ( $prefixLength ) {
2439 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2442 if ( $this->mLastSection
!= '' ) {
2443 $output .= '</' . $this->mLastSection
. '>';
2444 $this->mLastSection
= '';
2447 wfProfileOut( __METHOD__
);
2452 * Split up a string on ':', ignoring any occurrences inside tags
2453 * to prevent illegal overlapping.
2455 * @param $str String the string to split
2456 * @param &$before String set to everything before the ':'
2457 * @param &$after String set to everything after the ':'
2458 * @throws MWException
2459 * @return String the position of the ':', or false if none found
2461 function findColonNoLinks( $str, &$before, &$after ) {
2462 wfProfileIn( __METHOD__
);
2464 $pos = strpos( $str, ':' );
2465 if ( $pos === false ) {
2467 wfProfileOut( __METHOD__
);
2471 $lt = strpos( $str, '<' );
2472 if ( $lt === false ||
$lt > $pos ) {
2473 # Easy; no tag nesting to worry about
2474 $before = substr( $str, 0, $pos );
2475 $after = substr( $str, $pos+
1 );
2476 wfProfileOut( __METHOD__
);
2480 # Ugly state machine to walk through avoiding tags.
2481 $state = self
::COLON_STATE_TEXT
;
2483 $len = strlen( $str );
2484 for( $i = 0; $i < $len; $i++
) {
2488 # (Using the number is a performance hack for common cases)
2489 case 0: # self::COLON_STATE_TEXT:
2492 # Could be either a <start> tag or an </end> tag
2493 $state = self
::COLON_STATE_TAGSTART
;
2496 if ( $stack == 0 ) {
2498 $before = substr( $str, 0, $i );
2499 $after = substr( $str, $i +
1 );
2500 wfProfileOut( __METHOD__
);
2503 # Embedded in a tag; don't break it.
2506 # Skip ahead looking for something interesting
2507 $colon = strpos( $str, ':', $i );
2508 if ( $colon === false ) {
2509 # Nothing else interesting
2510 wfProfileOut( __METHOD__
);
2513 $lt = strpos( $str, '<', $i );
2514 if ( $stack === 0 ) {
2515 if ( $lt === false ||
$colon < $lt ) {
2517 $before = substr( $str, 0, $colon );
2518 $after = substr( $str, $colon +
1 );
2519 wfProfileOut( __METHOD__
);
2523 if ( $lt === false ) {
2524 # Nothing else interesting to find; abort!
2525 # We're nested, but there's no close tags left. Abort!
2528 # Skip ahead to next tag start
2530 $state = self
::COLON_STATE_TAGSTART
;
2533 case 1: # self::COLON_STATE_TAG:
2538 $state = self
::COLON_STATE_TEXT
;
2541 # Slash may be followed by >?
2542 $state = self
::COLON_STATE_TAGSLASH
;
2548 case 2: # self::COLON_STATE_TAGSTART:
2551 $state = self
::COLON_STATE_CLOSETAG
;
2554 $state = self
::COLON_STATE_COMMENT
;
2557 # Illegal early close? This shouldn't happen D:
2558 $state = self
::COLON_STATE_TEXT
;
2561 $state = self
::COLON_STATE_TAG
;
2564 case 3: # self::COLON_STATE_CLOSETAG:
2569 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2570 wfProfileOut( __METHOD__
);
2573 $state = self
::COLON_STATE_TEXT
;
2576 case self
::COLON_STATE_TAGSLASH
:
2578 # Yes, a self-closed tag <blah/>
2579 $state = self
::COLON_STATE_TEXT
;
2581 # Probably we're jumping the gun, and this is an attribute
2582 $state = self
::COLON_STATE_TAG
;
2585 case 5: # self::COLON_STATE_COMMENT:
2587 $state = self
::COLON_STATE_COMMENTDASH
;
2590 case self
::COLON_STATE_COMMENTDASH
:
2592 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2594 $state = self
::COLON_STATE_COMMENT
;
2597 case self
::COLON_STATE_COMMENTDASHDASH
:
2599 $state = self
::COLON_STATE_TEXT
;
2601 $state = self
::COLON_STATE_COMMENT
;
2605 throw new MWException( "State machine error in " . __METHOD__
);
2609 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2610 wfProfileOut( __METHOD__
);
2613 wfProfileOut( __METHOD__
);
2618 * Return value of a magic variable (like PAGENAME)
2622 * @param $index integer
2623 * @param bool|\PPFrame $frame
2625 * @throws MWException
2628 function getVariableValue( $index, $frame = false ) {
2629 global $wgContLang, $wgSitename, $wgServer;
2630 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2632 if ( is_null( $this->mTitle
) ) {
2633 // If no title set, bad things are going to happen
2634 // later. Title should always be set since this
2635 // should only be called in the middle of a parse
2636 // operation (but the unit-tests do funky stuff)
2637 throw new MWException( __METHOD__
. ' Should only be '
2638 . ' called while parsing (no title set)' );
2642 * Some of these require message or data lookups and can be
2643 * expensive to check many times.
2645 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2646 if ( isset( $this->mVarCache
[$index] ) ) {
2647 return $this->mVarCache
[$index];
2651 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2652 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2655 global $wgLocaltimezone;
2656 if ( isset( $wgLocaltimezone ) ) {
2657 $oldtz = date_default_timezone_get();
2658 date_default_timezone_set( $wgLocaltimezone );
2661 $localTimestamp = date( 'YmdHis', $ts );
2662 $localMonth = date( 'm', $ts );
2663 $localMonth1 = date( 'n', $ts );
2664 $localMonthName = date( 'n', $ts );
2665 $localDay = date( 'j', $ts );
2666 $localDay2 = date( 'd', $ts );
2667 $localDayOfWeek = date( 'w', $ts );
2668 $localWeek = date( 'W', $ts );
2669 $localYear = date( 'Y', $ts );
2670 $localHour = date( 'H', $ts );
2671 if ( isset( $wgLocaltimezone ) ) {
2672 date_default_timezone_set( $oldtz );
2675 $pageLang = $this->getFunctionLang();
2678 case 'currentmonth':
2679 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2681 case 'currentmonth1':
2682 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2684 case 'currentmonthname':
2685 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2687 case 'currentmonthnamegen':
2688 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2690 case 'currentmonthabbrev':
2691 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2694 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2697 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2700 $value = $pageLang->formatNum( $localMonth );
2703 $value = $pageLang->formatNum( $localMonth1 );
2705 case 'localmonthname':
2706 $value = $pageLang->getMonthName( $localMonthName );
2708 case 'localmonthnamegen':
2709 $value = $pageLang->getMonthNameGen( $localMonthName );
2711 case 'localmonthabbrev':
2712 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2715 $value = $pageLang->formatNum( $localDay );
2718 $value = $pageLang->formatNum( $localDay2 );
2721 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2724 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2726 case 'fullpagename':
2727 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2729 case 'fullpagenamee':
2730 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2733 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2735 case 'subpagenamee':
2736 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2738 case 'basepagename':
2739 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2741 case 'basepagenamee':
2742 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2744 case 'talkpagename':
2745 if ( $this->mTitle
->canTalk() ) {
2746 $talkPage = $this->mTitle
->getTalkPage();
2747 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2752 case 'talkpagenamee':
2753 if ( $this->mTitle
->canTalk() ) {
2754 $talkPage = $this->mTitle
->getTalkPage();
2755 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2760 case 'subjectpagename':
2761 $subjPage = $this->mTitle
->getSubjectPage();
2762 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2764 case 'subjectpagenamee':
2765 $subjPage = $this->mTitle
->getSubjectPage();
2766 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2768 case 'pageid': // requested in bug 23427
2769 $pageid = $this->getTitle()->getArticleId();
2770 if( $pageid == 0 ) {
2771 # 0 means the page doesn't exist in the database,
2772 # which means the user is previewing a new page.
2773 # The vary-revision flag must be set, because the magic word
2774 # will have a different value once the page is saved.
2775 $this->mOutput
->setFlag( 'vary-revision' );
2776 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2778 $value = $pageid ?
$pageid : null;
2781 # Let the edit saving system know we should parse the page
2782 # *after* a revision ID has been assigned.
2783 $this->mOutput
->setFlag( 'vary-revision' );
2784 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2785 $value = $this->mRevisionId
;
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__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2792 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2794 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2799 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2801 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2806 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2808 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2813 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2815 case 'revisionyear':
2816 # Let the edit saving system know we should parse the page
2817 # *after* a revision ID has been assigned. This is for null edits.
2818 $this->mOutput
->setFlag( 'vary-revision' );
2819 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2820 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2822 case 'revisiontimestamp':
2823 # Let the edit saving system know we should parse the page
2824 # *after* a revision ID has been assigned. This is for null edits.
2825 $this->mOutput
->setFlag( 'vary-revision' );
2826 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2827 $value = $this->getRevisionTimestamp();
2829 case 'revisionuser':
2830 # Let the edit saving system know we should parse the page
2831 # *after* a revision ID has been assigned. This is for null edits.
2832 $this->mOutput
->setFlag( 'vary-revision' );
2833 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2834 $value = $this->getRevisionUser();
2837 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2840 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2842 case 'namespacenumber':
2843 $value = $this->mTitle
->getNamespace();
2846 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2849 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2851 case 'subjectspace':
2852 $value = $this->mTitle
->getSubjectNsText();
2854 case 'subjectspacee':
2855 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2857 case 'currentdayname':
2858 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2861 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2864 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2867 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2870 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2871 # int to remove the padding
2872 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2875 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2877 case 'localdayname':
2878 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2881 $value = $pageLang->formatNum( $localYear, true );
2884 $value = $pageLang->time( $localTimestamp, false, false );
2887 $value = $pageLang->formatNum( $localHour, true );
2890 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2891 # int to remove the padding
2892 $value = $pageLang->formatNum( (int)$localWeek );
2895 $value = $pageLang->formatNum( $localDayOfWeek );
2897 case 'numberofarticles':
2898 $value = $pageLang->formatNum( SiteStats
::articles() );
2900 case 'numberoffiles':
2901 $value = $pageLang->formatNum( SiteStats
::images() );
2903 case 'numberofusers':
2904 $value = $pageLang->formatNum( SiteStats
::users() );
2906 case 'numberofactiveusers':
2907 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2909 case 'numberofpages':
2910 $value = $pageLang->formatNum( SiteStats
::pages() );
2912 case 'numberofadmins':
2913 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2915 case 'numberofedits':
2916 $value = $pageLang->formatNum( SiteStats
::edits() );
2918 case 'numberofviews':
2919 global $wgDisableCounters;
2920 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2922 case 'currenttimestamp':
2923 $value = wfTimestamp( TS_MW
, $ts );
2925 case 'localtimestamp':
2926 $value = $localTimestamp;
2928 case 'currentversion':
2929 $value = SpecialVersion
::getVersion();
2932 return $wgArticlePath;
2938 $serverParts = wfParseUrl( $wgServer );
2939 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2941 return $wgScriptPath;
2943 return $wgStylePath;
2944 case 'directionmark':
2945 return $pageLang->getDirMark();
2946 case 'contentlanguage':
2947 global $wgLanguageCode;
2948 return $wgLanguageCode;
2951 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2959 $this->mVarCache
[$index] = $value;
2966 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2970 function initialiseVariables() {
2971 wfProfileIn( __METHOD__
);
2972 $variableIDs = MagicWord
::getVariableIDs();
2973 $substIDs = MagicWord
::getSubstIDs();
2975 $this->mVariables
= new MagicWordArray( $variableIDs );
2976 $this->mSubstWords
= new MagicWordArray( $substIDs );
2977 wfProfileOut( __METHOD__
);
2981 * Preprocess some wikitext and return the document tree.
2982 * This is the ghost of replace_variables().
2984 * @param $text String: The text to parse
2985 * @param $flags Integer: bitwise combination of:
2986 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2987 * included. Default is to assume a direct page view.
2989 * The generated DOM tree must depend only on the input text and the flags.
2990 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2992 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2993 * change in the DOM tree for a given text, must be passed through the section identifier
2994 * in the section edit link and thus back to extractSections().
2996 * The output of this function is currently only cached in process memory, but a persistent
2997 * cache may be implemented at a later date which takes further advantage of these strict
2998 * dependency requirements.
3004 function preprocessToDom( $text, $flags = 0 ) {
3005 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3010 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3016 public static function splitWhitespace( $s ) {
3017 $ltrimmed = ltrim( $s );
3018 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3019 $trimmed = rtrim( $ltrimmed );
3020 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3022 $w2 = substr( $ltrimmed, -$diff );
3026 return array( $w1, $trimmed, $w2 );
3030 * Replace magic variables, templates, and template arguments
3031 * with the appropriate text. Templates are substituted recursively,
3032 * taking care to avoid infinite loops.
3034 * Note that the substitution depends on value of $mOutputType:
3035 * self::OT_WIKI: only {{subst:}} templates
3036 * self::OT_PREPROCESS: templates but not extension tags
3037 * self::OT_HTML: all templates and extension tags
3039 * @param $text String the text to transform
3040 * @param $frame PPFrame Object describing the arguments passed to the template.
3041 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3042 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3043 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3048 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3049 # Is there any text? Also, Prevent too big inclusions!
3050 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3053 wfProfileIn( __METHOD__
);
3055 if ( $frame === false ) {
3056 $frame = $this->getPreprocessor()->newFrame();
3057 } elseif ( !( $frame instanceof PPFrame
) ) {
3058 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3059 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3062 $dom = $this->preprocessToDom( $text );
3063 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3064 $text = $frame->expand( $dom, $flags );
3066 wfProfileOut( __METHOD__
);
3071 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3073 * @param $args array
3077 static function createAssocArgs( $args ) {
3078 $assocArgs = array();
3080 foreach ( $args as $arg ) {
3081 $eqpos = strpos( $arg, '=' );
3082 if ( $eqpos === false ) {
3083 $assocArgs[$index++
] = $arg;
3085 $name = trim( substr( $arg, 0, $eqpos ) );
3086 $value = trim( substr( $arg, $eqpos+
1 ) );
3087 if ( $value === false ) {
3090 if ( $name !== false ) {
3091 $assocArgs[$name] = $value;
3100 * Warn the user when a parser limitation is reached
3101 * Will warn at most once the user per limitation type
3103 * @param $limitationType String: should be one of:
3104 * 'expensive-parserfunction' (corresponding messages:
3105 * 'expensive-parserfunction-warning',
3106 * 'expensive-parserfunction-category')
3107 * 'post-expand-template-argument' (corresponding messages:
3108 * 'post-expand-template-argument-warning',
3109 * 'post-expand-template-argument-category')
3110 * 'post-expand-template-inclusion' (corresponding messages:
3111 * 'post-expand-template-inclusion-warning',
3112 * 'post-expand-template-inclusion-category')
3113 * @param $current int|null Current value
3114 * @param $max int|null Maximum allowed, when an explicit limit has been
3115 * exceeded, provide the values (optional)
3117 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3118 # does no harm if $current and $max are present but are unnecessary for the message
3119 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3120 ->inContentLanguage()->escaped();
3121 $this->mOutput
->addWarning( $warning );
3122 $this->addTrackingCategory( "$limitationType-category" );
3126 * Return the text of a template, after recursively
3127 * replacing any variables or templates within the template.
3129 * @param $piece Array: the parts of the template
3130 * $piece['title']: the title, i.e. the part before the |
3131 * $piece['parts']: the parameter array
3132 * $piece['lineStart']: whether the brace was at the start of a line
3133 * @param $frame PPFrame The current frame, contains template arguments
3134 * @throws MWException
3135 * @return String: the text of the template
3138 function braceSubstitution( $piece, $frame ) {
3140 wfProfileIn( __METHOD__
);
3141 wfProfileIn( __METHOD__
.'-setup' );
3144 $found = false; # $text has been filled
3145 $nowiki = false; # wiki markup in $text should be escaped
3146 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3147 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3148 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3149 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3151 # Title object, where $text came from
3154 # $part1 is the bit before the first |, and must contain only title characters.
3155 # Various prefixes will be stripped from it later.
3156 $titleWithSpaces = $frame->expand( $piece['title'] );
3157 $part1 = trim( $titleWithSpaces );
3160 # Original title text preserved for various purposes
3161 $originalTitle = $part1;
3163 # $args is a list of argument nodes, starting from index 0, not including $part1
3164 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3165 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3166 wfProfileOut( __METHOD__
.'-setup' );
3168 $titleProfileIn = null; // profile templates
3171 wfProfileIn( __METHOD__
.'-modifiers' );
3174 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3176 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3177 # Decide whether to expand template or keep wikitext as-is.
3178 if ( $this->ot
['wiki'] ) {
3179 if ( $substMatch === false ) {
3180 $literal = true; # literal when in PST with no prefix
3182 $literal = false; # expand when in PST with subst: or safesubst:
3185 if ( $substMatch == 'subst' ) {
3186 $literal = true; # literal when not in PST with plain subst:
3188 $literal = false; # expand when not in PST with safesubst: or no prefix
3192 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3199 if ( !$found && $args->getLength() == 0 ) {
3200 $id = $this->mVariables
->matchStartToEnd( $part1 );
3201 if ( $id !== false ) {
3202 $text = $this->getVariableValue( $id, $frame );
3203 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3204 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3210 # MSG, MSGNW and RAW
3213 $mwMsgnw = MagicWord
::get( 'msgnw' );
3214 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3217 # Remove obsolete MSG:
3218 $mwMsg = MagicWord
::get( 'msg' );
3219 $mwMsg->matchStartAndRemove( $part1 );
3223 $mwRaw = MagicWord
::get( 'raw' );
3224 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3225 $forceRawInterwiki = true;
3228 wfProfileOut( __METHOD__
.'-modifiers' );
3232 wfProfileIn( __METHOD__
. '-pfunc' );
3234 $colonPos = strpos( $part1, ':' );
3235 if ( $colonPos !== false ) {
3236 # Case sensitive functions
3237 $function = substr( $part1, 0, $colonPos );
3238 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3239 $function = $this->mFunctionSynonyms
[1][$function];
3241 # Case insensitive functions
3242 $function = $wgContLang->lc( $function );
3243 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3244 $function = $this->mFunctionSynonyms
[0][$function];
3250 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3251 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3252 $initialArgs = array( &$this );
3253 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3254 if ( $flags & SFH_OBJECT_ARGS
) {
3255 # Add a frame parameter, and pass the arguments as an array
3256 $allArgs = $initialArgs;
3257 $allArgs[] = $frame;
3258 for ( $i = 0; $i < $args->getLength(); $i++
) {
3259 $funcArgs[] = $args->item( $i );
3261 $allArgs[] = $funcArgs;
3263 # Convert arguments to plain text
3264 for ( $i = 0; $i < $args->getLength(); $i++
) {
3265 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3267 $allArgs = array_merge( $initialArgs, $funcArgs );
3270 # Workaround for PHP bug 35229 and similar
3271 if ( !is_callable( $callback ) ) {
3272 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3273 wfProfileOut( __METHOD__
. '-pfunc' );
3274 wfProfileOut( __METHOD__
);
3275 throw new MWException( "Tag hook for $function is not callable\n" );
3277 $result = call_user_func_array( $callback, $allArgs );
3280 $preprocessFlags = 0;
3282 if ( is_array( $result ) ) {
3283 if ( isset( $result[0] ) ) {
3285 unset( $result[0] );
3288 # Extract flags into the local scope
3289 # This allows callers to set flags such as nowiki, found, etc.
3295 $text = $this->preprocessToDom( $text, $preprocessFlags );
3298 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3301 wfProfileOut( __METHOD__
. '-pfunc' );
3304 # Finish mangling title and then check for loops.
3305 # Set $title to a Title object and $titleText to the PDBK
3308 # Split the title into page and subpage
3310 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3311 if ( $subpage !== '' ) {
3312 $ns = $this->mTitle
->getNamespace();
3314 $title = Title
::newFromText( $part1, $ns );
3316 $titleText = $title->getPrefixedText();
3317 # Check for language variants if the template is not found
3318 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3319 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3321 # Do recursion depth check
3322 $limit = $this->mOptions
->getMaxTemplateDepth();
3323 if ( $frame->depth
>= $limit ) {
3325 $text = '<span class="error">'
3326 . wfMessage( 'parser-template-recursion-depth-warning' )
3327 ->numParams( $limit )->inContentLanguage()->text()
3333 # Load from database
3334 if ( !$found && $title ) {
3335 if ( !Profiler
::instance()->isPersistent() ) {
3336 # Too many unique items can kill profiling DBs/collectors
3337 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3338 wfProfileIn( $titleProfileIn ); // template in
3340 wfProfileIn( __METHOD__
. '-loadtpl' );
3341 if ( !$title->isExternal() ) {
3342 if ( $title->isSpecialPage()
3343 && $this->mOptions
->getAllowSpecialInclusion()
3344 && $this->ot
['html'] )
3346 // Pass the template arguments as URL parameters.
3347 // "uselang" will have no effect since the Language object
3348 // is forced to the one defined in ParserOptions.
3349 $pageArgs = array();
3350 for ( $i = 0; $i < $args->getLength(); $i++
) {
3351 $bits = $args->item( $i )->splitArg();
3352 if ( strval( $bits['index'] ) === '' ) {
3353 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3354 $value = trim( $frame->expand( $bits['value'] ) );
3355 $pageArgs[$name] = $value;
3359 // Create a new context to execute the special page
3360 $context = new RequestContext
;
3361 $context->setTitle( $title );
3362 $context->setRequest( new FauxRequest( $pageArgs ) );
3363 $context->setUser( $this->getUser() );
3364 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3365 $ret = SpecialPageFactory
::capturePath( $title, $context );
3367 $text = $context->getOutput()->getHTML();
3368 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3371 $this->disableCache();
3373 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3374 $found = false; # access denied
3375 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3377 list( $text, $title ) = $this->getTemplateDom( $title );
3378 if ( $text !== false ) {
3384 # If the title is valid but undisplayable, make a link to it
3385 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3386 $text = "[[:$titleText]]";
3389 } elseif ( $title->isTrans() ) {
3390 # Interwiki transclusion
3391 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3392 $text = $this->interwikiTransclude( $title, 'render' );
3395 $text = $this->interwikiTransclude( $title, 'raw' );
3396 # Preprocess it like a template
3397 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3403 # Do infinite loop check
3404 # This has to be done after redirect resolution to avoid infinite loops via redirects
3405 if ( !$frame->loopCheck( $title ) ) {
3407 $text = '<span class="error">'
3408 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3410 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3412 wfProfileOut( __METHOD__
. '-loadtpl' );
3415 # If we haven't found text to substitute by now, we're done
3416 # Recover the source wikitext and return it
3418 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3419 if ( $titleProfileIn ) {
3420 wfProfileOut( $titleProfileIn ); // template out
3422 wfProfileOut( __METHOD__
);
3423 return array( 'object' => $text );
3426 # Expand DOM-style return values in a child frame
3427 if ( $isChildObj ) {
3428 # Clean up argument array
3429 $newFrame = $frame->newChild( $args, $title );
3432 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3433 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3434 # Expansion is eligible for the empty-frame cache
3435 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3436 $text = $this->mTplExpandCache
[$titleText];
3438 $text = $newFrame->expand( $text );
3439 $this->mTplExpandCache
[$titleText] = $text;
3442 # Uncached expansion
3443 $text = $newFrame->expand( $text );
3446 if ( $isLocalObj && $nowiki ) {
3447 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3448 $isLocalObj = false;
3451 if ( $titleProfileIn ) {
3452 wfProfileOut( $titleProfileIn ); // template out
3455 # Replace raw HTML by a placeholder
3457 $text = $this->insertStripItem( $text );
3458 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3459 # Escape nowiki-style return values
3460 $text = wfEscapeWikiText( $text );
3461 } elseif ( is_string( $text )
3462 && !$piece['lineStart']
3463 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3465 # Bug 529: if the template begins with a table or block-level
3466 # element, it should be treated as beginning a new line.
3467 # This behaviour is somewhat controversial.
3468 $text = "\n" . $text;
3471 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3472 # Error, oversize inclusion
3473 if ( $titleText !== false ) {
3474 # Make a working, properly escaped link if possible (bug 23588)
3475 $text = "[[:$titleText]]";
3477 # This will probably not be a working link, but at least it may
3478 # provide some hint of where the problem is
3479 preg_replace( '/^:/', '', $originalTitle );
3480 $text = "[[:$originalTitle]]";
3482 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3483 $this->limitationWarn( 'post-expand-template-inclusion' );
3486 if ( $isLocalObj ) {
3487 $ret = array( 'object' => $text );
3489 $ret = array( 'text' => $text );
3492 wfProfileOut( __METHOD__
);
3497 * Get the semi-parsed DOM representation of a template with a given title,
3498 * and its redirect destination title. Cached.
3500 * @param $title Title
3504 function getTemplateDom( $title ) {
3505 $cacheTitle = $title;
3506 $titleText = $title->getPrefixedDBkey();
3508 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3509 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3510 $title = Title
::makeTitle( $ns, $dbk );
3511 $titleText = $title->getPrefixedDBkey();
3513 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3514 return array( $this->mTplDomCache
[$titleText], $title );
3517 # Cache miss, go to the database
3518 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3520 if ( $text === false ) {
3521 $this->mTplDomCache
[$titleText] = false;
3522 return array( false, $title );
3525 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3526 $this->mTplDomCache
[ $titleText ] = $dom;
3528 if ( !$title->equals( $cacheTitle ) ) {
3529 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3530 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3533 return array( $dom, $title );
3537 * Fetch the unparsed text of a template and register a reference to it.
3538 * @param Title $title
3539 * @return Array ( string or false, Title )
3541 function fetchTemplateAndTitle( $title ) {
3542 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3543 $stuff = call_user_func( $templateCb, $title, $this );
3544 $text = $stuff['text'];
3545 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3546 if ( isset( $stuff['deps'] ) ) {
3547 foreach ( $stuff['deps'] as $dep ) {
3548 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3551 return array( $text, $finalTitle );
3555 * Fetch the unparsed text of a template and register a reference to it.
3556 * @param Title $title
3557 * @return mixed string or false
3559 function fetchTemplate( $title ) {
3560 $rv = $this->fetchTemplateAndTitle( $title );
3565 * Static function to get a template
3566 * Can be overridden via ParserOptions::setTemplateCallback().
3568 * @param $title Title
3569 * @param $parser Parser
3573 static function statelessFetchTemplate( $title, $parser = false ) {
3574 $text = $skip = false;
3575 $finalTitle = $title;
3578 # Loop to fetch the article, with up to 1 redirect
3579 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3580 # Give extensions a chance to select the revision instead
3581 $id = false; # Assume current
3582 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3583 array( $parser, $title, &$skip, &$id ) );
3589 'page_id' => $title->getArticleID(),
3596 ? Revision
::newFromId( $id )
3597 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3598 $rev_id = $rev ?
$rev->getId() : 0;
3599 # If there is no current revision, there is no page
3600 if ( $id === false && !$rev ) {
3601 $linkCache = LinkCache
::singleton();
3602 $linkCache->addBadLinkObj( $title );
3607 'page_id' => $title->getArticleID(),
3608 'rev_id' => $rev_id );
3609 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3610 # We fetched a rev from a different title; register it too...
3612 'title' => $rev->getTitle(),
3613 'page_id' => $rev->getPage(),
3614 'rev_id' => $rev_id );
3618 $content = $rev->getContent();
3619 $text = $content->getWikitextForTransclusion();
3621 if ( $text === false ||
$text === null ) {
3625 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3627 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3628 if ( !$message->exists() ) {
3632 $content = $message->content();
3633 $text = $message->plain();
3641 $finalTitle = $title;
3642 $title = $content->getRedirectTarget();
3646 'finalTitle' => $finalTitle,
3651 * Fetch a file and its title and register a reference to it.
3652 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3653 * @param Title $title
3654 * @param Array $options Array of options to RepoGroup::findFile
3657 function fetchFile( $title, $options = array() ) {
3658 $res = $this->fetchFileAndTitle( $title, $options );
3663 * Fetch a file and its title and register a reference to it.
3664 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3665 * @param Title $title
3666 * @param Array $options Array of options to RepoGroup::findFile
3667 * @return Array ( File or false, Title of file )
3669 function fetchFileAndTitle( $title, $options = array() ) {
3670 if ( isset( $options['broken'] ) ) {
3671 $file = false; // broken thumbnail forced by hook
3672 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3673 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3674 } else { // get by (name,timestamp)
3675 $file = wfFindFile( $title, $options );
3677 $time = $file ?
$file->getTimestamp() : false;
3678 $sha1 = $file ?
$file->getSha1() : false;
3679 # Register the file as a dependency...
3680 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3681 if ( $file && !$title->equals( $file->getTitle() ) ) {
3682 # Update fetched file title
3683 $title = $file->getTitle();
3684 if ( is_null( $file->getRedirectedTitle() ) ) {
3685 # This file was not a redirect, but the title does not match.
3686 # Register under the new name because otherwise the link will
3688 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3691 return array( $file, $title );
3695 * Transclude an interwiki link.
3697 * @param $title Title
3702 function interwikiTransclude( $title, $action ) {
3703 global $wgEnableScaryTranscluding;
3705 if ( !$wgEnableScaryTranscluding ) {
3706 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3709 $url = $title->getFullUrl( "action=$action" );
3711 if ( strlen( $url ) > 255 ) {
3712 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3714 return $this->fetchScaryTemplateMaybeFromCache( $url );
3718 * @param $url string
3719 * @return Mixed|String
3721 function fetchScaryTemplateMaybeFromCache( $url ) {
3722 global $wgTranscludeCacheExpiry;
3723 $dbr = wfGetDB( DB_SLAVE
);
3724 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3725 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3726 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3728 return $obj->tc_contents
;
3731 $req = MWHttpRequest
::factory( $url );
3732 $status = $req->execute(); // Status object
3733 if ( $status->isOK() ) {
3734 $text = $req->getContent();
3735 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3736 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3738 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3741 $dbw = wfGetDB( DB_MASTER
);
3742 $dbw->replace( 'transcache', array('tc_url'), array(
3744 'tc_time' => $dbw->timestamp( time() ),
3745 'tc_contents' => $text)
3751 * Triple brace replacement -- used for template arguments
3754 * @param $piece array
3755 * @param $frame PPFrame
3759 function argSubstitution( $piece, $frame ) {
3760 wfProfileIn( __METHOD__
);
3763 $parts = $piece['parts'];
3764 $nameWithSpaces = $frame->expand( $piece['title'] );
3765 $argName = trim( $nameWithSpaces );
3767 $text = $frame->getArgument( $argName );
3768 if ( $text === false && $parts->getLength() > 0
3772 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3775 # No match in frame, use the supplied default
3776 $object = $parts->item( 0 )->getChildren();
3778 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3779 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3780 $this->limitationWarn( 'post-expand-template-argument' );
3783 if ( $text === false && $object === false ) {
3785 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3787 if ( $error !== false ) {
3790 if ( $object !== false ) {
3791 $ret = array( 'object' => $object );
3793 $ret = array( 'text' => $text );
3796 wfProfileOut( __METHOD__
);
3801 * Return the text to be used for a given extension tag.
3802 * This is the ghost of strip().
3804 * @param $params array Associative array of parameters:
3805 * name PPNode for the tag name
3806 * attr PPNode for unparsed text where tag attributes are thought to be
3807 * attributes Optional associative array of parsed attributes
3808 * inner Contents of extension element
3809 * noClose Original text did not have a close tag
3810 * @param $frame PPFrame
3812 * @throws MWException
3815 function extensionSubstitution( $params, $frame ) {
3816 $name = $frame->expand( $params['name'] );
3817 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3818 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3819 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3821 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3822 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3823 if ( $isFunctionTag ) {
3824 $markerType = 'none';
3826 $markerType = 'general';
3828 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3829 $name = strtolower( $name );
3830 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3831 if ( isset( $params['attributes'] ) ) {
3832 $attributes = $attributes +
$params['attributes'];
3835 if ( isset( $this->mTagHooks
[$name] ) ) {
3836 # Workaround for PHP bug 35229 and similar
3837 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3838 throw new MWException( "Tag hook for $name is not callable\n" );
3840 $output = call_user_func_array( $this->mTagHooks
[$name],
3841 array( $content, $attributes, $this, $frame ) );
3842 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3843 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3844 if ( !is_callable( $callback ) ) {
3845 throw new MWException( "Tag hook for $name is not callable\n" );
3848 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3850 $output = '<span class="error">Invalid tag extension name: ' .
3851 htmlspecialchars( $name ) . '</span>';
3854 if ( is_array( $output ) ) {
3855 # Extract flags to local scope (to override $markerType)
3857 $output = $flags[0];
3862 if ( is_null( $attrText ) ) {
3865 if ( isset( $params['attributes'] ) ) {
3866 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3867 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3868 htmlspecialchars( $attrValue ) . '"';
3871 if ( $content === null ) {
3872 $output = "<$name$attrText/>";
3874 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3875 $output = "<$name$attrText>$content$close";
3879 if ( $markerType === 'none' ) {
3881 } elseif ( $markerType === 'nowiki' ) {
3882 $this->mStripState
->addNoWiki( $marker, $output );
3883 } elseif ( $markerType === 'general' ) {
3884 $this->mStripState
->addGeneral( $marker, $output );
3886 throw new MWException( __METHOD__
.': invalid marker type' );
3892 * Increment an include size counter
3894 * @param $type String: the type of expansion
3895 * @param $size Integer: the size of the text
3896 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3898 function incrementIncludeSize( $type, $size ) {
3899 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3902 $this->mIncludeSizes
[$type] +
= $size;
3908 * Increment the expensive function count
3910 * @return Boolean: false if the limit has been exceeded
3912 function incrementExpensiveFunctionCount() {
3913 $this->mExpensiveFunctionCount++
;
3914 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3918 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3919 * Fills $this->mDoubleUnderscores, returns the modified text
3921 * @param $text string
3925 function doDoubleUnderscore( $text ) {
3926 wfProfileIn( __METHOD__
);
3928 # The position of __TOC__ needs to be recorded
3929 $mw = MagicWord
::get( 'toc' );
3930 if ( $mw->match( $text ) ) {
3931 $this->mShowToc
= true;
3932 $this->mForceTocPosition
= true;
3934 # Set a placeholder. At the end we'll fill it in with the TOC.
3935 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3937 # Only keep the first one.
3938 $text = $mw->replace( '', $text );
3941 # Now match and remove the rest of them
3942 $mwa = MagicWord
::getDoubleUnderscoreArray();
3943 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3945 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3946 $this->mOutput
->mNoGallery
= true;
3948 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3949 $this->mShowToc
= false;
3951 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3952 $this->addTrackingCategory( 'hidden-category-category' );
3954 # (bug 8068) Allow control over whether robots index a page.
3956 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3957 # is not desirable, the last one on the page should win.
3958 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3959 $this->mOutput
->setIndexPolicy( 'noindex' );
3960 $this->addTrackingCategory( 'noindex-category' );
3962 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3963 $this->mOutput
->setIndexPolicy( 'index' );
3964 $this->addTrackingCategory( 'index-category' );
3967 # Cache all double underscores in the database
3968 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3969 $this->mOutput
->setProperty( $key, '' );
3972 wfProfileOut( __METHOD__
);
3977 * Add a tracking category, getting the title from a system message,
3978 * or print a debug message if the title is invalid.
3980 * @param $msg String: message key
3981 * @return Boolean: whether the addition was successful
3983 public function addTrackingCategory( $msg ) {
3984 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3985 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3988 // Important to parse with correct title (bug 31469)
3989 $cat = wfMessage( $msg )
3990 ->title( $this->getTitle() )
3991 ->inContentLanguage()
3994 # Allow tracking categories to be disabled by setting them to "-"
3995 if ( $cat === '-' ) {
3999 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4000 if ( $containerCategory ) {
4001 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4004 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
4010 * This function accomplishes several tasks:
4011 * 1) Auto-number headings if that option is enabled
4012 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4013 * 3) Add a Table of contents on the top for users who have enabled the option
4014 * 4) Auto-anchor headings
4016 * It loops through all headlines, collects the necessary data, then splits up the
4017 * string and re-inserts the newly formatted headlines.
4019 * @param $text String
4020 * @param $origText String: original, untouched wikitext
4021 * @param $isMain Boolean
4022 * @return mixed|string
4025 function formatHeadings( $text, $origText, $isMain=true ) {
4026 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4028 # Inhibit editsection links if requested in the page
4029 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4030 $maybeShowEditLink = $showEditLink = false;
4032 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4033 $showEditLink = $this->mOptions
->getEditSection();
4035 if ( $showEditLink ) {
4036 $this->mOutput
->setEditSectionTokens( true );
4039 # Get all headlines for numbering them and adding funky stuff like [edit]
4040 # links - this is for later, but we need the number of headlines right now
4042 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4044 # if there are fewer than 4 headlines in the article, do not show TOC
4045 # unless it's been explicitly enabled.
4046 $enoughToc = $this->mShowToc
&&
4047 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4049 # Allow user to stipulate that a page should have a "new section"
4050 # link added via __NEWSECTIONLINK__
4051 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4052 $this->mOutput
->setNewSection( true );
4055 # Allow user to remove the "new section"
4056 # link via __NONEWSECTIONLINK__
4057 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4058 $this->mOutput
->hideNewSection( true );
4061 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4062 # override above conditions and always show TOC above first header
4063 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4064 $this->mShowToc
= true;
4072 # Ugh .. the TOC should have neat indentation levels which can be
4073 # passed to the skin functions. These are determined here
4077 $sublevelCount = array();
4078 $levelCount = array();
4083 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4084 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4085 $oldType = $this->mOutputType
;
4086 $this->setOutputType( self
::OT_WIKI
);
4087 $frame = $this->getPreprocessor()->newFrame();
4088 $root = $this->preprocessToDom( $origText );
4089 $node = $root->getFirstChild();
4094 foreach ( $matches[3] as $headline ) {
4095 $isTemplate = false;
4097 $sectionIndex = false;
4099 $markerMatches = array();
4100 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4101 $serial = $markerMatches[1];
4102 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4103 $isTemplate = ( $titleText != $baseTitleText );
4104 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4108 $prevlevel = $level;
4110 $level = $matches[1][$headlineCount];
4112 if ( $level > $prevlevel ) {
4113 # Increase TOC level
4115 $sublevelCount[$toclevel] = 0;
4116 if ( $toclevel<$wgMaxTocLevel ) {
4117 $prevtoclevel = $toclevel;
4118 $toc .= Linker
::tocIndent();
4121 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4122 # Decrease TOC level, find level to jump to
4124 for ( $i = $toclevel; $i > 0; $i-- ) {
4125 if ( $levelCount[$i] == $level ) {
4126 # Found last matching level
4129 } elseif ( $levelCount[$i] < $level ) {
4130 # Found first matching level below current level
4138 if ( $toclevel<$wgMaxTocLevel ) {
4139 if ( $prevtoclevel < $wgMaxTocLevel ) {
4140 # Unindent only if the previous toc level was shown :p
4141 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4142 $prevtoclevel = $toclevel;
4144 $toc .= Linker
::tocLineEnd();
4148 # No change in level, end TOC line
4149 if ( $toclevel<$wgMaxTocLevel ) {
4150 $toc .= Linker
::tocLineEnd();
4154 $levelCount[$toclevel] = $level;
4156 # count number of headlines for each level
4157 @$sublevelCount[$toclevel]++
;
4159 for( $i = 1; $i <= $toclevel; $i++
) {
4160 if ( !empty( $sublevelCount[$i] ) ) {
4164 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4169 # The safe header is a version of the header text safe to use for links
4171 # Remove link placeholders by the link text.
4172 # <!--LINK number-->
4174 # link text with suffix
4175 # Do this before unstrip since link text can contain strip markers
4176 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4178 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4179 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4181 # Strip out HTML (first regex removes any tag not allowed)
4183 # * <sup> and <sub> (bug 8393)
4186 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4188 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4189 # to allow setting directionality in toc items.
4190 $tocline = preg_replace(
4191 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4192 array( '', '<$1>' ),
4195 $tocline = trim( $tocline );
4197 # For the anchor, strip out HTML-y stuff period
4198 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4199 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4201 # Save headline for section edit hint before it's escaped
4202 $headlineHint = $safeHeadline;
4204 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4205 # For reverse compatibility, provide an id that's
4206 # HTML4-compatible, like we used to.
4208 # It may be worth noting, academically, that it's possible for
4209 # the legacy anchor to conflict with a non-legacy headline
4210 # anchor on the page. In this case likely the "correct" thing
4211 # would be to either drop the legacy anchors or make sure
4212 # they're numbered first. However, this would require people
4213 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4214 # manually, so let's not bother worrying about it.
4215 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4216 array( 'noninitial', 'legacy' ) );
4217 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4219 if ( $legacyHeadline == $safeHeadline ) {
4220 # No reason to have both (in fact, we can't)
4221 $legacyHeadline = false;
4224 $legacyHeadline = false;
4225 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4229 # HTML names must be case-insensitively unique (bug 10721).
4230 # This does not apply to Unicode characters per
4231 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4232 # @todo FIXME: We may be changing them depending on the current locale.
4233 $arrayKey = strtolower( $safeHeadline );
4234 if ( $legacyHeadline === false ) {
4235 $legacyArrayKey = false;
4237 $legacyArrayKey = strtolower( $legacyHeadline );
4240 # count how many in assoc. array so we can track dupes in anchors
4241 if ( isset( $refers[$arrayKey] ) ) {
4242 $refers[$arrayKey]++
;
4244 $refers[$arrayKey] = 1;
4246 if ( isset( $refers[$legacyArrayKey] ) ) {
4247 $refers[$legacyArrayKey]++
;
4249 $refers[$legacyArrayKey] = 1;
4252 # Don't number the heading if it is the only one (looks silly)
4253 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4254 # the two are different if the line contains a link
4255 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4258 # Create the anchor for linking from the TOC to the section
4259 $anchor = $safeHeadline;
4260 $legacyAnchor = $legacyHeadline;
4261 if ( $refers[$arrayKey] > 1 ) {
4262 $anchor .= '_' . $refers[$arrayKey];
4264 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4265 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4267 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4268 $toc .= Linker
::tocLine( $anchor, $tocline,
4269 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4272 # Add the section to the section tree
4273 # Find the DOM node for this header
4274 while ( $node && !$isTemplate ) {
4275 if ( $node->getName() === 'h' ) {
4276 $bits = $node->splitHeading();
4277 if ( $bits['i'] == $sectionIndex ) {
4281 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4282 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4283 $node = $node->getNextSibling();
4286 'toclevel' => $toclevel,
4289 'number' => $numbering,
4290 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4291 'fromtitle' => $titleText,
4292 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4293 'anchor' => $anchor,
4296 # give headline the correct <h#> tag
4297 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4298 // Output edit section links as markers with styles that can be customized by skins
4299 if ( $isTemplate ) {
4300 # Put a T flag in the section identifier, to indicate to extractSections()
4301 # that sections inside <includeonly> should be counted.
4302 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4304 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4306 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4307 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4308 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4309 // so we don't have to worry about a user trying to input one of these markers directly.
4310 // We use a page and section attribute to stop the language converter from converting these important bits
4311 // of data, but put the headline hint inside a content block because the language converter is supposed to
4312 // be able to convert that piece of data.
4313 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4314 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4315 if ( isset($editlinkArgs[2]) ) {
4316 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4323 $head[$headlineCount] = Linker
::makeHeadline( $level,
4324 $matches['attrib'][$headlineCount], $anchor, $headline,
4325 $editlink, $legacyAnchor );
4330 $this->setOutputType( $oldType );
4332 # Never ever show TOC if no headers
4333 if ( $numVisible < 1 ) {
4338 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4339 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4341 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4342 $this->mOutput
->setTOCHTML( $toc );
4346 $this->mOutput
->setSections( $tocraw );
4349 # split up and insert constructed headlines
4350 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4353 // build an array of document sections
4354 $sections = array();
4355 foreach ( $blocks as $block ) {
4356 // $head is zero-based, sections aren't.
4357 if ( empty( $head[$i - 1] ) ) {
4358 $sections[$i] = $block;
4360 $sections[$i] = $head[$i - 1] . $block;
4364 * Send a hook, one per section.
4365 * The idea here is to be able to make section-level DIVs, but to do so in a
4366 * lower-impact, more correct way than r50769
4369 * $section : the section number
4370 * &$sectionContent : ref to the content of the section
4371 * $showEditLinks : boolean describing whether this section has an edit link
4373 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4378 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4379 // append the TOC at the beginning
4380 // Top anchor now in skin
4381 $sections[0] = $sections[0] . $toc . "\n";
4384 $full .= join( '', $sections );
4386 if ( $this->mForceTocPosition
) {
4387 return str_replace( '<!--MWTOC-->', $toc, $full );
4394 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4395 * conversion, substitting signatures, {{subst:}} templates, etc.
4397 * @param $text String: the text to transform
4398 * @param $title Title: the Title object for the current article
4399 * @param $user User: the User object describing the current user
4400 * @param $options ParserOptions: parsing options
4401 * @param $clearState Boolean: whether to clear the parser state first
4402 * @return String: the altered wiki markup
4404 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4405 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4406 $this->setUser( $user );
4411 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4412 if( $options->getPreSaveTransform() ) {
4413 $text = $this->pstPass2( $text, $user );
4415 $text = $this->mStripState
->unstripBoth( $text );
4417 $this->setUser( null ); #Reset
4423 * Pre-save transform helper function
4426 * @param $text string
4431 function pstPass2( $text, $user ) {
4432 global $wgContLang, $wgLocaltimezone;
4434 # Note: This is the timestamp saved as hardcoded wikitext to
4435 # the database, we use $wgContLang here in order to give
4436 # everyone the same signature and use the default one rather
4437 # than the one selected in each user's preferences.
4438 # (see also bug 12815)
4439 $ts = $this->mOptions
->getTimestamp();
4440 if ( isset( $wgLocaltimezone ) ) {
4441 $tz = $wgLocaltimezone;
4443 $tz = date_default_timezone_get();
4446 $unixts = wfTimestamp( TS_UNIX
, $ts );
4447 $oldtz = date_default_timezone_get();
4448 date_default_timezone_set( $tz );
4449 $ts = date( 'YmdHis', $unixts );
4450 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4452 # Allow translation of timezones through wiki. date() can return
4453 # whatever crap the system uses, localised or not, so we cannot
4454 # ship premade translations.
4455 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4456 $msg = wfMessage( $key )->inContentLanguage();
4457 if ( $msg->exists() ) {
4458 $tzMsg = $msg->text();
4461 date_default_timezone_set( $oldtz );
4463 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4465 # Variable replacement
4466 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4467 $text = $this->replaceVariables( $text );
4469 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4470 # which may corrupt this parser instance via its wfMessage()->text() call-
4473 $sigText = $this->getUserSig( $user );
4474 $text = strtr( $text, array(
4476 '~~~~' => "$sigText $d",
4480 # Context links: [[|name]] and [[name (context)|]]
4481 $tc = '[' . Title
::legalChars() . ']';
4482 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4484 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4485 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4486 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4487 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4489 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4490 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4491 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4492 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4494 $t = $this->mTitle
->getText();
4496 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4497 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4498 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4499 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4501 # if there's no context, don't bother duplicating the title
4502 $text = preg_replace( $p2, '[[\\1]]', $text );
4505 # Trim trailing whitespace
4506 $text = rtrim( $text );
4512 * Fetch the user's signature text, if any, and normalize to
4513 * validated, ready-to-insert wikitext.
4514 * If you have pre-fetched the nickname or the fancySig option, you can
4515 * specify them here to save a database query.
4516 * Do not reuse this parser instance after calling getUserSig(),
4517 * as it may have changed if it's the $wgParser.
4520 * @param $nickname String|bool nickname to use or false to use user's default nickname
4521 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4522 * or null to use default value
4525 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4526 global $wgMaxSigChars;
4528 $username = $user->getName();
4530 # If not given, retrieve from the user object.
4531 if ( $nickname === false )
4532 $nickname = $user->getOption( 'nickname' );
4534 if ( is_null( $fancySig ) ) {
4535 $fancySig = $user->getBoolOption( 'fancysig' );
4538 $nickname = $nickname == null ?
$username : $nickname;
4540 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4541 $nickname = $username;
4542 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4543 } elseif ( $fancySig !== false ) {
4544 # Sig. might contain markup; validate this
4545 if ( $this->validateSig( $nickname ) !== false ) {
4546 # Validated; clean up (if needed) and return it
4547 return $this->cleanSig( $nickname, true );
4549 # Failed to validate; fall back to the default
4550 $nickname = $username;
4551 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4555 # Make sure nickname doesnt get a sig in a sig
4556 $nickname = self
::cleanSigInSig( $nickname );
4558 # If we're still here, make it a link to the user page
4559 $userText = wfEscapeWikiText( $username );
4560 $nickText = wfEscapeWikiText( $nickname );
4561 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4563 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4567 * Check that the user's signature contains no bad XML
4569 * @param $text String
4570 * @return mixed An expanded string, or false if invalid.
4572 function validateSig( $text ) {
4573 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4577 * Clean up signature text
4579 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4580 * 2) Substitute all transclusions
4582 * @param $text String
4583 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4584 * @return String: signature text
4586 public function cleanSig( $text, $parsing = false ) {
4589 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4592 # Option to disable this feature
4593 if ( !$this->mOptions
->getCleanSignatures() ) {
4597 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4598 # => Move this logic to braceSubstitution()
4599 $substWord = MagicWord
::get( 'subst' );
4600 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4601 $substText = '{{' . $substWord->getSynonym( 0 );
4603 $text = preg_replace( $substRegex, $substText, $text );
4604 $text = self
::cleanSigInSig( $text );
4605 $dom = $this->preprocessToDom( $text );
4606 $frame = $this->getPreprocessor()->newFrame();
4607 $text = $frame->expand( $dom );
4610 $text = $this->mStripState
->unstripBoth( $text );
4617 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4619 * @param $text String
4620 * @return String: signature text with /~{3,5}/ removed
4622 public static function cleanSigInSig( $text ) {
4623 $text = preg_replace( '/~{3,5}/', '', $text );
4628 * Set up some variables which are usually set up in parse()
4629 * so that an external function can call some class members with confidence
4631 * @param $title Title|null
4632 * @param $options ParserOptions
4633 * @param $outputType
4634 * @param $clearState bool
4636 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4637 $this->startParse( $title, $options, $outputType, $clearState );
4641 * @param $title Title|null
4642 * @param $options ParserOptions
4643 * @param $outputType
4644 * @param $clearState bool
4646 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4647 $this->setTitle( $title );
4648 $this->mOptions
= $options;
4649 $this->setOutputType( $outputType );
4650 if ( $clearState ) {
4651 $this->clearState();
4656 * Wrapper for preprocess()
4658 * @param $text String: the text to preprocess
4659 * @param $options ParserOptions: options
4660 * @param $title Title object or null to use $wgTitle
4663 public function transformMsg( $text, $options, $title = null ) {
4664 static $executing = false;
4666 # Guard against infinite recursion
4672 wfProfileIn( __METHOD__
);
4678 # It's not uncommon having a null $wgTitle in scripts. See r80898
4679 # Create a ghost title in such case
4680 $title = Title
::newFromText( 'Dwimmerlaik' );
4682 $text = $this->preprocess( $text, $title, $options );
4685 wfProfileOut( __METHOD__
);
4690 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4691 * The callback should have the following form:
4692 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4694 * Transform and return $text. Use $parser for any required context, e.g. use
4695 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4697 * Hooks may return extended information by returning an array, of which the
4698 * first numbered element (index 0) must be the return string, and all other
4699 * entries are extracted into local variables within an internal function
4700 * in the Parser class.
4702 * This interface (introduced r61913) appears to be undocumented, but
4703 * 'markerName' is used by some core tag hooks to override which strip
4704 * array their results are placed in. **Use great caution if attempting
4705 * this interface, as it is not documented and injudicious use could smash
4706 * private variables.**
4708 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4709 * @param $callback Mixed: the callback function (and object) to use for the tag
4710 * @throws MWException
4711 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4713 public function setHook( $tag, $callback ) {
4714 $tag = strtolower( $tag );
4715 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4716 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4718 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4719 $this->mTagHooks
[$tag] = $callback;
4720 if ( !in_array( $tag, $this->mStripList
) ) {
4721 $this->mStripList
[] = $tag;
4728 * As setHook(), but letting the contents be parsed.
4730 * Transparent tag hooks are like regular XML-style tag hooks, except they
4731 * operate late in the transformation sequence, on HTML instead of wikitext.
4733 * This is probably obsoleted by things dealing with parser frames?
4734 * The only extension currently using it is geoserver.
4737 * @todo better document or deprecate this
4739 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4740 * @param $callback Mixed: the callback function (and object) to use for the tag
4741 * @throws MWException
4742 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4744 function setTransparentTagHook( $tag, $callback ) {
4745 $tag = strtolower( $tag );
4746 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4747 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4749 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4750 $this->mTransparentTagHooks
[$tag] = $callback;
4756 * Remove all tag hooks
4758 function clearTagHooks() {
4759 $this->mTagHooks
= array();
4760 $this->mFunctionTagHooks
= array();
4761 $this->mStripList
= $this->mDefaultStripList
;
4765 * Create a function, e.g. {{sum:1|2|3}}
4766 * The callback function should have the form:
4767 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4769 * Or with SFH_OBJECT_ARGS:
4770 * function myParserFunction( $parser, $frame, $args ) { ... }
4772 * The callback may either return the text result of the function, or an array with the text
4773 * in element 0, and a number of flags in the other elements. The names of the flags are
4774 * specified in the keys. Valid flags are:
4775 * found The text returned is valid, stop processing the template. This
4777 * nowiki Wiki markup in the return value should be escaped
4778 * isHTML The returned text is HTML, armour it against wikitext transformation
4780 * @param $id String: The magic word ID
4781 * @param $callback Mixed: the callback function (and object) to use
4782 * @param $flags Integer: a combination of the following flags:
4783 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4785 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4786 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4787 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4788 * the arguments, and to control the way they are expanded.
4790 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4791 * arguments, for instance:
4792 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4794 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4795 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4796 * working if/when this is changed.
4798 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4801 * Please read the documentation in includes/parser/Preprocessor.php for more information
4802 * about the methods available in PPFrame and PPNode.
4804 * @throws MWException
4805 * @return string|callback The old callback function for this name, if any
4807 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4810 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4811 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4813 # Add to function cache
4814 $mw = MagicWord
::get( $id );
4816 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4818 $synonyms = $mw->getSynonyms();
4819 $sensitive = intval( $mw->isCaseSensitive() );
4821 foreach ( $synonyms as $syn ) {
4823 if ( !$sensitive ) {
4824 $syn = $wgContLang->lc( $syn );
4827 if ( !( $flags & SFH_NO_HASH
) ) {
4830 # Remove trailing colon
4831 if ( substr( $syn, -1, 1 ) === ':' ) {
4832 $syn = substr( $syn, 0, -1 );
4834 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4840 * Get all registered function hook identifiers
4844 function getFunctionHooks() {
4845 return array_keys( $this->mFunctionHooks
);
4849 * Create a tag function, e.g. "<test>some stuff</test>".
4850 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4851 * Unlike parser functions, their content is not preprocessed.
4855 * @throws MWException
4858 function setFunctionTagHook( $tag, $callback, $flags ) {
4859 $tag = strtolower( $tag );
4860 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4861 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4862 $this->mFunctionTagHooks
[$tag] : null;
4863 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4865 if ( !in_array( $tag, $this->mStripList
) ) {
4866 $this->mStripList
[] = $tag;
4873 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4874 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4875 * Placeholders created in Skin::makeLinkObj()
4877 * @param $text string
4878 * @param $options int
4880 * @return array of link CSS classes, indexed by PDBK.
4882 function replaceLinkHolders( &$text, $options = 0 ) {
4883 return $this->mLinkHolders
->replace( $text );
4887 * Replace "<!--LINK-->" link placeholders with plain text of links
4888 * (not HTML-formatted).
4890 * @param $text String
4893 function replaceLinkHoldersText( $text ) {
4894 return $this->mLinkHolders
->replaceText( $text );
4898 * Renders an image gallery from a text with one line per image.
4899 * text labels may be given by using |-style alternative text. E.g.
4900 * Image:one.jpg|The number "1"
4901 * Image:tree.jpg|A tree
4902 * given as text will return the HTML of a gallery with two images,
4903 * labeled 'The number "1"' and
4906 * @param string $text
4907 * @param array $params
4908 * @return string HTML
4910 function renderImageGallery( $text, $params ) {
4911 $ig = new ImageGallery();
4912 $ig->setContextTitle( $this->mTitle
);
4913 $ig->setShowBytes( false );
4914 $ig->setShowFilename( false );
4915 $ig->setParser( $this );
4916 $ig->setHideBadImages();
4917 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4919 if ( isset( $params['showfilename'] ) ) {
4920 $ig->setShowFilename( true );
4922 $ig->setShowFilename( false );
4924 if ( isset( $params['caption'] ) ) {
4925 $caption = $params['caption'];
4926 $caption = htmlspecialchars( $caption );
4927 $caption = $this->replaceInternalLinks( $caption );
4928 $ig->setCaptionHtml( $caption );
4930 if ( isset( $params['perrow'] ) ) {
4931 $ig->setPerRow( $params['perrow'] );
4933 if ( isset( $params['widths'] ) ) {
4934 $ig->setWidths( $params['widths'] );
4936 if ( isset( $params['heights'] ) ) {
4937 $ig->setHeights( $params['heights'] );
4940 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4942 $lines = StringUtils
::explode( "\n", $text );
4943 foreach ( $lines as $line ) {
4944 # match lines like these:
4945 # Image:someimage.jpg|This is some image
4947 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4949 if ( count( $matches ) == 0 ) {
4953 if ( strpos( $matches[0], '%' ) !== false ) {
4954 $matches[1] = rawurldecode( $matches[1] );
4956 $title = Title
::newFromText( $matches[1], NS_FILE
);
4957 if ( is_null( $title ) ) {
4958 # Bogus title. Ignore these so we don't bomb out later.
4965 if ( isset( $matches[3] ) ) {
4966 // look for an |alt= definition while trying not to break existing
4967 // captions with multiple pipes (|) in it, until a more sensible grammar
4968 // is defined for images in galleries
4970 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4971 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4972 $magicWordAlt = MagicWord
::get( 'img_alt' );
4973 $magicWordLink = MagicWord
::get( 'img_link' );
4975 foreach ( $parameterMatches as $parameterMatch ) {
4976 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4977 $alt = $this->stripAltText( $match, false );
4979 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4980 $link = strip_tags($this->replaceLinkHoldersText($match));
4981 $chars = self
::EXT_LINK_URL_CLASS
;
4982 $prots = $this->mUrlProtocols
;
4983 //check to see if link matches an absolute url, if not then it must be a wiki link.
4984 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4985 $localLinkTitle = Title
::newFromText($link);
4986 $link = $localLinkTitle->getLocalURL();
4990 // concatenate all other pipes
4991 $label .= '|' . $parameterMatch;
4994 // remove the first pipe
4995 $label = substr( $label, 1 );
4998 $ig->add( $title, $label, $alt ,$link);
5000 return $ig->toHTML();
5007 function getImageParams( $handler ) {
5009 $handlerClass = get_class( $handler );
5013 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5014 # Initialise static lists
5015 static $internalParamNames = array(
5016 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5017 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5018 'bottom', 'text-bottom' ),
5019 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5020 'upright', 'border', 'link', 'alt', 'class' ),
5022 static $internalParamMap;
5023 if ( !$internalParamMap ) {
5024 $internalParamMap = array();
5025 foreach ( $internalParamNames as $type => $names ) {
5026 foreach ( $names as $name ) {
5027 $magicName = str_replace( '-', '_', "img_$name" );
5028 $internalParamMap[$magicName] = array( $type, $name );
5033 # Add handler params
5034 $paramMap = $internalParamMap;
5036 $handlerParamMap = $handler->getParamMap();
5037 foreach ( $handlerParamMap as $magic => $paramName ) {
5038 $paramMap[$magic] = array( 'handler', $paramName );
5041 $this->mImageParams
[$handlerClass] = $paramMap;
5042 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5044 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5048 * Parse image options text and use it to make an image
5050 * @param $title Title
5051 * @param $options String
5052 * @param $holders LinkHolderArray|bool
5053 * @return string HTML
5055 function makeImage( $title, $options, $holders = false ) {
5056 # Check if the options text is of the form "options|alt text"
5058 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5059 # * left no resizing, just left align. label is used for alt= only
5060 # * right same, but right aligned
5061 # * none same, but not aligned
5062 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5063 # * center center the image
5064 # * frame Keep original image size, no magnify-button.
5065 # * framed Same as "frame"
5066 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5067 # * upright reduce width for upright images, rounded to full __0 px
5068 # * border draw a 1px border around the image
5069 # * alt Text for HTML alt attribute (defaults to empty)
5070 # * class Set a class for img node
5071 # * link Set the target of the image link. Can be external, interwiki, or local
5072 # vertical-align values (no % or length right now):
5082 $parts = StringUtils
::explode( "|", $options );
5084 # Give extensions a chance to select the file revision for us
5087 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5088 array( $this, $title, &$options, &$descQuery ) );
5089 # Fetch and register the file (file title may be different via hooks)
5090 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5093 $handler = $file ?
$file->getHandler() : false;
5095 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5098 $this->addTrackingCategory( 'broken-file-category' );
5101 # Process the input parameters
5103 $params = array( 'frame' => array(), 'handler' => array(),
5104 'horizAlign' => array(), 'vertAlign' => array() );
5105 foreach ( $parts as $part ) {
5106 $part = trim( $part );
5107 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5109 if ( isset( $paramMap[$magicName] ) ) {
5110 list( $type, $paramName ) = $paramMap[$magicName];
5112 # Special case; width and height come in one variable together
5113 if ( $type === 'handler' && $paramName === 'width' ) {
5114 $parsedWidthParam = $this->parseWidthParam( $value );
5115 if( isset( $parsedWidthParam['width'] ) ) {
5116 $width = $parsedWidthParam['width'];
5117 if ( $handler->validateParam( 'width', $width ) ) {
5118 $params[$type]['width'] = $width;
5122 if( isset( $parsedWidthParam['height'] ) ) {
5123 $height = $parsedWidthParam['height'];
5124 if ( $handler->validateParam( 'height', $height ) ) {
5125 $params[$type]['height'] = $height;
5129 # else no validation -- bug 13436
5131 if ( $type === 'handler' ) {
5132 # Validate handler parameter
5133 $validated = $handler->validateParam( $paramName, $value );
5135 # Validate internal parameters
5136 switch( $paramName ) {
5140 # @todo FIXME: Possibly check validity here for
5141 # manualthumb? downstream behavior seems odd with
5142 # missing manual thumbs.
5144 $value = $this->stripAltText( $value, $holders );
5147 $chars = self
::EXT_LINK_URL_CLASS
;
5148 $prots = $this->mUrlProtocols
;
5149 if ( $value === '' ) {
5150 $paramName = 'no-link';
5153 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5154 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5155 $paramName = 'link-url';
5156 $this->mOutput
->addExternalLink( $value );
5157 if ( $this->mOptions
->getExternalLinkTarget() ) {
5158 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5163 $linkTitle = Title
::newFromText( $value );
5165 $paramName = 'link-title';
5166 $value = $linkTitle;
5167 $this->mOutput
->addLink( $linkTitle );
5173 # Most other things appear to be empty or numeric...
5174 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5179 $params[$type][$paramName] = $value;
5183 if ( !$validated ) {
5188 # Process alignment parameters
5189 if ( $params['horizAlign'] ) {
5190 $params['frame']['align'] = key( $params['horizAlign'] );
5192 if ( $params['vertAlign'] ) {
5193 $params['frame']['valign'] = key( $params['vertAlign'] );
5196 $params['frame']['caption'] = $caption;
5198 # Will the image be presented in a frame, with the caption below?
5199 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5200 isset( $params['frame']['framed'] ) ||
5201 isset( $params['frame']['thumbnail'] ) ||
5202 isset( $params['frame']['manualthumb'] );
5204 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5205 # came to also set the caption, ordinary text after the image -- which
5206 # makes no sense, because that just repeats the text multiple times in
5207 # screen readers. It *also* came to set the title attribute.
5209 # Now that we have an alt attribute, we should not set the alt text to
5210 # equal the caption: that's worse than useless, it just repeats the
5211 # text. This is the framed/thumbnail case. If there's no caption, we
5212 # use the unnamed parameter for alt text as well, just for the time be-
5213 # ing, if the unnamed param is set and the alt param is not.
5215 # For the future, we need to figure out if we want to tweak this more,
5216 # e.g., introducing a title= parameter for the title; ignoring the un-
5217 # named parameter entirely for images without a caption; adding an ex-
5218 # plicit caption= parameter and preserving the old magic unnamed para-
5220 if ( $imageIsFramed ) { # Framed image
5221 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5222 # No caption or alt text, add the filename as the alt text so
5223 # that screen readers at least get some description of the image
5224 $params['frame']['alt'] = $title->getText();
5226 # Do not set $params['frame']['title'] because tooltips don't make sense
5228 } else { # Inline image
5229 if ( !isset( $params['frame']['alt'] ) ) {
5230 # No alt text, use the "caption" for the alt text
5231 if ( $caption !== '') {
5232 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5234 # No caption, fall back to using the filename for the
5236 $params['frame']['alt'] = $title->getText();
5239 # Use the "caption" for the tooltip text
5240 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5243 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5245 # Linker does the rest
5246 $time = isset( $options['time'] ) ?
$options['time'] : false;
5247 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5248 $time, $descQuery, $this->mOptions
->getThumbSize() );
5250 # Give the handler a chance to modify the parser object
5252 $handler->parserTransformHook( $this, $file );
5260 * @param $holders LinkHolderArray
5261 * @return mixed|String
5263 protected function stripAltText( $caption, $holders ) {
5264 # Strip bad stuff out of the title (tooltip). We can't just use
5265 # replaceLinkHoldersText() here, because if this function is called
5266 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5268 $tooltip = $holders->replaceText( $caption );
5270 $tooltip = $this->replaceLinkHoldersText( $caption );
5273 # make sure there are no placeholders in thumbnail attributes
5274 # that are later expanded to html- so expand them now and
5276 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5277 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5283 * Set a flag in the output object indicating that the content is dynamic and
5284 * shouldn't be cached.
5286 function disableCache() {
5287 wfDebug( "Parser output marked as uncacheable.\n" );
5288 if ( !$this->mOutput
) {
5289 throw new MWException( __METHOD__
.
5290 " can only be called when actually parsing something" );
5292 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5293 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5297 * Callback from the Sanitizer for expanding items found in HTML attribute
5298 * values, so they can be safely tested and escaped.
5300 * @param $text String
5301 * @param $frame PPFrame
5304 function attributeStripCallback( &$text, $frame = false ) {
5305 $text = $this->replaceVariables( $text, $frame );
5306 $text = $this->mStripState
->unstripBoth( $text );
5315 function getTags() {
5316 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5320 * Replace transparent tags in $text with the values given by the callbacks.
5322 * Transparent tag hooks are like regular XML-style tag hooks, except they
5323 * operate late in the transformation sequence, on HTML instead of wikitext.
5325 * @param $text string
5329 function replaceTransparentTags( $text ) {
5331 $elements = array_keys( $this->mTransparentTagHooks
);
5332 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5333 $replacements = array();
5335 foreach ( $matches as $marker => $data ) {
5336 list( $element, $content, $params, $tag ) = $data;
5337 $tagName = strtolower( $element );
5338 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5339 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5343 $replacements[$marker] = $output;
5345 return strtr( $text, $replacements );
5349 * Break wikitext input into sections, and either pull or replace
5350 * some particular section's text.
5352 * External callers should use the getSection and replaceSection methods.
5354 * @param $text String: Page wikitext
5355 * @param $section String: a section identifier string of the form:
5356 * "<flag1> - <flag2> - ... - <section number>"
5358 * Currently the only recognised flag is "T", which means the target section number
5359 * was derived during a template inclusion parse, in other words this is a template
5360 * section edit link. If no flags are given, it was an ordinary section edit link.
5361 * This flag is required to avoid a section numbering mismatch when a section is
5362 * enclosed by "<includeonly>" (bug 6563).
5364 * The section number 0 pulls the text before the first heading; other numbers will
5365 * pull the given section along with its lower-level subsections. If the section is
5366 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5368 * Section 0 is always considered to exist, even if it only contains the empty
5369 * string. If $text is the empty string and section 0 is replaced, $newText is
5372 * @param $mode String: one of "get" or "replace"
5373 * @param $newText String: replacement text for section data.
5374 * @return String: for "get", the extracted section text.
5375 * for "replace", the whole page with the section replaced.
5377 private function extractSections( $text, $section, $mode, $newText='' ) {
5378 global $wgTitle; # not generally used but removes an ugly failure mode
5379 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5381 $frame = $this->getPreprocessor()->newFrame();
5383 # Process section extraction flags
5385 $sectionParts = explode( '-', $section );
5386 $sectionIndex = array_pop( $sectionParts );
5387 foreach ( $sectionParts as $part ) {
5388 if ( $part === 'T' ) {
5389 $flags |
= self
::PTD_FOR_INCLUSION
;
5393 # Check for empty input
5394 if ( strval( $text ) === '' ) {
5395 # Only sections 0 and T-0 exist in an empty document
5396 if ( $sectionIndex == 0 ) {
5397 if ( $mode === 'get' ) {
5403 if ( $mode === 'get' ) {
5411 # Preprocess the text
5412 $root = $this->preprocessToDom( $text, $flags );
5414 # <h> nodes indicate section breaks
5415 # They can only occur at the top level, so we can find them by iterating the root's children
5416 $node = $root->getFirstChild();
5418 # Find the target section
5419 if ( $sectionIndex == 0 ) {
5420 # Section zero doesn't nest, level=big
5421 $targetLevel = 1000;
5424 if ( $node->getName() === 'h' ) {
5425 $bits = $node->splitHeading();
5426 if ( $bits['i'] == $sectionIndex ) {
5427 $targetLevel = $bits['level'];
5431 if ( $mode === 'replace' ) {
5432 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5434 $node = $node->getNextSibling();
5440 if ( $mode === 'get' ) {
5447 # Find the end of the section, including nested sections
5449 if ( $node->getName() === 'h' ) {
5450 $bits = $node->splitHeading();
5451 $curLevel = $bits['level'];
5452 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5456 if ( $mode === 'get' ) {
5457 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5459 $node = $node->getNextSibling();
5462 # Write out the remainder (in replace mode only)
5463 if ( $mode === 'replace' ) {
5464 # Output the replacement text
5465 # Add two newlines on -- trailing whitespace in $newText is conventionally
5466 # stripped by the editor, so we need both newlines to restore the paragraph gap
5467 # Only add trailing whitespace if there is newText
5468 if ( $newText != "" ) {
5469 $outText .= $newText . "\n\n";
5473 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5474 $node = $node->getNextSibling();
5478 if ( is_string( $outText ) ) {
5479 # Re-insert stripped tags
5480 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5487 * This function returns the text of a section, specified by a number ($section).
5488 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5489 * the first section before any such heading (section 0).
5491 * If a section contains subsections, these are also returned.
5493 * @param $text String: text to look in
5494 * @param $section String: section identifier
5495 * @param $deftext String: default to return if section is not found
5496 * @return string text of the requested section
5498 public function getSection( $text, $section, $deftext='' ) {
5499 return $this->extractSections( $text, $section, "get", $deftext );
5503 * This function returns $oldtext after the content of the section
5504 * specified by $section has been replaced with $text. If the target
5505 * section does not exist, $oldtext is returned unchanged.
5507 * @param $oldtext String: former text of the article
5508 * @param $section int section identifier
5509 * @param $text String: replacing text
5510 * @return String: modified text
5512 public function replaceSection( $oldtext, $section, $text ) {
5513 return $this->extractSections( $oldtext, $section, "replace", $text );
5517 * Get the ID of the revision we are parsing
5519 * @return Mixed: integer or null
5521 function getRevisionId() {
5522 return $this->mRevisionId
;
5526 * Get the revision object for $this->mRevisionId
5528 * @return Revision|null either a Revision object or null
5530 protected function getRevisionObject() {
5531 if ( !is_null( $this->mRevisionObject
) ) {
5532 return $this->mRevisionObject
;
5534 if ( is_null( $this->mRevisionId
) ) {
5538 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5539 return $this->mRevisionObject
;
5543 * Get the timestamp associated with the current revision, adjusted for
5544 * the default server-local timestamp
5546 function getRevisionTimestamp() {
5547 if ( is_null( $this->mRevisionTimestamp
) ) {
5548 wfProfileIn( __METHOD__
);
5552 $revObject = $this->getRevisionObject();
5553 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5555 # The cryptic '' timezone parameter tells to use the site-default
5556 # timezone offset instead of the user settings.
5558 # Since this value will be saved into the parser cache, served
5559 # to other users, and potentially even used inside links and such,
5560 # it needs to be consistent for all visitors.
5561 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5563 wfProfileOut( __METHOD__
);
5565 return $this->mRevisionTimestamp
;
5569 * Get the name of the user that edited the last revision
5571 * @return String: user name
5573 function getRevisionUser() {
5574 if( is_null( $this->mRevisionUser
) ) {
5575 $revObject = $this->getRevisionObject();
5577 # if this template is subst: the revision id will be blank,
5578 # so just use the current user's name
5580 $this->mRevisionUser
= $revObject->getUserText();
5581 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5582 $this->mRevisionUser
= $this->getUser()->getName();
5585 return $this->mRevisionUser
;
5589 * Mutator for $mDefaultSort
5591 * @param $sort string New value
5593 public function setDefaultSort( $sort ) {
5594 $this->mDefaultSort
= $sort;
5595 $this->mOutput
->setProperty( 'defaultsort', $sort );
5599 * Accessor for $mDefaultSort
5600 * Will use the empty string if none is set.
5602 * This value is treated as a prefix, so the
5603 * empty string is equivalent to sorting by
5608 public function getDefaultSort() {
5609 if ( $this->mDefaultSort
!== false ) {
5610 return $this->mDefaultSort
;
5617 * Accessor for $mDefaultSort
5618 * Unlike getDefaultSort(), will return false if none is set
5620 * @return string or false
5622 public function getCustomDefaultSort() {
5623 return $this->mDefaultSort
;
5627 * Try to guess the section anchor name based on a wikitext fragment
5628 * presumably extracted from a heading, for example "Header" from
5631 * @param $text string
5635 public function guessSectionNameFromWikiText( $text ) {
5636 # Strip out wikitext links(they break the anchor)
5637 $text = $this->stripSectionName( $text );
5638 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5639 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5643 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5644 * instead. For use in redirects, since IE6 interprets Redirect: headers
5645 * as something other than UTF-8 (apparently?), resulting in breakage.
5647 * @param $text String: The section name
5648 * @return string An anchor
5650 public function guessLegacySectionNameFromWikiText( $text ) {
5651 # Strip out wikitext links(they break the anchor)
5652 $text = $this->stripSectionName( $text );
5653 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5654 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5658 * Strips a text string of wikitext for use in a section anchor
5660 * Accepts a text string and then removes all wikitext from the
5661 * string and leaves only the resultant text (i.e. the result of
5662 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5663 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5664 * to create valid section anchors by mimicing the output of the
5665 * parser when headings are parsed.
5667 * @param $text String: text string to be stripped of wikitext
5668 * for use in a Section anchor
5669 * @return string Filtered text string
5671 public function stripSectionName( $text ) {
5672 # Strip internal link markup
5673 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5674 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5676 # Strip external link markup
5677 # @todo FIXME: Not tolerant to blank link text
5678 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5679 # on how many empty links there are on the page - need to figure that out.
5680 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5682 # Parse wikitext quotes (italics & bold)
5683 $text = $this->doQuotes( $text );
5686 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5691 * strip/replaceVariables/unstrip for preprocessor regression testing
5693 * @param $text string
5694 * @param $title Title
5695 * @param $options ParserOptions
5696 * @param $outputType int
5700 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5701 $this->startParse( $title, $options, $outputType, true );
5703 $text = $this->replaceVariables( $text );
5704 $text = $this->mStripState
->unstripBoth( $text );
5705 $text = Sanitizer
::removeHTMLtags( $text );
5710 * @param $text string
5711 * @param $title Title
5712 * @param $options ParserOptions
5715 function testPst( $text, Title
$title, ParserOptions
$options ) {
5716 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5721 * @param $title Title
5722 * @param $options ParserOptions
5725 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5726 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5730 * Call a callback function on all regions of the given text that are not
5731 * inside strip markers, and replace those regions with the return value
5732 * of the callback. For example, with input:
5736 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5737 * two strings will be replaced with the value returned by the callback in
5745 function markerSkipCallback( $s, $callback ) {
5748 while ( $i < strlen( $s ) ) {
5749 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5750 if ( $markerStart === false ) {
5751 $out .= call_user_func( $callback, substr( $s, $i ) );
5754 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5755 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5756 if ( $markerEnd === false ) {
5757 $out .= substr( $s, $markerStart );
5760 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5761 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5770 * Remove any strip markers found in the given text.
5772 * @param $text Input string
5775 function killMarkers( $text ) {
5776 return $this->mStripState
->killMarkers( $text );
5780 * Save the parser state required to convert the given half-parsed text to
5781 * HTML. "Half-parsed" in this context means the output of
5782 * recursiveTagParse() or internalParse(). This output has strip markers
5783 * from replaceVariables (extensionSubstitution() etc.), and link
5784 * placeholders from replaceLinkHolders().
5786 * Returns an array which can be serialized and stored persistently. This
5787 * array can later be loaded into another parser instance with
5788 * unserializeHalfParsedText(). The text can then be safely incorporated into
5789 * the return value of a parser hook.
5791 * @param $text string
5795 function serializeHalfParsedText( $text ) {
5796 wfProfileIn( __METHOD__
);
5799 'version' => self
::HALF_PARSED_VERSION
,
5800 'stripState' => $this->mStripState
->getSubState( $text ),
5801 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5803 wfProfileOut( __METHOD__
);
5808 * Load the parser state given in the $data array, which is assumed to
5809 * have been generated by serializeHalfParsedText(). The text contents is
5810 * extracted from the array, and its markers are transformed into markers
5811 * appropriate for the current Parser instance. This transformed text is
5812 * returned, and can be safely included in the return value of a parser
5815 * If the $data array has been stored persistently, the caller should first
5816 * check whether it is still valid, by calling isValidHalfParsedText().
5818 * @param $data array Serialized data
5819 * @throws MWException
5822 function unserializeHalfParsedText( $data ) {
5823 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5824 throw new MWException( __METHOD__
.': invalid version' );
5827 # First, extract the strip state.
5828 $texts = array( $data['text'] );
5829 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5831 # Now renumber links
5832 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5834 # Should be good to go.
5839 * Returns true if the given array, presumed to be generated by
5840 * serializeHalfParsedText(), is compatible with the current version of the
5843 * @param $data Array
5847 function isValidHalfParsedText( $data ) {
5848 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5852 * Parsed a width param of imagelink like 300px or 200x300px
5854 * @param $value String
5859 public function parseWidthParam( $value ) {
5860 $parsedWidthParam = array();
5861 if( $value === '' ) {
5862 return $parsedWidthParam;
5865 # (bug 13500) In both cases (width/height and width only),
5866 # permit trailing "px" for backward compatibility.
5867 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5868 $width = intval( $m[1] );
5869 $height = intval( $m[2] );
5870 $parsedWidthParam['width'] = $width;
5871 $parsedWidthParam['height'] = $height;
5872 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5873 $width = intval( $value );
5874 $parsedWidthParam['width'] = $width;
5876 return $parsedWidthParam;