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 behaviour of <nowiki> in a link.
310 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
311 $this->mStripState
= new StripState( $this->mUniqPrefix
);
314 # Clear these on every parse, bug 4549
315 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
317 $this->mShowToc
= true;
318 $this->mForceTocPosition
= false;
319 $this->mIncludeSizes
= array(
323 $this->mPPNodeCount
= 0;
324 $this->mGeneratedPPNodeCount
= 0;
325 $this->mHighestExpansionDepth
= 0;
326 $this->mDefaultSort
= false;
327 $this->mHeadings
= array();
328 $this->mDoubleUnderscores
= array();
329 $this->mExpensiveFunctionCount
= 0;
332 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
333 $this->mPreprocessor
= null;
336 wfRunHooks( 'ParserClearState', array( &$this ) );
337 wfProfileOut( __METHOD__
);
341 * Convert wikitext to HTML
342 * Do not call this function recursively.
344 * @param $text String: text we want to parse
345 * @param $title Title object
346 * @param $options ParserOptions
347 * @param $linestart boolean
348 * @param $clearState boolean
349 * @param $revid Int: number to pass in {{REVISIONID}}
350 * @return ParserOutput a ParserOutput
352 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
354 * First pass--just handle <nowiki> sections, pass the rest off
355 * to internalParse() which does all the real work.
358 global $wgUseTidy, $wgAlwaysUseTidy;
359 $fname = __METHOD__
. '-' . wfGetCaller();
360 wfProfileIn( __METHOD__
);
361 wfProfileIn( $fname );
363 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
365 # Remove the strip marker tag prefix from the input, if present.
367 $text = str_replace( $this->mUniqPrefix
, '', $text );
370 $oldRevisionId = $this->mRevisionId
;
371 $oldRevisionObject = $this->mRevisionObject
;
372 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
373 $oldRevisionUser = $this->mRevisionUser
;
374 if ( $revid !== null ) {
375 $this->mRevisionId
= $revid;
376 $this->mRevisionObject
= null;
377 $this->mRevisionTimestamp
= null;
378 $this->mRevisionUser
= null;
381 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
383 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
384 $text = $this->internalParse( $text );
385 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
387 $text = $this->mStripState
->unstripGeneral( $text );
389 # Clean up special characters, only run once, next-to-last before doBlockLevels
391 # french spaces, last one Guillemet-left
392 # only if there is something before the space
393 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
394 # french spaces, Guillemet-right
395 '/(\\302\\253) /' => '\\1 ',
396 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
398 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
400 $text = $this->doBlockLevels( $text, $linestart );
402 $this->replaceLinkHolders( $text );
405 * The input doesn't get language converted if
407 * b) Content isn't converted
408 * c) It's a conversion table
409 * d) it is an interface message (which is in the user language)
411 if ( !( $options->getDisableContentConversion()
412 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
414 if ( !$this->mOptions
->getInterfaceMessage() ) {
415 # The position of the convert() call should not be changed. it
416 # assumes that the links are all replaced and the only thing left
417 # is the <nowiki> mark.
418 $text = $this->getConverterLanguage()->convert( $text );
423 * A converted title will be provided in the output object if title and
424 * content conversion are enabled, the article text does not contain
425 * a conversion-suppressing double-underscore tag, and no
426 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
427 * automatic link conversion.
429 if ( !( $options->getDisableTitleConversion()
430 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
431 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
432 ||
$this->mOutput
->getDisplayTitle() !== false ) )
434 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
435 if ( $convruletitle ) {
436 $this->mOutput
->setTitleText( $convruletitle );
438 $titleText = $this->getConverterLanguage()->convertTitle( $title );
439 $this->mOutput
->setTitleText( $titleText );
443 $text = $this->mStripState
->unstripNoWiki( $text );
445 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
447 $text = $this->replaceTransparentTags( $text );
448 $text = $this->mStripState
->unstripGeneral( $text );
450 $text = Sanitizer
::normalizeCharReferences( $text );
452 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
453 $text = MWTidy
::tidy( $text );
455 # attempt to sanitize at least some nesting problems
456 # (bug #2702 and quite a few others)
458 # ''Something [http://www.cool.com cool''] -->
459 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
460 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
461 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
462 # fix up an anchor inside another anchor, only
463 # at least for a single single nested link (bug 3695)
464 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
465 '\\1\\2</a>\\3</a>\\1\\4</a>',
466 # fix div inside inline elements- doBlockLevels won't wrap a line which
467 # contains a div, so fix it up here; replace
468 # div with escaped text
469 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
470 '\\1\\3<div\\5>\\6</div>\\8\\9',
471 # remove empty italic or bold tag pairs, some
472 # introduced by rules above
473 '/<([bi])><\/\\1>/' => '',
476 $text = preg_replace(
477 array_keys( $tidyregs ),
478 array_values( $tidyregs ),
482 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
483 $this->limitationWarn( 'expensive-parserfunction',
484 $this->mExpensiveFunctionCount
,
485 $this->mOptions
->getExpensiveParserFunctionLimit()
489 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
491 # Information on include size limits, for the benefit of users who try to skirt them
492 if ( $this->mOptions
->getEnableLimitReport() ) {
493 $max = $this->mOptions
->getMaxIncludeSize();
494 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
496 "NewPP limit report\n" .
497 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
498 "Preprocessor generated node count: " .
499 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
500 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
501 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
502 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
504 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
505 $text .= "\n<!-- \n$limitReport-->\n";
507 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
508 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
509 $this->mTitle
->getPrefixedDBkey() );
512 $this->mOutput
->setText( $text );
514 $this->mRevisionId
= $oldRevisionId;
515 $this->mRevisionObject
= $oldRevisionObject;
516 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
517 $this->mRevisionUser
= $oldRevisionUser;
518 wfProfileOut( $fname );
519 wfProfileOut( __METHOD__
);
521 return $this->mOutput
;
525 * Recursive parser entry point that can be called from an extension tag
528 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
530 * @param $text String: text extension wants to have parsed
531 * @param $frame PPFrame: The frame to use for expanding any template variables
535 function recursiveTagParse( $text, $frame=false ) {
536 wfProfileIn( __METHOD__
);
537 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
538 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
539 $text = $this->internalParse( $text, false, $frame );
540 wfProfileOut( __METHOD__
);
545 * Expand templates and variables in the text, producing valid, static wikitext.
546 * Also removes comments.
547 * @return mixed|string
549 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
550 wfProfileIn( __METHOD__
);
551 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
552 if ( $revid !== null ) {
553 $this->mRevisionId
= $revid;
555 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
556 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
557 $text = $this->replaceVariables( $text );
558 $text = $this->mStripState
->unstripBoth( $text );
559 wfProfileOut( __METHOD__
);
564 * Recursive parser entry point that can be called from an extension tag
567 * @param $text String: text to be expanded
568 * @param $frame PPFrame: The frame to use for expanding any template variables
572 public function recursivePreprocess( $text, $frame = false ) {
573 wfProfileIn( __METHOD__
);
574 $text = $this->replaceVariables( $text, $frame );
575 $text = $this->mStripState
->unstripBoth( $text );
576 wfProfileOut( __METHOD__
);
581 * Process the wikitext for the "?preload=" feature. (bug 5210)
583 * "<noinclude>", "<includeonly>" etc. are parsed as for template
584 * transclusion, comments, templates, arguments, tags hooks and parser
585 * functions are untouched.
587 * @param $text String
588 * @param $title Title
589 * @param $options ParserOptions
592 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
593 # Parser (re)initialisation
594 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
596 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
597 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
598 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
599 $text = $this->mStripState
->unstripBoth( $text );
604 * Get a random string
608 public static function getRandomString() {
609 return wfRandomString( 16 );
613 * Set the current user.
614 * Should only be used when doing pre-save transform.
616 * @param $user Mixed: User object or null (to reset)
618 function setUser( $user ) {
619 $this->mUser
= $user;
623 * Accessor for mUniqPrefix.
627 public function uniqPrefix() {
628 if ( !isset( $this->mUniqPrefix
) ) {
629 # @todo FIXME: This is probably *horribly wrong*
630 # LanguageConverter seems to want $wgParser's uniqPrefix, however
631 # if this is called for a parser cache hit, the parser may not
632 # have ever been initialized in the first place.
633 # Not really sure what the heck is supposed to be going on here.
635 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
637 return $this->mUniqPrefix
;
641 * Set the context title
645 function setTitle( $t ) {
646 if ( !$t ||
$t instanceof FakeTitle
) {
647 $t = Title
::newFromText( 'NO TITLE' );
650 if ( strval( $t->getFragment() ) !== '' ) {
651 # Strip the fragment to avoid various odd effects
652 $this->mTitle
= clone $t;
653 $this->mTitle
->setFragment( '' );
660 * Accessor for the Title object
662 * @return Title object
664 function getTitle() {
665 return $this->mTitle
;
669 * Accessor/mutator for the Title object
671 * @param $x Title object or null to just get the current one
672 * @return Title object
674 function Title( $x = null ) {
675 return wfSetVar( $this->mTitle
, $x );
679 * Set the output type
681 * @param $ot Integer: new value
683 function setOutputType( $ot ) {
684 $this->mOutputType
= $ot;
687 'html' => $ot == self
::OT_HTML
,
688 'wiki' => $ot == self
::OT_WIKI
,
689 'pre' => $ot == self
::OT_PREPROCESS
,
690 'plain' => $ot == self
::OT_PLAIN
,
695 * Accessor/mutator for the output type
697 * @param $x int|null New value or null to just get the current one
700 function OutputType( $x = null ) {
701 return wfSetVar( $this->mOutputType
, $x );
705 * Get the ParserOutput object
707 * @return ParserOutput object
709 function getOutput() {
710 return $this->mOutput
;
714 * Get the ParserOptions object
716 * @return ParserOptions object
718 function getOptions() {
719 return $this->mOptions
;
723 * Accessor/mutator for the ParserOptions object
725 * @param $x ParserOptions New value or null to just get the current one
726 * @return ParserOptions Current ParserOptions object
728 function Options( $x = null ) {
729 return wfSetVar( $this->mOptions
, $x );
735 function nextLinkID() {
736 return $this->mLinkID++
;
742 function setLinkID( $id ) {
743 $this->mLinkID
= $id;
747 * Get a language object for use in parser functions such as {{FORMATNUM:}}
750 function getFunctionLang() {
751 return $this->getTargetLanguage();
755 * Get the target language for the content being parsed. This is usually the
756 * language that the content is in.
760 * @throws MWException
761 * @return Language|null
763 public function getTargetLanguage() {
764 $target = $this->mOptions
->getTargetLanguage();
766 if ( $target !== null ) {
768 } elseif( $this->mOptions
->getInterfaceMessage() ) {
769 return $this->mOptions
->getUserLangObj();
770 } elseif( is_null( $this->mTitle
) ) {
771 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
774 return $this->mTitle
->getPageLanguage();
778 * Get the language object for language conversion
780 function getConverterLanguage() {
781 return $this->getTargetLanguage();
785 * Get a User object either from $this->mUser, if set, or from the
786 * ParserOptions object otherwise
788 * @return User object
791 if ( !is_null( $this->mUser
) ) {
794 return $this->mOptions
->getUser();
798 * Get a preprocessor object
800 * @return Preprocessor instance
802 function getPreprocessor() {
803 if ( !isset( $this->mPreprocessor
) ) {
804 $class = $this->mPreprocessorClass
;
805 $this->mPreprocessor
= new $class( $this );
807 return $this->mPreprocessor
;
811 * Replaces all occurrences of HTML-style comments and the given tags
812 * in the text with a random marker and returns the next text. The output
813 * parameter $matches will be an associative array filled with data in
817 * 'UNIQ-xxxxx' => array(
820 * array( 'param' => 'x' ),
821 * '<element param="x">tag content</element>' ) )
824 * @param $elements array list of element names. Comments are always extracted.
825 * @param $text string Source text string.
826 * @param $matches array Out parameter, Array: extracted tags
827 * @param $uniq_prefix string
828 * @return String: stripped text
830 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
835 $taglist = implode( '|', $elements );
836 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
838 while ( $text != '' ) {
839 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
841 if ( count( $p ) < 5 ) {
844 if ( count( $p ) > 5 ) {
858 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
859 $stripped .= $marker;
861 if ( $close === '/>' ) {
862 # Empty element tag, <tag />
867 if ( $element === '!--' ) {
870 $end = "/(<\\/$element\\s*>)/i";
872 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
874 if ( count( $q ) < 3 ) {
875 # No end tag -- let it run out to the end of the text.
884 $matches[$marker] = array( $element,
886 Sanitizer
::decodeTagAttributes( $attributes ),
887 "<$element$attributes$close$content$tail" );
893 * Get a list of strippable XML-like elements
897 function getStripList() {
898 return $this->mStripList
;
902 * Add an item to the strip state
903 * Returns the unique tag which must be inserted into the stripped text
904 * The tag will be replaced with the original text in unstrip()
906 * @param $text string
910 function insertStripItem( $text ) {
911 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
912 $this->mMarkerIndex++
;
913 $this->mStripState
->addGeneral( $rnd, $text );
918 * parse the wiki syntax used to render tables
923 function doTableStuff( $text ) {
924 wfProfileIn( __METHOD__
);
926 $lines = StringUtils
::explode( "\n", $text );
928 $td_history = array(); # Is currently a td tag open?
929 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
930 $tr_history = array(); # Is currently a tr tag open?
931 $tr_attributes = array(); # history of tr attributes
932 $has_opened_tr = array(); # Did this table open a <tr> element?
933 $indent_level = 0; # indent level of the table
935 foreach ( $lines as $outLine ) {
936 $line = trim( $outLine );
938 if ( $line === '' ) { # empty line, go to next line
939 $out .= $outLine . "\n";
943 $first_character = $line[0];
946 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
947 # First check if we are starting a new table
948 $indent_level = strlen( $matches[1] );
950 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
951 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
953 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
954 array_push( $td_history, false );
955 array_push( $last_tag_history, '' );
956 array_push( $tr_history, false );
957 array_push( $tr_attributes, '' );
958 array_push( $has_opened_tr, false );
959 } elseif ( count( $td_history ) == 0 ) {
960 # Don't do any of the following
961 $out .= $outLine . "\n";
963 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
964 # We are ending a table
965 $line = '</table>' . substr( $line, 2 );
966 $last_tag = array_pop( $last_tag_history );
968 if ( !array_pop( $has_opened_tr ) ) {
969 $line = "<tr><td></td></tr>{$line}";
972 if ( array_pop( $tr_history ) ) {
973 $line = "</tr>{$line}";
976 if ( array_pop( $td_history ) ) {
977 $line = "</{$last_tag}>{$line}";
979 array_pop( $tr_attributes );
980 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
981 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
982 # Now we have a table row
983 $line = preg_replace( '#^\|-+#', '', $line );
985 # Whats after the tag is now only attributes
986 $attributes = $this->mStripState
->unstripBoth( $line );
987 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
988 array_pop( $tr_attributes );
989 array_push( $tr_attributes, $attributes );
992 $last_tag = array_pop( $last_tag_history );
993 array_pop( $has_opened_tr );
994 array_push( $has_opened_tr, true );
996 if ( array_pop( $tr_history ) ) {
1000 if ( array_pop( $td_history ) ) {
1001 $line = "</{$last_tag}>{$line}";
1005 array_push( $tr_history, false );
1006 array_push( $td_history, false );
1007 array_push( $last_tag_history, '' );
1008 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1009 # This might be cell elements, td, th or captions
1010 if ( substr( $line, 0, 2 ) === '|+' ) {
1011 $first_character = '+';
1012 $line = substr( $line, 1 );
1015 $line = substr( $line, 1 );
1017 if ( $first_character === '!' ) {
1018 $line = str_replace( '!!', '||', $line );
1021 # Split up multiple cells on the same line.
1022 # FIXME : This can result in improper nesting of tags processed
1023 # by earlier parser steps, but should avoid splitting up eg
1024 # attribute values containing literal "||".
1025 $cells = StringUtils
::explodeMarkup( '||', $line );
1029 # Loop through each table cell
1030 foreach ( $cells as $cell ) {
1032 if ( $first_character !== '+' ) {
1033 $tr_after = array_pop( $tr_attributes );
1034 if ( !array_pop( $tr_history ) ) {
1035 $previous = "<tr{$tr_after}>\n";
1037 array_push( $tr_history, true );
1038 array_push( $tr_attributes, '' );
1039 array_pop( $has_opened_tr );
1040 array_push( $has_opened_tr, true );
1043 $last_tag = array_pop( $last_tag_history );
1045 if ( array_pop( $td_history ) ) {
1046 $previous = "</{$last_tag}>\n{$previous}";
1049 if ( $first_character === '|' ) {
1051 } elseif ( $first_character === '!' ) {
1053 } elseif ( $first_character === '+' ) {
1054 $last_tag = 'caption';
1059 array_push( $last_tag_history, $last_tag );
1061 # A cell could contain both parameters and data
1062 $cell_data = explode( '|', $cell, 2 );
1064 # Bug 553: Note that a '|' inside an invalid link should not
1065 # be mistaken as delimiting cell parameters
1066 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1067 $cell = "{$previous}<{$last_tag}>{$cell}";
1068 } elseif ( count( $cell_data ) == 1 ) {
1069 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1071 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1072 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1073 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1077 array_push( $td_history, true );
1080 $out .= $outLine . "\n";
1083 # Closing open td, tr && table
1084 while ( count( $td_history ) > 0 ) {
1085 if ( array_pop( $td_history ) ) {
1088 if ( array_pop( $tr_history ) ) {
1091 if ( !array_pop( $has_opened_tr ) ) {
1092 $out .= "<tr><td></td></tr>\n" ;
1095 $out .= "</table>\n";
1098 # Remove trailing line-ending (b/c)
1099 if ( substr( $out, -1 ) === "\n" ) {
1100 $out = substr( $out, 0, -1 );
1103 # special case: don't return empty table
1104 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1108 wfProfileOut( __METHOD__
);
1114 * Helper function for parse() that transforms wiki markup into
1115 * HTML. Only called for $mOutputType == self::OT_HTML.
1119 * @param $text string
1120 * @param $isMain bool
1121 * @param $frame bool
1125 function internalParse( $text, $isMain = true, $frame = false ) {
1126 wfProfileIn( __METHOD__
);
1130 # Hook to suspend the parser in this state
1131 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1132 wfProfileOut( __METHOD__
);
1136 # if $frame is provided, then use $frame for replacing any variables
1138 # use frame depth to infer how include/noinclude tags should be handled
1139 # depth=0 means this is the top-level document; otherwise it's an included document
1140 if ( !$frame->depth
) {
1143 $flag = Parser
::PTD_FOR_INCLUSION
;
1145 $dom = $this->preprocessToDom( $text, $flag );
1146 $text = $frame->expand( $dom );
1148 # if $frame is not provided, then use old-style replaceVariables
1149 $text = $this->replaceVariables( $text );
1152 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1153 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1154 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1156 # Tables need to come after variable replacement for things to work
1157 # properly; putting them before other transformations should keep
1158 # exciting things like link expansions from showing up in surprising
1160 $text = $this->doTableStuff( $text );
1162 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1164 $text = $this->doDoubleUnderscore( $text );
1166 $text = $this->doHeadings( $text );
1167 $text = $this->replaceInternalLinks( $text );
1168 $text = $this->doAllQuotes( $text );
1169 $text = $this->replaceExternalLinks( $text );
1171 # replaceInternalLinks may sometimes leave behind
1172 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1173 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1175 $text = $this->doMagicLinks( $text );
1176 $text = $this->formatHeadings( $text, $origText, $isMain );
1178 wfProfileOut( __METHOD__
);
1183 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1184 * magic external links.
1189 * @param $text string
1193 function doMagicLinks( $text ) {
1194 wfProfileIn( __METHOD__
);
1195 $prots = wfUrlProtocolsWithoutProtRel();
1196 $urlChar = self
::EXT_LINK_URL_CLASS
;
1197 $text = preg_replace_callback(
1199 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1200 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1201 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1202 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1203 ISBN\s+(\b # m[5]: ISBN, capture number
1204 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1205 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1206 [0-9Xx] # check digit
1208 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1209 wfProfileOut( __METHOD__
);
1214 * @throws MWException
1216 * @return HTML|string
1218 function magicLinkCallback( $m ) {
1219 if ( isset( $m[1] ) && $m[1] !== '' ) {
1222 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1225 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1226 # Free external link
1227 return $this->makeFreeExternalLink( $m[0] );
1228 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1230 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1233 $CssClass = 'mw-magiclink-rfc';
1235 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1237 $urlmsg = 'pubmedurl';
1238 $CssClass = 'mw-magiclink-pmid';
1241 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1242 substr( $m[0], 0, 20 ) . '"' );
1244 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1245 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1246 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1249 $num = strtr( $isbn, array(
1254 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1256 htmlspecialchars( $titleObj->getLocalUrl() ) .
1257 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1264 * Make a free external link, given a user-supplied URL
1266 * @param $url string
1268 * @return string HTML
1271 function makeFreeExternalLink( $url ) {
1272 wfProfileIn( __METHOD__
);
1276 # The characters '<' and '>' (which were escaped by
1277 # removeHTMLtags()) should not be included in
1278 # URLs, per RFC 2396.
1280 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1281 $trail = substr( $url, $m2[0][1] ) . $trail;
1282 $url = substr( $url, 0, $m2[0][1] );
1285 # Move trailing punctuation to $trail
1287 # If there is no left bracket, then consider right brackets fair game too
1288 if ( strpos( $url, '(' ) === false ) {
1292 $numSepChars = strspn( strrev( $url ), $sep );
1293 if ( $numSepChars ) {
1294 $trail = substr( $url, -$numSepChars ) . $trail;
1295 $url = substr( $url, 0, -$numSepChars );
1298 $url = Sanitizer
::cleanUrl( $url );
1300 # Is this an external image?
1301 $text = $this->maybeMakeExternalImage( $url );
1302 if ( $text === false ) {
1303 # Not an image, make a link
1304 $text = Linker
::makeExternalLink( $url,
1305 $this->getConverterLanguage()->markNoConversion( $url, true ),
1307 $this->getExternalLinkAttribs( $url ) );
1308 # Register it in the output object...
1309 # Replace unnecessary URL escape codes with their equivalent characters
1310 $pasteurized = self
::replaceUnusualEscapes( $url );
1311 $this->mOutput
->addExternalLink( $pasteurized );
1313 wfProfileOut( __METHOD__
);
1314 return $text . $trail;
1319 * Parse headers and return html
1323 * @param $text string
1327 function doHeadings( $text ) {
1328 wfProfileIn( __METHOD__
);
1329 for ( $i = 6; $i >= 1; --$i ) {
1330 $h = str_repeat( '=', $i );
1331 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1333 wfProfileOut( __METHOD__
);
1338 * Replace single quotes with HTML markup
1341 * @param $text string
1343 * @return string the altered text
1345 function doAllQuotes( $text ) {
1346 wfProfileIn( __METHOD__
);
1348 $lines = StringUtils
::explode( "\n", $text );
1349 foreach ( $lines as $line ) {
1350 $outtext .= $this->doQuotes( $line ) . "\n";
1352 $outtext = substr( $outtext, 0, -1 );
1353 wfProfileOut( __METHOD__
);
1358 * Helper function for doAllQuotes()
1360 * @param $text string
1364 public function doQuotes( $text ) {
1365 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1366 if ( count( $arr ) == 1 ) {
1369 # First, do some preliminary work. This may shift some apostrophes from
1370 # being mark-up to being text. It also counts the number of occurrences
1371 # of bold and italics mark-ups.
1374 for ( $i = 0; $i < count( $arr ); $i++
) {
1375 if ( ( $i %
2 ) == 1 ) {
1376 # If there are ever four apostrophes, assume the first is supposed to
1377 # be text, and the remaining three constitute mark-up for bold text.
1378 if ( strlen( $arr[$i] ) == 4 ) {
1381 } elseif ( strlen( $arr[$i] ) > 5 ) {
1382 # If there are more than 5 apostrophes in a row, assume they're all
1383 # text except for the last 5.
1384 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1387 # Count the number of occurrences of bold and italics mark-ups.
1388 # We are not counting sequences of five apostrophes.
1389 if ( strlen( $arr[$i] ) == 2 ) {
1391 } elseif ( strlen( $arr[$i] ) == 3 ) {
1393 } elseif ( strlen( $arr[$i] ) == 5 ) {
1400 # If there is an odd number of both bold and italics, it is likely
1401 # that one of the bold ones was meant to be an apostrophe followed
1402 # by italics. Which one we cannot know for certain, but it is more
1403 # likely to be one that has a single-letter word before it.
1404 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1406 $firstsingleletterword = -1;
1407 $firstmultiletterword = -1;
1409 foreach ( $arr as $r ) {
1410 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1411 $x1 = substr( $arr[$i-1], -1 );
1412 $x2 = substr( $arr[$i-1], -2, 1 );
1413 if ( $x1 === ' ' ) {
1414 if ( $firstspace == -1 ) {
1417 } elseif ( $x2 === ' ') {
1418 if ( $firstsingleletterword == -1 ) {
1419 $firstsingleletterword = $i;
1422 if ( $firstmultiletterword == -1 ) {
1423 $firstmultiletterword = $i;
1430 # If there is a single-letter word, use it!
1431 if ( $firstsingleletterword > -1 ) {
1432 $arr[$firstsingleletterword] = "''";
1433 $arr[$firstsingleletterword-1] .= "'";
1434 } elseif ( $firstmultiletterword > -1 ) {
1435 # If not, but there's a multi-letter word, use that one.
1436 $arr[$firstmultiletterword] = "''";
1437 $arr[$firstmultiletterword-1] .= "'";
1438 } elseif ( $firstspace > -1 ) {
1439 # ... otherwise use the first one that has neither.
1440 # (notice that it is possible for all three to be -1 if, for example,
1441 # there is only one pentuple-apostrophe in the line)
1442 $arr[$firstspace] = "''";
1443 $arr[$firstspace-1] .= "'";
1447 # Now let's actually convert our apostrophic mush to HTML!
1452 foreach ( $arr as $r ) {
1453 if ( ( $i %
2 ) == 0 ) {
1454 if ( $state === 'both' ) {
1460 if ( strlen( $r ) == 2 ) {
1461 if ( $state === 'i' ) {
1462 $output .= '</i>'; $state = '';
1463 } elseif ( $state === 'bi' ) {
1464 $output .= '</i>'; $state = 'b';
1465 } elseif ( $state === 'ib' ) {
1466 $output .= '</b></i><b>'; $state = 'b';
1467 } elseif ( $state === 'both' ) {
1468 $output .= '<b><i>' . $buffer . '</i>'; $state = 'b';
1469 } else { # $state can be 'b' or ''
1470 $output .= '<i>'; $state .= 'i';
1472 } elseif ( strlen( $r ) == 3 ) {
1473 if ( $state === 'b' ) {
1474 $output .= '</b>'; $state = '';
1475 } elseif ( $state === 'bi' ) {
1476 $output .= '</i></b><i>'; $state = 'i';
1477 } elseif ( $state === 'ib' ) {
1478 $output .= '</b>'; $state = 'i';
1479 } elseif ( $state === 'both' ) {
1480 $output .= '<i><b>' . $buffer . '</b>'; $state = 'i';
1481 } else { # $state can be 'i' or ''
1482 $output .= '<b>'; $state .= 'b';
1484 } elseif ( strlen( $r ) == 5 ) {
1485 if ( $state === 'b' ) {
1486 $output .= '</b><i>'; $state = 'i';
1487 } elseif ( $state === 'i' ) {
1488 $output .= '</i><b>'; $state = 'b';
1489 } elseif ( $state === 'bi' ) {
1490 $output .= '</i></b>'; $state = '';
1491 } elseif ( $state === 'ib' ) {
1492 $output .= '</b></i>'; $state = '';
1493 } elseif ( $state === 'both' ) {
1494 $output .= '<i><b>' . $buffer . '</b></i>'; $state = '';
1495 } else { # ($state == '')
1496 $buffer = ''; $state = 'both';
1502 # Now close all remaining tags. Notice that the order is important.
1503 if ( $state === 'b' ||
$state === 'ib' ) {
1506 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1509 if ( $state === 'bi' ) {
1512 # There might be lonely ''''', so make sure we have a buffer
1513 if ( $state === 'both' && $buffer ) {
1514 $output .= '<b><i>' . $buffer . '</i></b>';
1521 * Replace external links (REL)
1523 * Note: this is all very hackish and the order of execution matters a lot.
1524 * Make sure to run maintenance/parserTests.php if you change this code.
1528 * @param $text string
1530 * @throws MWException
1533 function replaceExternalLinks( $text ) {
1534 wfProfileIn( __METHOD__
);
1536 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1537 if ( $bits === false ) {
1538 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1540 $s = array_shift( $bits );
1543 while ( $i<count( $bits ) ) {
1545 // @todo FIXME: Unused variable.
1546 $protocol = $bits[$i++
];
1547 $text = $bits[$i++
];
1548 $trail = $bits[$i++
];
1550 # The characters '<' and '>' (which were escaped by
1551 # removeHTMLtags()) should not be included in
1552 # URLs, per RFC 2396.
1554 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1555 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1556 $url = substr( $url, 0, $m2[0][1] );
1559 # If the link text is an image URL, replace it with an <img> tag
1560 # This happened by accident in the original parser, but some people used it extensively
1561 $img = $this->maybeMakeExternalImage( $text );
1562 if ( $img !== false ) {
1568 # Set linktype for CSS - if URL==text, link is essentially free
1569 $linktype = ( $text === $url ) ?
'free' : 'text';
1571 # No link text, e.g. [http://domain.tld/some.link]
1572 if ( $text == '' ) {
1574 $langObj = $this->getTargetLanguage();
1575 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1576 $linktype = 'autonumber';
1578 # Have link text, e.g. [http://domain.tld/some.link text]s
1580 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1583 $text = $this->getConverterLanguage()->markNoConversion( $text );
1585 $url = Sanitizer
::cleanUrl( $url );
1587 # Use the encoded URL
1588 # This means that users can paste URLs directly into the text
1589 # Funny characters like ö aren't valid in URLs anyway
1590 # This was changed in August 2004
1591 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1592 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1594 # Register link in the output object.
1595 # Replace unnecessary URL escape codes with the referenced character
1596 # This prevents spammers from hiding links from the filters
1597 $pasteurized = self
::replaceUnusualEscapes( $url );
1598 $this->mOutput
->addExternalLink( $pasteurized );
1601 wfProfileOut( __METHOD__
);
1605 * Get the rel attribute for a particular external link.
1608 * @param $url String|bool optional URL, to extract the domain from for rel =>
1609 * nofollow if appropriate
1610 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1611 * @return string|null rel attribute for $url
1613 public static function getExternalLinkRel( $url = false, $title = null ) {
1614 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1615 $ns = $title ?
$title->getNamespace() : false;
1616 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1617 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1624 * Get an associative array of additional HTML attributes appropriate for a
1625 * particular external link. This currently may include rel => nofollow
1626 * (depending on configuration, namespace, and the URL's domain) and/or a
1627 * target attribute (depending on configuration).
1629 * @param $url String|bool optional URL, to extract the domain from for rel =>
1630 * nofollow if appropriate
1631 * @return Array associative array of HTML attributes
1633 function getExternalLinkAttribs( $url = false ) {
1635 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1637 if ( $this->mOptions
->getExternalLinkTarget() ) {
1638 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1644 * Replace unusual URL escape codes with their equivalent characters
1646 * @param $url String
1649 * @todo This can merge genuinely required bits in the path or query string,
1650 * breaking legit URLs. A proper fix would treat the various parts of
1651 * the URL differently; as a workaround, just use the output for
1652 * statistical records, not for actual linking/output.
1654 static function replaceUnusualEscapes( $url ) {
1655 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1656 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1660 * Callback function used in replaceUnusualEscapes().
1661 * Replaces unusual URL escape codes with their equivalent character
1663 * @param $matches array
1667 private static function replaceUnusualEscapesCallback( $matches ) {
1668 $char = urldecode( $matches[0] );
1669 $ord = ord( $char );
1670 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1671 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1672 # No, shouldn't be escaped
1675 # Yes, leave it escaped
1681 * make an image if it's allowed, either through the global
1682 * option, through the exception, or through the on-wiki whitelist
1685 * $param $url string
1689 function maybeMakeExternalImage( $url ) {
1690 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1691 $imagesexception = !empty( $imagesfrom );
1693 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1694 if ( $imagesexception && is_array( $imagesfrom ) ) {
1695 $imagematch = false;
1696 foreach ( $imagesfrom as $match ) {
1697 if ( strpos( $url, $match ) === 0 ) {
1702 } elseif ( $imagesexception ) {
1703 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1705 $imagematch = false;
1707 if ( $this->mOptions
->getAllowExternalImages()
1708 ||
( $imagesexception && $imagematch ) ) {
1709 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1711 $text = Linker
::makeExternalImage( $url );
1714 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1715 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1716 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1717 foreach ( $whitelist as $entry ) {
1718 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1719 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1722 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1723 # Image matches a whitelist entry
1724 $text = Linker
::makeExternalImage( $url );
1733 * Process [[ ]] wikilinks
1737 * @return String: processed text
1741 function replaceInternalLinks( $s ) {
1742 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1747 * Process [[ ]] wikilinks (RIL)
1749 * @throws MWException
1750 * @return LinkHolderArray
1754 function replaceInternalLinks2( &$s ) {
1755 wfProfileIn( __METHOD__
);
1757 wfProfileIn( __METHOD__
. '-setup' );
1758 static $tc = FALSE, $e1, $e1_img;
1759 # the % is needed to support urlencoded titles as well
1761 $tc = Title
::legalChars() . '#%';
1762 # Match a link having the form [[namespace:link|alternate]]trail
1763 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1764 # Match cases where there is no "]]", which might still be images
1765 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1768 $holders = new LinkHolderArray( $this );
1770 # split the entire text string on occurrences of [[
1771 $a = StringUtils
::explode( '[[', ' ' . $s );
1772 # get the first element (all text up to first [[), and remove the space we added
1775 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1776 $s = substr( $s, 1 );
1778 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1780 if ( $useLinkPrefixExtension ) {
1781 # Match the end of a line for a word that's not followed by whitespace,
1782 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1783 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1786 if ( is_null( $this->mTitle
) ) {
1787 wfProfileOut( __METHOD__
. '-setup' );
1788 wfProfileOut( __METHOD__
);
1789 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1791 $nottalk = !$this->mTitle
->isTalkPage();
1793 if ( $useLinkPrefixExtension ) {
1795 if ( preg_match( $e2, $s, $m ) ) {
1796 $first_prefix = $m[2];
1798 $first_prefix = false;
1804 $useSubpages = $this->areSubpagesAllowed();
1805 wfProfileOut( __METHOD__
. '-setup' );
1807 # Loop for each link
1808 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1809 # Check for excessive memory usage
1810 if ( $holders->isBig() ) {
1812 # Do the existence check, replace the link holders and clear the array
1813 $holders->replace( $s );
1817 if ( $useLinkPrefixExtension ) {
1818 wfProfileIn( __METHOD__
. '-prefixhandling' );
1819 if ( preg_match( $e2, $s, $m ) ) {
1826 if ( $first_prefix ) {
1827 $prefix = $first_prefix;
1828 $first_prefix = false;
1830 wfProfileOut( __METHOD__
. '-prefixhandling' );
1833 $might_be_img = false;
1835 wfProfileIn( __METHOD__
. "-e1" );
1836 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1838 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1839 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1840 # the real problem is with the $e1 regex
1843 # Still some problems for cases where the ] is meant to be outside punctuation,
1844 # and no image is in sight. See bug 2095.
1846 if ( $text !== '' &&
1847 substr( $m[3], 0, 1 ) === ']' &&
1848 strpos( $text, '[' ) !== false
1851 $text .= ']'; # so that replaceExternalLinks($text) works later
1852 $m[3] = substr( $m[3], 1 );
1854 # fix up urlencoded title texts
1855 if ( strpos( $m[1], '%' ) !== false ) {
1856 # Should anchors '#' also be rejected?
1857 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1860 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1861 $might_be_img = true;
1863 if ( strpos( $m[1], '%' ) !== false ) {
1864 $m[1] = rawurldecode( $m[1] );
1867 } else { # Invalid form; output directly
1868 $s .= $prefix . '[[' . $line ;
1869 wfProfileOut( __METHOD__
. "-e1" );
1872 wfProfileOut( __METHOD__
. "-e1" );
1873 wfProfileIn( __METHOD__
. "-misc" );
1875 # Don't allow internal links to pages containing
1876 # PROTO: where PROTO is a valid URL protocol; these
1877 # should be external links.
1878 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1879 $s .= $prefix . '[[' . $line ;
1880 wfProfileOut( __METHOD__
. "-misc" );
1884 # Make subpage if necessary
1885 if ( $useSubpages ) {
1886 $link = $this->maybeDoSubpageLink( $m[1], $text );
1891 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1893 # Strip off leading ':'
1894 $link = substr( $link, 1 );
1897 wfProfileOut( __METHOD__
. "-misc" );
1898 wfProfileIn( __METHOD__
. "-title" );
1899 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1900 if ( $nt === null ) {
1901 $s .= $prefix . '[[' . $line;
1902 wfProfileOut( __METHOD__
. "-title" );
1906 $ns = $nt->getNamespace();
1907 $iw = $nt->getInterWiki();
1908 wfProfileOut( __METHOD__
. "-title" );
1910 if ( $might_be_img ) { # if this is actually an invalid link
1911 wfProfileIn( __METHOD__
. "-might_be_img" );
1912 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1915 # look at the next 'line' to see if we can close it there
1917 $next_line = $a->current();
1918 if ( $next_line === false ||
$next_line === null ) {
1921 $m = explode( ']]', $next_line, 3 );
1922 if ( count( $m ) == 3 ) {
1923 # the first ]] closes the inner link, the second the image
1925 $text .= "[[{$m[0]}]]{$m[1]}";
1928 } elseif ( count( $m ) == 2 ) {
1929 # if there's exactly one ]] that's fine, we'll keep looking
1930 $text .= "[[{$m[0]}]]{$m[1]}";
1932 # if $next_line is invalid too, we need look no further
1933 $text .= '[[' . $next_line;
1938 # we couldn't find the end of this imageLink, so output it raw
1939 # but don't ignore what might be perfectly normal links in the text we've examined
1940 $holders->merge( $this->replaceInternalLinks2( $text ) );
1941 $s .= "{$prefix}[[$link|$text";
1942 # note: no $trail, because without an end, there *is* no trail
1943 wfProfileOut( __METHOD__
. "-might_be_img" );
1946 } else { # it's not an image, so output it raw
1947 $s .= "{$prefix}[[$link|$text";
1948 # note: no $trail, because without an end, there *is* no trail
1949 wfProfileOut( __METHOD__
. "-might_be_img" );
1952 wfProfileOut( __METHOD__
. "-might_be_img" );
1955 $wasblank = ( $text == '' );
1959 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1960 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1961 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1962 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1963 $text = $this->doQuotes( $text );
1966 # Link not escaped by : , create the various objects
1969 wfProfileIn( __METHOD__
. "-interwiki" );
1970 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1971 // XXX: the above check prevents links to sites with identifiers that are not language codes
1973 # Bug 24502: filter duplicates
1974 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1975 $this->mLangLinkLanguages
[$iw] = true;
1976 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1979 $s = rtrim( $s . $prefix );
1980 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1981 wfProfileOut( __METHOD__
. "-interwiki" );
1984 wfProfileOut( __METHOD__
. "-interwiki" );
1986 if ( $ns == NS_FILE
) {
1987 wfProfileIn( __METHOD__
. "-image" );
1988 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1990 # if no parameters were passed, $text
1991 # becomes something like "File:Foo.png",
1992 # which we don't want to pass on to the
1996 # recursively parse links inside the image caption
1997 # actually, this will parse them in any other parameters, too,
1998 # but it might be hard to fix that, and it doesn't matter ATM
1999 $text = $this->replaceExternalLinks( $text );
2000 $holders->merge( $this->replaceInternalLinks2( $text ) );
2002 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2003 $s .= $prefix . $this->armorLinks(
2004 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2006 $s .= $prefix . $trail;
2008 wfProfileOut( __METHOD__
. "-image" );
2012 if ( $ns == NS_CATEGORY
) {
2013 wfProfileIn( __METHOD__
. "-category" );
2014 $s = rtrim( $s . "\n" ); # bug 87
2017 $sortkey = $this->getDefaultSort();
2021 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2022 $sortkey = str_replace( "\n", '', $sortkey );
2023 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2024 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2027 * Strip the whitespace Category links produce, see bug 87
2028 * @todo We might want to use trim($tmp, "\n") here.
2030 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2032 wfProfileOut( __METHOD__
. "-category" );
2037 # Self-link checking
2038 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2039 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2040 $this->mTitle
->getPrefixedText(),
2041 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2044 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2049 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2050 # @todo FIXME: Should do batch file existence checks, see comment below
2051 if ( $ns == NS_MEDIA
) {
2052 wfProfileIn( __METHOD__
. "-media" );
2053 # Give extensions a chance to select the file revision for us
2056 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2057 array( $this, $nt, &$options, &$descQuery ) );
2058 # Fetch and register the file (file title may be different via hooks)
2059 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2060 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2061 $s .= $prefix . $this->armorLinks(
2062 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2063 wfProfileOut( __METHOD__
. "-media" );
2067 wfProfileIn( __METHOD__
. "-always_known" );
2068 # Some titles, such as valid special pages or files in foreign repos, should
2069 # be shown as bluelinks even though they're not included in the page table
2071 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2072 # batch file existence checks for NS_FILE and NS_MEDIA
2073 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2074 $this->mOutput
->addLink( $nt );
2075 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2077 # Links will be added to the output link list after checking
2078 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2080 wfProfileOut( __METHOD__
. "-always_known" );
2082 wfProfileOut( __METHOD__
);
2087 * Render a forced-blue link inline; protect against double expansion of
2088 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2089 * Since this little disaster has to split off the trail text to avoid
2090 * breaking URLs in the following text without breaking trails on the
2091 * wiki links, it's been made into a horrible function.
2094 * @param $text String
2095 * @param $query Array or String
2096 * @param $trail String
2097 * @param $prefix String
2098 * @return String: HTML-wikitext mix oh yuck
2100 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2101 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2103 if ( is_string( $query ) ) {
2104 $query = wfCgiToArray( $query );
2106 if ( $text == '' ) {
2107 $text = htmlspecialchars( $nt->getPrefixedText() );
2110 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2112 return $this->armorLinks( $link ) . $trail;
2116 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2117 * going to go through further parsing steps before inline URL expansion.
2119 * Not needed quite as much as it used to be since free links are a bit
2120 * more sensible these days. But bracketed links are still an issue.
2122 * @param $text String: more-or-less HTML
2123 * @return String: less-or-more HTML with NOPARSE bits
2125 function armorLinks( $text ) {
2126 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2127 "{$this->mUniqPrefix}NOPARSE$1", $text );
2131 * Return true if subpage links should be expanded on this page.
2134 function areSubpagesAllowed() {
2135 # Some namespaces don't allow subpages
2136 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2140 * Handle link to subpage if necessary
2142 * @param $target String: the source of the link
2143 * @param &$text String: the link text, modified as necessary
2144 * @return string the full name of the link
2147 function maybeDoSubpageLink( $target, &$text ) {
2148 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2152 * Used by doBlockLevels()
2157 function closeParagraph() {
2159 if ( $this->mLastSection
!= '' ) {
2160 $result = '</' . $this->mLastSection
. ">\n";
2162 $this->mInPre
= false;
2163 $this->mLastSection
= '';
2168 * getCommon() returns the length of the longest common substring
2169 * of both arguments, starting at the beginning of both.
2172 * @param $st1 string
2173 * @param $st2 string
2177 function getCommon( $st1, $st2 ) {
2178 $fl = strlen( $st1 );
2179 $shorter = strlen( $st2 );
2180 if ( $fl < $shorter ) {
2184 for ( $i = 0; $i < $shorter; ++
$i ) {
2185 if ( $st1[$i] != $st2[$i] ) {
2193 * These next three functions open, continue, and close the list
2194 * element appropriate to the prefix character passed into them.
2197 * @param $char string
2201 function openList( $char ) {
2202 $result = $this->closeParagraph();
2204 if ( '*' === $char ) {
2205 $result .= '<ul><li>';
2206 } elseif ( '#' === $char ) {
2207 $result .= '<ol><li>';
2208 } elseif ( ':' === $char ) {
2209 $result .= '<dl><dd>';
2210 } elseif ( ';' === $char ) {
2211 $result .= '<dl><dt>';
2212 $this->mDTopen
= true;
2214 $result = '<!-- ERR 1 -->';
2222 * @param $char String
2227 function nextItem( $char ) {
2228 if ( '*' === $char ||
'#' === $char ) {
2230 } elseif ( ':' === $char ||
';' === $char ) {
2232 if ( $this->mDTopen
) {
2235 if ( ';' === $char ) {
2236 $this->mDTopen
= true;
2237 return $close . '<dt>';
2239 $this->mDTopen
= false;
2240 return $close . '<dd>';
2243 return '<!-- ERR 2 -->';
2248 * @param $char String
2253 function closeList( $char ) {
2254 if ( '*' === $char ) {
2255 $text = '</li></ul>';
2256 } elseif ( '#' === $char ) {
2257 $text = '</li></ol>';
2258 } elseif ( ':' === $char ) {
2259 if ( $this->mDTopen
) {
2260 $this->mDTopen
= false;
2261 $text = '</dt></dl>';
2263 $text = '</dd></dl>';
2266 return '<!-- ERR 3 -->';
2268 return $text . "\n";
2273 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2275 * @param $text String
2276 * @param $linestart Boolean: whether or not this is at the start of a line.
2278 * @return string the lists rendered as HTML
2280 function doBlockLevels( $text, $linestart ) {
2281 wfProfileIn( __METHOD__
);
2283 # Parsing through the text line by line. The main thing
2284 # happening here is handling of block-level elements p, pre,
2285 # and making lists from lines starting with * # : etc.
2287 $textLines = StringUtils
::explode( "\n", $text );
2289 $lastPrefix = $output = '';
2290 $this->mDTopen
= $inBlockElem = false;
2292 $paragraphStack = false;
2294 foreach ( $textLines as $oLine ) {
2296 if ( !$linestart ) {
2306 $lastPrefixLength = strlen( $lastPrefix );
2307 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2308 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2309 # If not in a <pre> element, scan for and figure out what prefixes are there.
2310 if ( !$this->mInPre
) {
2311 # Multiple prefixes may abut each other for nested lists.
2312 $prefixLength = strspn( $oLine, '*#:;' );
2313 $prefix = substr( $oLine, 0, $prefixLength );
2316 # ; and : are both from definition-lists, so they're equivalent
2317 # for the purposes of determining whether or not we need to open/close
2319 $prefix2 = str_replace( ';', ':', $prefix );
2320 $t = substr( $oLine, $prefixLength );
2321 $this->mInPre
= (bool)$preOpenMatch;
2323 # Don't interpret any other prefixes in preformatted text
2325 $prefix = $prefix2 = '';
2330 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2331 # Same as the last item, so no need to deal with nesting or opening stuff
2332 $output .= $this->nextItem( substr( $prefix, -1 ) );
2333 $paragraphStack = false;
2335 if ( substr( $prefix, -1 ) === ';') {
2336 # The one nasty exception: definition lists work like this:
2337 # ; title : definition text
2338 # So we check for : in the remainder text to split up the
2339 # title and definition, without b0rking links.
2341 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2343 $output .= $term . $this->nextItem( ':' );
2346 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2347 # We need to open or close prefixes, or both.
2349 # Either open or close a level...
2350 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2351 $paragraphStack = false;
2353 # Close all the prefixes which aren't shared.
2354 while ( $commonPrefixLength < $lastPrefixLength ) {
2355 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2356 --$lastPrefixLength;
2359 # Continue the current prefix if appropriate.
2360 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2361 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2364 # Open prefixes where appropriate.
2365 while ( $prefixLength > $commonPrefixLength ) {
2366 $char = substr( $prefix, $commonPrefixLength, 1 );
2367 $output .= $this->openList( $char );
2369 if ( ';' === $char ) {
2370 # @todo FIXME: This is dupe of code above
2371 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2373 $output .= $term . $this->nextItem( ':' );
2376 ++
$commonPrefixLength;
2378 $lastPrefix = $prefix2;
2381 # If we have no prefixes, go to paragraph mode.
2382 if ( 0 == $prefixLength ) {
2383 wfProfileIn( __METHOD__
. "-paragraph" );
2384 # No prefix (not in list)--go to paragraph mode
2385 # XXX: use a stack for nestable elements like span, table and div
2386 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2387 $closematch = preg_match(
2388 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2389 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2390 if ( $openmatch or $closematch ) {
2391 $paragraphStack = false;
2392 # TODO bug 5718: paragraph closed
2393 $output .= $this->closeParagraph();
2394 if ( $preOpenMatch and !$preCloseMatch ) {
2395 $this->mInPre
= true;
2397 $inBlockElem = !$closematch;
2398 } elseif ( !$inBlockElem && !$this->mInPre
) {
2399 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2401 if ( $this->mLastSection
!== 'pre' ) {
2402 $paragraphStack = false;
2403 $output .= $this->closeParagraph() . '<pre>';
2404 $this->mLastSection
= 'pre';
2406 $t = substr( $t, 1 );
2409 if ( trim( $t ) === '' ) {
2410 if ( $paragraphStack ) {
2411 $output .= $paragraphStack . '<br />';
2412 $paragraphStack = false;
2413 $this->mLastSection
= 'p';
2415 if ( $this->mLastSection
!== 'p' ) {
2416 $output .= $this->closeParagraph();
2417 $this->mLastSection
= '';
2418 $paragraphStack = '<p>';
2420 $paragraphStack = '</p><p>';
2424 if ( $paragraphStack ) {
2425 $output .= $paragraphStack;
2426 $paragraphStack = false;
2427 $this->mLastSection
= 'p';
2428 } elseif ( $this->mLastSection
!== 'p' ) {
2429 $output .= $this->closeParagraph() . '<p>';
2430 $this->mLastSection
= 'p';
2435 wfProfileOut( __METHOD__
. "-paragraph" );
2437 # somewhere above we forget to get out of pre block (bug 785)
2438 if ( $preCloseMatch && $this->mInPre
) {
2439 $this->mInPre
= false;
2441 if ( $paragraphStack === false ) {
2442 $output .= $t . "\n";
2445 while ( $prefixLength ) {
2446 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2449 if ( $this->mLastSection
!= '' ) {
2450 $output .= '</' . $this->mLastSection
. '>';
2451 $this->mLastSection
= '';
2454 wfProfileOut( __METHOD__
);
2459 * Split up a string on ':', ignoring any occurrences inside tags
2460 * to prevent illegal overlapping.
2462 * @param $str String the string to split
2463 * @param &$before String set to everything before the ':'
2464 * @param &$after String set to everything after the ':'
2465 * @throws MWException
2466 * @return String the position of the ':', or false if none found
2468 function findColonNoLinks( $str, &$before, &$after ) {
2469 wfProfileIn( __METHOD__
);
2471 $pos = strpos( $str, ':' );
2472 if ( $pos === false ) {
2474 wfProfileOut( __METHOD__
);
2478 $lt = strpos( $str, '<' );
2479 if ( $lt === false ||
$lt > $pos ) {
2480 # Easy; no tag nesting to worry about
2481 $before = substr( $str, 0, $pos );
2482 $after = substr( $str, $pos+
1 );
2483 wfProfileOut( __METHOD__
);
2487 # Ugly state machine to walk through avoiding tags.
2488 $state = self
::COLON_STATE_TEXT
;
2490 $len = strlen( $str );
2491 for( $i = 0; $i < $len; $i++
) {
2495 # (Using the number is a performance hack for common cases)
2496 case 0: # self::COLON_STATE_TEXT:
2499 # Could be either a <start> tag or an </end> tag
2500 $state = self
::COLON_STATE_TAGSTART
;
2503 if ( $stack == 0 ) {
2505 $before = substr( $str, 0, $i );
2506 $after = substr( $str, $i +
1 );
2507 wfProfileOut( __METHOD__
);
2510 # Embedded in a tag; don't break it.
2513 # Skip ahead looking for something interesting
2514 $colon = strpos( $str, ':', $i );
2515 if ( $colon === false ) {
2516 # Nothing else interesting
2517 wfProfileOut( __METHOD__
);
2520 $lt = strpos( $str, '<', $i );
2521 if ( $stack === 0 ) {
2522 if ( $lt === false ||
$colon < $lt ) {
2524 $before = substr( $str, 0, $colon );
2525 $after = substr( $str, $colon +
1 );
2526 wfProfileOut( __METHOD__
);
2530 if ( $lt === false ) {
2531 # Nothing else interesting to find; abort!
2532 # We're nested, but there's no close tags left. Abort!
2535 # Skip ahead to next tag start
2537 $state = self
::COLON_STATE_TAGSTART
;
2540 case 1: # self::COLON_STATE_TAG:
2545 $state = self
::COLON_STATE_TEXT
;
2548 # Slash may be followed by >?
2549 $state = self
::COLON_STATE_TAGSLASH
;
2555 case 2: # self::COLON_STATE_TAGSTART:
2558 $state = self
::COLON_STATE_CLOSETAG
;
2561 $state = self
::COLON_STATE_COMMENT
;
2564 # Illegal early close? This shouldn't happen D:
2565 $state = self
::COLON_STATE_TEXT
;
2568 $state = self
::COLON_STATE_TAG
;
2571 case 3: # self::COLON_STATE_CLOSETAG:
2576 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2577 wfProfileOut( __METHOD__
);
2580 $state = self
::COLON_STATE_TEXT
;
2583 case self
::COLON_STATE_TAGSLASH
:
2585 # Yes, a self-closed tag <blah/>
2586 $state = self
::COLON_STATE_TEXT
;
2588 # Probably we're jumping the gun, and this is an attribute
2589 $state = self
::COLON_STATE_TAG
;
2592 case 5: # self::COLON_STATE_COMMENT:
2594 $state = self
::COLON_STATE_COMMENTDASH
;
2597 case self
::COLON_STATE_COMMENTDASH
:
2599 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2601 $state = self
::COLON_STATE_COMMENT
;
2604 case self
::COLON_STATE_COMMENTDASHDASH
:
2606 $state = self
::COLON_STATE_TEXT
;
2608 $state = self
::COLON_STATE_COMMENT
;
2612 throw new MWException( "State machine error in " . __METHOD__
);
2616 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2617 wfProfileOut( __METHOD__
);
2620 wfProfileOut( __METHOD__
);
2625 * Return value of a magic variable (like PAGENAME)
2629 * @param $index integer
2630 * @param bool|\PPFrame $frame
2632 * @throws MWException
2635 function getVariableValue( $index, $frame = false ) {
2636 global $wgContLang, $wgSitename, $wgServer;
2637 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2639 if ( is_null( $this->mTitle
) ) {
2640 // If no title set, bad things are going to happen
2641 // later. Title should always be set since this
2642 // should only be called in the middle of a parse
2643 // operation (but the unit-tests do funky stuff)
2644 throw new MWException( __METHOD__
. ' Should only be '
2645 . ' called while parsing (no title set)' );
2649 * Some of these require message or data lookups and can be
2650 * expensive to check many times.
2652 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2653 if ( isset( $this->mVarCache
[$index] ) ) {
2654 return $this->mVarCache
[$index];
2658 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2659 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2662 global $wgLocaltimezone;
2663 if ( isset( $wgLocaltimezone ) ) {
2664 $oldtz = date_default_timezone_get();
2665 date_default_timezone_set( $wgLocaltimezone );
2668 $localTimestamp = date( 'YmdHis', $ts );
2669 $localMonth = date( 'm', $ts );
2670 $localMonth1 = date( 'n', $ts );
2671 $localMonthName = date( 'n', $ts );
2672 $localDay = date( 'j', $ts );
2673 $localDay2 = date( 'd', $ts );
2674 $localDayOfWeek = date( 'w', $ts );
2675 $localWeek = date( 'W', $ts );
2676 $localYear = date( 'Y', $ts );
2677 $localHour = date( 'H', $ts );
2678 if ( isset( $wgLocaltimezone ) ) {
2679 date_default_timezone_set( $oldtz );
2682 $pageLang = $this->getFunctionLang();
2685 case 'currentmonth':
2686 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2688 case 'currentmonth1':
2689 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2691 case 'currentmonthname':
2692 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2694 case 'currentmonthnamegen':
2695 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2697 case 'currentmonthabbrev':
2698 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2701 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2704 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2707 $value = $pageLang->formatNum( $localMonth );
2710 $value = $pageLang->formatNum( $localMonth1 );
2712 case 'localmonthname':
2713 $value = $pageLang->getMonthName( $localMonthName );
2715 case 'localmonthnamegen':
2716 $value = $pageLang->getMonthNameGen( $localMonthName );
2718 case 'localmonthabbrev':
2719 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2722 $value = $pageLang->formatNum( $localDay );
2725 $value = $pageLang->formatNum( $localDay2 );
2728 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2731 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2733 case 'fullpagename':
2734 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2736 case 'fullpagenamee':
2737 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2740 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2742 case 'subpagenamee':
2743 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2745 case 'basepagename':
2746 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2748 case 'basepagenamee':
2749 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2751 case 'talkpagename':
2752 if ( $this->mTitle
->canTalk() ) {
2753 $talkPage = $this->mTitle
->getTalkPage();
2754 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2759 case 'talkpagenamee':
2760 if ( $this->mTitle
->canTalk() ) {
2761 $talkPage = $this->mTitle
->getTalkPage();
2762 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2767 case 'subjectpagename':
2768 $subjPage = $this->mTitle
->getSubjectPage();
2769 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2771 case 'subjectpagenamee':
2772 $subjPage = $this->mTitle
->getSubjectPage();
2773 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2775 case 'pageid': // requested in bug 23427
2776 $pageid = $this->getTitle()->getArticleId();
2777 if( $pageid == 0 ) {
2778 # 0 means the page doesn't exist in the database,
2779 # which means the user is previewing a new page.
2780 # The vary-revision flag must be set, because the magic word
2781 # will have a different value once the page is saved.
2782 $this->mOutput
->setFlag( 'vary-revision' );
2783 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2785 $value = $pageid ?
$pageid : null;
2788 # Let the edit saving system know we should parse the page
2789 # *after* a revision ID has been assigned.
2790 $this->mOutput
->setFlag( 'vary-revision' );
2791 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2792 $value = $this->mRevisionId
;
2795 # Let the edit saving system know we should parse the page
2796 # *after* a revision ID has been assigned. This is for null edits.
2797 $this->mOutput
->setFlag( 'vary-revision' );
2798 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2799 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2801 case 'revisionday2':
2802 # Let the edit saving system know we should parse the page
2803 # *after* a revision ID has been assigned. This is for null edits.
2804 $this->mOutput
->setFlag( 'vary-revision' );
2805 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2806 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2808 case 'revisionmonth':
2809 # Let the edit saving system know we should parse the page
2810 # *after* a revision ID has been assigned. This is for null edits.
2811 $this->mOutput
->setFlag( 'vary-revision' );
2812 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2813 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2815 case 'revisionmonth1':
2816 # Let the edit saving system know we should parse the page
2817 # *after* a revision ID has been assigned. This is for null edits.
2818 $this->mOutput
->setFlag( 'vary-revision' );
2819 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2820 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2822 case 'revisionyear':
2823 # Let the edit saving system know we should parse the page
2824 # *after* a revision ID has been assigned. This is for null edits.
2825 $this->mOutput
->setFlag( 'vary-revision' );
2826 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2827 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2829 case 'revisiontimestamp':
2830 # Let the edit saving system know we should parse the page
2831 # *after* a revision ID has been assigned. This is for null edits.
2832 $this->mOutput
->setFlag( 'vary-revision' );
2833 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2834 $value = $this->getRevisionTimestamp();
2836 case 'revisionuser':
2837 # Let the edit saving system know we should parse the page
2838 # *after* a revision ID has been assigned. This is for null edits.
2839 $this->mOutput
->setFlag( 'vary-revision' );
2840 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2841 $value = $this->getRevisionUser();
2844 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2847 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2849 case 'namespacenumber':
2850 $value = $this->mTitle
->getNamespace();
2853 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2856 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2858 case 'subjectspace':
2859 $value = $this->mTitle
->getSubjectNsText();
2861 case 'subjectspacee':
2862 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2864 case 'currentdayname':
2865 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2868 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2871 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2874 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2877 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2878 # int to remove the padding
2879 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2882 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2884 case 'localdayname':
2885 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2888 $value = $pageLang->formatNum( $localYear, true );
2891 $value = $pageLang->time( $localTimestamp, false, false );
2894 $value = $pageLang->formatNum( $localHour, 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)$localWeek );
2902 $value = $pageLang->formatNum( $localDayOfWeek );
2904 case 'numberofarticles':
2905 $value = $pageLang->formatNum( SiteStats
::articles() );
2907 case 'numberoffiles':
2908 $value = $pageLang->formatNum( SiteStats
::images() );
2910 case 'numberofusers':
2911 $value = $pageLang->formatNum( SiteStats
::users() );
2913 case 'numberofactiveusers':
2914 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2916 case 'numberofpages':
2917 $value = $pageLang->formatNum( SiteStats
::pages() );
2919 case 'numberofadmins':
2920 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2922 case 'numberofedits':
2923 $value = $pageLang->formatNum( SiteStats
::edits() );
2925 case 'numberofviews':
2926 global $wgDisableCounters;
2927 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2929 case 'currenttimestamp':
2930 $value = wfTimestamp( TS_MW
, $ts );
2932 case 'localtimestamp':
2933 $value = $localTimestamp;
2935 case 'currentversion':
2936 $value = SpecialVersion
::getVersion();
2939 return $wgArticlePath;
2945 $serverParts = wfParseUrl( $wgServer );
2946 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2948 return $wgScriptPath;
2950 return $wgStylePath;
2951 case 'directionmark':
2952 return $pageLang->getDirMark();
2953 case 'contentlanguage':
2954 global $wgLanguageCode;
2955 return $wgLanguageCode;
2958 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2966 $this->mVarCache
[$index] = $value;
2973 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2977 function initialiseVariables() {
2978 wfProfileIn( __METHOD__
);
2979 $variableIDs = MagicWord
::getVariableIDs();
2980 $substIDs = MagicWord
::getSubstIDs();
2982 $this->mVariables
= new MagicWordArray( $variableIDs );
2983 $this->mSubstWords
= new MagicWordArray( $substIDs );
2984 wfProfileOut( __METHOD__
);
2988 * Preprocess some wikitext and return the document tree.
2989 * This is the ghost of replace_variables().
2991 * @param $text String: The text to parse
2992 * @param $flags Integer: bitwise combination of:
2993 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2994 * included. Default is to assume a direct page view.
2996 * The generated DOM tree must depend only on the input text and the flags.
2997 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2999 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3000 * change in the DOM tree for a given text, must be passed through the section identifier
3001 * in the section edit link and thus back to extractSections().
3003 * The output of this function is currently only cached in process memory, but a persistent
3004 * cache may be implemented at a later date which takes further advantage of these strict
3005 * dependency requirements.
3011 function preprocessToDom( $text, $flags = 0 ) {
3012 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3017 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3023 public static function splitWhitespace( $s ) {
3024 $ltrimmed = ltrim( $s );
3025 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3026 $trimmed = rtrim( $ltrimmed );
3027 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3029 $w2 = substr( $ltrimmed, -$diff );
3033 return array( $w1, $trimmed, $w2 );
3037 * Replace magic variables, templates, and template arguments
3038 * with the appropriate text. Templates are substituted recursively,
3039 * taking care to avoid infinite loops.
3041 * Note that the substitution depends on value of $mOutputType:
3042 * self::OT_WIKI: only {{subst:}} templates
3043 * self::OT_PREPROCESS: templates but not extension tags
3044 * self::OT_HTML: all templates and extension tags
3046 * @param $text String the text to transform
3047 * @param $frame PPFrame Object describing the arguments passed to the template.
3048 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3049 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3050 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3055 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3056 # Is there any text? Also, Prevent too big inclusions!
3057 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3060 wfProfileIn( __METHOD__
);
3062 if ( $frame === false ) {
3063 $frame = $this->getPreprocessor()->newFrame();
3064 } elseif ( !( $frame instanceof PPFrame
) ) {
3065 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3066 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3069 $dom = $this->preprocessToDom( $text );
3070 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3071 $text = $frame->expand( $dom, $flags );
3073 wfProfileOut( __METHOD__
);
3078 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3080 * @param $args array
3084 static function createAssocArgs( $args ) {
3085 $assocArgs = array();
3087 foreach ( $args as $arg ) {
3088 $eqpos = strpos( $arg, '=' );
3089 if ( $eqpos === false ) {
3090 $assocArgs[$index++
] = $arg;
3092 $name = trim( substr( $arg, 0, $eqpos ) );
3093 $value = trim( substr( $arg, $eqpos+
1 ) );
3094 if ( $value === false ) {
3097 if ( $name !== false ) {
3098 $assocArgs[$name] = $value;
3107 * Warn the user when a parser limitation is reached
3108 * Will warn at most once the user per limitation type
3110 * @param $limitationType String: should be one of:
3111 * 'expensive-parserfunction' (corresponding messages:
3112 * 'expensive-parserfunction-warning',
3113 * 'expensive-parserfunction-category')
3114 * 'post-expand-template-argument' (corresponding messages:
3115 * 'post-expand-template-argument-warning',
3116 * 'post-expand-template-argument-category')
3117 * 'post-expand-template-inclusion' (corresponding messages:
3118 * 'post-expand-template-inclusion-warning',
3119 * 'post-expand-template-inclusion-category')
3120 * @param $current int|null Current value
3121 * @param $max int|null Maximum allowed, when an explicit limit has been
3122 * exceeded, provide the values (optional)
3124 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3125 # does no harm if $current and $max are present but are unnecessary for the message
3126 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3127 ->inContentLanguage()->escaped();
3128 $this->mOutput
->addWarning( $warning );
3129 $this->addTrackingCategory( "$limitationType-category" );
3133 * Return the text of a template, after recursively
3134 * replacing any variables or templates within the template.
3136 * @param $piece Array: the parts of the template
3137 * $piece['title']: the title, i.e. the part before the |
3138 * $piece['parts']: the parameter array
3139 * $piece['lineStart']: whether the brace was at the start of a line
3140 * @param $frame PPFrame The current frame, contains template arguments
3141 * @throws MWException
3142 * @return String: the text of the template
3145 function braceSubstitution( $piece, $frame ) {
3147 wfProfileIn( __METHOD__
);
3148 wfProfileIn( __METHOD__
. '-setup' );
3151 $found = false; # $text has been filled
3152 $nowiki = false; # wiki markup in $text should be escaped
3153 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3154 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3155 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3156 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3158 # Title object, where $text came from
3161 # $part1 is the bit before the first |, and must contain only title characters.
3162 # Various prefixes will be stripped from it later.
3163 $titleWithSpaces = $frame->expand( $piece['title'] );
3164 $part1 = trim( $titleWithSpaces );
3167 # Original title text preserved for various purposes
3168 $originalTitle = $part1;
3170 # $args is a list of argument nodes, starting from index 0, not including $part1
3171 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3172 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3173 wfProfileOut( __METHOD__
. '-setup' );
3175 $titleProfileIn = null; // profile templates
3178 wfProfileIn( __METHOD__
. '-modifiers' );
3181 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3183 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3184 # Decide whether to expand template or keep wikitext as-is.
3185 if ( $this->ot
['wiki'] ) {
3186 if ( $substMatch === false ) {
3187 $literal = true; # literal when in PST with no prefix
3189 $literal = false; # expand when in PST with subst: or safesubst:
3192 if ( $substMatch == 'subst' ) {
3193 $literal = true; # literal when not in PST with plain subst:
3195 $literal = false; # expand when not in PST with safesubst: or no prefix
3199 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3206 if ( !$found && $args->getLength() == 0 ) {
3207 $id = $this->mVariables
->matchStartToEnd( $part1 );
3208 if ( $id !== false ) {
3209 $text = $this->getVariableValue( $id, $frame );
3210 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3211 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3217 # MSG, MSGNW and RAW
3220 $mwMsgnw = MagicWord
::get( 'msgnw' );
3221 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3224 # Remove obsolete MSG:
3225 $mwMsg = MagicWord
::get( 'msg' );
3226 $mwMsg->matchStartAndRemove( $part1 );
3230 $mwRaw = MagicWord
::get( 'raw' );
3231 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3232 $forceRawInterwiki = true;
3235 wfProfileOut( __METHOD__
. '-modifiers' );
3239 wfProfileIn( __METHOD__
. '-pfunc' );
3241 $colonPos = strpos( $part1, ':' );
3242 if ( $colonPos !== false ) {
3243 # Case sensitive functions
3244 $function = substr( $part1, 0, $colonPos );
3245 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3246 $function = $this->mFunctionSynonyms
[1][$function];
3248 # Case insensitive functions
3249 $function = $wgContLang->lc( $function );
3250 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3251 $function = $this->mFunctionSynonyms
[0][$function];
3257 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3258 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3259 $initialArgs = array( &$this );
3260 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3261 if ( $flags & SFH_OBJECT_ARGS
) {
3262 # Add a frame parameter, and pass the arguments as an array
3263 $allArgs = $initialArgs;
3264 $allArgs[] = $frame;
3265 for ( $i = 0; $i < $args->getLength(); $i++
) {
3266 $funcArgs[] = $args->item( $i );
3268 $allArgs[] = $funcArgs;
3270 # Convert arguments to plain text
3271 for ( $i = 0; $i < $args->getLength(); $i++
) {
3272 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3274 $allArgs = array_merge( $initialArgs, $funcArgs );
3277 # Workaround for PHP bug 35229 and similar
3278 if ( !is_callable( $callback ) ) {
3279 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3280 wfProfileOut( __METHOD__
. '-pfunc' );
3281 wfProfileOut( __METHOD__
);
3282 throw new MWException( "Tag hook for $function is not callable\n" );
3284 $result = call_user_func_array( $callback, $allArgs );
3287 $preprocessFlags = 0;
3289 if ( is_array( $result ) ) {
3290 if ( isset( $result[0] ) ) {
3292 unset( $result[0] );
3295 # Extract flags into the local scope
3296 # This allows callers to set flags such as nowiki, found, etc.
3302 $text = $this->preprocessToDom( $text, $preprocessFlags );
3305 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3308 wfProfileOut( __METHOD__
. '-pfunc' );
3311 # Finish mangling title and then check for loops.
3312 # Set $title to a Title object and $titleText to the PDBK
3315 # Split the title into page and subpage
3317 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3318 if ( $subpage !== '' ) {
3319 $ns = $this->mTitle
->getNamespace();
3321 $title = Title
::newFromText( $part1, $ns );
3323 $titleText = $title->getPrefixedText();
3324 # Check for language variants if the template is not found
3325 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3326 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3328 # Do recursion depth check
3329 $limit = $this->mOptions
->getMaxTemplateDepth();
3330 if ( $frame->depth
>= $limit ) {
3332 $text = '<span class="error">'
3333 . wfMessage( 'parser-template-recursion-depth-warning' )
3334 ->numParams( $limit )->inContentLanguage()->text()
3340 # Load from database
3341 if ( !$found && $title ) {
3342 if ( !Profiler
::instance()->isPersistent() ) {
3343 # Too many unique items can kill profiling DBs/collectors
3344 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3345 wfProfileIn( $titleProfileIn ); // template in
3347 wfProfileIn( __METHOD__
. '-loadtpl' );
3348 if ( !$title->isExternal() ) {
3349 if ( $title->isSpecialPage()
3350 && $this->mOptions
->getAllowSpecialInclusion()
3351 && $this->ot
['html'] )
3353 // Pass the template arguments as URL parameters.
3354 // "uselang" will have no effect since the Language object
3355 // is forced to the one defined in ParserOptions.
3356 $pageArgs = array();
3357 for ( $i = 0; $i < $args->getLength(); $i++
) {
3358 $bits = $args->item( $i )->splitArg();
3359 if ( strval( $bits['index'] ) === '' ) {
3360 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3361 $value = trim( $frame->expand( $bits['value'] ) );
3362 $pageArgs[$name] = $value;
3366 // Create a new context to execute the special page
3367 $context = new RequestContext
;
3368 $context->setTitle( $title );
3369 $context->setRequest( new FauxRequest( $pageArgs ) );
3370 $context->setUser( $this->getUser() );
3371 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3372 $ret = SpecialPageFactory
::capturePath( $title, $context );
3374 $text = $context->getOutput()->getHTML();
3375 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3378 $this->disableCache();
3380 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3381 $found = false; # access denied
3382 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3384 list( $text, $title ) = $this->getTemplateDom( $title );
3385 if ( $text !== false ) {
3391 # If the title is valid but undisplayable, make a link to it
3392 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3393 $text = "[[:$titleText]]";
3396 } elseif ( $title->isTrans() ) {
3397 # Interwiki transclusion
3398 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3399 $text = $this->interwikiTransclude( $title, 'render' );
3402 $text = $this->interwikiTransclude( $title, 'raw' );
3403 # Preprocess it like a template
3404 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3410 # Do infinite loop check
3411 # This has to be done after redirect resolution to avoid infinite loops via redirects
3412 if ( !$frame->loopCheck( $title ) ) {
3414 $text = '<span class="error">'
3415 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3417 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3419 wfProfileOut( __METHOD__
. '-loadtpl' );
3422 # If we haven't found text to substitute by now, we're done
3423 # Recover the source wikitext and return it
3425 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3426 if ( $titleProfileIn ) {
3427 wfProfileOut( $titleProfileIn ); // template out
3429 wfProfileOut( __METHOD__
);
3430 return array( 'object' => $text );
3433 # Expand DOM-style return values in a child frame
3434 if ( $isChildObj ) {
3435 # Clean up argument array
3436 $newFrame = $frame->newChild( $args, $title );
3439 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3440 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3441 # Expansion is eligible for the empty-frame cache
3442 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3443 $text = $this->mTplExpandCache
[$titleText];
3445 $text = $newFrame->expand( $text );
3446 $this->mTplExpandCache
[$titleText] = $text;
3449 # Uncached expansion
3450 $text = $newFrame->expand( $text );
3453 if ( $isLocalObj && $nowiki ) {
3454 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3455 $isLocalObj = false;
3458 if ( $titleProfileIn ) {
3459 wfProfileOut( $titleProfileIn ); // template out
3462 # Replace raw HTML by a placeholder
3464 $text = $this->insertStripItem( $text );
3465 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3466 # Escape nowiki-style return values
3467 $text = wfEscapeWikiText( $text );
3468 } elseif ( is_string( $text )
3469 && !$piece['lineStart']
3470 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3472 # Bug 529: if the template begins with a table or block-level
3473 # element, it should be treated as beginning a new line.
3474 # This behaviour is somewhat controversial.
3475 $text = "\n" . $text;
3478 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3479 # Error, oversize inclusion
3480 if ( $titleText !== false ) {
3481 # Make a working, properly escaped link if possible (bug 23588)
3482 $text = "[[:$titleText]]";
3484 # This will probably not be a working link, but at least it may
3485 # provide some hint of where the problem is
3486 preg_replace( '/^:/', '', $originalTitle );
3487 $text = "[[:$originalTitle]]";
3489 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3490 $this->limitationWarn( 'post-expand-template-inclusion' );
3493 if ( $isLocalObj ) {
3494 $ret = array( 'object' => $text );
3496 $ret = array( 'text' => $text );
3499 wfProfileOut( __METHOD__
);
3504 * Get the semi-parsed DOM representation of a template with a given title,
3505 * and its redirect destination title. Cached.
3507 * @param $title Title
3511 function getTemplateDom( $title ) {
3512 $cacheTitle = $title;
3513 $titleText = $title->getPrefixedDBkey();
3515 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3516 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3517 $title = Title
::makeTitle( $ns, $dbk );
3518 $titleText = $title->getPrefixedDBkey();
3520 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3521 return array( $this->mTplDomCache
[$titleText], $title );
3524 # Cache miss, go to the database
3525 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3527 if ( $text === false ) {
3528 $this->mTplDomCache
[$titleText] = false;
3529 return array( false, $title );
3532 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3533 $this->mTplDomCache
[ $titleText ] = $dom;
3535 if ( !$title->equals( $cacheTitle ) ) {
3536 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3537 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3540 return array( $dom, $title );
3544 * Fetch the unparsed text of a template and register a reference to it.
3545 * @param Title $title
3546 * @return Array ( string or false, Title )
3548 function fetchTemplateAndTitle( $title ) {
3549 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3550 $stuff = call_user_func( $templateCb, $title, $this );
3551 $text = $stuff['text'];
3552 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3553 if ( isset( $stuff['deps'] ) ) {
3554 foreach ( $stuff['deps'] as $dep ) {
3555 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3558 return array( $text, $finalTitle );
3562 * Fetch the unparsed text of a template and register a reference to it.
3563 * @param Title $title
3564 * @return mixed string or false
3566 function fetchTemplate( $title ) {
3567 $rv = $this->fetchTemplateAndTitle( $title );
3572 * Static function to get a template
3573 * Can be overridden via ParserOptions::setTemplateCallback().
3575 * @param $title Title
3576 * @param $parser Parser
3580 static function statelessFetchTemplate( $title, $parser = false ) {
3581 $text = $skip = false;
3582 $finalTitle = $title;
3585 # Loop to fetch the article, with up to 1 redirect
3586 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3587 # Give extensions a chance to select the revision instead
3588 $id = false; # Assume current
3589 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3590 array( $parser, $title, &$skip, &$id ) );
3596 'page_id' => $title->getArticleID(),
3603 ? Revision
::newFromId( $id )
3604 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3605 $rev_id = $rev ?
$rev->getId() : 0;
3606 # If there is no current revision, there is no page
3607 if ( $id === false && !$rev ) {
3608 $linkCache = LinkCache
::singleton();
3609 $linkCache->addBadLinkObj( $title );
3614 'page_id' => $title->getArticleID(),
3615 'rev_id' => $rev_id );
3616 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3617 # We fetched a rev from a different title; register it too...
3619 'title' => $rev->getTitle(),
3620 'page_id' => $rev->getPage(),
3621 'rev_id' => $rev_id );
3625 $content = $rev->getContent();
3626 $text = $content ?
$content->getWikitextForTransclusion() : null;
3628 if ( $text === false ||
$text === null ) {
3632 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3634 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3635 if ( !$message->exists() ) {
3639 $content = $message->content();
3640 $text = $message->plain();
3648 $finalTitle = $title;
3649 $title = $content->getRedirectTarget();
3653 'finalTitle' => $finalTitle,
3658 * Fetch a file and its title and register a reference to it.
3659 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3660 * @param Title $title
3661 * @param Array $options Array of options to RepoGroup::findFile
3664 function fetchFile( $title, $options = array() ) {
3665 $res = $this->fetchFileAndTitle( $title, $options );
3670 * Fetch a file and its title and register a reference to it.
3671 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3672 * @param Title $title
3673 * @param Array $options Array of options to RepoGroup::findFile
3674 * @return Array ( File or false, Title of file )
3676 function fetchFileAndTitle( $title, $options = array() ) {
3677 if ( isset( $options['broken'] ) ) {
3678 $file = false; // broken thumbnail forced by hook
3679 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3680 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3681 } else { // get by (name,timestamp)
3682 $file = wfFindFile( $title, $options );
3684 $time = $file ?
$file->getTimestamp() : false;
3685 $sha1 = $file ?
$file->getSha1() : false;
3686 # Register the file as a dependency...
3687 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3688 if ( $file && !$title->equals( $file->getTitle() ) ) {
3689 # Update fetched file title
3690 $title = $file->getTitle();
3691 if ( is_null( $file->getRedirectedTitle() ) ) {
3692 # This file was not a redirect, but the title does not match.
3693 # Register under the new name because otherwise the link will
3695 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3698 return array( $file, $title );
3702 * Transclude an interwiki link.
3704 * @param $title Title
3709 function interwikiTransclude( $title, $action ) {
3710 global $wgEnableScaryTranscluding;
3712 if ( !$wgEnableScaryTranscluding ) {
3713 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3716 $url = $title->getFullUrl( "action=$action" );
3718 if ( strlen( $url ) > 255 ) {
3719 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3721 return $this->fetchScaryTemplateMaybeFromCache( $url );
3725 * @param $url string
3726 * @return Mixed|String
3728 function fetchScaryTemplateMaybeFromCache( $url ) {
3729 global $wgTranscludeCacheExpiry;
3730 $dbr = wfGetDB( DB_SLAVE
);
3731 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3732 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3733 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3735 return $obj->tc_contents
;
3738 $req = MWHttpRequest
::factory( $url );
3739 $status = $req->execute(); // Status object
3740 if ( $status->isOK() ) {
3741 $text = $req->getContent();
3742 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3743 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3745 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3748 $dbw = wfGetDB( DB_MASTER
);
3749 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3751 'tc_time' => $dbw->timestamp( time() ),
3752 'tc_contents' => $text)
3758 * Triple brace replacement -- used for template arguments
3761 * @param $piece array
3762 * @param $frame PPFrame
3766 function argSubstitution( $piece, $frame ) {
3767 wfProfileIn( __METHOD__
);
3770 $parts = $piece['parts'];
3771 $nameWithSpaces = $frame->expand( $piece['title'] );
3772 $argName = trim( $nameWithSpaces );
3774 $text = $frame->getArgument( $argName );
3775 if ( $text === false && $parts->getLength() > 0
3779 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3782 # No match in frame, use the supplied default
3783 $object = $parts->item( 0 )->getChildren();
3785 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3786 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3787 $this->limitationWarn( 'post-expand-template-argument' );
3790 if ( $text === false && $object === false ) {
3792 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3794 if ( $error !== false ) {
3797 if ( $object !== false ) {
3798 $ret = array( 'object' => $object );
3800 $ret = array( 'text' => $text );
3803 wfProfileOut( __METHOD__
);
3808 * Return the text to be used for a given extension tag.
3809 * This is the ghost of strip().
3811 * @param $params array Associative array of parameters:
3812 * name PPNode for the tag name
3813 * attr PPNode for unparsed text where tag attributes are thought to be
3814 * attributes Optional associative array of parsed attributes
3815 * inner Contents of extension element
3816 * noClose Original text did not have a close tag
3817 * @param $frame PPFrame
3819 * @throws MWException
3822 function extensionSubstitution( $params, $frame ) {
3823 $name = $frame->expand( $params['name'] );
3824 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3825 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3826 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3828 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3829 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3830 if ( $isFunctionTag ) {
3831 $markerType = 'none';
3833 $markerType = 'general';
3835 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3836 $name = strtolower( $name );
3837 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3838 if ( isset( $params['attributes'] ) ) {
3839 $attributes = $attributes +
$params['attributes'];
3842 if ( isset( $this->mTagHooks
[$name] ) ) {
3843 # Workaround for PHP bug 35229 and similar
3844 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3845 throw new MWException( "Tag hook for $name is not callable\n" );
3847 $output = call_user_func_array( $this->mTagHooks
[$name],
3848 array( $content, $attributes, $this, $frame ) );
3849 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3850 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3851 if ( !is_callable( $callback ) ) {
3852 throw new MWException( "Tag hook for $name is not callable\n" );
3855 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3857 $output = '<span class="error">Invalid tag extension name: ' .
3858 htmlspecialchars( $name ) . '</span>';
3861 if ( is_array( $output ) ) {
3862 # Extract flags to local scope (to override $markerType)
3864 $output = $flags[0];
3869 if ( is_null( $attrText ) ) {
3872 if ( isset( $params['attributes'] ) ) {
3873 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3874 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3875 htmlspecialchars( $attrValue ) . '"';
3878 if ( $content === null ) {
3879 $output = "<$name$attrText/>";
3881 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3882 $output = "<$name$attrText>$content$close";
3886 if ( $markerType === 'none' ) {
3888 } elseif ( $markerType === 'nowiki' ) {
3889 $this->mStripState
->addNoWiki( $marker, $output );
3890 } elseif ( $markerType === 'general' ) {
3891 $this->mStripState
->addGeneral( $marker, $output );
3893 throw new MWException( __METHOD__
. ': invalid marker type' );
3899 * Increment an include size counter
3901 * @param $type String: the type of expansion
3902 * @param $size Integer: the size of the text
3903 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3905 function incrementIncludeSize( $type, $size ) {
3906 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3909 $this->mIncludeSizes
[$type] +
= $size;
3915 * Increment the expensive function count
3917 * @return Boolean: false if the limit has been exceeded
3919 function incrementExpensiveFunctionCount() {
3920 $this->mExpensiveFunctionCount++
;
3921 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3925 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3926 * Fills $this->mDoubleUnderscores, returns the modified text
3928 * @param $text string
3932 function doDoubleUnderscore( $text ) {
3933 wfProfileIn( __METHOD__
);
3935 # The position of __TOC__ needs to be recorded
3936 $mw = MagicWord
::get( 'toc' );
3937 if ( $mw->match( $text ) ) {
3938 $this->mShowToc
= true;
3939 $this->mForceTocPosition
= true;
3941 # Set a placeholder. At the end we'll fill it in with the TOC.
3942 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3944 # Only keep the first one.
3945 $text = $mw->replace( '', $text );
3948 # Now match and remove the rest of them
3949 $mwa = MagicWord
::getDoubleUnderscoreArray();
3950 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3952 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3953 $this->mOutput
->mNoGallery
= true;
3955 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3956 $this->mShowToc
= false;
3958 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3959 $this->addTrackingCategory( 'hidden-category-category' );
3961 # (bug 8068) Allow control over whether robots index a page.
3963 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3964 # is not desirable, the last one on the page should win.
3965 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3966 $this->mOutput
->setIndexPolicy( 'noindex' );
3967 $this->addTrackingCategory( 'noindex-category' );
3969 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3970 $this->mOutput
->setIndexPolicy( 'index' );
3971 $this->addTrackingCategory( 'index-category' );
3974 # Cache all double underscores in the database
3975 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3976 $this->mOutput
->setProperty( $key, '' );
3979 wfProfileOut( __METHOD__
);
3984 * Add a tracking category, getting the title from a system message,
3985 * or print a debug message if the title is invalid.
3987 * @param $msg String: message key
3988 * @return Boolean: whether the addition was successful
3990 public function addTrackingCategory( $msg ) {
3991 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3992 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
3995 // Important to parse with correct title (bug 31469)
3996 $cat = wfMessage( $msg )
3997 ->title( $this->getTitle() )
3998 ->inContentLanguage()
4001 # Allow tracking categories to be disabled by setting them to "-"
4002 if ( $cat === '-' ) {
4006 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4007 if ( $containerCategory ) {
4008 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4011 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4017 * This function accomplishes several tasks:
4018 * 1) Auto-number headings if that option is enabled
4019 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4020 * 3) Add a Table of contents on the top for users who have enabled the option
4021 * 4) Auto-anchor headings
4023 * It loops through all headlines, collects the necessary data, then splits up the
4024 * string and re-inserts the newly formatted headlines.
4026 * @param $text String
4027 * @param $origText String: original, untouched wikitext
4028 * @param $isMain Boolean
4029 * @return mixed|string
4032 function formatHeadings( $text, $origText, $isMain=true ) {
4033 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4035 # Inhibit editsection links if requested in the page
4036 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4037 $maybeShowEditLink = $showEditLink = false;
4039 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4040 $showEditLink = $this->mOptions
->getEditSection();
4042 if ( $showEditLink ) {
4043 $this->mOutput
->setEditSectionTokens( true );
4046 # Get all headlines for numbering them and adding funky stuff like [edit]
4047 # links - this is for later, but we need the number of headlines right now
4049 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4051 # if there are fewer than 4 headlines in the article, do not show TOC
4052 # unless it's been explicitly enabled.
4053 $enoughToc = $this->mShowToc
&&
4054 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4056 # Allow user to stipulate that a page should have a "new section"
4057 # link added via __NEWSECTIONLINK__
4058 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4059 $this->mOutput
->setNewSection( true );
4062 # Allow user to remove the "new section"
4063 # link via __NONEWSECTIONLINK__
4064 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4065 $this->mOutput
->hideNewSection( true );
4068 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4069 # override above conditions and always show TOC above first header
4070 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4071 $this->mShowToc
= true;
4079 # Ugh .. the TOC should have neat indentation levels which can be
4080 # passed to the skin functions. These are determined here
4084 $sublevelCount = array();
4085 $levelCount = array();
4090 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4091 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4092 $oldType = $this->mOutputType
;
4093 $this->setOutputType( self
::OT_WIKI
);
4094 $frame = $this->getPreprocessor()->newFrame();
4095 $root = $this->preprocessToDom( $origText );
4096 $node = $root->getFirstChild();
4101 foreach ( $matches[3] as $headline ) {
4102 $isTemplate = false;
4104 $sectionIndex = false;
4106 $markerMatches = array();
4107 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4108 $serial = $markerMatches[1];
4109 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4110 $isTemplate = ( $titleText != $baseTitleText );
4111 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4115 $prevlevel = $level;
4117 $level = $matches[1][$headlineCount];
4119 if ( $level > $prevlevel ) {
4120 # Increase TOC level
4122 $sublevelCount[$toclevel] = 0;
4123 if ( $toclevel<$wgMaxTocLevel ) {
4124 $prevtoclevel = $toclevel;
4125 $toc .= Linker
::tocIndent();
4128 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4129 # Decrease TOC level, find level to jump to
4131 for ( $i = $toclevel; $i > 0; $i-- ) {
4132 if ( $levelCount[$i] == $level ) {
4133 # Found last matching level
4136 } elseif ( $levelCount[$i] < $level ) {
4137 # Found first matching level below current level
4145 if ( $toclevel<$wgMaxTocLevel ) {
4146 if ( $prevtoclevel < $wgMaxTocLevel ) {
4147 # Unindent only if the previous toc level was shown :p
4148 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4149 $prevtoclevel = $toclevel;
4151 $toc .= Linker
::tocLineEnd();
4155 # No change in level, end TOC line
4156 if ( $toclevel<$wgMaxTocLevel ) {
4157 $toc .= Linker
::tocLineEnd();
4161 $levelCount[$toclevel] = $level;
4163 # count number of headlines for each level
4164 @$sublevelCount[$toclevel]++
;
4166 for( $i = 1; $i <= $toclevel; $i++
) {
4167 if ( !empty( $sublevelCount[$i] ) ) {
4171 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4176 # The safe header is a version of the header text safe to use for links
4178 # Remove link placeholders by the link text.
4179 # <!--LINK number-->
4181 # link text with suffix
4182 # Do this before unstrip since link text can contain strip markers
4183 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4185 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4186 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4188 # Strip out HTML (first regex removes any tag not allowed)
4190 # * <sup> and <sub> (bug 8393)
4193 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4195 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4196 # to allow setting directionality in toc items.
4197 $tocline = preg_replace(
4198 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4199 array( '', '<$1>' ),
4202 $tocline = trim( $tocline );
4204 # For the anchor, strip out HTML-y stuff period
4205 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4206 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4208 # Save headline for section edit hint before it's escaped
4209 $headlineHint = $safeHeadline;
4211 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4212 # For reverse compatibility, provide an id that's
4213 # HTML4-compatible, like we used to.
4215 # It may be worth noting, academically, that it's possible for
4216 # the legacy anchor to conflict with a non-legacy headline
4217 # anchor on the page. In this case likely the "correct" thing
4218 # would be to either drop the legacy anchors or make sure
4219 # they're numbered first. However, this would require people
4220 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4221 # manually, so let's not bother worrying about it.
4222 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4223 array( 'noninitial', 'legacy' ) );
4224 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4226 if ( $legacyHeadline == $safeHeadline ) {
4227 # No reason to have both (in fact, we can't)
4228 $legacyHeadline = false;
4231 $legacyHeadline = false;
4232 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4236 # HTML names must be case-insensitively unique (bug 10721).
4237 # This does not apply to Unicode characters per
4238 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4239 # @todo FIXME: We may be changing them depending on the current locale.
4240 $arrayKey = strtolower( $safeHeadline );
4241 if ( $legacyHeadline === false ) {
4242 $legacyArrayKey = false;
4244 $legacyArrayKey = strtolower( $legacyHeadline );
4247 # count how many in assoc. array so we can track dupes in anchors
4248 if ( isset( $refers[$arrayKey] ) ) {
4249 $refers[$arrayKey]++
;
4251 $refers[$arrayKey] = 1;
4253 if ( isset( $refers[$legacyArrayKey] ) ) {
4254 $refers[$legacyArrayKey]++
;
4256 $refers[$legacyArrayKey] = 1;
4259 # Don't number the heading if it is the only one (looks silly)
4260 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4261 # the two are different if the line contains a link
4262 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4265 # Create the anchor for linking from the TOC to the section
4266 $anchor = $safeHeadline;
4267 $legacyAnchor = $legacyHeadline;
4268 if ( $refers[$arrayKey] > 1 ) {
4269 $anchor .= '_' . $refers[$arrayKey];
4271 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4272 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4274 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4275 $toc .= Linker
::tocLine( $anchor, $tocline,
4276 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4279 # Add the section to the section tree
4280 # Find the DOM node for this header
4281 while ( $node && !$isTemplate ) {
4282 if ( $node->getName() === 'h' ) {
4283 $bits = $node->splitHeading();
4284 if ( $bits['i'] == $sectionIndex ) {
4288 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4289 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4290 $node = $node->getNextSibling();
4293 'toclevel' => $toclevel,
4296 'number' => $numbering,
4297 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4298 'fromtitle' => $titleText,
4299 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4300 'anchor' => $anchor,
4303 # give headline the correct <h#> tag
4304 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4305 // Output edit section links as markers with styles that can be customized by skins
4306 if ( $isTemplate ) {
4307 # Put a T flag in the section identifier, to indicate to extractSections()
4308 # that sections inside <includeonly> should be counted.
4309 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4311 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4313 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4314 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4315 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4316 // so we don't have to worry about a user trying to input one of these markers directly.
4317 // We use a page and section attribute to stop the language converter from converting these important bits
4318 // of data, but put the headline hint inside a content block because the language converter is supposed to
4319 // be able to convert that piece of data.
4320 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4321 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4322 if ( isset( $editlinkArgs[2] ) ) {
4323 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4330 $head[$headlineCount] = Linker
::makeHeadline( $level,
4331 $matches['attrib'][$headlineCount], $anchor, $headline,
4332 $editlink, $legacyAnchor );
4337 $this->setOutputType( $oldType );
4339 # Never ever show TOC if no headers
4340 if ( $numVisible < 1 ) {
4345 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4346 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4348 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4349 $this->mOutput
->setTOCHTML( $toc );
4353 $this->mOutput
->setSections( $tocraw );
4356 # split up and insert constructed headlines
4357 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4360 // build an array of document sections
4361 $sections = array();
4362 foreach ( $blocks as $block ) {
4363 // $head is zero-based, sections aren't.
4364 if ( empty( $head[$i - 1] ) ) {
4365 $sections[$i] = $block;
4367 $sections[$i] = $head[$i - 1] . $block;
4371 * Send a hook, one per section.
4372 * The idea here is to be able to make section-level DIVs, but to do so in a
4373 * lower-impact, more correct way than r50769
4376 * $section : the section number
4377 * &$sectionContent : ref to the content of the section
4378 * $showEditLinks : boolean describing whether this section has an edit link
4380 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4385 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4386 // append the TOC at the beginning
4387 // Top anchor now in skin
4388 $sections[0] = $sections[0] . $toc . "\n";
4391 $full .= join( '', $sections );
4393 if ( $this->mForceTocPosition
) {
4394 return str_replace( '<!--MWTOC-->', $toc, $full );
4401 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4402 * conversion, substitting signatures, {{subst:}} templates, etc.
4404 * @param $text String: the text to transform
4405 * @param $title Title: the Title object for the current article
4406 * @param $user User: the User object describing the current user
4407 * @param $options ParserOptions: parsing options
4408 * @param $clearState Boolean: whether to clear the parser state first
4409 * @return String: the altered wiki markup
4411 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4412 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4413 $this->setUser( $user );
4418 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4419 if( $options->getPreSaveTransform() ) {
4420 $text = $this->pstPass2( $text, $user );
4422 $text = $this->mStripState
->unstripBoth( $text );
4424 $this->setUser( null ); #Reset
4430 * Pre-save transform helper function
4433 * @param $text string
4438 function pstPass2( $text, $user ) {
4439 global $wgContLang, $wgLocaltimezone;
4441 # Note: This is the timestamp saved as hardcoded wikitext to
4442 # the database, we use $wgContLang here in order to give
4443 # everyone the same signature and use the default one rather
4444 # than the one selected in each user's preferences.
4445 # (see also bug 12815)
4446 $ts = $this->mOptions
->getTimestamp();
4447 if ( isset( $wgLocaltimezone ) ) {
4448 $tz = $wgLocaltimezone;
4450 $tz = date_default_timezone_get();
4453 $unixts = wfTimestamp( TS_UNIX
, $ts );
4454 $oldtz = date_default_timezone_get();
4455 date_default_timezone_set( $tz );
4456 $ts = date( 'YmdHis', $unixts );
4457 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4459 # Allow translation of timezones through wiki. date() can return
4460 # whatever crap the system uses, localised or not, so we cannot
4461 # ship premade translations.
4462 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4463 $msg = wfMessage( $key )->inContentLanguage();
4464 if ( $msg->exists() ) {
4465 $tzMsg = $msg->text();
4468 date_default_timezone_set( $oldtz );
4470 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4472 # Variable replacement
4473 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4474 $text = $this->replaceVariables( $text );
4476 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4477 # which may corrupt this parser instance via its wfMessage()->text() call-
4480 $sigText = $this->getUserSig( $user );
4481 $text = strtr( $text, array(
4483 '~~~~' => "$sigText $d",
4487 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4488 $tc = '[' . Title
::legalChars() . ']';
4489 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4491 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4492 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4493 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4494 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4496 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4497 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4498 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4499 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4501 $t = $this->mTitle
->getText();
4503 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4504 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4505 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4506 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4508 # if there's no context, don't bother duplicating the title
4509 $text = preg_replace( $p2, '[[\\1]]', $text );
4512 # Trim trailing whitespace
4513 $text = rtrim( $text );
4519 * Fetch the user's signature text, if any, and normalize to
4520 * validated, ready-to-insert wikitext.
4521 * If you have pre-fetched the nickname or the fancySig option, you can
4522 * specify them here to save a database query.
4523 * Do not reuse this parser instance after calling getUserSig(),
4524 * as it may have changed if it's the $wgParser.
4527 * @param $nickname String|bool nickname to use or false to use user's default nickname
4528 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4529 * or null to use default value
4532 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4533 global $wgMaxSigChars;
4535 $username = $user->getName();
4537 # If not given, retrieve from the user object.
4538 if ( $nickname === false )
4539 $nickname = $user->getOption( 'nickname' );
4541 if ( is_null( $fancySig ) ) {
4542 $fancySig = $user->getBoolOption( 'fancysig' );
4545 $nickname = $nickname == null ?
$username : $nickname;
4547 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4548 $nickname = $username;
4549 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4550 } elseif ( $fancySig !== false ) {
4551 # Sig. might contain markup; validate this
4552 if ( $this->validateSig( $nickname ) !== false ) {
4553 # Validated; clean up (if needed) and return it
4554 return $this->cleanSig( $nickname, true );
4556 # Failed to validate; fall back to the default
4557 $nickname = $username;
4558 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4562 # Make sure nickname doesnt get a sig in a sig
4563 $nickname = self
::cleanSigInSig( $nickname );
4565 # If we're still here, make it a link to the user page
4566 $userText = wfEscapeWikiText( $username );
4567 $nickText = wfEscapeWikiText( $nickname );
4568 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4570 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4574 * Check that the user's signature contains no bad XML
4576 * @param $text String
4577 * @return mixed An expanded string, or false if invalid.
4579 function validateSig( $text ) {
4580 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4584 * Clean up signature text
4586 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4587 * 2) Substitute all transclusions
4589 * @param $text String
4590 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4591 * @return String: signature text
4593 public function cleanSig( $text, $parsing = false ) {
4596 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4599 # Option to disable this feature
4600 if ( !$this->mOptions
->getCleanSignatures() ) {
4604 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4605 # => Move this logic to braceSubstitution()
4606 $substWord = MagicWord
::get( 'subst' );
4607 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4608 $substText = '{{' . $substWord->getSynonym( 0 );
4610 $text = preg_replace( $substRegex, $substText, $text );
4611 $text = self
::cleanSigInSig( $text );
4612 $dom = $this->preprocessToDom( $text );
4613 $frame = $this->getPreprocessor()->newFrame();
4614 $text = $frame->expand( $dom );
4617 $text = $this->mStripState
->unstripBoth( $text );
4624 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4626 * @param $text String
4627 * @return String: signature text with /~{3,5}/ removed
4629 public static function cleanSigInSig( $text ) {
4630 $text = preg_replace( '/~{3,5}/', '', $text );
4635 * Set up some variables which are usually set up in parse()
4636 * so that an external function can call some class members with confidence
4638 * @param $title Title|null
4639 * @param $options ParserOptions
4640 * @param $outputType
4641 * @param $clearState bool
4643 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4644 $this->startParse( $title, $options, $outputType, $clearState );
4648 * @param $title Title|null
4649 * @param $options ParserOptions
4650 * @param $outputType
4651 * @param $clearState bool
4653 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4654 $this->setTitle( $title );
4655 $this->mOptions
= $options;
4656 $this->setOutputType( $outputType );
4657 if ( $clearState ) {
4658 $this->clearState();
4663 * Wrapper for preprocess()
4665 * @param $text String: the text to preprocess
4666 * @param $options ParserOptions: options
4667 * @param $title Title object or null to use $wgTitle
4670 public function transformMsg( $text, $options, $title = null ) {
4671 static $executing = false;
4673 # Guard against infinite recursion
4679 wfProfileIn( __METHOD__
);
4685 $text = $this->preprocess( $text, $title, $options );
4688 wfProfileOut( __METHOD__
);
4693 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4694 * The callback should have the following form:
4695 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4697 * Transform and return $text. Use $parser for any required context, e.g. use
4698 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4700 * Hooks may return extended information by returning an array, of which the
4701 * first numbered element (index 0) must be the return string, and all other
4702 * entries are extracted into local variables within an internal function
4703 * in the Parser class.
4705 * This interface (introduced r61913) appears to be undocumented, but
4706 * 'markerName' is used by some core tag hooks to override which strip
4707 * array their results are placed in. **Use great caution if attempting
4708 * this interface, as it is not documented and injudicious use could smash
4709 * private variables.**
4711 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4712 * @param $callback Mixed: the callback function (and object) to use for the tag
4713 * @throws MWException
4714 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4716 public function setHook( $tag, $callback ) {
4717 $tag = strtolower( $tag );
4718 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4719 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4721 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4722 $this->mTagHooks
[$tag] = $callback;
4723 if ( !in_array( $tag, $this->mStripList
) ) {
4724 $this->mStripList
[] = $tag;
4731 * As setHook(), but letting the contents be parsed.
4733 * Transparent tag hooks are like regular XML-style tag hooks, except they
4734 * operate late in the transformation sequence, on HTML instead of wikitext.
4736 * This is probably obsoleted by things dealing with parser frames?
4737 * The only extension currently using it is geoserver.
4740 * @todo better document or deprecate this
4742 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4743 * @param $callback Mixed: the callback function (and object) to use for the tag
4744 * @throws MWException
4745 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4747 function setTransparentTagHook( $tag, $callback ) {
4748 $tag = strtolower( $tag );
4749 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4750 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4752 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4753 $this->mTransparentTagHooks
[$tag] = $callback;
4759 * Remove all tag hooks
4761 function clearTagHooks() {
4762 $this->mTagHooks
= array();
4763 $this->mFunctionTagHooks
= array();
4764 $this->mStripList
= $this->mDefaultStripList
;
4768 * Create a function, e.g. {{sum:1|2|3}}
4769 * The callback function should have the form:
4770 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4772 * Or with SFH_OBJECT_ARGS:
4773 * function myParserFunction( $parser, $frame, $args ) { ... }
4775 * The callback may either return the text result of the function, or an array with the text
4776 * in element 0, and a number of flags in the other elements. The names of the flags are
4777 * specified in the keys. Valid flags are:
4778 * found The text returned is valid, stop processing the template. This
4780 * nowiki Wiki markup in the return value should be escaped
4781 * isHTML The returned text is HTML, armour it against wikitext transformation
4783 * @param $id String: The magic word ID
4784 * @param $callback Mixed: the callback function (and object) to use
4785 * @param $flags Integer: a combination of the following flags:
4786 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4788 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4789 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4790 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4791 * the arguments, and to control the way they are expanded.
4793 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4794 * arguments, for instance:
4795 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4797 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4798 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4799 * working if/when this is changed.
4801 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4804 * Please read the documentation in includes/parser/Preprocessor.php for more information
4805 * about the methods available in PPFrame and PPNode.
4807 * @throws MWException
4808 * @return string|callback The old callback function for this name, if any
4810 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4813 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4814 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4816 # Add to function cache
4817 $mw = MagicWord
::get( $id );
4819 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4821 $synonyms = $mw->getSynonyms();
4822 $sensitive = intval( $mw->isCaseSensitive() );
4824 foreach ( $synonyms as $syn ) {
4826 if ( !$sensitive ) {
4827 $syn = $wgContLang->lc( $syn );
4830 if ( !( $flags & SFH_NO_HASH
) ) {
4833 # Remove trailing colon
4834 if ( substr( $syn, -1, 1 ) === ':' ) {
4835 $syn = substr( $syn, 0, -1 );
4837 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4843 * Get all registered function hook identifiers
4847 function getFunctionHooks() {
4848 return array_keys( $this->mFunctionHooks
);
4852 * Create a tag function, e.g. "<test>some stuff</test>".
4853 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4854 * Unlike parser functions, their content is not preprocessed.
4858 * @throws MWException
4861 function setFunctionTagHook( $tag, $callback, $flags ) {
4862 $tag = strtolower( $tag );
4863 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4864 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4865 $this->mFunctionTagHooks
[$tag] : null;
4866 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4868 if ( !in_array( $tag, $this->mStripList
) ) {
4869 $this->mStripList
[] = $tag;
4876 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4877 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4878 * Placeholders created in Skin::makeLinkObj()
4880 * @param $text string
4881 * @param $options int
4883 * @return array of link CSS classes, indexed by PDBK.
4885 function replaceLinkHolders( &$text, $options = 0 ) {
4886 return $this->mLinkHolders
->replace( $text );
4890 * Replace "<!--LINK-->" link placeholders with plain text of links
4891 * (not HTML-formatted).
4893 * @param $text String
4896 function replaceLinkHoldersText( $text ) {
4897 return $this->mLinkHolders
->replaceText( $text );
4901 * Renders an image gallery from a text with one line per image.
4902 * text labels may be given by using |-style alternative text. E.g.
4903 * Image:one.jpg|The number "1"
4904 * Image:tree.jpg|A tree
4905 * given as text will return the HTML of a gallery with two images,
4906 * labeled 'The number "1"' and
4909 * @param string $text
4910 * @param array $params
4911 * @return string HTML
4913 function renderImageGallery( $text, $params ) {
4914 $ig = new ImageGallery();
4915 $ig->setContextTitle( $this->mTitle
);
4916 $ig->setShowBytes( false );
4917 $ig->setShowFilename( false );
4918 $ig->setParser( $this );
4919 $ig->setHideBadImages();
4920 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4922 if ( isset( $params['showfilename'] ) ) {
4923 $ig->setShowFilename( true );
4925 $ig->setShowFilename( false );
4927 if ( isset( $params['caption'] ) ) {
4928 $caption = $params['caption'];
4929 $caption = htmlspecialchars( $caption );
4930 $caption = $this->replaceInternalLinks( $caption );
4931 $ig->setCaptionHtml( $caption );
4933 if ( isset( $params['perrow'] ) ) {
4934 $ig->setPerRow( $params['perrow'] );
4936 if ( isset( $params['widths'] ) ) {
4937 $ig->setWidths( $params['widths'] );
4939 if ( isset( $params['heights'] ) ) {
4940 $ig->setHeights( $params['heights'] );
4943 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4945 $lines = StringUtils
::explode( "\n", $text );
4946 foreach ( $lines as $line ) {
4947 # match lines like these:
4948 # Image:someimage.jpg|This is some image
4950 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4952 if ( count( $matches ) == 0 ) {
4956 if ( strpos( $matches[0], '%' ) !== false ) {
4957 $matches[1] = rawurldecode( $matches[1] );
4959 $title = Title
::newFromText( $matches[1], NS_FILE
);
4960 if ( is_null( $title ) ) {
4961 # Bogus title. Ignore these so we don't bomb out later.
4968 if ( isset( $matches[3] ) ) {
4969 // look for an |alt= definition while trying not to break existing
4970 // captions with multiple pipes (|) in it, until a more sensible grammar
4971 // is defined for images in galleries
4973 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4974 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
4975 $magicWordAlt = MagicWord
::get( 'img_alt' );
4976 $magicWordLink = MagicWord
::get( 'img_link' );
4978 foreach ( $parameterMatches as $parameterMatch ) {
4979 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4980 $alt = $this->stripAltText( $match, false );
4982 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
4983 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
4984 $chars = self
::EXT_LINK_URL_CLASS
;
4985 $prots = $this->mUrlProtocols
;
4986 //check to see if link matches an absolute url, if not then it must be a wiki link.
4987 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
4990 $localLinkTitle = Title
::newFromText( $linkValue );
4991 if ( $localLinkTitle !== null ) {
4992 $link = $localLinkTitle->getLocalURL();
4997 // concatenate all other pipes
4998 $label .= '|' . $parameterMatch;
5001 // remove the first pipe
5002 $label = substr( $label, 1 );
5005 $ig->add( $title, $label, $alt, $link );
5007 return $ig->toHTML();
5014 function getImageParams( $handler ) {
5016 $handlerClass = get_class( $handler );
5020 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5021 # Initialise static lists
5022 static $internalParamNames = array(
5023 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5024 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5025 'bottom', 'text-bottom' ),
5026 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5027 'upright', 'border', 'link', 'alt', 'class' ),
5029 static $internalParamMap;
5030 if ( !$internalParamMap ) {
5031 $internalParamMap = array();
5032 foreach ( $internalParamNames as $type => $names ) {
5033 foreach ( $names as $name ) {
5034 $magicName = str_replace( '-', '_', "img_$name" );
5035 $internalParamMap[$magicName] = array( $type, $name );
5040 # Add handler params
5041 $paramMap = $internalParamMap;
5043 $handlerParamMap = $handler->getParamMap();
5044 foreach ( $handlerParamMap as $magic => $paramName ) {
5045 $paramMap[$magic] = array( 'handler', $paramName );
5048 $this->mImageParams
[$handlerClass] = $paramMap;
5049 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5051 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5055 * Parse image options text and use it to make an image
5057 * @param $title Title
5058 * @param $options String
5059 * @param $holders LinkHolderArray|bool
5060 * @return string HTML
5062 function makeImage( $title, $options, $holders = false ) {
5063 # Check if the options text is of the form "options|alt text"
5065 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5066 # * left no resizing, just left align. label is used for alt= only
5067 # * right same, but right aligned
5068 # * none same, but not aligned
5069 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5070 # * center center the image
5071 # * frame Keep original image size, no magnify-button.
5072 # * framed Same as "frame"
5073 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5074 # * upright reduce width for upright images, rounded to full __0 px
5075 # * border draw a 1px border around the image
5076 # * alt Text for HTML alt attribute (defaults to empty)
5077 # * class Set a class for img node
5078 # * link Set the target of the image link. Can be external, interwiki, or local
5079 # vertical-align values (no % or length right now):
5089 $parts = StringUtils
::explode( "|", $options );
5091 # Give extensions a chance to select the file revision for us
5094 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5095 array( $this, $title, &$options, &$descQuery ) );
5096 # Fetch and register the file (file title may be different via hooks)
5097 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5100 $handler = $file ?
$file->getHandler() : false;
5102 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5105 $this->addTrackingCategory( 'broken-file-category' );
5108 # Process the input parameters
5110 $params = array( 'frame' => array(), 'handler' => array(),
5111 'horizAlign' => array(), 'vertAlign' => array() );
5112 foreach ( $parts as $part ) {
5113 $part = trim( $part );
5114 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5116 if ( isset( $paramMap[$magicName] ) ) {
5117 list( $type, $paramName ) = $paramMap[$magicName];
5119 # Special case; width and height come in one variable together
5120 if ( $type === 'handler' && $paramName === 'width' ) {
5121 $parsedWidthParam = $this->parseWidthParam( $value );
5122 if( isset( $parsedWidthParam['width'] ) ) {
5123 $width = $parsedWidthParam['width'];
5124 if ( $handler->validateParam( 'width', $width ) ) {
5125 $params[$type]['width'] = $width;
5129 if( isset( $parsedWidthParam['height'] ) ) {
5130 $height = $parsedWidthParam['height'];
5131 if ( $handler->validateParam( 'height', $height ) ) {
5132 $params[$type]['height'] = $height;
5136 # else no validation -- bug 13436
5138 if ( $type === 'handler' ) {
5139 # Validate handler parameter
5140 $validated = $handler->validateParam( $paramName, $value );
5142 # Validate internal parameters
5143 switch( $paramName ) {
5147 # @todo FIXME: Possibly check validity here for
5148 # manualthumb? downstream behavior seems odd with
5149 # missing manual thumbs.
5151 $value = $this->stripAltText( $value, $holders );
5154 $chars = self
::EXT_LINK_URL_CLASS
;
5155 $prots = $this->mUrlProtocols
;
5156 if ( $value === '' ) {
5157 $paramName = 'no-link';
5160 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5161 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5162 $paramName = 'link-url';
5163 $this->mOutput
->addExternalLink( $value );
5164 if ( $this->mOptions
->getExternalLinkTarget() ) {
5165 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5170 $linkTitle = Title
::newFromText( $value );
5172 $paramName = 'link-title';
5173 $value = $linkTitle;
5174 $this->mOutput
->addLink( $linkTitle );
5180 # Most other things appear to be empty or numeric...
5181 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5186 $params[$type][$paramName] = $value;
5190 if ( !$validated ) {
5195 # Process alignment parameters
5196 if ( $params['horizAlign'] ) {
5197 $params['frame']['align'] = key( $params['horizAlign'] );
5199 if ( $params['vertAlign'] ) {
5200 $params['frame']['valign'] = key( $params['vertAlign'] );
5203 $params['frame']['caption'] = $caption;
5205 # Will the image be presented in a frame, with the caption below?
5206 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5207 isset( $params['frame']['framed'] ) ||
5208 isset( $params['frame']['thumbnail'] ) ||
5209 isset( $params['frame']['manualthumb'] );
5211 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5212 # came to also set the caption, ordinary text after the image -- which
5213 # makes no sense, because that just repeats the text multiple times in
5214 # screen readers. It *also* came to set the title attribute.
5216 # Now that we have an alt attribute, we should not set the alt text to
5217 # equal the caption: that's worse than useless, it just repeats the
5218 # text. This is the framed/thumbnail case. If there's no caption, we
5219 # use the unnamed parameter for alt text as well, just for the time be-
5220 # ing, if the unnamed param is set and the alt param is not.
5222 # For the future, we need to figure out if we want to tweak this more,
5223 # e.g., introducing a title= parameter for the title; ignoring the un-
5224 # named parameter entirely for images without a caption; adding an ex-
5225 # plicit caption= parameter and preserving the old magic unnamed para-
5227 if ( $imageIsFramed ) { # Framed image
5228 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5229 # No caption or alt text, add the filename as the alt text so
5230 # that screen readers at least get some description of the image
5231 $params['frame']['alt'] = $title->getText();
5233 # Do not set $params['frame']['title'] because tooltips don't make sense
5235 } else { # Inline image
5236 if ( !isset( $params['frame']['alt'] ) ) {
5237 # No alt text, use the "caption" for the alt text
5238 if ( $caption !== '') {
5239 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5241 # No caption, fall back to using the filename for the
5243 $params['frame']['alt'] = $title->getText();
5246 # Use the "caption" for the tooltip text
5247 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5250 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5252 # Linker does the rest
5253 $time = isset( $options['time'] ) ?
$options['time'] : false;
5254 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5255 $time, $descQuery, $this->mOptions
->getThumbSize() );
5257 # Give the handler a chance to modify the parser object
5259 $handler->parserTransformHook( $this, $file );
5267 * @param $holders LinkHolderArray
5268 * @return mixed|String
5270 protected function stripAltText( $caption, $holders ) {
5271 # Strip bad stuff out of the title (tooltip). We can't just use
5272 # replaceLinkHoldersText() here, because if this function is called
5273 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5275 $tooltip = $holders->replaceText( $caption );
5277 $tooltip = $this->replaceLinkHoldersText( $caption );
5280 # make sure there are no placeholders in thumbnail attributes
5281 # that are later expanded to html- so expand them now and
5283 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5284 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5290 * Set a flag in the output object indicating that the content is dynamic and
5291 * shouldn't be cached.
5293 function disableCache() {
5294 wfDebug( "Parser output marked as uncacheable.\n" );
5295 if ( !$this->mOutput
) {
5296 throw new MWException( __METHOD__
.
5297 " can only be called when actually parsing something" );
5299 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5300 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5304 * Callback from the Sanitizer for expanding items found in HTML attribute
5305 * values, so they can be safely tested and escaped.
5307 * @param $text String
5308 * @param $frame PPFrame
5311 function attributeStripCallback( &$text, $frame = false ) {
5312 $text = $this->replaceVariables( $text, $frame );
5313 $text = $this->mStripState
->unstripBoth( $text );
5322 function getTags() {
5323 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5327 * Replace transparent tags in $text with the values given by the callbacks.
5329 * Transparent tag hooks are like regular XML-style tag hooks, except they
5330 * operate late in the transformation sequence, on HTML instead of wikitext.
5332 * @param $text string
5336 function replaceTransparentTags( $text ) {
5338 $elements = array_keys( $this->mTransparentTagHooks
);
5339 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5340 $replacements = array();
5342 foreach ( $matches as $marker => $data ) {
5343 list( $element, $content, $params, $tag ) = $data;
5344 $tagName = strtolower( $element );
5345 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5346 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5350 $replacements[$marker] = $output;
5352 return strtr( $text, $replacements );
5356 * Break wikitext input into sections, and either pull or replace
5357 * some particular section's text.
5359 * External callers should use the getSection and replaceSection methods.
5361 * @param $text String: Page wikitext
5362 * @param $section String: a section identifier string of the form:
5363 * "<flag1> - <flag2> - ... - <section number>"
5365 * Currently the only recognised flag is "T", which means the target section number
5366 * was derived during a template inclusion parse, in other words this is a template
5367 * section edit link. If no flags are given, it was an ordinary section edit link.
5368 * This flag is required to avoid a section numbering mismatch when a section is
5369 * enclosed by "<includeonly>" (bug 6563).
5371 * The section number 0 pulls the text before the first heading; other numbers will
5372 * pull the given section along with its lower-level subsections. If the section is
5373 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5375 * Section 0 is always considered to exist, even if it only contains the empty
5376 * string. If $text is the empty string and section 0 is replaced, $newText is
5379 * @param $mode String: one of "get" or "replace"
5380 * @param $newText String: replacement text for section data.
5381 * @return String: for "get", the extracted section text.
5382 * for "replace", the whole page with the section replaced.
5384 private function extractSections( $text, $section, $mode, $newText = '' ) {
5385 global $wgTitle; # not generally used but removes an ugly failure mode
5386 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5388 $frame = $this->getPreprocessor()->newFrame();
5390 # Process section extraction flags
5392 $sectionParts = explode( '-', $section );
5393 $sectionIndex = array_pop( $sectionParts );
5394 foreach ( $sectionParts as $part ) {
5395 if ( $part === 'T' ) {
5396 $flags |
= self
::PTD_FOR_INCLUSION
;
5400 # Check for empty input
5401 if ( strval( $text ) === '' ) {
5402 # Only sections 0 and T-0 exist in an empty document
5403 if ( $sectionIndex == 0 ) {
5404 if ( $mode === 'get' ) {
5410 if ( $mode === 'get' ) {
5418 # Preprocess the text
5419 $root = $this->preprocessToDom( $text, $flags );
5421 # <h> nodes indicate section breaks
5422 # They can only occur at the top level, so we can find them by iterating the root's children
5423 $node = $root->getFirstChild();
5425 # Find the target section
5426 if ( $sectionIndex == 0 ) {
5427 # Section zero doesn't nest, level=big
5428 $targetLevel = 1000;
5431 if ( $node->getName() === 'h' ) {
5432 $bits = $node->splitHeading();
5433 if ( $bits['i'] == $sectionIndex ) {
5434 $targetLevel = $bits['level'];
5438 if ( $mode === 'replace' ) {
5439 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5441 $node = $node->getNextSibling();
5447 if ( $mode === 'get' ) {
5454 # Find the end of the section, including nested sections
5456 if ( $node->getName() === 'h' ) {
5457 $bits = $node->splitHeading();
5458 $curLevel = $bits['level'];
5459 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5463 if ( $mode === 'get' ) {
5464 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5466 $node = $node->getNextSibling();
5469 # Write out the remainder (in replace mode only)
5470 if ( $mode === 'replace' ) {
5471 # Output the replacement text
5472 # Add two newlines on -- trailing whitespace in $newText is conventionally
5473 # stripped by the editor, so we need both newlines to restore the paragraph gap
5474 # Only add trailing whitespace if there is newText
5475 if ( $newText != "" ) {
5476 $outText .= $newText . "\n\n";
5480 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5481 $node = $node->getNextSibling();
5485 if ( is_string( $outText ) ) {
5486 # Re-insert stripped tags
5487 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5494 * This function returns the text of a section, specified by a number ($section).
5495 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5496 * the first section before any such heading (section 0).
5498 * If a section contains subsections, these are also returned.
5500 * @param $text String: text to look in
5501 * @param $section String: section identifier
5502 * @param $deftext String: default to return if section is not found
5503 * @return string text of the requested section
5505 public function getSection( $text, $section, $deftext = '' ) {
5506 return $this->extractSections( $text, $section, "get", $deftext );
5510 * This function returns $oldtext after the content of the section
5511 * specified by $section has been replaced with $text. If the target
5512 * section does not exist, $oldtext is returned unchanged.
5514 * @param $oldtext String: former text of the article
5515 * @param $section int section identifier
5516 * @param $text String: replacing text
5517 * @return String: modified text
5519 public function replaceSection( $oldtext, $section, $text ) {
5520 return $this->extractSections( $oldtext, $section, "replace", $text );
5524 * Get the ID of the revision we are parsing
5526 * @return Mixed: integer or null
5528 function getRevisionId() {
5529 return $this->mRevisionId
;
5533 * Get the revision object for $this->mRevisionId
5535 * @return Revision|null either a Revision object or null
5537 protected function getRevisionObject() {
5538 if ( !is_null( $this->mRevisionObject
) ) {
5539 return $this->mRevisionObject
;
5541 if ( is_null( $this->mRevisionId
) ) {
5545 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5546 return $this->mRevisionObject
;
5550 * Get the timestamp associated with the current revision, adjusted for
5551 * the default server-local timestamp
5553 function getRevisionTimestamp() {
5554 if ( is_null( $this->mRevisionTimestamp
) ) {
5555 wfProfileIn( __METHOD__
);
5559 $revObject = $this->getRevisionObject();
5560 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5562 # The cryptic '' timezone parameter tells to use the site-default
5563 # timezone offset instead of the user settings.
5565 # Since this value will be saved into the parser cache, served
5566 # to other users, and potentially even used inside links and such,
5567 # it needs to be consistent for all visitors.
5568 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5570 wfProfileOut( __METHOD__
);
5572 return $this->mRevisionTimestamp
;
5576 * Get the name of the user that edited the last revision
5578 * @return String: user name
5580 function getRevisionUser() {
5581 if( is_null( $this->mRevisionUser
) ) {
5582 $revObject = $this->getRevisionObject();
5584 # if this template is subst: the revision id will be blank,
5585 # so just use the current user's name
5587 $this->mRevisionUser
= $revObject->getUserText();
5588 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5589 $this->mRevisionUser
= $this->getUser()->getName();
5592 return $this->mRevisionUser
;
5596 * Mutator for $mDefaultSort
5598 * @param $sort string New value
5600 public function setDefaultSort( $sort ) {
5601 $this->mDefaultSort
= $sort;
5602 $this->mOutput
->setProperty( 'defaultsort', $sort );
5606 * Accessor for $mDefaultSort
5607 * Will use the empty string if none is set.
5609 * This value is treated as a prefix, so the
5610 * empty string is equivalent to sorting by
5615 public function getDefaultSort() {
5616 if ( $this->mDefaultSort
!== false ) {
5617 return $this->mDefaultSort
;
5624 * Accessor for $mDefaultSort
5625 * Unlike getDefaultSort(), will return false if none is set
5627 * @return string or false
5629 public function getCustomDefaultSort() {
5630 return $this->mDefaultSort
;
5634 * Try to guess the section anchor name based on a wikitext fragment
5635 * presumably extracted from a heading, for example "Header" from
5638 * @param $text string
5642 public function guessSectionNameFromWikiText( $text ) {
5643 # Strip out wikitext links(they break the anchor)
5644 $text = $this->stripSectionName( $text );
5645 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5646 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5650 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5651 * instead. For use in redirects, since IE6 interprets Redirect: headers
5652 * as something other than UTF-8 (apparently?), resulting in breakage.
5654 * @param $text String: The section name
5655 * @return string An anchor
5657 public function guessLegacySectionNameFromWikiText( $text ) {
5658 # Strip out wikitext links(they break the anchor)
5659 $text = $this->stripSectionName( $text );
5660 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5661 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5665 * Strips a text string of wikitext for use in a section anchor
5667 * Accepts a text string and then removes all wikitext from the
5668 * string and leaves only the resultant text (i.e. the result of
5669 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5670 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5671 * to create valid section anchors by mimicing the output of the
5672 * parser when headings are parsed.
5674 * @param $text String: text string to be stripped of wikitext
5675 * for use in a Section anchor
5676 * @return string Filtered text string
5678 public function stripSectionName( $text ) {
5679 # Strip internal link markup
5680 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5681 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5683 # Strip external link markup
5684 # @todo FIXME: Not tolerant to blank link text
5685 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5686 # on how many empty links there are on the page - need to figure that out.
5687 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5689 # Parse wikitext quotes (italics & bold)
5690 $text = $this->doQuotes( $text );
5693 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5698 * strip/replaceVariables/unstrip for preprocessor regression testing
5700 * @param $text string
5701 * @param $title Title
5702 * @param $options ParserOptions
5703 * @param $outputType int
5707 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5708 $this->startParse( $title, $options, $outputType, true );
5710 $text = $this->replaceVariables( $text );
5711 $text = $this->mStripState
->unstripBoth( $text );
5712 $text = Sanitizer
::removeHTMLtags( $text );
5717 * @param $text string
5718 * @param $title Title
5719 * @param $options ParserOptions
5722 function testPst( $text, Title
$title, ParserOptions
$options ) {
5723 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5728 * @param $title Title
5729 * @param $options ParserOptions
5732 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5733 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5737 * Call a callback function on all regions of the given text that are not
5738 * inside strip markers, and replace those regions with the return value
5739 * of the callback. For example, with input:
5743 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5744 * two strings will be replaced with the value returned by the callback in
5752 function markerSkipCallback( $s, $callback ) {
5755 while ( $i < strlen( $s ) ) {
5756 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5757 if ( $markerStart === false ) {
5758 $out .= call_user_func( $callback, substr( $s, $i ) );
5761 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5762 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5763 if ( $markerEnd === false ) {
5764 $out .= substr( $s, $markerStart );
5767 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5768 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5777 * Remove any strip markers found in the given text.
5779 * @param $text Input string
5782 function killMarkers( $text ) {
5783 return $this->mStripState
->killMarkers( $text );
5787 * Save the parser state required to convert the given half-parsed text to
5788 * HTML. "Half-parsed" in this context means the output of
5789 * recursiveTagParse() or internalParse(). This output has strip markers
5790 * from replaceVariables (extensionSubstitution() etc.), and link
5791 * placeholders from replaceLinkHolders().
5793 * Returns an array which can be serialized and stored persistently. This
5794 * array can later be loaded into another parser instance with
5795 * unserializeHalfParsedText(). The text can then be safely incorporated into
5796 * the return value of a parser hook.
5798 * @param $text string
5802 function serializeHalfParsedText( $text ) {
5803 wfProfileIn( __METHOD__
);
5806 'version' => self
::HALF_PARSED_VERSION
,
5807 'stripState' => $this->mStripState
->getSubState( $text ),
5808 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5810 wfProfileOut( __METHOD__
);
5815 * Load the parser state given in the $data array, which is assumed to
5816 * have been generated by serializeHalfParsedText(). The text contents is
5817 * extracted from the array, and its markers are transformed into markers
5818 * appropriate for the current Parser instance. This transformed text is
5819 * returned, and can be safely included in the return value of a parser
5822 * If the $data array has been stored persistently, the caller should first
5823 * check whether it is still valid, by calling isValidHalfParsedText().
5825 * @param $data array Serialized data
5826 * @throws MWException
5829 function unserializeHalfParsedText( $data ) {
5830 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5831 throw new MWException( __METHOD__
. ': invalid version' );
5834 # First, extract the strip state.
5835 $texts = array( $data['text'] );
5836 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5838 # Now renumber links
5839 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5841 # Should be good to go.
5846 * Returns true if the given array, presumed to be generated by
5847 * serializeHalfParsedText(), is compatible with the current version of the
5850 * @param $data Array
5854 function isValidHalfParsedText( $data ) {
5855 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5859 * Parsed a width param of imagelink like 300px or 200x300px
5861 * @param $value String
5866 public function parseWidthParam( $value ) {
5867 $parsedWidthParam = array();
5868 if( $value === '' ) {
5869 return $parsedWidthParam;
5872 # (bug 13500) In both cases (width/height and width only),
5873 # permit trailing "px" for backward compatibility.
5874 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5875 $width = intval( $m[1] );
5876 $height = intval( $m[2] );
5877 $parsedWidthParam['width'] = $width;
5878 $parsedWidthParam['height'] = $height;
5879 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5880 $width = intval( $value );
5881 $parsedWidthParam['width'] = $width;
5883 return $parsedWidthParam;