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
70 * Update this version number when the ParserOutput format
71 * changes in an incompatible way, so the parser cache
72 * can automatically discard old data.
74 const VERSION
= '1.6.4';
77 * Update this version number when the output of serialiseHalfParsedText()
78 * changes in an incompatible way
80 const HALF_PARSED_VERSION
= 2;
82 # Flags for Parser::setFunctionHook
83 # Also available as global constants from Defines.php
84 const SFH_NO_HASH
= 1;
85 const SFH_OBJECT_ARGS
= 2;
87 # Constants needed for external link processing
88 # Everything except bracket, space, or control characters
89 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
90 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
92 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
93 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
95 # State constants for the definition list colon extraction
96 const COLON_STATE_TEXT
= 0;
97 const COLON_STATE_TAG
= 1;
98 const COLON_STATE_TAGSTART
= 2;
99 const COLON_STATE_CLOSETAG
= 3;
100 const COLON_STATE_TAGSLASH
= 4;
101 const COLON_STATE_COMMENT
= 5;
102 const COLON_STATE_COMMENTDASH
= 6;
103 const COLON_STATE_COMMENTDASHDASH
= 7;
105 # Flags for preprocessToDom
106 const PTD_FOR_INCLUSION
= 1;
108 # Allowed values for $this->mOutputType
109 # Parameter to startExternalParse().
110 const OT_HTML
= 1; # like parse()
111 const OT_WIKI
= 2; # like preSaveTransform()
112 const OT_PREPROCESS
= 3; # like preprocess()
114 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
116 # Marker Suffix needs to be accessible staticly.
117 const MARKER_SUFFIX
= "-QINU\x7f";
120 var $mTagHooks = array();
121 var $mTransparentTagHooks = array();
122 var $mFunctionHooks = array();
123 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
124 var $mFunctionTagHooks = array();
125 var $mStripList = array();
126 var $mDefaultStripList = array();
127 var $mVarCache = array();
128 var $mImageParams = array();
129 var $mImageParamsMagicArray = array();
130 var $mMarkerIndex = 0;
131 var $mFirstCall = true;
133 # Initialised by initialiseVariables()
136 * @var MagicWordArray
141 * @var MagicWordArray
144 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
146 # Cleared with clearState():
151 var $mAutonumber, $mDTopen;
158 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
160 * @var LinkHolderArray
165 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
167 var $mTplExpandCache; # empty-frame expansion cache
168 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
169 var $mExpensiveFunctionCount; # number of expensive parser function calls
170 var $mShowToc, $mForceTocPosition;
175 var $mUser; # User object; only used when doing pre-save transform
178 # These are variables reset at least once per parse regardless of $clearState
188 var $mTitle; # Title context, used for self-link rendering and similar things
189 var $mOutputType; # Output type, one of the OT_xxx constants
190 var $ot; # Shortcut alias, see setOutputType()
191 var $mRevisionObject; # The revision object of the specified revision ID
192 var $mRevisionId; # ID to display in {{REVISIONID}} tags
193 var $mRevisionTimestamp; # The timestamp of the specified revision ID
194 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
195 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
203 * @var Array with the language name of each language link (i.e. the
204 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
205 * duplicate language links to the ParserOutput.
207 var $mLangLinkLanguages;
214 public function __construct( $conf = array() ) {
215 $this->mConf
= $conf;
216 $this->mUrlProtocols
= wfUrlProtocols();
217 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
218 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
219 if ( isset( $conf['preprocessorClass'] ) ) {
220 $this->mPreprocessorClass
= $conf['preprocessorClass'];
221 } elseif ( defined( 'MW_COMPILED' ) ) {
222 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
223 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 } elseif ( extension_loaded( 'domxml' ) ) {
225 # PECL extension that conflicts with the core DOM extension (bug 13770)
226 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
227 $this->mPreprocessorClass
= 'Preprocessor_Hash';
228 } elseif ( extension_loaded( 'dom' ) ) {
229 $this->mPreprocessorClass
= 'Preprocessor_DOM';
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
233 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
237 * Reduce memory usage to reduce the impact of circular references
239 function __destruct() {
240 if ( isset( $this->mLinkHolders
) ) {
241 unset( $this->mLinkHolders
);
243 foreach ( $this as $name => $value ) {
244 unset( $this->$name );
249 * Allow extensions to clean up when the parser is cloned
252 wfRunHooks( 'ParserCloned', array( $this ) );
256 * Do various kinds of initialisation on the first call of the parser
258 function firstCallInit() {
259 if ( !$this->mFirstCall
) {
262 $this->mFirstCall
= false;
264 wfProfileIn( __METHOD__
);
266 CoreParserFunctions
::register( $this );
267 CoreTagHooks
::register( $this );
268 $this->initialiseVariables();
270 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
271 wfProfileOut( __METHOD__
);
279 function clearState() {
280 wfProfileIn( __METHOD__
);
281 if ( $this->mFirstCall
) {
282 $this->firstCallInit();
284 $this->mOutput
= new ParserOutput
;
285 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
286 $this->mAutonumber
= 0;
287 $this->mLastSection
= '';
288 $this->mDTopen
= false;
289 $this->mIncludeCount
= array();
290 $this->mArgStack
= false;
291 $this->mInPre
= false;
292 $this->mLinkHolders
= new LinkHolderArray( $this );
294 $this->mRevisionObject
= $this->mRevisionTimestamp
=
295 $this->mRevisionId
= $this->mRevisionUser
= null;
296 $this->mVarCache
= array();
298 $this->mLangLinkLanguages
= array();
301 * Prefix for temporary replacement strings for the multipass parser.
302 * \x07 should never appear in input as it's disallowed in XML.
303 * Using it at the front also gives us a little extra robustness
304 * since it shouldn't match when butted up against identifier-like
307 * Must not consist of all title characters, or else it will change
308 * the behavior of <nowiki> in a link.
310 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
311 $this->mStripState
= new StripState( $this->mUniqPrefix
);
313 # Clear these on every parse, bug 4549
314 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
316 $this->mShowToc
= true;
317 $this->mForceTocPosition
= false;
318 $this->mIncludeSizes
= array(
322 $this->mPPNodeCount
= 0;
323 $this->mGeneratedPPNodeCount
= 0;
324 $this->mHighestExpansionDepth
= 0;
325 $this->mDefaultSort
= false;
326 $this->mHeadings
= array();
327 $this->mDoubleUnderscores
= array();
328 $this->mExpensiveFunctionCount
= 0;
331 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
332 $this->mPreprocessor
= null;
335 wfRunHooks( 'ParserClearState', array( &$this ) );
336 wfProfileOut( __METHOD__
);
340 * Convert wikitext to HTML
341 * Do not call this function recursively.
343 * @param string $text text we want to parse
344 * @param $title Title object
345 * @param $options ParserOptions
346 * @param $linestart boolean
347 * @param $clearState boolean
348 * @param int $revid number to pass in {{REVISIONID}}
349 * @return ParserOutput a ParserOutput
351 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
353 * First pass--just handle <nowiki> sections, pass the rest off
354 * to internalParse() which does all the real work.
357 global $wgUseTidy, $wgAlwaysUseTidy;
358 $fname = __METHOD__
. '-' . wfGetCaller();
359 wfProfileIn( __METHOD__
);
360 wfProfileIn( $fname );
362 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
364 # Remove the strip marker tag prefix from the input, if present.
366 $text = str_replace( $this->mUniqPrefix
, '', $text );
369 $oldRevisionId = $this->mRevisionId
;
370 $oldRevisionObject = $this->mRevisionObject
;
371 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
372 $oldRevisionUser = $this->mRevisionUser
;
373 if ( $revid !== null ) {
374 $this->mRevisionId
= $revid;
375 $this->mRevisionObject
= null;
376 $this->mRevisionTimestamp
= null;
377 $this->mRevisionUser
= null;
380 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
382 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
383 $text = $this->internalParse( $text );
384 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
386 $text = $this->mStripState
->unstripGeneral( $text );
388 # Clean up special characters, only run once, next-to-last before doBlockLevels
390 # french spaces, last one Guillemet-left
391 # only if there is something before the space
392 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
393 # french spaces, Guillemet-right
394 '/(\\302\\253) /' => '\\1 ',
395 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
397 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
399 $text = $this->doBlockLevels( $text, $linestart );
401 $this->replaceLinkHolders( $text );
404 * The input doesn't get language converted if
406 * b) Content isn't converted
407 * c) It's a conversion table
408 * d) it is an interface message (which is in the user language)
410 if ( !( $options->getDisableContentConversion()
411 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
413 if ( !$this->mOptions
->getInterfaceMessage() ) {
414 # The position of the convert() call should not be changed. it
415 # assumes that the links are all replaced and the only thing left
416 # is the <nowiki> mark.
417 $text = $this->getConverterLanguage()->convert( $text );
422 * A converted title will be provided in the output object if title and
423 * content conversion are enabled, the article text does not contain
424 * a conversion-suppressing double-underscore tag, and no
425 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
426 * automatic link conversion.
428 if ( !( $options->getDisableTitleConversion()
429 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
430 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
431 ||
$this->mOutput
->getDisplayTitle() !== false ) )
433 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
434 if ( $convruletitle ) {
435 $this->mOutput
->setTitleText( $convruletitle );
437 $titleText = $this->getConverterLanguage()->convertTitle( $title );
438 $this->mOutput
->setTitleText( $titleText );
442 $text = $this->mStripState
->unstripNoWiki( $text );
444 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
446 $text = $this->replaceTransparentTags( $text );
447 $text = $this->mStripState
->unstripGeneral( $text );
449 $text = Sanitizer
::normalizeCharReferences( $text );
451 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
452 $text = MWTidy
::tidy( $text );
454 # attempt to sanitize at least some nesting problems
455 # (bug #2702 and quite a few others)
457 # ''Something [http://www.cool.com cool''] -->
458 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
459 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
460 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
461 # fix up an anchor inside another anchor, only
462 # at least for a single single nested link (bug 3695)
463 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
464 '\\1\\2</a>\\3</a>\\1\\4</a>',
465 # fix div inside inline elements- doBlockLevels won't wrap a line which
466 # contains a div, so fix it up here; replace
467 # div with escaped text
468 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
469 '\\1\\3<div\\5>\\6</div>\\8\\9',
470 # remove empty italic or bold tag pairs, some
471 # introduced by rules above
472 '/<([bi])><\/\\1>/' => '',
475 $text = preg_replace(
476 array_keys( $tidyregs ),
477 array_values( $tidyregs ),
481 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
482 $this->limitationWarn( 'expensive-parserfunction',
483 $this->mExpensiveFunctionCount
,
484 $this->mOptions
->getExpensiveParserFunctionLimit()
488 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
490 # Information on include size limits, for the benefit of users who try to skirt them
491 if ( $this->mOptions
->getEnableLimitReport() ) {
492 $max = $this->mOptions
->getMaxIncludeSize();
493 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
495 "NewPP limit report\n" .
496 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
497 "Preprocessor generated node count: " .
498 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
499 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
500 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
501 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
503 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
505 // Sanitize for comment. Note '‐' in the replacement is U+2010,
506 // which looks much like the problematic '-'.
507 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
509 $text .= "\n<!-- \n$limitReport-->\n";
511 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
512 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
513 $this->mTitle
->getPrefixedDBkey() );
516 $this->mOutput
->setText( $text );
518 $this->mRevisionId
= $oldRevisionId;
519 $this->mRevisionObject
= $oldRevisionObject;
520 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
521 $this->mRevisionUser
= $oldRevisionUser;
522 wfProfileOut( $fname );
523 wfProfileOut( __METHOD__
);
525 return $this->mOutput
;
529 * Recursive parser entry point that can be called from an extension tag
532 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
534 * @param string $text text extension wants to have parsed
535 * @param $frame PPFrame: The frame to use for expanding any template variables
539 function recursiveTagParse( $text, $frame = false ) {
540 wfProfileIn( __METHOD__
);
541 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
542 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
543 $text = $this->internalParse( $text, false, $frame );
544 wfProfileOut( __METHOD__
);
549 * Expand templates and variables in the text, producing valid, static wikitext.
550 * Also removes comments.
551 * @return mixed|string
553 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
554 wfProfileIn( __METHOD__
);
555 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
556 if ( $revid !== null ) {
557 $this->mRevisionId
= $revid;
559 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
560 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
561 $text = $this->replaceVariables( $text );
562 $text = $this->mStripState
->unstripBoth( $text );
563 wfProfileOut( __METHOD__
);
568 * Recursive parser entry point that can be called from an extension tag
571 * @param string $text text to be expanded
572 * @param $frame PPFrame: The frame to use for expanding any template variables
576 public function recursivePreprocess( $text, $frame = false ) {
577 wfProfileIn( __METHOD__
);
578 $text = $this->replaceVariables( $text, $frame );
579 $text = $this->mStripState
->unstripBoth( $text );
580 wfProfileOut( __METHOD__
);
585 * Process the wikitext for the "?preload=" feature. (bug 5210)
587 * "<noinclude>", "<includeonly>" etc. are parsed as for template
588 * transclusion, comments, templates, arguments, tags hooks and parser
589 * functions are untouched.
591 * @param $text String
592 * @param $title Title
593 * @param $options ParserOptions
596 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
597 # Parser (re)initialisation
598 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
600 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
601 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
602 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
603 $text = $this->mStripState
->unstripBoth( $text );
608 * Get a random string
612 public static function getRandomString() {
613 return wfRandomString( 16 );
617 * Set the current user.
618 * Should only be used when doing pre-save transform.
620 * @param $user Mixed: User object or null (to reset)
622 function setUser( $user ) {
623 $this->mUser
= $user;
627 * Accessor for mUniqPrefix.
631 public function uniqPrefix() {
632 if ( !isset( $this->mUniqPrefix
) ) {
633 # @todo FIXME: This is probably *horribly wrong*
634 # LanguageConverter seems to want $wgParser's uniqPrefix, however
635 # if this is called for a parser cache hit, the parser may not
636 # have ever been initialized in the first place.
637 # Not really sure what the heck is supposed to be going on here.
639 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
641 return $this->mUniqPrefix
;
645 * Set the context title
649 function setTitle( $t ) {
650 if ( !$t ||
$t instanceof FakeTitle
) {
651 $t = Title
::newFromText( 'NO TITLE' );
654 if ( strval( $t->getFragment() ) !== '' ) {
655 # Strip the fragment to avoid various odd effects
656 $this->mTitle
= clone $t;
657 $this->mTitle
->setFragment( '' );
664 * Accessor for the Title object
666 * @return Title object
668 function getTitle() {
669 return $this->mTitle
;
673 * Accessor/mutator for the Title object
675 * @param $x Title object or null to just get the current one
676 * @return Title object
678 function Title( $x = null ) {
679 return wfSetVar( $this->mTitle
, $x );
683 * Set the output type
685 * @param $ot Integer: new value
687 function setOutputType( $ot ) {
688 $this->mOutputType
= $ot;
691 'html' => $ot == self
::OT_HTML
,
692 'wiki' => $ot == self
::OT_WIKI
,
693 'pre' => $ot == self
::OT_PREPROCESS
,
694 'plain' => $ot == self
::OT_PLAIN
,
699 * Accessor/mutator for the output type
701 * @param int|null $x New value or null to just get the current one
704 function OutputType( $x = null ) {
705 return wfSetVar( $this->mOutputType
, $x );
709 * Get the ParserOutput object
711 * @return ParserOutput object
713 function getOutput() {
714 return $this->mOutput
;
718 * Get the ParserOptions object
720 * @return ParserOptions object
722 function getOptions() {
723 return $this->mOptions
;
727 * Accessor/mutator for the ParserOptions object
729 * @param $x ParserOptions New value or null to just get the current one
730 * @return ParserOptions Current ParserOptions object
732 function Options( $x = null ) {
733 return wfSetVar( $this->mOptions
, $x );
739 function nextLinkID() {
740 return $this->mLinkID++
;
746 function setLinkID( $id ) {
747 $this->mLinkID
= $id;
751 * Get a language object for use in parser functions such as {{FORMATNUM:}}
754 function getFunctionLang() {
755 return $this->getTargetLanguage();
759 * Get the target language for the content being parsed. This is usually the
760 * language that the content is in.
764 * @throws MWException
765 * @return Language|null
767 public function getTargetLanguage() {
768 $target = $this->mOptions
->getTargetLanguage();
770 if ( $target !== null ) {
772 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
773 return $this->mOptions
->getUserLangObj();
774 } elseif ( is_null( $this->mTitle
) ) {
775 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
778 return $this->mTitle
->getPageLanguage();
782 * Get the language object for language conversion
784 function getConverterLanguage() {
785 return $this->getTargetLanguage();
789 * Get a User object either from $this->mUser, if set, or from the
790 * ParserOptions object otherwise
792 * @return User object
795 if ( !is_null( $this->mUser
) ) {
798 return $this->mOptions
->getUser();
802 * Get a preprocessor object
804 * @return Preprocessor instance
806 function getPreprocessor() {
807 if ( !isset( $this->mPreprocessor
) ) {
808 $class = $this->mPreprocessorClass
;
809 $this->mPreprocessor
= new $class( $this );
811 return $this->mPreprocessor
;
815 * Replaces all occurrences of HTML-style comments and the given tags
816 * in the text with a random marker and returns the next text. The output
817 * parameter $matches will be an associative array filled with data in
821 * 'UNIQ-xxxxx' => array(
824 * array( 'param' => 'x' ),
825 * '<element param="x">tag content</element>' ) )
828 * @param array $elements list of element names. Comments are always extracted.
829 * @param string $text Source text string.
830 * @param array $matches Out parameter, Array: extracted tags
831 * @param $uniq_prefix string
832 * @return String: stripped text
834 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
839 $taglist = implode( '|', $elements );
840 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
842 while ( $text != '' ) {
843 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
845 if ( count( $p ) < 5 ) {
848 if ( count( $p ) > 5 ) {
862 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
863 $stripped .= $marker;
865 if ( $close === '/>' ) {
866 # Empty element tag, <tag />
871 if ( $element === '!--' ) {
874 $end = "/(<\\/$element\\s*>)/i";
876 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
878 if ( count( $q ) < 3 ) {
879 # No end tag -- let it run out to the end of the text.
888 $matches[$marker] = array( $element,
890 Sanitizer
::decodeTagAttributes( $attributes ),
891 "<$element$attributes$close$content$tail" );
897 * Get a list of strippable XML-like elements
901 function getStripList() {
902 return $this->mStripList
;
906 * Add an item to the strip state
907 * Returns the unique tag which must be inserted into the stripped text
908 * The tag will be replaced with the original text in unstrip()
910 * @param $text string
914 function insertStripItem( $text ) {
915 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
916 $this->mMarkerIndex++
;
917 $this->mStripState
->addGeneral( $rnd, $text );
922 * parse the wiki syntax used to render tables
927 function doTableStuff( $text ) {
928 wfProfileIn( __METHOD__
);
930 $lines = StringUtils
::explode( "\n", $text );
932 $td_history = array(); # Is currently a td tag open?
933 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
934 $tr_history = array(); # Is currently a tr tag open?
935 $tr_attributes = array(); # history of tr attributes
936 $has_opened_tr = array(); # Did this table open a <tr> element?
937 $indent_level = 0; # indent level of the table
939 foreach ( $lines as $outLine ) {
940 $line = trim( $outLine );
942 if ( $line === '' ) { # empty line, go to next line
943 $out .= $outLine . "\n";
947 $first_character = $line[0];
950 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
951 # First check if we are starting a new table
952 $indent_level = strlen( $matches[1] );
954 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
955 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
957 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
958 array_push( $td_history, false );
959 array_push( $last_tag_history, '' );
960 array_push( $tr_history, false );
961 array_push( $tr_attributes, '' );
962 array_push( $has_opened_tr, false );
963 } elseif ( count( $td_history ) == 0 ) {
964 # Don't do any of the following
965 $out .= $outLine . "\n";
967 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
968 # We are ending a table
969 $line = '</table>' . substr( $line, 2 );
970 $last_tag = array_pop( $last_tag_history );
972 if ( !array_pop( $has_opened_tr ) ) {
973 $line = "<tr><td></td></tr>{$line}";
976 if ( array_pop( $tr_history ) ) {
977 $line = "</tr>{$line}";
980 if ( array_pop( $td_history ) ) {
981 $line = "</{$last_tag}>{$line}";
983 array_pop( $tr_attributes );
984 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
985 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
986 # Now we have a table row
987 $line = preg_replace( '#^\|-+#', '', $line );
989 # Whats after the tag is now only attributes
990 $attributes = $this->mStripState
->unstripBoth( $line );
991 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
992 array_pop( $tr_attributes );
993 array_push( $tr_attributes, $attributes );
996 $last_tag = array_pop( $last_tag_history );
997 array_pop( $has_opened_tr );
998 array_push( $has_opened_tr, true );
1000 if ( array_pop( $tr_history ) ) {
1004 if ( array_pop( $td_history ) ) {
1005 $line = "</{$last_tag}>{$line}";
1009 array_push( $tr_history, false );
1010 array_push( $td_history, false );
1011 array_push( $last_tag_history, '' );
1012 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1013 # This might be cell elements, td, th or captions
1014 if ( substr( $line, 0, 2 ) === '|+' ) {
1015 $first_character = '+';
1016 $line = substr( $line, 1 );
1019 $line = substr( $line, 1 );
1021 if ( $first_character === '!' ) {
1022 $line = str_replace( '!!', '||', $line );
1025 # Split up multiple cells on the same line.
1026 # FIXME : This can result in improper nesting of tags processed
1027 # by earlier parser steps, but should avoid splitting up eg
1028 # attribute values containing literal "||".
1029 $cells = StringUtils
::explodeMarkup( '||', $line );
1033 # Loop through each table cell
1034 foreach ( $cells as $cell ) {
1036 if ( $first_character !== '+' ) {
1037 $tr_after = array_pop( $tr_attributes );
1038 if ( !array_pop( $tr_history ) ) {
1039 $previous = "<tr{$tr_after}>\n";
1041 array_push( $tr_history, true );
1042 array_push( $tr_attributes, '' );
1043 array_pop( $has_opened_tr );
1044 array_push( $has_opened_tr, true );
1047 $last_tag = array_pop( $last_tag_history );
1049 if ( array_pop( $td_history ) ) {
1050 $previous = "</{$last_tag}>\n{$previous}";
1053 if ( $first_character === '|' ) {
1055 } elseif ( $first_character === '!' ) {
1057 } elseif ( $first_character === '+' ) {
1058 $last_tag = 'caption';
1063 array_push( $last_tag_history, $last_tag );
1065 # A cell could contain both parameters and data
1066 $cell_data = explode( '|', $cell, 2 );
1068 # Bug 553: Note that a '|' inside an invalid link should not
1069 # be mistaken as delimiting cell parameters
1070 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1071 $cell = "{$previous}<{$last_tag}>{$cell}";
1072 } elseif ( count( $cell_data ) == 1 ) {
1073 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1075 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1076 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1077 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1081 array_push( $td_history, true );
1084 $out .= $outLine . "\n";
1087 # Closing open td, tr && table
1088 while ( count( $td_history ) > 0 ) {
1089 if ( array_pop( $td_history ) ) {
1092 if ( array_pop( $tr_history ) ) {
1095 if ( !array_pop( $has_opened_tr ) ) {
1096 $out .= "<tr><td></td></tr>\n";
1099 $out .= "</table>\n";
1102 # Remove trailing line-ending (b/c)
1103 if ( substr( $out, -1 ) === "\n" ) {
1104 $out = substr( $out, 0, -1 );
1107 # special case: don't return empty table
1108 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1112 wfProfileOut( __METHOD__
);
1118 * Helper function for parse() that transforms wiki markup into
1119 * HTML. Only called for $mOutputType == self::OT_HTML.
1123 * @param $text string
1124 * @param $isMain bool
1125 * @param $frame bool
1129 function internalParse( $text, $isMain = true, $frame = false ) {
1130 wfProfileIn( __METHOD__
);
1134 # Hook to suspend the parser in this state
1135 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1136 wfProfileOut( __METHOD__
);
1140 # if $frame is provided, then use $frame for replacing any variables
1142 # use frame depth to infer how include/noinclude tags should be handled
1143 # depth=0 means this is the top-level document; otherwise it's an included document
1144 if ( !$frame->depth
) {
1147 $flag = Parser
::PTD_FOR_INCLUSION
;
1149 $dom = $this->preprocessToDom( $text, $flag );
1150 $text = $frame->expand( $dom );
1152 # if $frame is not provided, then use old-style replaceVariables
1153 $text = $this->replaceVariables( $text );
1156 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1157 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1158 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1160 # Tables need to come after variable replacement for things to work
1161 # properly; putting them before other transformations should keep
1162 # exciting things like link expansions from showing up in surprising
1164 $text = $this->doTableStuff( $text );
1166 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1168 $text = $this->doDoubleUnderscore( $text );
1170 $text = $this->doHeadings( $text );
1171 $text = $this->replaceInternalLinks( $text );
1172 $text = $this->doAllQuotes( $text );
1173 $text = $this->replaceExternalLinks( $text );
1175 # replaceInternalLinks may sometimes leave behind
1176 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1177 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1179 $text = $this->doMagicLinks( $text );
1180 $text = $this->formatHeadings( $text, $origText, $isMain );
1182 wfProfileOut( __METHOD__
);
1187 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1188 * magic external links.
1193 * @param $text string
1197 function doMagicLinks( $text ) {
1198 wfProfileIn( __METHOD__
);
1199 $prots = wfUrlProtocolsWithoutProtRel();
1200 $urlChar = self
::EXT_LINK_URL_CLASS
;
1201 $text = preg_replace_callback(
1203 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1204 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1205 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1206 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1207 ISBN\s+(\b # m[5]: ISBN, capture number
1208 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1209 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1210 [0-9Xx] # check digit
1212 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1213 wfProfileOut( __METHOD__
);
1218 * @throws MWException
1220 * @return HTML|string
1222 function magicLinkCallback( $m ) {
1223 if ( isset( $m[1] ) && $m[1] !== '' ) {
1226 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1229 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1230 # Free external link
1231 return $this->makeFreeExternalLink( $m[0] );
1232 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1234 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1237 $CssClass = 'mw-magiclink-rfc';
1239 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1241 $urlmsg = 'pubmedurl';
1242 $CssClass = 'mw-magiclink-pmid';
1245 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1246 substr( $m[0], 0, 20 ) . '"' );
1248 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1249 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1250 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1253 $num = strtr( $isbn, array(
1258 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1259 return '<a href="' .
1260 htmlspecialchars( $titleObj->getLocalURL() ) .
1261 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1268 * Make a free external link, given a user-supplied URL
1270 * @param $url string
1272 * @return string HTML
1275 function makeFreeExternalLink( $url ) {
1276 wfProfileIn( __METHOD__
);
1280 # The characters '<' and '>' (which were escaped by
1281 # removeHTMLtags()) should not be included in
1282 # URLs, per RFC 2396.
1284 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1285 $trail = substr( $url, $m2[0][1] ) . $trail;
1286 $url = substr( $url, 0, $m2[0][1] );
1289 # Move trailing punctuation to $trail
1291 # If there is no left bracket, then consider right brackets fair game too
1292 if ( strpos( $url, '(' ) === false ) {
1296 $numSepChars = strspn( strrev( $url ), $sep );
1297 if ( $numSepChars ) {
1298 $trail = substr( $url, -$numSepChars ) . $trail;
1299 $url = substr( $url, 0, -$numSepChars );
1302 $url = Sanitizer
::cleanUrl( $url );
1304 # Is this an external image?
1305 $text = $this->maybeMakeExternalImage( $url );
1306 if ( $text === false ) {
1307 # Not an image, make a link
1308 $text = Linker
::makeExternalLink( $url,
1309 $this->getConverterLanguage()->markNoConversion( $url, true ),
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;
1322 * Parse headers and return html
1326 * @param $text string
1330 function doHeadings( $text ) {
1331 wfProfileIn( __METHOD__
);
1332 for ( $i = 6; $i >= 1; --$i ) {
1333 $h = str_repeat( '=', $i );
1334 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1336 wfProfileOut( __METHOD__
);
1341 * Replace single quotes with HTML markup
1344 * @param $text string
1346 * @return string the altered text
1348 function doAllQuotes( $text ) {
1349 wfProfileIn( __METHOD__
);
1351 $lines = StringUtils
::explode( "\n", $text );
1352 foreach ( $lines as $line ) {
1353 $outtext .= $this->doQuotes( $line ) . "\n";
1355 $outtext = substr( $outtext, 0, -1 );
1356 wfProfileOut( __METHOD__
);
1361 * Helper function for doAllQuotes()
1363 * @param $text string
1367 public function doQuotes( $text ) {
1368 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1369 if ( count( $arr ) == 1 ) {
1372 # First, do some preliminary work. This may shift some apostrophes from
1373 # being mark-up to being text. It also counts the number of occurrences
1374 # of bold and italics mark-ups.
1377 for ( $i = 0; $i < count( $arr ); $i++
) {
1378 if ( ( $i %
2 ) == 1 ) {
1379 # If there are ever four apostrophes, assume the first is supposed to
1380 # be text, and the remaining three constitute mark-up for bold text.
1381 if ( strlen( $arr[$i] ) == 4 ) {
1382 $arr[$i - 1] .= "'";
1384 } elseif ( strlen( $arr[$i] ) > 5 ) {
1385 # If there are more than 5 apostrophes in a row, assume they're all
1386 # text except for the last 5.
1387 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1390 # Count the number of occurrences of bold and italics mark-ups.
1391 # We are not counting sequences of five apostrophes.
1392 if ( strlen( $arr[$i] ) == 2 ) {
1394 } elseif ( strlen( $arr[$i] ) == 3 ) {
1396 } elseif ( strlen( $arr[$i] ) == 5 ) {
1403 # If there is an odd number of both bold and italics, it is likely
1404 # that one of the bold ones was meant to be an apostrophe followed
1405 # by italics. Which one we cannot know for certain, but it is more
1406 # likely to be one that has a single-letter word before it.
1407 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1409 $firstsingleletterword = -1;
1410 $firstmultiletterword = -1;
1412 foreach ( $arr as $r ) {
1413 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1414 $x1 = substr( $arr[$i - 1], -1 );
1415 $x2 = substr( $arr[$i - 1], -2, 1 );
1416 if ( $x1 === ' ' ) {
1417 if ( $firstspace == -1 ) {
1420 } elseif ( $x2 === ' ' ) {
1421 if ( $firstsingleletterword == -1 ) {
1422 $firstsingleletterword = $i;
1425 if ( $firstmultiletterword == -1 ) {
1426 $firstmultiletterword = $i;
1433 # If there is a single-letter word, use it!
1434 if ( $firstsingleletterword > -1 ) {
1435 $arr[$firstsingleletterword] = "''";
1436 $arr[$firstsingleletterword - 1] .= "'";
1437 } elseif ( $firstmultiletterword > -1 ) {
1438 # If not, but there's a multi-letter word, use that one.
1439 $arr[$firstmultiletterword] = "''";
1440 $arr[$firstmultiletterword - 1] .= "'";
1441 } elseif ( $firstspace > -1 ) {
1442 # ... otherwise use the first one that has neither.
1443 # (notice that it is possible for all three to be -1 if, for example,
1444 # there is only one pentuple-apostrophe in the line)
1445 $arr[$firstspace] = "''";
1446 $arr[$firstspace - 1] .= "'";
1450 # Now let's actually convert our apostrophic mush to HTML!
1455 foreach ( $arr as $r ) {
1456 if ( ( $i %
2 ) == 0 ) {
1457 if ( $state === 'both' ) {
1463 if ( strlen( $r ) == 2 ) {
1464 if ( $state === 'i' ) {
1467 } elseif ( $state === 'bi' ) {
1470 } elseif ( $state === 'ib' ) {
1471 $output .= '</b></i><b>';
1473 } elseif ( $state === 'both' ) {
1474 $output .= '<b><i>' . $buffer . '</i>';
1476 } else { # $state can be 'b' or ''
1480 } elseif ( strlen( $r ) == 3 ) {
1481 if ( $state === 'b' ) {
1484 } elseif ( $state === 'bi' ) {
1485 $output .= '</i></b><i>';
1487 } elseif ( $state === 'ib' ) {
1490 } elseif ( $state === 'both' ) {
1491 $output .= '<i><b>' . $buffer . '</b>';
1493 } else { # $state can be 'i' or ''
1497 } elseif ( strlen( $r ) == 5 ) {
1498 if ( $state === 'b' ) {
1499 $output .= '</b><i>';
1501 } elseif ( $state === 'i' ) {
1502 $output .= '</i><b>';
1504 } elseif ( $state === 'bi' ) {
1505 $output .= '</i></b>';
1507 } elseif ( $state === 'ib' ) {
1508 $output .= '</b></i>';
1510 } elseif ( $state === 'both' ) {
1511 $output .= '<i><b>' . $buffer . '</b></i>';
1513 } else { # ($state == '')
1521 # Now close all remaining tags. Notice that the order is important.
1522 if ( $state === 'b' ||
$state === 'ib' ) {
1525 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1528 if ( $state === 'bi' ) {
1531 # There might be lonely ''''', so make sure we have a buffer
1532 if ( $state === 'both' && $buffer ) {
1533 $output .= '<b><i>' . $buffer . '</i></b>';
1540 * Replace external links (REL)
1542 * Note: this is all very hackish and the order of execution matters a lot.
1543 * Make sure to run maintenance/parserTests.php if you change this code.
1547 * @param $text string
1549 * @throws MWException
1552 function replaceExternalLinks( $text ) {
1553 wfProfileIn( __METHOD__
);
1555 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1556 if ( $bits === false ) {
1557 wfProfileOut( __METHOD__
);
1558 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1560 $s = array_shift( $bits );
1563 while ( $i < count( $bits ) ) {
1566 $text = $bits[$i++
];
1567 $trail = $bits[$i++
];
1569 # The characters '<' and '>' (which were escaped by
1570 # removeHTMLtags()) should not be included in
1571 # URLs, per RFC 2396.
1573 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1574 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1575 $url = substr( $url, 0, $m2[0][1] );
1578 # If the link text is an image URL, replace it with an <img> tag
1579 # This happened by accident in the original parser, but some people used it extensively
1580 $img = $this->maybeMakeExternalImage( $text );
1581 if ( $img !== false ) {
1587 # Set linktype for CSS - if URL==text, link is essentially free
1588 $linktype = ( $text === $url ) ?
'free' : 'text';
1590 # No link text, e.g. [http://domain.tld/some.link]
1591 if ( $text == '' ) {
1593 $langObj = $this->getTargetLanguage();
1594 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1595 $linktype = 'autonumber';
1597 # Have link text, e.g. [http://domain.tld/some.link text]s
1599 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1602 $text = $this->getConverterLanguage()->markNoConversion( $text );
1604 $url = Sanitizer
::cleanUrl( $url );
1606 # Use the encoded URL
1607 # This means that users can paste URLs directly into the text
1608 # Funny characters like ö aren't valid in URLs anyway
1609 # This was changed in August 2004
1610 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1611 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1613 # Register link in the output object.
1614 # Replace unnecessary URL escape codes with the referenced character
1615 # This prevents spammers from hiding links from the filters
1616 $pasteurized = self
::replaceUnusualEscapes( $url );
1617 $this->mOutput
->addExternalLink( $pasteurized );
1620 wfProfileOut( __METHOD__
);
1624 * Get the rel attribute for a particular external link.
1627 * @param string|bool $url optional URL, to extract the domain from for rel =>
1628 * nofollow if appropriate
1629 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1630 * @return string|null rel attribute for $url
1632 public static function getExternalLinkRel( $url = false, $title = null ) {
1633 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1634 $ns = $title ?
$title->getNamespace() : false;
1635 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1636 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1643 * Get an associative array of additional HTML attributes appropriate for a
1644 * particular external link. This currently may include rel => nofollow
1645 * (depending on configuration, namespace, and the URL's domain) and/or a
1646 * target attribute (depending on configuration).
1648 * @param string|bool $url optional URL, to extract the domain from for rel =>
1649 * nofollow if appropriate
1650 * @return Array associative array of HTML attributes
1652 function getExternalLinkAttribs( $url = false ) {
1654 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1656 if ( $this->mOptions
->getExternalLinkTarget() ) {
1657 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1663 * Replace unusual URL escape codes with their equivalent characters
1665 * @param $url String
1668 * @todo This can merge genuinely required bits in the path or query string,
1669 * breaking legit URLs. A proper fix would treat the various parts of
1670 * the URL differently; as a workaround, just use the output for
1671 * statistical records, not for actual linking/output.
1673 static function replaceUnusualEscapes( $url ) {
1674 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1675 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1679 * Callback function used in replaceUnusualEscapes().
1680 * Replaces unusual URL escape codes with their equivalent character
1682 * @param $matches array
1686 private static function replaceUnusualEscapesCallback( $matches ) {
1687 $char = urldecode( $matches[0] );
1688 $ord = ord( $char );
1689 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1690 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1691 # No, shouldn't be escaped
1694 # Yes, leave it escaped
1700 * make an image if it's allowed, either through the global
1701 * option, through the exception, or through the on-wiki whitelist
1704 * $param $url string
1708 function maybeMakeExternalImage( $url ) {
1709 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1710 $imagesexception = !empty( $imagesfrom );
1712 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1713 if ( $imagesexception && is_array( $imagesfrom ) ) {
1714 $imagematch = false;
1715 foreach ( $imagesfrom as $match ) {
1716 if ( strpos( $url, $match ) === 0 ) {
1721 } elseif ( $imagesexception ) {
1722 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1724 $imagematch = false;
1726 if ( $this->mOptions
->getAllowExternalImages()
1727 ||
( $imagesexception && $imagematch ) ) {
1728 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1730 $text = Linker
::makeExternalImage( $url );
1733 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1734 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1735 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1736 foreach ( $whitelist as $entry ) {
1737 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1738 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1741 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1742 # Image matches a whitelist entry
1743 $text = Linker
::makeExternalImage( $url );
1752 * Process [[ ]] wikilinks
1756 * @return String: processed text
1760 function replaceInternalLinks( $s ) {
1761 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1766 * Process [[ ]] wikilinks (RIL)
1768 * @throws MWException
1769 * @return LinkHolderArray
1773 function replaceInternalLinks2( &$s ) {
1774 wfProfileIn( __METHOD__
);
1776 wfProfileIn( __METHOD__
. '-setup' );
1777 static $tc = false, $e1, $e1_img;
1778 # the % is needed to support urlencoded titles as well
1780 $tc = Title
::legalChars() . '#%';
1781 # Match a link having the form [[namespace:link|alternate]]trail
1782 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1783 # Match cases where there is no "]]", which might still be images
1784 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1787 $holders = new LinkHolderArray( $this );
1789 # split the entire text string on occurrences of [[
1790 $a = StringUtils
::explode( '[[', ' ' . $s );
1791 # get the first element (all text up to first [[), and remove the space we added
1794 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1795 $s = substr( $s, 1 );
1797 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1799 if ( $useLinkPrefixExtension ) {
1800 # Match the end of a line for a word that's not followed by whitespace,
1801 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1802 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1805 if ( is_null( $this->mTitle
) ) {
1806 wfProfileOut( __METHOD__
. '-setup' );
1807 wfProfileOut( __METHOD__
);
1808 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1810 $nottalk = !$this->mTitle
->isTalkPage();
1812 if ( $useLinkPrefixExtension ) {
1814 if ( preg_match( $e2, $s, $m ) ) {
1815 $first_prefix = $m[2];
1817 $first_prefix = false;
1823 $useSubpages = $this->areSubpagesAllowed();
1824 wfProfileOut( __METHOD__
. '-setup' );
1826 # Loop for each link
1827 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1828 # Check for excessive memory usage
1829 if ( $holders->isBig() ) {
1831 # Do the existence check, replace the link holders and clear the array
1832 $holders->replace( $s );
1836 if ( $useLinkPrefixExtension ) {
1837 wfProfileIn( __METHOD__
. '-prefixhandling' );
1838 if ( preg_match( $e2, $s, $m ) ) {
1845 if ( $first_prefix ) {
1846 $prefix = $first_prefix;
1847 $first_prefix = false;
1849 wfProfileOut( __METHOD__
. '-prefixhandling' );
1852 $might_be_img = false;
1854 wfProfileIn( __METHOD__
. "-e1" );
1855 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1857 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1858 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1859 # the real problem is with the $e1 regex
1862 # Still some problems for cases where the ] is meant to be outside punctuation,
1863 # and no image is in sight. See bug 2095.
1865 if ( $text !== '' &&
1866 substr( $m[3], 0, 1 ) === ']' &&
1867 strpos( $text, '[' ) !== false
1870 $text .= ']'; # so that replaceExternalLinks($text) works later
1871 $m[3] = substr( $m[3], 1 );
1873 # fix up urlencoded title texts
1874 if ( strpos( $m[1], '%' ) !== false ) {
1875 # Should anchors '#' also be rejected?
1876 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1879 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1880 $might_be_img = true;
1882 if ( strpos( $m[1], '%' ) !== false ) {
1883 $m[1] = rawurldecode( $m[1] );
1886 } else { # Invalid form; output directly
1887 $s .= $prefix . '[[' . $line;
1888 wfProfileOut( __METHOD__
. "-e1" );
1891 wfProfileOut( __METHOD__
. "-e1" );
1892 wfProfileIn( __METHOD__
. "-misc" );
1894 # Don't allow internal links to pages containing
1895 # PROTO: where PROTO is a valid URL protocol; these
1896 # should be external links.
1897 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1898 $s .= $prefix . '[[' . $line;
1899 wfProfileOut( __METHOD__
. "-misc" );
1903 # Make subpage if necessary
1904 if ( $useSubpages ) {
1905 $link = $this->maybeDoSubpageLink( $m[1], $text );
1910 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1912 # Strip off leading ':'
1913 $link = substr( $link, 1 );
1916 wfProfileOut( __METHOD__
. "-misc" );
1917 wfProfileIn( __METHOD__
. "-title" );
1918 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1919 if ( $nt === null ) {
1920 $s .= $prefix . '[[' . $line;
1921 wfProfileOut( __METHOD__
. "-title" );
1925 $ns = $nt->getNamespace();
1926 $iw = $nt->getInterWiki();
1927 wfProfileOut( __METHOD__
. "-title" );
1929 if ( $might_be_img ) { # if this is actually an invalid link
1930 wfProfileIn( __METHOD__
. "-might_be_img" );
1931 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1934 # look at the next 'line' to see if we can close it there
1936 $next_line = $a->current();
1937 if ( $next_line === false ||
$next_line === null ) {
1940 $m = explode( ']]', $next_line, 3 );
1941 if ( count( $m ) == 3 ) {
1942 # the first ]] closes the inner link, the second the image
1944 $text .= "[[{$m[0]}]]{$m[1]}";
1947 } elseif ( count( $m ) == 2 ) {
1948 # if there's exactly one ]] that's fine, we'll keep looking
1949 $text .= "[[{$m[0]}]]{$m[1]}";
1951 # if $next_line is invalid too, we need look no further
1952 $text .= '[[' . $next_line;
1957 # we couldn't find the end of this imageLink, so output it raw
1958 # but don't ignore what might be perfectly normal links in the text we've examined
1959 $holders->merge( $this->replaceInternalLinks2( $text ) );
1960 $s .= "{$prefix}[[$link|$text";
1961 # note: no $trail, because without an end, there *is* no trail
1962 wfProfileOut( __METHOD__
. "-might_be_img" );
1965 } else { # it's not an image, so output it raw
1966 $s .= "{$prefix}[[$link|$text";
1967 # note: no $trail, because without an end, there *is* no trail
1968 wfProfileOut( __METHOD__
. "-might_be_img" );
1971 wfProfileOut( __METHOD__
. "-might_be_img" );
1974 $wasblank = ( $text == '' );
1978 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1979 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1980 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1981 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1982 $text = $this->doQuotes( $text );
1985 # Link not escaped by : , create the various objects
1988 wfProfileIn( __METHOD__
. "-interwiki" );
1989 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1990 // XXX: the above check prevents links to sites with identifiers that are not language codes
1992 # Bug 24502: filter duplicates
1993 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1994 $this->mLangLinkLanguages
[$iw] = true;
1995 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1998 $s = rtrim( $s . $prefix );
1999 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2000 wfProfileOut( __METHOD__
. "-interwiki" );
2003 wfProfileOut( __METHOD__
. "-interwiki" );
2005 if ( $ns == NS_FILE
) {
2006 wfProfileIn( __METHOD__
. "-image" );
2007 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2009 # if no parameters were passed, $text
2010 # becomes something like "File:Foo.png",
2011 # which we don't want to pass on to the
2015 # recursively parse links inside the image caption
2016 # actually, this will parse them in any other parameters, too,
2017 # but it might be hard to fix that, and it doesn't matter ATM
2018 $text = $this->replaceExternalLinks( $text );
2019 $holders->merge( $this->replaceInternalLinks2( $text ) );
2021 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2022 $s .= $prefix . $this->armorLinks(
2023 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2025 $s .= $prefix . $trail;
2027 wfProfileOut( __METHOD__
. "-image" );
2031 if ( $ns == NS_CATEGORY
) {
2032 wfProfileIn( __METHOD__
. "-category" );
2033 $s = rtrim( $s . "\n" ); # bug 87
2036 $sortkey = $this->getDefaultSort();
2040 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2041 $sortkey = str_replace( "\n", '', $sortkey );
2042 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2043 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2046 * Strip the whitespace Category links produce, see bug 87
2047 * @todo We might want to use trim($tmp, "\n") here.
2049 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2051 wfProfileOut( __METHOD__
. "-category" );
2056 # Self-link checking
2057 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2058 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2059 $this->mTitle
->getPrefixedText(),
2060 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2063 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2068 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2069 # @todo FIXME: Should do batch file existence checks, see comment below
2070 if ( $ns == NS_MEDIA
) {
2071 wfProfileIn( __METHOD__
. "-media" );
2072 # Give extensions a chance to select the file revision for us
2075 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2076 array( $this, $nt, &$options, &$descQuery ) );
2077 # Fetch and register the file (file title may be different via hooks)
2078 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2079 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2080 $s .= $prefix . $this->armorLinks(
2081 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2082 wfProfileOut( __METHOD__
. "-media" );
2086 wfProfileIn( __METHOD__
. "-always_known" );
2087 # Some titles, such as valid special pages or files in foreign repos, should
2088 # be shown as bluelinks even though they're not included in the page table
2090 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2091 # batch file existence checks for NS_FILE and NS_MEDIA
2092 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2093 $this->mOutput
->addLink( $nt );
2094 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2096 # Links will be added to the output link list after checking
2097 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2099 wfProfileOut( __METHOD__
. "-always_known" );
2101 wfProfileOut( __METHOD__
);
2106 * Render a forced-blue link inline; protect against double expansion of
2107 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2108 * Since this little disaster has to split off the trail text to avoid
2109 * breaking URLs in the following text without breaking trails on the
2110 * wiki links, it's been made into a horrible function.
2113 * @param $text String
2114 * @param array $query or String
2115 * @param $trail String
2116 * @param $prefix String
2117 * @return String: HTML-wikitext mix oh yuck
2119 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2120 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2122 if ( is_string( $query ) ) {
2123 $query = wfCgiToArray( $query );
2125 if ( $text == '' ) {
2126 $text = htmlspecialchars( $nt->getPrefixedText() );
2129 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2131 return $this->armorLinks( $link ) . $trail;
2135 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2136 * going to go through further parsing steps before inline URL expansion.
2138 * Not needed quite as much as it used to be since free links are a bit
2139 * more sensible these days. But bracketed links are still an issue.
2141 * @param string $text more-or-less HTML
2142 * @return String: less-or-more HTML with NOPARSE bits
2144 function armorLinks( $text ) {
2145 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2146 "{$this->mUniqPrefix}NOPARSE$1", $text );
2150 * Return true if subpage links should be expanded on this page.
2153 function areSubpagesAllowed() {
2154 # Some namespaces don't allow subpages
2155 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2159 * Handle link to subpage if necessary
2161 * @param string $target the source of the link
2162 * @param &$text String: the link text, modified as necessary
2163 * @return string the full name of the link
2166 function maybeDoSubpageLink( $target, &$text ) {
2167 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2171 * Used by doBlockLevels()
2176 function closeParagraph() {
2178 if ( $this->mLastSection
!= '' ) {
2179 $result = '</' . $this->mLastSection
. ">\n";
2181 $this->mInPre
= false;
2182 $this->mLastSection
= '';
2187 * getCommon() returns the length of the longest common substring
2188 * of both arguments, starting at the beginning of both.
2191 * @param $st1 string
2192 * @param $st2 string
2196 function getCommon( $st1, $st2 ) {
2197 $fl = strlen( $st1 );
2198 $shorter = strlen( $st2 );
2199 if ( $fl < $shorter ) {
2203 for ( $i = 0; $i < $shorter; ++
$i ) {
2204 if ( $st1[$i] != $st2[$i] ) {
2212 * These next three functions open, continue, and close the list
2213 * element appropriate to the prefix character passed into them.
2216 * @param $char string
2220 function openList( $char ) {
2221 $result = $this->closeParagraph();
2223 if ( '*' === $char ) {
2224 $result .= '<ul><li>';
2225 } elseif ( '#' === $char ) {
2226 $result .= '<ol><li>';
2227 } elseif ( ':' === $char ) {
2228 $result .= '<dl><dd>';
2229 } elseif ( ';' === $char ) {
2230 $result .= '<dl><dt>';
2231 $this->mDTopen
= true;
2233 $result = '<!-- ERR 1 -->';
2241 * @param $char String
2246 function nextItem( $char ) {
2247 if ( '*' === $char ||
'#' === $char ) {
2249 } elseif ( ':' === $char ||
';' === $char ) {
2251 if ( $this->mDTopen
) {
2254 if ( ';' === $char ) {
2255 $this->mDTopen
= true;
2256 return $close . '<dt>';
2258 $this->mDTopen
= false;
2259 return $close . '<dd>';
2262 return '<!-- ERR 2 -->';
2267 * @param $char String
2272 function closeList( $char ) {
2273 if ( '*' === $char ) {
2274 $text = '</li></ul>';
2275 } elseif ( '#' === $char ) {
2276 $text = '</li></ol>';
2277 } elseif ( ':' === $char ) {
2278 if ( $this->mDTopen
) {
2279 $this->mDTopen
= false;
2280 $text = '</dt></dl>';
2282 $text = '</dd></dl>';
2285 return '<!-- ERR 3 -->';
2287 return $text . "\n";
2292 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2294 * @param $text String
2295 * @param $linestart Boolean: whether or not this is at the start of a line.
2297 * @return string the lists rendered as HTML
2299 function doBlockLevels( $text, $linestart ) {
2300 wfProfileIn( __METHOD__
);
2302 # Parsing through the text line by line. The main thing
2303 # happening here is handling of block-level elements p, pre,
2304 # and making lists from lines starting with * # : etc.
2306 $textLines = StringUtils
::explode( "\n", $text );
2308 $lastPrefix = $output = '';
2309 $this->mDTopen
= $inBlockElem = false;
2311 $paragraphStack = false;
2313 foreach ( $textLines as $oLine ) {
2315 if ( !$linestart ) {
2325 $lastPrefixLength = strlen( $lastPrefix );
2326 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2327 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2328 # If not in a <pre> element, scan for and figure out what prefixes are there.
2329 if ( !$this->mInPre
) {
2330 # Multiple prefixes may abut each other for nested lists.
2331 $prefixLength = strspn( $oLine, '*#:;' );
2332 $prefix = substr( $oLine, 0, $prefixLength );
2335 # ; and : are both from definition-lists, so they're equivalent
2336 # for the purposes of determining whether or not we need to open/close
2338 $prefix2 = str_replace( ';', ':', $prefix );
2339 $t = substr( $oLine, $prefixLength );
2340 $this->mInPre
= (bool)$preOpenMatch;
2342 # Don't interpret any other prefixes in preformatted text
2344 $prefix = $prefix2 = '';
2349 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2350 # Same as the last item, so no need to deal with nesting or opening stuff
2351 $output .= $this->nextItem( substr( $prefix, -1 ) );
2352 $paragraphStack = false;
2354 if ( substr( $prefix, -1 ) === ';' ) {
2355 # The one nasty exception: definition lists work like this:
2356 # ; title : definition text
2357 # So we check for : in the remainder text to split up the
2358 # title and definition, without b0rking links.
2360 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2362 $output .= $term . $this->nextItem( ':' );
2365 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2366 # We need to open or close prefixes, or both.
2368 # Either open or close a level...
2369 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2370 $paragraphStack = false;
2372 # Close all the prefixes which aren't shared.
2373 while ( $commonPrefixLength < $lastPrefixLength ) {
2374 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2375 --$lastPrefixLength;
2378 # Continue the current prefix if appropriate.
2379 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2380 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2383 # Open prefixes where appropriate.
2384 while ( $prefixLength > $commonPrefixLength ) {
2385 $char = substr( $prefix, $commonPrefixLength, 1 );
2386 $output .= $this->openList( $char );
2388 if ( ';' === $char ) {
2389 # @todo FIXME: This is dupe of code above
2390 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2392 $output .= $term . $this->nextItem( ':' );
2395 ++
$commonPrefixLength;
2397 $lastPrefix = $prefix2;
2400 # If we have no prefixes, go to paragraph mode.
2401 if ( 0 == $prefixLength ) {
2402 wfProfileIn( __METHOD__
. "-paragraph" );
2403 # No prefix (not in list)--go to paragraph mode
2404 # XXX: use a stack for nestable elements like span, table and div
2405 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2406 $closematch = preg_match(
2407 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2408 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2409 if ( $openmatch or $closematch ) {
2410 $paragraphStack = false;
2411 # TODO bug 5718: paragraph closed
2412 $output .= $this->closeParagraph();
2413 if ( $preOpenMatch and !$preCloseMatch ) {
2414 $this->mInPre
= true;
2416 $inBlockElem = !$closematch;
2417 } elseif ( !$inBlockElem && !$this->mInPre
) {
2418 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2420 if ( $this->mLastSection
!== 'pre' ) {
2421 $paragraphStack = false;
2422 $output .= $this->closeParagraph() . '<pre>';
2423 $this->mLastSection
= 'pre';
2425 $t = substr( $t, 1 );
2428 if ( trim( $t ) === '' ) {
2429 if ( $paragraphStack ) {
2430 $output .= $paragraphStack . '<br />';
2431 $paragraphStack = false;
2432 $this->mLastSection
= 'p';
2434 if ( $this->mLastSection
!== 'p' ) {
2435 $output .= $this->closeParagraph();
2436 $this->mLastSection
= '';
2437 $paragraphStack = '<p>';
2439 $paragraphStack = '</p><p>';
2443 if ( $paragraphStack ) {
2444 $output .= $paragraphStack;
2445 $paragraphStack = false;
2446 $this->mLastSection
= 'p';
2447 } elseif ( $this->mLastSection
!== 'p' ) {
2448 $output .= $this->closeParagraph() . '<p>';
2449 $this->mLastSection
= 'p';
2454 wfProfileOut( __METHOD__
. "-paragraph" );
2456 # somewhere above we forget to get out of pre block (bug 785)
2457 if ( $preCloseMatch && $this->mInPre
) {
2458 $this->mInPre
= false;
2460 if ( $paragraphStack === false ) {
2461 $output .= $t . "\n";
2464 while ( $prefixLength ) {
2465 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2468 if ( $this->mLastSection
!= '' ) {
2469 $output .= '</' . $this->mLastSection
. '>';
2470 $this->mLastSection
= '';
2473 wfProfileOut( __METHOD__
);
2478 * Split up a string on ':', ignoring any occurrences inside tags
2479 * to prevent illegal overlapping.
2481 * @param string $str the string to split
2482 * @param &$before String set to everything before the ':'
2483 * @param &$after String set to everything after the ':'
2484 * @throws MWException
2485 * @return String the position of the ':', or false if none found
2487 function findColonNoLinks( $str, &$before, &$after ) {
2488 wfProfileIn( __METHOD__
);
2490 $pos = strpos( $str, ':' );
2491 if ( $pos === false ) {
2493 wfProfileOut( __METHOD__
);
2497 $lt = strpos( $str, '<' );
2498 if ( $lt === false ||
$lt > $pos ) {
2499 # Easy; no tag nesting to worry about
2500 $before = substr( $str, 0, $pos );
2501 $after = substr( $str, $pos +
1 );
2502 wfProfileOut( __METHOD__
);
2506 # Ugly state machine to walk through avoiding tags.
2507 $state = self
::COLON_STATE_TEXT
;
2509 $len = strlen( $str );
2510 for ( $i = 0; $i < $len; $i++
) {
2514 # (Using the number is a performance hack for common cases)
2515 case 0: # self::COLON_STATE_TEXT:
2518 # Could be either a <start> tag or an </end> tag
2519 $state = self
::COLON_STATE_TAGSTART
;
2522 if ( $stack == 0 ) {
2524 $before = substr( $str, 0, $i );
2525 $after = substr( $str, $i +
1 );
2526 wfProfileOut( __METHOD__
);
2529 # Embedded in a tag; don't break it.
2532 # Skip ahead looking for something interesting
2533 $colon = strpos( $str, ':', $i );
2534 if ( $colon === false ) {
2535 # Nothing else interesting
2536 wfProfileOut( __METHOD__
);
2539 $lt = strpos( $str, '<', $i );
2540 if ( $stack === 0 ) {
2541 if ( $lt === false ||
$colon < $lt ) {
2543 $before = substr( $str, 0, $colon );
2544 $after = substr( $str, $colon +
1 );
2545 wfProfileOut( __METHOD__
);
2549 if ( $lt === false ) {
2550 # Nothing else interesting to find; abort!
2551 # We're nested, but there's no close tags left. Abort!
2554 # Skip ahead to next tag start
2556 $state = self
::COLON_STATE_TAGSTART
;
2559 case 1: # self::COLON_STATE_TAG:
2564 $state = self
::COLON_STATE_TEXT
;
2567 # Slash may be followed by >?
2568 $state = self
::COLON_STATE_TAGSLASH
;
2574 case 2: # self::COLON_STATE_TAGSTART:
2577 $state = self
::COLON_STATE_CLOSETAG
;
2580 $state = self
::COLON_STATE_COMMENT
;
2583 # Illegal early close? This shouldn't happen D:
2584 $state = self
::COLON_STATE_TEXT
;
2587 $state = self
::COLON_STATE_TAG
;
2590 case 3: # self::COLON_STATE_CLOSETAG:
2595 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2596 wfProfileOut( __METHOD__
);
2599 $state = self
::COLON_STATE_TEXT
;
2602 case self
::COLON_STATE_TAGSLASH
:
2604 # Yes, a self-closed tag <blah/>
2605 $state = self
::COLON_STATE_TEXT
;
2607 # Probably we're jumping the gun, and this is an attribute
2608 $state = self
::COLON_STATE_TAG
;
2611 case 5: # self::COLON_STATE_COMMENT:
2613 $state = self
::COLON_STATE_COMMENTDASH
;
2616 case self
::COLON_STATE_COMMENTDASH
:
2618 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2620 $state = self
::COLON_STATE_COMMENT
;
2623 case self
::COLON_STATE_COMMENTDASHDASH
:
2625 $state = self
::COLON_STATE_TEXT
;
2627 $state = self
::COLON_STATE_COMMENT
;
2631 wfProfileOut( __METHOD__
);
2632 throw new MWException( "State machine error in " . __METHOD__
);
2636 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2637 wfProfileOut( __METHOD__
);
2640 wfProfileOut( __METHOD__
);
2645 * Return value of a magic variable (like PAGENAME)
2649 * @param $index integer
2650 * @param bool|\PPFrame $frame
2652 * @throws MWException
2655 function getVariableValue( $index, $frame = false ) {
2656 global $wgContLang, $wgSitename, $wgServer;
2657 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2659 if ( is_null( $this->mTitle
) ) {
2660 // If no title set, bad things are going to happen
2661 // later. Title should always be set since this
2662 // should only be called in the middle of a parse
2663 // operation (but the unit-tests do funky stuff)
2664 throw new MWException( __METHOD__
. ' Should only be '
2665 . ' called while parsing (no title set)' );
2669 * Some of these require message or data lookups and can be
2670 * expensive to check many times.
2672 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2673 if ( isset( $this->mVarCache
[$index] ) ) {
2674 return $this->mVarCache
[$index];
2678 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2679 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2682 global $wgLocaltimezone;
2683 if ( isset( $wgLocaltimezone ) ) {
2684 $oldtz = date_default_timezone_get();
2685 date_default_timezone_set( $wgLocaltimezone );
2688 $localTimestamp = date( 'YmdHis', $ts );
2689 $localMonth = date( 'm', $ts );
2690 $localMonth1 = date( 'n', $ts );
2691 $localMonthName = date( 'n', $ts );
2692 $localDay = date( 'j', $ts );
2693 $localDay2 = date( 'd', $ts );
2694 $localDayOfWeek = date( 'w', $ts );
2695 $localWeek = date( 'W', $ts );
2696 $localYear = date( 'Y', $ts );
2697 $localHour = date( 'H', $ts );
2698 if ( isset( $wgLocaltimezone ) ) {
2699 date_default_timezone_set( $oldtz );
2702 $pageLang = $this->getFunctionLang();
2705 case 'currentmonth':
2706 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2708 case 'currentmonth1':
2709 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2711 case 'currentmonthname':
2712 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2714 case 'currentmonthnamegen':
2715 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2717 case 'currentmonthabbrev':
2718 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2721 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2724 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2727 $value = $pageLang->formatNum( $localMonth );
2730 $value = $pageLang->formatNum( $localMonth1 );
2732 case 'localmonthname':
2733 $value = $pageLang->getMonthName( $localMonthName );
2735 case 'localmonthnamegen':
2736 $value = $pageLang->getMonthNameGen( $localMonthName );
2738 case 'localmonthabbrev':
2739 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2742 $value = $pageLang->formatNum( $localDay );
2745 $value = $pageLang->formatNum( $localDay2 );
2748 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2751 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2753 case 'fullpagename':
2754 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2756 case 'fullpagenamee':
2757 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2760 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2762 case 'subpagenamee':
2763 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2765 case 'basepagename':
2766 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2768 case 'basepagenamee':
2769 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2771 case 'talkpagename':
2772 if ( $this->mTitle
->canTalk() ) {
2773 $talkPage = $this->mTitle
->getTalkPage();
2774 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2779 case 'talkpagenamee':
2780 if ( $this->mTitle
->canTalk() ) {
2781 $talkPage = $this->mTitle
->getTalkPage();
2782 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2787 case 'subjectpagename':
2788 $subjPage = $this->mTitle
->getSubjectPage();
2789 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2791 case 'subjectpagenamee':
2792 $subjPage = $this->mTitle
->getSubjectPage();
2793 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2795 case 'pageid': // requested in bug 23427
2796 $pageid = $this->getTitle()->getArticleID();
2797 if ( $pageid == 0 ) {
2798 # 0 means the page doesn't exist in the database,
2799 # which means the user is previewing a new page.
2800 # The vary-revision flag must be set, because the magic word
2801 # will have a different value once the page is saved.
2802 $this->mOutput
->setFlag( 'vary-revision' );
2803 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2805 $value = $pageid ?
$pageid : null;
2808 # Let the edit saving system know we should parse the page
2809 # *after* a revision ID has been assigned.
2810 $this->mOutput
->setFlag( 'vary-revision' );
2811 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2812 $value = $this->mRevisionId
;
2815 # Let the edit saving system know we should parse the page
2816 # *after* a revision ID has been assigned. This is for null edits.
2817 $this->mOutput
->setFlag( 'vary-revision' );
2818 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2819 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2821 case 'revisionday2':
2822 # Let the edit saving system know we should parse the page
2823 # *after* a revision ID has been assigned. This is for null edits.
2824 $this->mOutput
->setFlag( 'vary-revision' );
2825 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2826 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2828 case 'revisionmonth':
2829 # Let the edit saving system know we should parse the page
2830 # *after* a revision ID has been assigned. This is for null edits.
2831 $this->mOutput
->setFlag( 'vary-revision' );
2832 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2833 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2835 case 'revisionmonth1':
2836 # Let the edit saving system know we should parse the page
2837 # *after* a revision ID has been assigned. This is for null edits.
2838 $this->mOutput
->setFlag( 'vary-revision' );
2839 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2840 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2842 case 'revisionyear':
2843 # Let the edit saving system know we should parse the page
2844 # *after* a revision ID has been assigned. This is for null edits.
2845 $this->mOutput
->setFlag( 'vary-revision' );
2846 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2847 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2849 case 'revisiontimestamp':
2850 # Let the edit saving system know we should parse the page
2851 # *after* a revision ID has been assigned. This is for null edits.
2852 $this->mOutput
->setFlag( 'vary-revision' );
2853 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2854 $value = $this->getRevisionTimestamp();
2856 case 'revisionuser':
2857 # Let the edit saving system know we should parse the page
2858 # *after* a revision ID has been assigned. This is for null edits.
2859 $this->mOutput
->setFlag( 'vary-revision' );
2860 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2861 $value = $this->getRevisionUser();
2864 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2867 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2869 case 'namespacenumber':
2870 $value = $this->mTitle
->getNamespace();
2873 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2876 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2878 case 'subjectspace':
2879 $value = $this->mTitle
->getSubjectNsText();
2881 case 'subjectspacee':
2882 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2884 case 'currentdayname':
2885 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2888 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2891 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2894 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2897 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2898 # int to remove the padding
2899 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2902 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2904 case 'localdayname':
2905 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2908 $value = $pageLang->formatNum( $localYear, true );
2911 $value = $pageLang->time( $localTimestamp, false, false );
2914 $value = $pageLang->formatNum( $localHour, true );
2917 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2918 # int to remove the padding
2919 $value = $pageLang->formatNum( (int)$localWeek );
2922 $value = $pageLang->formatNum( $localDayOfWeek );
2924 case 'numberofarticles':
2925 $value = $pageLang->formatNum( SiteStats
::articles() );
2927 case 'numberoffiles':
2928 $value = $pageLang->formatNum( SiteStats
::images() );
2930 case 'numberofusers':
2931 $value = $pageLang->formatNum( SiteStats
::users() );
2933 case 'numberofactiveusers':
2934 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2936 case 'numberofpages':
2937 $value = $pageLang->formatNum( SiteStats
::pages() );
2939 case 'numberofadmins':
2940 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2942 case 'numberofedits':
2943 $value = $pageLang->formatNum( SiteStats
::edits() );
2945 case 'numberofviews':
2946 global $wgDisableCounters;
2947 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2949 case 'currenttimestamp':
2950 $value = wfTimestamp( TS_MW
, $ts );
2952 case 'localtimestamp':
2953 $value = $localTimestamp;
2955 case 'currentversion':
2956 $value = SpecialVersion
::getVersion();
2959 return $wgArticlePath;
2965 $serverParts = wfParseUrl( $wgServer );
2966 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2968 return $wgScriptPath;
2970 return $wgStylePath;
2971 case 'directionmark':
2972 return $pageLang->getDirMark();
2973 case 'contentlanguage':
2974 global $wgLanguageCode;
2975 return $wgLanguageCode;
2978 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2986 $this->mVarCache
[$index] = $value;
2993 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2997 function initialiseVariables() {
2998 wfProfileIn( __METHOD__
);
2999 $variableIDs = MagicWord
::getVariableIDs();
3000 $substIDs = MagicWord
::getSubstIDs();
3002 $this->mVariables
= new MagicWordArray( $variableIDs );
3003 $this->mSubstWords
= new MagicWordArray( $substIDs );
3004 wfProfileOut( __METHOD__
);
3008 * Preprocess some wikitext and return the document tree.
3009 * This is the ghost of replace_variables().
3011 * @param string $text The text to parse
3012 * @param $flags Integer: bitwise combination of:
3013 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3014 * included. Default is to assume a direct page view.
3016 * The generated DOM tree must depend only on the input text and the flags.
3017 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3019 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3020 * change in the DOM tree for a given text, must be passed through the section identifier
3021 * in the section edit link and thus back to extractSections().
3023 * The output of this function is currently only cached in process memory, but a persistent
3024 * cache may be implemented at a later date which takes further advantage of these strict
3025 * dependency requirements.
3031 function preprocessToDom( $text, $flags = 0 ) {
3032 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3037 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3043 public static function splitWhitespace( $s ) {
3044 $ltrimmed = ltrim( $s );
3045 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3046 $trimmed = rtrim( $ltrimmed );
3047 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3049 $w2 = substr( $ltrimmed, -$diff );
3053 return array( $w1, $trimmed, $w2 );
3057 * Replace magic variables, templates, and template arguments
3058 * with the appropriate text. Templates are substituted recursively,
3059 * taking care to avoid infinite loops.
3061 * Note that the substitution depends on value of $mOutputType:
3062 * self::OT_WIKI: only {{subst:}} templates
3063 * self::OT_PREPROCESS: templates but not extension tags
3064 * self::OT_HTML: all templates and extension tags
3066 * @param string $text the text to transform
3067 * @param $frame PPFrame Object describing the arguments passed to the template.
3068 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3069 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3070 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3075 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3076 # Is there any text? Also, Prevent too big inclusions!
3077 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3080 wfProfileIn( __METHOD__
);
3082 if ( $frame === false ) {
3083 $frame = $this->getPreprocessor()->newFrame();
3084 } elseif ( !( $frame instanceof PPFrame
) ) {
3085 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3086 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3089 $dom = $this->preprocessToDom( $text );
3090 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3091 $text = $frame->expand( $dom, $flags );
3093 wfProfileOut( __METHOD__
);
3098 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3100 * @param $args array
3104 static function createAssocArgs( $args ) {
3105 $assocArgs = array();
3107 foreach ( $args as $arg ) {
3108 $eqpos = strpos( $arg, '=' );
3109 if ( $eqpos === false ) {
3110 $assocArgs[$index++
] = $arg;
3112 $name = trim( substr( $arg, 0, $eqpos ) );
3113 $value = trim( substr( $arg, $eqpos +
1 ) );
3114 if ( $value === false ) {
3117 if ( $name !== false ) {
3118 $assocArgs[$name] = $value;
3127 * Warn the user when a parser limitation is reached
3128 * Will warn at most once the user per limitation type
3130 * @param string $limitationType should be one of:
3131 * 'expensive-parserfunction' (corresponding messages:
3132 * 'expensive-parserfunction-warning',
3133 * 'expensive-parserfunction-category')
3134 * 'post-expand-template-argument' (corresponding messages:
3135 * 'post-expand-template-argument-warning',
3136 * 'post-expand-template-argument-category')
3137 * 'post-expand-template-inclusion' (corresponding messages:
3138 * 'post-expand-template-inclusion-warning',
3139 * 'post-expand-template-inclusion-category')
3140 * @param int|null $current Current value
3141 * @param int|null $max Maximum allowed, when an explicit limit has been
3142 * exceeded, provide the values (optional)
3144 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3145 # does no harm if $current and $max are present but are unnecessary for the message
3146 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3147 ->inContentLanguage()->escaped();
3148 $this->mOutput
->addWarning( $warning );
3149 $this->addTrackingCategory( "$limitationType-category" );
3153 * Return the text of a template, after recursively
3154 * replacing any variables or templates within the template.
3156 * @param array $piece the parts of the template
3157 * $piece['title']: the title, i.e. the part before the |
3158 * $piece['parts']: the parameter array
3159 * $piece['lineStart']: whether the brace was at the start of a line
3160 * @param $frame PPFrame The current frame, contains template arguments
3161 * @throws MWException
3162 * @return String: the text of the template
3165 function braceSubstitution( $piece, $frame ) {
3166 wfProfileIn( __METHOD__
);
3167 wfProfileIn( __METHOD__
. '-setup' );
3170 $found = false; # $text has been filled
3171 $nowiki = false; # wiki markup in $text should be escaped
3172 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3173 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3174 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3175 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3177 # Title object, where $text came from
3180 # $part1 is the bit before the first |, and must contain only title characters.
3181 # Various prefixes will be stripped from it later.
3182 $titleWithSpaces = $frame->expand( $piece['title'] );
3183 $part1 = trim( $titleWithSpaces );
3186 # Original title text preserved for various purposes
3187 $originalTitle = $part1;
3189 # $args is a list of argument nodes, starting from index 0, not including $part1
3190 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3191 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3192 wfProfileOut( __METHOD__
. '-setup' );
3194 $titleProfileIn = null; // profile templates
3197 wfProfileIn( __METHOD__
. '-modifiers' );
3200 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3202 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3203 # Decide whether to expand template or keep wikitext as-is.
3204 if ( $this->ot
['wiki'] ) {
3205 if ( $substMatch === false ) {
3206 $literal = true; # literal when in PST with no prefix
3208 $literal = false; # expand when in PST with subst: or safesubst:
3211 if ( $substMatch == 'subst' ) {
3212 $literal = true; # literal when not in PST with plain subst:
3214 $literal = false; # expand when not in PST with safesubst: or no prefix
3218 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3225 if ( !$found && $args->getLength() == 0 ) {
3226 $id = $this->mVariables
->matchStartToEnd( $part1 );
3227 if ( $id !== false ) {
3228 $text = $this->getVariableValue( $id, $frame );
3229 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3230 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3236 # MSG, MSGNW and RAW
3239 $mwMsgnw = MagicWord
::get( 'msgnw' );
3240 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3243 # Remove obsolete MSG:
3244 $mwMsg = MagicWord
::get( 'msg' );
3245 $mwMsg->matchStartAndRemove( $part1 );
3249 $mwRaw = MagicWord
::get( 'raw' );
3250 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3251 $forceRawInterwiki = true;
3254 wfProfileOut( __METHOD__
. '-modifiers' );
3258 wfProfileIn( __METHOD__
. '-pfunc' );
3260 $colonPos = strpos( $part1, ':' );
3261 if ( $colonPos !== false ) {
3262 $func = substr( $part1, 0, $colonPos );
3263 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3264 for ( $i = 0; $i < $args->getLength(); $i++
) {
3265 $funcArgs[] = $args->item( $i );
3268 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3269 } catch ( Exception
$ex ) {
3270 wfProfileOut( __METHOD__
. '-pfunc' );
3271 wfProfileOut( __METHOD__
);
3275 # The interface for parser functions allows for extracting
3276 # flags into the local scope. Extract any forwarded flags
3280 wfProfileOut( __METHOD__
. '-pfunc' );
3283 # Finish mangling title and then check for loops.
3284 # Set $title to a Title object and $titleText to the PDBK
3287 # Split the title into page and subpage
3289 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3290 if ( $subpage !== '' ) {
3291 $ns = $this->mTitle
->getNamespace();
3293 $title = Title
::newFromText( $part1, $ns );
3295 $titleText = $title->getPrefixedText();
3296 # Check for language variants if the template is not found
3297 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3298 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3300 # Do recursion depth check
3301 $limit = $this->mOptions
->getMaxTemplateDepth();
3302 if ( $frame->depth
>= $limit ) {
3304 $text = '<span class="error">'
3305 . wfMessage( 'parser-template-recursion-depth-warning' )
3306 ->numParams( $limit )->inContentLanguage()->text()
3312 # Load from database
3313 if ( !$found && $title ) {
3314 if ( !Profiler
::instance()->isPersistent() ) {
3315 # Too many unique items can kill profiling DBs/collectors
3316 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBkey();
3317 wfProfileIn( $titleProfileIn ); // template in
3319 wfProfileIn( __METHOD__
. '-loadtpl' );
3320 if ( !$title->isExternal() ) {
3321 if ( $title->isSpecialPage()
3322 && $this->mOptions
->getAllowSpecialInclusion()
3323 && $this->ot
['html'] )
3325 // Pass the template arguments as URL parameters.
3326 // "uselang" will have no effect since the Language object
3327 // is forced to the one defined in ParserOptions.
3328 $pageArgs = array();
3329 for ( $i = 0; $i < $args->getLength(); $i++
) {
3330 $bits = $args->item( $i )->splitArg();
3331 if ( strval( $bits['index'] ) === '' ) {
3332 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3333 $value = trim( $frame->expand( $bits['value'] ) );
3334 $pageArgs[$name] = $value;
3338 // Create a new context to execute the special page
3339 $context = new RequestContext
;
3340 $context->setTitle( $title );
3341 $context->setRequest( new FauxRequest( $pageArgs ) );
3342 $context->setUser( $this->getUser() );
3343 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3344 $ret = SpecialPageFactory
::capturePath( $title, $context );
3346 $text = $context->getOutput()->getHTML();
3347 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3350 $this->disableCache();
3352 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3353 $found = false; # access denied
3354 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3356 list( $text, $title ) = $this->getTemplateDom( $title );
3357 if ( $text !== false ) {
3363 # If the title is valid but undisplayable, make a link to it
3364 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3365 $text = "[[:$titleText]]";
3368 } elseif ( $title->isTrans() ) {
3369 # Interwiki transclusion
3370 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3371 $text = $this->interwikiTransclude( $title, 'render' );
3374 $text = $this->interwikiTransclude( $title, 'raw' );
3375 # Preprocess it like a template
3376 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3382 # Do infinite loop check
3383 # This has to be done after redirect resolution to avoid infinite loops via redirects
3384 if ( !$frame->loopCheck( $title ) ) {
3386 $text = '<span class="error">'
3387 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3389 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3391 wfProfileOut( __METHOD__
. '-loadtpl' );
3394 # If we haven't found text to substitute by now, we're done
3395 # Recover the source wikitext and return it
3397 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3398 if ( $titleProfileIn ) {
3399 wfProfileOut( $titleProfileIn ); // template out
3401 wfProfileOut( __METHOD__
);
3402 return array( 'object' => $text );
3405 # Expand DOM-style return values in a child frame
3406 if ( $isChildObj ) {
3407 # Clean up argument array
3408 $newFrame = $frame->newChild( $args, $title );
3411 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3412 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3413 # Expansion is eligible for the empty-frame cache
3414 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3415 $text = $this->mTplExpandCache
[$titleText];
3417 $text = $newFrame->expand( $text );
3418 $this->mTplExpandCache
[$titleText] = $text;
3421 # Uncached expansion
3422 $text = $newFrame->expand( $text );
3425 if ( $isLocalObj && $nowiki ) {
3426 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3427 $isLocalObj = false;
3430 if ( $titleProfileIn ) {
3431 wfProfileOut( $titleProfileIn ); // template out
3434 # Replace raw HTML by a placeholder
3436 $text = $this->insertStripItem( $text );
3437 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3438 # Escape nowiki-style return values
3439 $text = wfEscapeWikiText( $text );
3440 } elseif ( is_string( $text )
3441 && !$piece['lineStart']
3442 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3444 # Bug 529: if the template begins with a table or block-level
3445 # element, it should be treated as beginning a new line.
3446 # This behavior is somewhat controversial.
3447 $text = "\n" . $text;
3450 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3451 # Error, oversize inclusion
3452 if ( $titleText !== false ) {
3453 # Make a working, properly escaped link if possible (bug 23588)
3454 $text = "[[:$titleText]]";
3456 # This will probably not be a working link, but at least it may
3457 # provide some hint of where the problem is
3458 preg_replace( '/^:/', '', $originalTitle );
3459 $text = "[[:$originalTitle]]";
3461 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3462 $this->limitationWarn( 'post-expand-template-inclusion' );
3465 if ( $isLocalObj ) {
3466 $ret = array( 'object' => $text );
3468 $ret = array( 'text' => $text );
3471 wfProfileOut( __METHOD__
);
3476 * Call a parser function and return an array with text and flags.
3478 * The returned array will always contain a boolean 'found', indicating
3479 * whether the parser function was found or not. It may also contain the
3481 * text: string|object, resulting wikitext or PP DOM object
3482 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3483 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3484 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3485 * nowiki: bool, wiki markup in $text should be escaped
3488 * @param $frame PPFrame The current frame, contains template arguments
3489 * @param $function string Function name
3490 * @param $args array Arguments to the function
3493 public function callParserFunction( $frame, $function, array $args = array() ) {
3496 wfProfileIn( __METHOD__
);
3498 # Case sensitive functions
3499 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3500 $function = $this->mFunctionSynonyms
[1][$function];
3502 # Case insensitive functions
3503 $function = $wgContLang->lc( $function );
3504 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3505 $function = $this->mFunctionSynonyms
[0][$function];
3507 wfProfileOut( __METHOD__
);
3508 return array( 'found' => false );
3512 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3513 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3515 # Workaround for PHP bug 35229 and similar
3516 if ( !is_callable( $callback ) ) {
3517 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3518 wfProfileOut( __METHOD__
);
3519 throw new MWException( "Tag hook for $function is not callable\n" );
3522 $allArgs = array( &$this );
3523 if ( $flags & SFH_OBJECT_ARGS
) {
3524 # Convert arguments to PPNodes and collect for appending to $allArgs
3525 $funcArgs = array();
3526 foreach ( $args as $k => $v ) {
3527 if ( $v instanceof PPNode ||
$k === 0 ) {
3530 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3534 # Add a frame parameter, and pass the arguments as an array
3535 $allArgs[] = $frame;
3536 $allArgs[] = $funcArgs;
3538 # Convert arguments to plain text and append to $allArgs
3539 foreach ( $args as $k => $v ) {
3540 if ( $v instanceof PPNode
) {
3541 $allArgs[] = trim( $frame->expand( $v ) );
3542 } elseif ( is_int( $k ) && $k >= 0 ) {
3543 $allArgs[] = trim( $v );
3545 $allArgs[] = trim( "$k=$v" );
3550 $result = call_user_func_array( $callback, $allArgs );
3552 # The interface for function hooks allows them to return a wikitext
3553 # string or an array containing the string and any flags. This mungs
3554 # things around to match what this method should return.
3555 if ( !is_array( $result ) ) {
3561 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3562 $result['text'] = $result[0];
3564 unset( $result[0] );
3571 $preprocessFlags = 0;
3572 if ( isset( $result['noparse'] ) ) {
3573 $noparse = $result['noparse'];
3575 if ( isset( $result['preprocessFlags'] ) ) {
3576 $preprocessFlags = $result['preprocessFlags'];
3580 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3581 $result['isChildObj'] = true;
3583 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3584 wfProfileOut( __METHOD__
);
3590 * Get the semi-parsed DOM representation of a template with a given title,
3591 * and its redirect destination title. Cached.
3593 * @param $title Title
3597 function getTemplateDom( $title ) {
3598 $cacheTitle = $title;
3599 $titleText = $title->getPrefixedDBkey();
3601 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3602 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3603 $title = Title
::makeTitle( $ns, $dbk );
3604 $titleText = $title->getPrefixedDBkey();
3606 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3607 return array( $this->mTplDomCache
[$titleText], $title );
3610 # Cache miss, go to the database
3611 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3613 if ( $text === false ) {
3614 $this->mTplDomCache
[$titleText] = false;
3615 return array( false, $title );
3618 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3619 $this->mTplDomCache
[$titleText] = $dom;
3621 if ( !$title->equals( $cacheTitle ) ) {
3622 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3623 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3626 return array( $dom, $title );
3630 * Fetch the unparsed text of a template and register a reference to it.
3631 * @param Title $title
3632 * @return Array ( string or false, Title )
3634 function fetchTemplateAndTitle( $title ) {
3635 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3636 $stuff = call_user_func( $templateCb, $title, $this );
3637 $text = $stuff['text'];
3638 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3639 if ( isset( $stuff['deps'] ) ) {
3640 foreach ( $stuff['deps'] as $dep ) {
3641 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3644 return array( $text, $finalTitle );
3648 * Fetch the unparsed text of a template and register a reference to it.
3649 * @param Title $title
3650 * @return mixed string or false
3652 function fetchTemplate( $title ) {
3653 $rv = $this->fetchTemplateAndTitle( $title );
3658 * Static function to get a template
3659 * Can be overridden via ParserOptions::setTemplateCallback().
3661 * @param $title Title
3662 * @param $parser Parser
3666 static function statelessFetchTemplate( $title, $parser = false ) {
3667 $text = $skip = false;
3668 $finalTitle = $title;
3671 # Loop to fetch the article, with up to 1 redirect
3672 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3673 # Give extensions a chance to select the revision instead
3674 $id = false; # Assume current
3675 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3676 array( $parser, $title, &$skip, &$id ) );
3682 'page_id' => $title->getArticleID(),
3689 ? Revision
::newFromId( $id )
3690 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3691 $rev_id = $rev ?
$rev->getId() : 0;
3692 # If there is no current revision, there is no page
3693 if ( $id === false && !$rev ) {
3694 $linkCache = LinkCache
::singleton();
3695 $linkCache->addBadLinkObj( $title );
3700 'page_id' => $title->getArticleID(),
3701 'rev_id' => $rev_id );
3702 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3703 # We fetched a rev from a different title; register it too...
3705 'title' => $rev->getTitle(),
3706 'page_id' => $rev->getPage(),
3707 'rev_id' => $rev_id );
3711 $content = $rev->getContent();
3712 $text = $content ?
$content->getWikitextForTransclusion() : null;
3714 if ( $text === false ||
$text === null ) {
3718 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3720 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3721 if ( !$message->exists() ) {
3725 $content = $message->content();
3726 $text = $message->plain();
3734 $finalTitle = $title;
3735 $title = $content->getRedirectTarget();
3739 'finalTitle' => $finalTitle,
3744 * Fetch a file and its title and register a reference to it.
3745 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3746 * @param Title $title
3747 * @param array $options Array of options to RepoGroup::findFile
3750 function fetchFile( $title, $options = array() ) {
3751 $res = $this->fetchFileAndTitle( $title, $options );
3756 * Fetch a file and its title and register a reference to it.
3757 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3758 * @param Title $title
3759 * @param array $options Array of options to RepoGroup::findFile
3760 * @return Array ( File or false, Title of file )
3762 function fetchFileAndTitle( $title, $options = array() ) {
3763 if ( isset( $options['broken'] ) ) {
3764 $file = false; // broken thumbnail forced by hook
3765 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3766 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3767 } else { // get by (name,timestamp)
3768 $file = wfFindFile( $title, $options );
3770 $time = $file ?
$file->getTimestamp() : false;
3771 $sha1 = $file ?
$file->getSha1() : false;
3772 # Register the file as a dependency...
3773 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3774 if ( $file && !$title->equals( $file->getTitle() ) ) {
3775 # Update fetched file title
3776 $title = $file->getTitle();
3777 if ( is_null( $file->getRedirectedTitle() ) ) {
3778 # This file was not a redirect, but the title does not match.
3779 # Register under the new name because otherwise the link will
3781 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3784 return array( $file, $title );
3788 * Transclude an interwiki link.
3790 * @param $title Title
3795 function interwikiTransclude( $title, $action ) {
3796 global $wgEnableScaryTranscluding;
3798 if ( !$wgEnableScaryTranscluding ) {
3799 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3802 $url = $title->getFullURL( "action=$action" );
3804 if ( strlen( $url ) > 255 ) {
3805 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3807 return $this->fetchScaryTemplateMaybeFromCache( $url );
3811 * @param $url string
3812 * @return Mixed|String
3814 function fetchScaryTemplateMaybeFromCache( $url ) {
3815 global $wgTranscludeCacheExpiry;
3816 $dbr = wfGetDB( DB_SLAVE
);
3817 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3818 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3819 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3821 return $obj->tc_contents
;
3824 $req = MWHttpRequest
::factory( $url );
3825 $status = $req->execute(); // Status object
3826 if ( $status->isOK() ) {
3827 $text = $req->getContent();
3828 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3829 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3831 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3834 $dbw = wfGetDB( DB_MASTER
);
3835 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3837 'tc_time' => $dbw->timestamp( time() ),
3838 'tc_contents' => $text
3844 * Triple brace replacement -- used for template arguments
3847 * @param $piece array
3848 * @param $frame PPFrame
3852 function argSubstitution( $piece, $frame ) {
3853 wfProfileIn( __METHOD__
);
3856 $parts = $piece['parts'];
3857 $nameWithSpaces = $frame->expand( $piece['title'] );
3858 $argName = trim( $nameWithSpaces );
3860 $text = $frame->getArgument( $argName );
3861 if ( $text === false && $parts->getLength() > 0
3865 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3868 # No match in frame, use the supplied default
3869 $object = $parts->item( 0 )->getChildren();
3871 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3872 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3873 $this->limitationWarn( 'post-expand-template-argument' );
3876 if ( $text === false && $object === false ) {
3878 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3880 if ( $error !== false ) {
3883 if ( $object !== false ) {
3884 $ret = array( 'object' => $object );
3886 $ret = array( 'text' => $text );
3889 wfProfileOut( __METHOD__
);
3894 * Return the text to be used for a given extension tag.
3895 * This is the ghost of strip().
3897 * @param array $params Associative array of parameters:
3898 * name PPNode for the tag name
3899 * attr PPNode for unparsed text where tag attributes are thought to be
3900 * attributes Optional associative array of parsed attributes
3901 * inner Contents of extension element
3902 * noClose Original text did not have a close tag
3903 * @param $frame PPFrame
3905 * @throws MWException
3908 function extensionSubstitution( $params, $frame ) {
3909 $name = $frame->expand( $params['name'] );
3910 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3911 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3912 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3914 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3915 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3916 if ( $isFunctionTag ) {
3917 $markerType = 'none';
3919 $markerType = 'general';
3921 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3922 $name = strtolower( $name );
3923 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3924 if ( isset( $params['attributes'] ) ) {
3925 $attributes = $attributes +
$params['attributes'];
3928 if ( isset( $this->mTagHooks
[$name] ) ) {
3929 # Workaround for PHP bug 35229 and similar
3930 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3931 throw new MWException( "Tag hook for $name is not callable\n" );
3933 $output = call_user_func_array( $this->mTagHooks
[$name],
3934 array( $content, $attributes, $this, $frame ) );
3935 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3936 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3937 if ( !is_callable( $callback ) ) {
3938 throw new MWException( "Tag hook for $name is not callable\n" );
3941 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3943 $output = '<span class="error">Invalid tag extension name: ' .
3944 htmlspecialchars( $name ) . '</span>';
3947 if ( is_array( $output ) ) {
3948 # Extract flags to local scope (to override $markerType)
3950 $output = $flags[0];
3955 if ( is_null( $attrText ) ) {
3958 if ( isset( $params['attributes'] ) ) {
3959 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3960 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3961 htmlspecialchars( $attrValue ) . '"';
3964 if ( $content === null ) {
3965 $output = "<$name$attrText/>";
3967 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3968 $output = "<$name$attrText>$content$close";
3972 if ( $markerType === 'none' ) {
3974 } elseif ( $markerType === 'nowiki' ) {
3975 $this->mStripState
->addNoWiki( $marker, $output );
3976 } elseif ( $markerType === 'general' ) {
3977 $this->mStripState
->addGeneral( $marker, $output );
3979 throw new MWException( __METHOD__
. ': invalid marker type' );
3985 * Increment an include size counter
3987 * @param string $type the type of expansion
3988 * @param $size Integer: the size of the text
3989 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3991 function incrementIncludeSize( $type, $size ) {
3992 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3995 $this->mIncludeSizes
[$type] +
= $size;
4001 * Increment the expensive function count
4003 * @return Boolean: false if the limit has been exceeded
4005 function incrementExpensiveFunctionCount() {
4006 $this->mExpensiveFunctionCount++
;
4007 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4011 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4012 * Fills $this->mDoubleUnderscores, returns the modified text
4014 * @param $text string
4018 function doDoubleUnderscore( $text ) {
4019 wfProfileIn( __METHOD__
);
4021 # The position of __TOC__ needs to be recorded
4022 $mw = MagicWord
::get( 'toc' );
4023 if ( $mw->match( $text ) ) {
4024 $this->mShowToc
= true;
4025 $this->mForceTocPosition
= true;
4027 # Set a placeholder. At the end we'll fill it in with the TOC.
4028 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4030 # Only keep the first one.
4031 $text = $mw->replace( '', $text );
4034 # Now match and remove the rest of them
4035 $mwa = MagicWord
::getDoubleUnderscoreArray();
4036 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4038 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4039 $this->mOutput
->mNoGallery
= true;
4041 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4042 $this->mShowToc
= false;
4044 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4045 $this->addTrackingCategory( 'hidden-category-category' );
4047 # (bug 8068) Allow control over whether robots index a page.
4049 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4050 # is not desirable, the last one on the page should win.
4051 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4052 $this->mOutput
->setIndexPolicy( 'noindex' );
4053 $this->addTrackingCategory( 'noindex-category' );
4055 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4056 $this->mOutput
->setIndexPolicy( 'index' );
4057 $this->addTrackingCategory( 'index-category' );
4060 # Cache all double underscores in the database
4061 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4062 $this->mOutput
->setProperty( $key, '' );
4065 wfProfileOut( __METHOD__
);
4070 * Add a tracking category, getting the title from a system message,
4071 * or print a debug message if the title is invalid.
4073 * @param string $msg message key
4074 * @return Boolean: whether the addition was successful
4076 public function addTrackingCategory( $msg ) {
4077 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4078 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4081 // Important to parse with correct title (bug 31469)
4082 $cat = wfMessage( $msg )
4083 ->title( $this->getTitle() )
4084 ->inContentLanguage()
4087 # Allow tracking categories to be disabled by setting them to "-"
4088 if ( $cat === '-' ) {
4092 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4093 if ( $containerCategory ) {
4094 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4097 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4103 * This function accomplishes several tasks:
4104 * 1) Auto-number headings if that option is enabled
4105 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4106 * 3) Add a Table of contents on the top for users who have enabled the option
4107 * 4) Auto-anchor headings
4109 * It loops through all headlines, collects the necessary data, then splits up the
4110 * string and re-inserts the newly formatted headlines.
4112 * @param $text String
4113 * @param string $origText original, untouched wikitext
4114 * @param $isMain Boolean
4115 * @return mixed|string
4118 function formatHeadings( $text, $origText, $isMain = true ) {
4119 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4121 # Inhibit editsection links if requested in the page
4122 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4123 $maybeShowEditLink = $showEditLink = false;
4125 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4126 $showEditLink = $this->mOptions
->getEditSection();
4128 if ( $showEditLink ) {
4129 $this->mOutput
->setEditSectionTokens( true );
4132 # Get all headlines for numbering them and adding funky stuff like [edit]
4133 # links - this is for later, but we need the number of headlines right now
4135 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4137 # if there are fewer than 4 headlines in the article, do not show TOC
4138 # unless it's been explicitly enabled.
4139 $enoughToc = $this->mShowToc
&&
4140 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4142 # Allow user to stipulate that a page should have a "new section"
4143 # link added via __NEWSECTIONLINK__
4144 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4145 $this->mOutput
->setNewSection( true );
4148 # Allow user to remove the "new section"
4149 # link via __NONEWSECTIONLINK__
4150 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4151 $this->mOutput
->hideNewSection( true );
4154 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4155 # override above conditions and always show TOC above first header
4156 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4157 $this->mShowToc
= true;
4165 # Ugh .. the TOC should have neat indentation levels which can be
4166 # passed to the skin functions. These are determined here
4170 $sublevelCount = array();
4171 $levelCount = array();
4176 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4177 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4178 $oldType = $this->mOutputType
;
4179 $this->setOutputType( self
::OT_WIKI
);
4180 $frame = $this->getPreprocessor()->newFrame();
4181 $root = $this->preprocessToDom( $origText );
4182 $node = $root->getFirstChild();
4187 foreach ( $matches[3] as $headline ) {
4188 $isTemplate = false;
4190 $sectionIndex = false;
4192 $markerMatches = array();
4193 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4194 $serial = $markerMatches[1];
4195 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4196 $isTemplate = ( $titleText != $baseTitleText );
4197 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4201 $prevlevel = $level;
4203 $level = $matches[1][$headlineCount];
4205 if ( $level > $prevlevel ) {
4206 # Increase TOC level
4208 $sublevelCount[$toclevel] = 0;
4209 if ( $toclevel < $wgMaxTocLevel ) {
4210 $prevtoclevel = $toclevel;
4211 $toc .= Linker
::tocIndent();
4214 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4215 # Decrease TOC level, find level to jump to
4217 for ( $i = $toclevel; $i > 0; $i-- ) {
4218 if ( $levelCount[$i] == $level ) {
4219 # Found last matching level
4222 } elseif ( $levelCount[$i] < $level ) {
4223 # Found first matching level below current level
4231 if ( $toclevel < $wgMaxTocLevel ) {
4232 if ( $prevtoclevel < $wgMaxTocLevel ) {
4233 # Unindent only if the previous toc level was shown :p
4234 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4235 $prevtoclevel = $toclevel;
4237 $toc .= Linker
::tocLineEnd();
4241 # No change in level, end TOC line
4242 if ( $toclevel < $wgMaxTocLevel ) {
4243 $toc .= Linker
::tocLineEnd();
4247 $levelCount[$toclevel] = $level;
4249 # count number of headlines for each level
4250 $sublevelCount[$toclevel]++
;
4252 for ( $i = 1; $i <= $toclevel; $i++
) {
4253 if ( !empty( $sublevelCount[$i] ) ) {
4257 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4262 # The safe header is a version of the header text safe to use for links
4264 # Remove link placeholders by the link text.
4265 # <!--LINK number-->
4267 # link text with suffix
4268 # Do this before unstrip since link text can contain strip markers
4269 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4271 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4272 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4274 # Strip out HTML (first regex removes any tag not allowed)
4276 # * <sup> and <sub> (bug 8393)
4279 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4281 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4282 # to allow setting directionality in toc items.
4283 $tocline = preg_replace(
4284 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4285 array( '', '<$1>' ),
4288 $tocline = trim( $tocline );
4290 # For the anchor, strip out HTML-y stuff period
4291 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4292 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4294 # Save headline for section edit hint before it's escaped
4295 $headlineHint = $safeHeadline;
4297 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4298 # For reverse compatibility, provide an id that's
4299 # HTML4-compatible, like we used to.
4301 # It may be worth noting, academically, that it's possible for
4302 # the legacy anchor to conflict with a non-legacy headline
4303 # anchor on the page. In this case likely the "correct" thing
4304 # would be to either drop the legacy anchors or make sure
4305 # they're numbered first. However, this would require people
4306 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4307 # manually, so let's not bother worrying about it.
4308 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4309 array( 'noninitial', 'legacy' ) );
4310 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4312 if ( $legacyHeadline == $safeHeadline ) {
4313 # No reason to have both (in fact, we can't)
4314 $legacyHeadline = false;
4317 $legacyHeadline = false;
4318 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4322 # HTML names must be case-insensitively unique (bug 10721).
4323 # This does not apply to Unicode characters per
4324 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4325 # @todo FIXME: We may be changing them depending on the current locale.
4326 $arrayKey = strtolower( $safeHeadline );
4327 if ( $legacyHeadline === false ) {
4328 $legacyArrayKey = false;
4330 $legacyArrayKey = strtolower( $legacyHeadline );
4333 # count how many in assoc. array so we can track dupes in anchors
4334 if ( isset( $refers[$arrayKey] ) ) {
4335 $refers[$arrayKey]++
;
4337 $refers[$arrayKey] = 1;
4339 if ( isset( $refers[$legacyArrayKey] ) ) {
4340 $refers[$legacyArrayKey]++
;
4342 $refers[$legacyArrayKey] = 1;
4345 # Don't number the heading if it is the only one (looks silly)
4346 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4347 # the two are different if the line contains a link
4348 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4351 # Create the anchor for linking from the TOC to the section
4352 $anchor = $safeHeadline;
4353 $legacyAnchor = $legacyHeadline;
4354 if ( $refers[$arrayKey] > 1 ) {
4355 $anchor .= '_' . $refers[$arrayKey];
4357 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4358 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4360 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4361 $toc .= Linker
::tocLine( $anchor, $tocline,
4362 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4365 # Add the section to the section tree
4366 # Find the DOM node for this header
4367 while ( $node && !$isTemplate ) {
4368 if ( $node->getName() === 'h' ) {
4369 $bits = $node->splitHeading();
4370 if ( $bits['i'] == $sectionIndex ) {
4374 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4375 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4376 $node = $node->getNextSibling();
4379 'toclevel' => $toclevel,
4382 'number' => $numbering,
4383 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4384 'fromtitle' => $titleText,
4385 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4386 'anchor' => $anchor,
4389 # give headline the correct <h#> tag
4390 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4391 // Output edit section links as markers with styles that can be customized by skins
4392 if ( $isTemplate ) {
4393 # Put a T flag in the section identifier, to indicate to extractSections()
4394 # that sections inside <includeonly> should be counted.
4395 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4397 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4399 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4400 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4401 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4402 // so we don't have to worry about a user trying to input one of these markers directly.
4403 // We use a page and section attribute to stop the language converter from converting these important bits
4404 // of data, but put the headline hint inside a content block because the language converter is supposed to
4405 // be able to convert that piece of data.
4406 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4407 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4408 if ( isset( $editlinkArgs[2] ) ) {
4409 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4416 $head[$headlineCount] = Linker
::makeHeadline( $level,
4417 $matches['attrib'][$headlineCount], $anchor, $headline,
4418 $editlink, $legacyAnchor );
4423 $this->setOutputType( $oldType );
4425 # Never ever show TOC if no headers
4426 if ( $numVisible < 1 ) {
4431 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4432 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4434 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4435 $this->mOutput
->setTOCHTML( $toc );
4439 $this->mOutput
->setSections( $tocraw );
4442 # split up and insert constructed headlines
4443 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4446 // build an array of document sections
4447 $sections = array();
4448 foreach ( $blocks as $block ) {
4449 // $head is zero-based, sections aren't.
4450 if ( empty( $head[$i - 1] ) ) {
4451 $sections[$i] = $block;
4453 $sections[$i] = $head[$i - 1] . $block;
4457 * Send a hook, one per section.
4458 * The idea here is to be able to make section-level DIVs, but to do so in a
4459 * lower-impact, more correct way than r50769
4462 * $section : the section number
4463 * &$sectionContent : ref to the content of the section
4464 * $showEditLinks : boolean describing whether this section has an edit link
4466 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4471 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4472 // append the TOC at the beginning
4473 // Top anchor now in skin
4474 $sections[0] = $sections[0] . $toc . "\n";
4477 $full .= join( '', $sections );
4479 if ( $this->mForceTocPosition
) {
4480 return str_replace( '<!--MWTOC-->', $toc, $full );
4487 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4488 * conversion, substitting signatures, {{subst:}} templates, etc.
4490 * @param string $text the text to transform
4491 * @param $title Title: the Title object for the current article
4492 * @param $user User: the User object describing the current user
4493 * @param $options ParserOptions: parsing options
4494 * @param $clearState Boolean: whether to clear the parser state first
4495 * @return String: the altered wiki markup
4497 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4498 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4499 $this->setUser( $user );
4504 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4505 if ( $options->getPreSaveTransform() ) {
4506 $text = $this->pstPass2( $text, $user );
4508 $text = $this->mStripState
->unstripBoth( $text );
4510 $this->setUser( null ); #Reset
4516 * Pre-save transform helper function
4519 * @param $text string
4524 function pstPass2( $text, $user ) {
4525 global $wgContLang, $wgLocaltimezone;
4527 # Note: This is the timestamp saved as hardcoded wikitext to
4528 # the database, we use $wgContLang here in order to give
4529 # everyone the same signature and use the default one rather
4530 # than the one selected in each user's preferences.
4531 # (see also bug 12815)
4532 $ts = $this->mOptions
->getTimestamp();
4533 if ( isset( $wgLocaltimezone ) ) {
4534 $tz = $wgLocaltimezone;
4536 $tz = date_default_timezone_get();
4539 $unixts = wfTimestamp( TS_UNIX
, $ts );
4540 $oldtz = date_default_timezone_get();
4541 date_default_timezone_set( $tz );
4542 $ts = date( 'YmdHis', $unixts );
4543 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4545 # Allow translation of timezones through wiki. date() can return
4546 # whatever crap the system uses, localised or not, so we cannot
4547 # ship premade translations.
4548 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4549 $msg = wfMessage( $key )->inContentLanguage();
4550 if ( $msg->exists() ) {
4551 $tzMsg = $msg->text();
4554 date_default_timezone_set( $oldtz );
4556 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4558 # Variable replacement
4559 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4560 $text = $this->replaceVariables( $text );
4562 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4563 # which may corrupt this parser instance via its wfMessage()->text() call-
4566 $sigText = $this->getUserSig( $user );
4567 $text = strtr( $text, array(
4569 '~~~~' => "$sigText $d",
4573 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4574 $tc = '[' . Title
::legalChars() . ']';
4575 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4577 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4578 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4579 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4580 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4582 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4583 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4584 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4585 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4587 $t = $this->mTitle
->getText();
4589 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4590 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4591 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4592 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4594 # if there's no context, don't bother duplicating the title
4595 $text = preg_replace( $p2, '[[\\1]]', $text );
4598 # Trim trailing whitespace
4599 $text = rtrim( $text );
4605 * Fetch the user's signature text, if any, and normalize to
4606 * validated, ready-to-insert wikitext.
4607 * If you have pre-fetched the nickname or the fancySig option, you can
4608 * specify them here to save a database query.
4609 * Do not reuse this parser instance after calling getUserSig(),
4610 * as it may have changed if it's the $wgParser.
4613 * @param string|bool $nickname nickname to use or false to use user's default nickname
4614 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4615 * or null to use default value
4618 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4619 global $wgMaxSigChars;
4621 $username = $user->getName();
4623 # If not given, retrieve from the user object.
4624 if ( $nickname === false ) {
4625 $nickname = $user->getOption( 'nickname' );
4628 if ( is_null( $fancySig ) ) {
4629 $fancySig = $user->getBoolOption( 'fancysig' );
4632 $nickname = $nickname == null ?
$username : $nickname;
4634 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4635 $nickname = $username;
4636 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4637 } elseif ( $fancySig !== false ) {
4638 # Sig. might contain markup; validate this
4639 if ( $this->validateSig( $nickname ) !== false ) {
4640 # Validated; clean up (if needed) and return it
4641 return $this->cleanSig( $nickname, true );
4643 # Failed to validate; fall back to the default
4644 $nickname = $username;
4645 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4649 # Make sure nickname doesnt get a sig in a sig
4650 $nickname = self
::cleanSigInSig( $nickname );
4652 # If we're still here, make it a link to the user page
4653 $userText = wfEscapeWikiText( $username );
4654 $nickText = wfEscapeWikiText( $nickname );
4655 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4657 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4661 * Check that the user's signature contains no bad XML
4663 * @param $text String
4664 * @return mixed An expanded string, or false if invalid.
4666 function validateSig( $text ) {
4667 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4671 * Clean up signature text
4673 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4674 * 2) Substitute all transclusions
4676 * @param $text String
4677 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4678 * @return String: signature text
4680 public function cleanSig( $text, $parsing = false ) {
4683 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4686 # Option to disable this feature
4687 if ( !$this->mOptions
->getCleanSignatures() ) {
4691 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4692 # => Move this logic to braceSubstitution()
4693 $substWord = MagicWord
::get( 'subst' );
4694 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4695 $substText = '{{' . $substWord->getSynonym( 0 );
4697 $text = preg_replace( $substRegex, $substText, $text );
4698 $text = self
::cleanSigInSig( $text );
4699 $dom = $this->preprocessToDom( $text );
4700 $frame = $this->getPreprocessor()->newFrame();
4701 $text = $frame->expand( $dom );
4704 $text = $this->mStripState
->unstripBoth( $text );
4711 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4713 * @param $text String
4714 * @return String: signature text with /~{3,5}/ removed
4716 public static function cleanSigInSig( $text ) {
4717 $text = preg_replace( '/~{3,5}/', '', $text );
4722 * Set up some variables which are usually set up in parse()
4723 * so that an external function can call some class members with confidence
4725 * @param $title Title|null
4726 * @param $options ParserOptions
4727 * @param $outputType
4728 * @param $clearState bool
4730 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4731 $this->startParse( $title, $options, $outputType, $clearState );
4735 * @param $title Title|null
4736 * @param $options ParserOptions
4737 * @param $outputType
4738 * @param $clearState bool
4740 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4741 $this->setTitle( $title );
4742 $this->mOptions
= $options;
4743 $this->setOutputType( $outputType );
4744 if ( $clearState ) {
4745 $this->clearState();
4750 * Wrapper for preprocess()
4752 * @param string $text the text to preprocess
4753 * @param $options ParserOptions: options
4754 * @param $title Title object or null to use $wgTitle
4757 public function transformMsg( $text, $options, $title = null ) {
4758 static $executing = false;
4760 # Guard against infinite recursion
4766 wfProfileIn( __METHOD__
);
4772 $text = $this->preprocess( $text, $title, $options );
4775 wfProfileOut( __METHOD__
);
4780 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4781 * The callback should have the following form:
4782 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4784 * Transform and return $text. Use $parser for any required context, e.g. use
4785 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4787 * Hooks may return extended information by returning an array, of which the
4788 * first numbered element (index 0) must be the return string, and all other
4789 * entries are extracted into local variables within an internal function
4790 * in the Parser class.
4792 * This interface (introduced r61913) appears to be undocumented, but
4793 * 'markerName' is used by some core tag hooks to override which strip
4794 * array their results are placed in. **Use great caution if attempting
4795 * this interface, as it is not documented and injudicious use could smash
4796 * private variables.**
4798 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4799 * @param $callback Mixed: the callback function (and object) to use for the tag
4800 * @throws MWException
4801 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4803 public function setHook( $tag, $callback ) {
4804 $tag = strtolower( $tag );
4805 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4806 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4808 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4809 $this->mTagHooks
[$tag] = $callback;
4810 if ( !in_array( $tag, $this->mStripList
) ) {
4811 $this->mStripList
[] = $tag;
4818 * As setHook(), but letting the contents be parsed.
4820 * Transparent tag hooks are like regular XML-style tag hooks, except they
4821 * operate late in the transformation sequence, on HTML instead of wikitext.
4823 * This is probably obsoleted by things dealing with parser frames?
4824 * The only extension currently using it is geoserver.
4827 * @todo better document or deprecate this
4829 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4830 * @param $callback Mixed: the callback function (and object) to use for the tag
4831 * @throws MWException
4832 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4834 function setTransparentTagHook( $tag, $callback ) {
4835 $tag = strtolower( $tag );
4836 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4837 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4839 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4840 $this->mTransparentTagHooks
[$tag] = $callback;
4846 * Remove all tag hooks
4848 function clearTagHooks() {
4849 $this->mTagHooks
= array();
4850 $this->mFunctionTagHooks
= array();
4851 $this->mStripList
= $this->mDefaultStripList
;
4855 * Create a function, e.g. {{sum:1|2|3}}
4856 * The callback function should have the form:
4857 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4859 * Or with SFH_OBJECT_ARGS:
4860 * function myParserFunction( $parser, $frame, $args ) { ... }
4862 * The callback may either return the text result of the function, or an array with the text
4863 * in element 0, and a number of flags in the other elements. The names of the flags are
4864 * specified in the keys. Valid flags are:
4865 * found The text returned is valid, stop processing the template. This
4867 * nowiki Wiki markup in the return value should be escaped
4868 * isHTML The returned text is HTML, armour it against wikitext transformation
4870 * @param string $id The magic word ID
4871 * @param $callback Mixed: the callback function (and object) to use
4872 * @param $flags Integer: a combination of the following flags:
4873 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4875 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4876 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4877 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4878 * the arguments, and to control the way they are expanded.
4880 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4881 * arguments, for instance:
4882 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4884 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4885 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4886 * working if/when this is changed.
4888 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4891 * Please read the documentation in includes/parser/Preprocessor.php for more information
4892 * about the methods available in PPFrame and PPNode.
4894 * @throws MWException
4895 * @return string|callback The old callback function for this name, if any
4897 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4900 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4901 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4903 # Add to function cache
4904 $mw = MagicWord
::get( $id );
4906 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4909 $synonyms = $mw->getSynonyms();
4910 $sensitive = intval( $mw->isCaseSensitive() );
4912 foreach ( $synonyms as $syn ) {
4914 if ( !$sensitive ) {
4915 $syn = $wgContLang->lc( $syn );
4918 if ( !( $flags & SFH_NO_HASH
) ) {
4921 # Remove trailing colon
4922 if ( substr( $syn, -1, 1 ) === ':' ) {
4923 $syn = substr( $syn, 0, -1 );
4925 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4931 * Get all registered function hook identifiers
4935 function getFunctionHooks() {
4936 return array_keys( $this->mFunctionHooks
);
4940 * Create a tag function, e.g. "<test>some stuff</test>".
4941 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4942 * Unlike parser functions, their content is not preprocessed.
4946 * @throws MWException
4949 function setFunctionTagHook( $tag, $callback, $flags ) {
4950 $tag = strtolower( $tag );
4951 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4952 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4954 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4955 $this->mFunctionTagHooks
[$tag] : null;
4956 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4958 if ( !in_array( $tag, $this->mStripList
) ) {
4959 $this->mStripList
[] = $tag;
4966 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4967 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4968 * Placeholders created in Skin::makeLinkObj()
4970 * @param $text string
4971 * @param $options int
4973 * @return array of link CSS classes, indexed by PDBK.
4975 function replaceLinkHolders( &$text, $options = 0 ) {
4976 return $this->mLinkHolders
->replace( $text );
4980 * Replace "<!--LINK-->" link placeholders with plain text of links
4981 * (not HTML-formatted).
4983 * @param $text String
4986 function replaceLinkHoldersText( $text ) {
4987 return $this->mLinkHolders
->replaceText( $text );
4991 * Renders an image gallery from a text with one line per image.
4992 * text labels may be given by using |-style alternative text. E.g.
4993 * Image:one.jpg|The number "1"
4994 * Image:tree.jpg|A tree
4995 * given as text will return the HTML of a gallery with two images,
4996 * labeled 'The number "1"' and
4999 * @param string $text
5000 * @param array $params
5001 * @return string HTML
5003 function renderImageGallery( $text, $params ) {
5004 $ig = new ImageGallery();
5005 $ig->setContextTitle( $this->mTitle
);
5006 $ig->setShowBytes( false );
5007 $ig->setShowFilename( false );
5008 $ig->setParser( $this );
5009 $ig->setHideBadImages();
5010 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5012 if ( isset( $params['showfilename'] ) ) {
5013 $ig->setShowFilename( true );
5015 $ig->setShowFilename( false );
5017 if ( isset( $params['caption'] ) ) {
5018 $caption = $params['caption'];
5019 $caption = htmlspecialchars( $caption );
5020 $caption = $this->replaceInternalLinks( $caption );
5021 $ig->setCaptionHtml( $caption );
5023 if ( isset( $params['perrow'] ) ) {
5024 $ig->setPerRow( $params['perrow'] );
5026 if ( isset( $params['widths'] ) ) {
5027 $ig->setWidths( $params['widths'] );
5029 if ( isset( $params['heights'] ) ) {
5030 $ig->setHeights( $params['heights'] );
5033 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5035 $lines = StringUtils
::explode( "\n", $text );
5036 foreach ( $lines as $line ) {
5037 # match lines like these:
5038 # Image:someimage.jpg|This is some image
5040 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5042 if ( count( $matches ) == 0 ) {
5046 if ( strpos( $matches[0], '%' ) !== false ) {
5047 $matches[1] = rawurldecode( $matches[1] );
5049 $title = Title
::newFromText( $matches[1], NS_FILE
);
5050 if ( is_null( $title ) ) {
5051 # Bogus title. Ignore these so we don't bomb out later.
5058 if ( isset( $matches[3] ) ) {
5059 // look for an |alt= definition while trying not to break existing
5060 // captions with multiple pipes (|) in it, until a more sensible grammar
5061 // is defined for images in galleries
5063 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5064 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5065 $magicWordAlt = MagicWord
::get( 'img_alt' );
5066 $magicWordLink = MagicWord
::get( 'img_link' );
5068 foreach ( $parameterMatches as $parameterMatch ) {
5069 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
5070 $alt = $this->stripAltText( $match, false );
5072 elseif ( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
5073 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5074 $chars = self
::EXT_LINK_URL_CLASS
;
5075 $prots = $this->mUrlProtocols
;
5076 //check to see if link matches an absolute url, if not then it must be a wiki link.
5077 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5080 $localLinkTitle = Title
::newFromText( $linkValue );
5081 if ( $localLinkTitle !== null ) {
5082 $link = $localLinkTitle->getLocalURL();
5087 // concatenate all other pipes
5088 $label .= '|' . $parameterMatch;
5091 // remove the first pipe
5092 $label = substr( $label, 1 );
5095 $ig->add( $title, $label, $alt, $link );
5097 return $ig->toHTML();
5104 function getImageParams( $handler ) {
5106 $handlerClass = get_class( $handler );
5110 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5111 # Initialise static lists
5112 static $internalParamNames = array(
5113 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5114 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5115 'bottom', 'text-bottom' ),
5116 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5117 'upright', 'border', 'link', 'alt', 'class' ),
5119 static $internalParamMap;
5120 if ( !$internalParamMap ) {
5121 $internalParamMap = array();
5122 foreach ( $internalParamNames as $type => $names ) {
5123 foreach ( $names as $name ) {
5124 $magicName = str_replace( '-', '_', "img_$name" );
5125 $internalParamMap[$magicName] = array( $type, $name );
5130 # Add handler params
5131 $paramMap = $internalParamMap;
5133 $handlerParamMap = $handler->getParamMap();
5134 foreach ( $handlerParamMap as $magic => $paramName ) {
5135 $paramMap[$magic] = array( 'handler', $paramName );
5138 $this->mImageParams
[$handlerClass] = $paramMap;
5139 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5141 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5145 * Parse image options text and use it to make an image
5147 * @param $title Title
5148 * @param $options String
5149 * @param $holders LinkHolderArray|bool
5150 * @return string HTML
5152 function makeImage( $title, $options, $holders = false ) {
5153 # Check if the options text is of the form "options|alt text"
5155 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5156 # * left no resizing, just left align. label is used for alt= only
5157 # * right same, but right aligned
5158 # * none same, but not aligned
5159 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5160 # * center center the image
5161 # * frame Keep original image size, no magnify-button.
5162 # * framed Same as "frame"
5163 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5164 # * upright reduce width for upright images, rounded to full __0 px
5165 # * border draw a 1px border around the image
5166 # * alt Text for HTML alt attribute (defaults to empty)
5167 # * class Set a class for img node
5168 # * link Set the target of the image link. Can be external, interwiki, or local
5169 # vertical-align values (no % or length right now):
5179 $parts = StringUtils
::explode( "|", $options );
5181 # Give extensions a chance to select the file revision for us
5184 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5185 array( $this, $title, &$options, &$descQuery ) );
5186 # Fetch and register the file (file title may be different via hooks)
5187 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5190 $handler = $file ?
$file->getHandler() : false;
5192 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5195 $this->addTrackingCategory( 'broken-file-category' );
5198 # Process the input parameters
5200 $params = array( 'frame' => array(), 'handler' => array(),
5201 'horizAlign' => array(), 'vertAlign' => array() );
5202 foreach ( $parts as $part ) {
5203 $part = trim( $part );
5204 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5206 if ( isset( $paramMap[$magicName] ) ) {
5207 list( $type, $paramName ) = $paramMap[$magicName];
5209 # Special case; width and height come in one variable together
5210 if ( $type === 'handler' && $paramName === 'width' ) {
5211 $parsedWidthParam = $this->parseWidthParam( $value );
5212 if ( isset( $parsedWidthParam['width'] ) ) {
5213 $width = $parsedWidthParam['width'];
5214 if ( $handler->validateParam( 'width', $width ) ) {
5215 $params[$type]['width'] = $width;
5219 if ( isset( $parsedWidthParam['height'] ) ) {
5220 $height = $parsedWidthParam['height'];
5221 if ( $handler->validateParam( 'height', $height ) ) {
5222 $params[$type]['height'] = $height;
5226 # else no validation -- bug 13436
5228 if ( $type === 'handler' ) {
5229 # Validate handler parameter
5230 $validated = $handler->validateParam( $paramName, $value );
5232 # Validate internal parameters
5233 switch( $paramName ) {
5237 # @todo FIXME: Possibly check validity here for
5238 # manualthumb? downstream behavior seems odd with
5239 # missing manual thumbs.
5241 $value = $this->stripAltText( $value, $holders );
5244 $chars = self
::EXT_LINK_URL_CLASS
;
5245 $prots = $this->mUrlProtocols
;
5246 if ( $value === '' ) {
5247 $paramName = 'no-link';
5250 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5251 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5252 $paramName = 'link-url';
5253 $this->mOutput
->addExternalLink( $value );
5254 if ( $this->mOptions
->getExternalLinkTarget() ) {
5255 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5260 $linkTitle = Title
::newFromText( $value );
5262 $paramName = 'link-title';
5263 $value = $linkTitle;
5264 $this->mOutput
->addLink( $linkTitle );
5270 # Most other things appear to be empty or numeric...
5271 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5276 $params[$type][$paramName] = $value;
5280 if ( !$validated ) {
5285 # Process alignment parameters
5286 if ( $params['horizAlign'] ) {
5287 $params['frame']['align'] = key( $params['horizAlign'] );
5289 if ( $params['vertAlign'] ) {
5290 $params['frame']['valign'] = key( $params['vertAlign'] );
5293 $params['frame']['caption'] = $caption;
5295 # Will the image be presented in a frame, with the caption below?
5296 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5297 isset( $params['frame']['framed'] ) ||
5298 isset( $params['frame']['thumbnail'] ) ||
5299 isset( $params['frame']['manualthumb'] );
5301 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5302 # came to also set the caption, ordinary text after the image -- which
5303 # makes no sense, because that just repeats the text multiple times in
5304 # screen readers. It *also* came to set the title attribute.
5306 # Now that we have an alt attribute, we should not set the alt text to
5307 # equal the caption: that's worse than useless, it just repeats the
5308 # text. This is the framed/thumbnail case. If there's no caption, we
5309 # use the unnamed parameter for alt text as well, just for the time be-
5310 # ing, if the unnamed param is set and the alt param is not.
5312 # For the future, we need to figure out if we want to tweak this more,
5313 # e.g., introducing a title= parameter for the title; ignoring the un-
5314 # named parameter entirely for images without a caption; adding an ex-
5315 # plicit caption= parameter and preserving the old magic unnamed para-
5317 if ( $imageIsFramed ) { # Framed image
5318 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5319 # No caption or alt text, add the filename as the alt text so
5320 # that screen readers at least get some description of the image
5321 $params['frame']['alt'] = $title->getText();
5323 # Do not set $params['frame']['title'] because tooltips don't make sense
5325 } else { # Inline image
5326 if ( !isset( $params['frame']['alt'] ) ) {
5327 # No alt text, use the "caption" for the alt text
5328 if ( $caption !== '' ) {
5329 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5331 # No caption, fall back to using the filename for the
5333 $params['frame']['alt'] = $title->getText();
5336 # Use the "caption" for the tooltip text
5337 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5340 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5342 # Linker does the rest
5343 $time = isset( $options['time'] ) ?
$options['time'] : false;
5344 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5345 $time, $descQuery, $this->mOptions
->getThumbSize() );
5347 # Give the handler a chance to modify the parser object
5349 $handler->parserTransformHook( $this, $file );
5357 * @param $holders LinkHolderArray
5358 * @return mixed|String
5360 protected function stripAltText( $caption, $holders ) {
5361 # Strip bad stuff out of the title (tooltip). We can't just use
5362 # replaceLinkHoldersText() here, because if this function is called
5363 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5365 $tooltip = $holders->replaceText( $caption );
5367 $tooltip = $this->replaceLinkHoldersText( $caption );
5370 # make sure there are no placeholders in thumbnail attributes
5371 # that are later expanded to html- so expand them now and
5373 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5374 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5380 * Set a flag in the output object indicating that the content is dynamic and
5381 * shouldn't be cached.
5383 function disableCache() {
5384 wfDebug( "Parser output marked as uncacheable.\n" );
5385 if ( !$this->mOutput
) {
5386 throw new MWException( __METHOD__
.
5387 " can only be called when actually parsing something" );
5389 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5390 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5394 * Callback from the Sanitizer for expanding items found in HTML attribute
5395 * values, so they can be safely tested and escaped.
5397 * @param $text String
5398 * @param $frame PPFrame
5401 function attributeStripCallback( &$text, $frame = false ) {
5402 $text = $this->replaceVariables( $text, $frame );
5403 $text = $this->mStripState
->unstripBoth( $text );
5412 function getTags() {
5413 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5417 * Replace transparent tags in $text with the values given by the callbacks.
5419 * Transparent tag hooks are like regular XML-style tag hooks, except they
5420 * operate late in the transformation sequence, on HTML instead of wikitext.
5422 * @param $text string
5426 function replaceTransparentTags( $text ) {
5428 $elements = array_keys( $this->mTransparentTagHooks
);
5429 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5430 $replacements = array();
5432 foreach ( $matches as $marker => $data ) {
5433 list( $element, $content, $params, $tag ) = $data;
5434 $tagName = strtolower( $element );
5435 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5436 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5440 $replacements[$marker] = $output;
5442 return strtr( $text, $replacements );
5446 * Break wikitext input into sections, and either pull or replace
5447 * some particular section's text.
5449 * External callers should use the getSection and replaceSection methods.
5451 * @param string $text Page wikitext
5452 * @param string $section a section identifier string of the form:
5453 * "<flag1> - <flag2> - ... - <section number>"
5455 * Currently the only recognised flag is "T", which means the target section number
5456 * was derived during a template inclusion parse, in other words this is a template
5457 * section edit link. If no flags are given, it was an ordinary section edit link.
5458 * This flag is required to avoid a section numbering mismatch when a section is
5459 * enclosed by "<includeonly>" (bug 6563).
5461 * The section number 0 pulls the text before the first heading; other numbers will
5462 * pull the given section along with its lower-level subsections. If the section is
5463 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5465 * Section 0 is always considered to exist, even if it only contains the empty
5466 * string. If $text is the empty string and section 0 is replaced, $newText is
5469 * @param string $mode one of "get" or "replace"
5470 * @param string $newText replacement text for section data.
5471 * @return String: for "get", the extracted section text.
5472 * for "replace", the whole page with the section replaced.
5474 private function extractSections( $text, $section, $mode, $newText = '' ) {
5475 global $wgTitle; # not generally used but removes an ugly failure mode
5476 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5478 $frame = $this->getPreprocessor()->newFrame();
5480 # Process section extraction flags
5482 $sectionParts = explode( '-', $section );
5483 $sectionIndex = array_pop( $sectionParts );
5484 foreach ( $sectionParts as $part ) {
5485 if ( $part === 'T' ) {
5486 $flags |
= self
::PTD_FOR_INCLUSION
;
5490 # Check for empty input
5491 if ( strval( $text ) === '' ) {
5492 # Only sections 0 and T-0 exist in an empty document
5493 if ( $sectionIndex == 0 ) {
5494 if ( $mode === 'get' ) {
5500 if ( $mode === 'get' ) {
5508 # Preprocess the text
5509 $root = $this->preprocessToDom( $text, $flags );
5511 # <h> nodes indicate section breaks
5512 # They can only occur at the top level, so we can find them by iterating the root's children
5513 $node = $root->getFirstChild();
5515 # Find the target section
5516 if ( $sectionIndex == 0 ) {
5517 # Section zero doesn't nest, level=big
5518 $targetLevel = 1000;
5521 if ( $node->getName() === 'h' ) {
5522 $bits = $node->splitHeading();
5523 if ( $bits['i'] == $sectionIndex ) {
5524 $targetLevel = $bits['level'];
5528 if ( $mode === 'replace' ) {
5529 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5531 $node = $node->getNextSibling();
5537 if ( $mode === 'get' ) {
5544 # Find the end of the section, including nested sections
5546 if ( $node->getName() === 'h' ) {
5547 $bits = $node->splitHeading();
5548 $curLevel = $bits['level'];
5549 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5553 if ( $mode === 'get' ) {
5554 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5556 $node = $node->getNextSibling();
5559 # Write out the remainder (in replace mode only)
5560 if ( $mode === 'replace' ) {
5561 # Output the replacement text
5562 # Add two newlines on -- trailing whitespace in $newText is conventionally
5563 # stripped by the editor, so we need both newlines to restore the paragraph gap
5564 # Only add trailing whitespace if there is newText
5565 if ( $newText != "" ) {
5566 $outText .= $newText . "\n\n";
5570 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5571 $node = $node->getNextSibling();
5575 if ( is_string( $outText ) ) {
5576 # Re-insert stripped tags
5577 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5584 * This function returns the text of a section, specified by a number ($section).
5585 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5586 * the first section before any such heading (section 0).
5588 * If a section contains subsections, these are also returned.
5590 * @param string $text text to look in
5591 * @param string $section section identifier
5592 * @param string $deftext default to return if section is not found
5593 * @return string text of the requested section
5595 public function getSection( $text, $section, $deftext = '' ) {
5596 return $this->extractSections( $text, $section, "get", $deftext );
5600 * This function returns $oldtext after the content of the section
5601 * specified by $section has been replaced with $text. If the target
5602 * section does not exist, $oldtext is returned unchanged.
5604 * @param string $oldtext former text of the article
5605 * @param int $section section identifier
5606 * @param string $text replacing text
5607 * @return String: modified text
5609 public function replaceSection( $oldtext, $section, $text ) {
5610 return $this->extractSections( $oldtext, $section, "replace", $text );
5614 * Get the ID of the revision we are parsing
5616 * @return Mixed: integer or null
5618 function getRevisionId() {
5619 return $this->mRevisionId
;
5623 * Get the revision object for $this->mRevisionId
5625 * @return Revision|null either a Revision object or null
5627 protected function getRevisionObject() {
5628 if ( !is_null( $this->mRevisionObject
) ) {
5629 return $this->mRevisionObject
;
5631 if ( is_null( $this->mRevisionId
) ) {
5635 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5636 return $this->mRevisionObject
;
5640 * Get the timestamp associated with the current revision, adjusted for
5641 * the default server-local timestamp
5643 function getRevisionTimestamp() {
5644 if ( is_null( $this->mRevisionTimestamp
) ) {
5645 wfProfileIn( __METHOD__
);
5649 $revObject = $this->getRevisionObject();
5650 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5652 # The cryptic '' timezone parameter tells to use the site-default
5653 # timezone offset instead of the user settings.
5655 # Since this value will be saved into the parser cache, served
5656 # to other users, and potentially even used inside links and such,
5657 # it needs to be consistent for all visitors.
5658 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5660 wfProfileOut( __METHOD__
);
5662 return $this->mRevisionTimestamp
;
5666 * Get the name of the user that edited the last revision
5668 * @return String: user name
5670 function getRevisionUser() {
5671 if ( is_null( $this->mRevisionUser
) ) {
5672 $revObject = $this->getRevisionObject();
5674 # if this template is subst: the revision id will be blank,
5675 # so just use the current user's name
5677 $this->mRevisionUser
= $revObject->getUserText();
5678 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5679 $this->mRevisionUser
= $this->getUser()->getName();
5682 return $this->mRevisionUser
;
5686 * Mutator for $mDefaultSort
5688 * @param string $sort New value
5690 public function setDefaultSort( $sort ) {
5691 $this->mDefaultSort
= $sort;
5692 $this->mOutput
->setProperty( 'defaultsort', $sort );
5696 * Accessor for $mDefaultSort
5697 * Will use the empty string if none is set.
5699 * This value is treated as a prefix, so the
5700 * empty string is equivalent to sorting by
5705 public function getDefaultSort() {
5706 if ( $this->mDefaultSort
!== false ) {
5707 return $this->mDefaultSort
;
5714 * Accessor for $mDefaultSort
5715 * Unlike getDefaultSort(), will return false if none is set
5717 * @return string or false
5719 public function getCustomDefaultSort() {
5720 return $this->mDefaultSort
;
5724 * Try to guess the section anchor name based on a wikitext fragment
5725 * presumably extracted from a heading, for example "Header" from
5728 * @param $text string
5732 public function guessSectionNameFromWikiText( $text ) {
5733 # Strip out wikitext links(they break the anchor)
5734 $text = $this->stripSectionName( $text );
5735 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5736 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5740 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5741 * instead. For use in redirects, since IE6 interprets Redirect: headers
5742 * as something other than UTF-8 (apparently?), resulting in breakage.
5744 * @param string $text The section name
5745 * @return string An anchor
5747 public function guessLegacySectionNameFromWikiText( $text ) {
5748 # Strip out wikitext links(they break the anchor)
5749 $text = $this->stripSectionName( $text );
5750 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5751 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5755 * Strips a text string of wikitext for use in a section anchor
5757 * Accepts a text string and then removes all wikitext from the
5758 * string and leaves only the resultant text (i.e. the result of
5759 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5760 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5761 * to create valid section anchors by mimicing the output of the
5762 * parser when headings are parsed.
5764 * @param string $text text string to be stripped of wikitext
5765 * for use in a Section anchor
5766 * @return string Filtered text string
5768 public function stripSectionName( $text ) {
5769 # Strip internal link markup
5770 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5771 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5773 # Strip external link markup
5774 # @todo FIXME: Not tolerant to blank link text
5775 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5776 # on how many empty links there are on the page - need to figure that out.
5777 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5779 # Parse wikitext quotes (italics & bold)
5780 $text = $this->doQuotes( $text );
5783 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5788 * strip/replaceVariables/unstrip for preprocessor regression testing
5790 * @param $text string
5791 * @param $title Title
5792 * @param $options ParserOptions
5793 * @param $outputType int
5797 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5798 $this->startParse( $title, $options, $outputType, true );
5800 $text = $this->replaceVariables( $text );
5801 $text = $this->mStripState
->unstripBoth( $text );
5802 $text = Sanitizer
::removeHTMLtags( $text );
5807 * @param $text string
5808 * @param $title Title
5809 * @param $options ParserOptions
5812 function testPst( $text, Title
$title, ParserOptions
$options ) {
5813 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5818 * @param $title Title
5819 * @param $options ParserOptions
5822 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5823 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5827 * Call a callback function on all regions of the given text that are not
5828 * inside strip markers, and replace those regions with the return value
5829 * of the callback. For example, with input:
5833 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5834 * two strings will be replaced with the value returned by the callback in
5842 function markerSkipCallback( $s, $callback ) {
5845 while ( $i < strlen( $s ) ) {
5846 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5847 if ( $markerStart === false ) {
5848 $out .= call_user_func( $callback, substr( $s, $i ) );
5851 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5852 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5853 if ( $markerEnd === false ) {
5854 $out .= substr( $s, $markerStart );
5857 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5858 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5867 * Remove any strip markers found in the given text.
5869 * @param $text Input string
5872 function killMarkers( $text ) {
5873 return $this->mStripState
->killMarkers( $text );
5877 * Save the parser state required to convert the given half-parsed text to
5878 * HTML. "Half-parsed" in this context means the output of
5879 * recursiveTagParse() or internalParse(). This output has strip markers
5880 * from replaceVariables (extensionSubstitution() etc.), and link
5881 * placeholders from replaceLinkHolders().
5883 * Returns an array which can be serialized and stored persistently. This
5884 * array can later be loaded into another parser instance with
5885 * unserializeHalfParsedText(). The text can then be safely incorporated into
5886 * the return value of a parser hook.
5888 * @param $text string
5892 function serializeHalfParsedText( $text ) {
5893 wfProfileIn( __METHOD__
);
5896 'version' => self
::HALF_PARSED_VERSION
,
5897 'stripState' => $this->mStripState
->getSubState( $text ),
5898 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5900 wfProfileOut( __METHOD__
);
5905 * Load the parser state given in the $data array, which is assumed to
5906 * have been generated by serializeHalfParsedText(). The text contents is
5907 * extracted from the array, and its markers are transformed into markers
5908 * appropriate for the current Parser instance. This transformed text is
5909 * returned, and can be safely included in the return value of a parser
5912 * If the $data array has been stored persistently, the caller should first
5913 * check whether it is still valid, by calling isValidHalfParsedText().
5915 * @param array $data Serialized data
5916 * @throws MWException
5919 function unserializeHalfParsedText( $data ) {
5920 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5921 throw new MWException( __METHOD__
. ': invalid version' );
5924 # First, extract the strip state.
5925 $texts = array( $data['text'] );
5926 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5928 # Now renumber links
5929 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5931 # Should be good to go.
5936 * Returns true if the given array, presumed to be generated by
5937 * serializeHalfParsedText(), is compatible with the current version of the
5940 * @param $data Array
5944 function isValidHalfParsedText( $data ) {
5945 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5949 * Parsed a width param of imagelink like 300px or 200x300px
5951 * @param $value String
5956 public function parseWidthParam( $value ) {
5957 $parsedWidthParam = array();
5958 if ( $value === '' ) {
5959 return $parsedWidthParam;
5962 # (bug 13500) In both cases (width/height and width only),
5963 # permit trailing "px" for backward compatibility.
5964 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5965 $width = intval( $m[1] );
5966 $height = intval( $m[2] );
5967 $parsedWidthParam['width'] = $width;
5968 $parsedWidthParam['height'] = $height;
5969 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5970 $width = intval( $value );
5971 $parsedWidthParam['width'] = $width;
5973 return $parsedWidthParam;