3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into XHTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
58 * $wgNamespacesWithSubpages
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
70 * Update this version number when the ParserOutput format
71 * changes in an incompatible way, so the parser cache
72 * can automatically discard old data.
74 const VERSION
= '1.6.4';
77 * Update this version number when the output of serialiseHalfParsedText()
78 * changes in an incompatible way
80 const HALF_PARSED_VERSION
= 2;
82 # Flags for Parser::setFunctionHook
83 # Also available as global constants from Defines.php
84 const SFH_NO_HASH
= 1;
85 const SFH_OBJECT_ARGS
= 2;
87 # Constants needed for external link processing
88 # Everything except bracket, space, or control characters
89 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
90 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
91 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
92 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
93 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
95 # State constants for the definition list colon extraction
96 const COLON_STATE_TEXT
= 0;
97 const COLON_STATE_TAG
= 1;
98 const COLON_STATE_TAGSTART
= 2;
99 const COLON_STATE_CLOSETAG
= 3;
100 const COLON_STATE_TAGSLASH
= 4;
101 const COLON_STATE_COMMENT
= 5;
102 const COLON_STATE_COMMENTDASH
= 6;
103 const COLON_STATE_COMMENTDASHDASH
= 7;
105 # Flags for preprocessToDom
106 const PTD_FOR_INCLUSION
= 1;
108 # Allowed values for $this->mOutputType
109 # Parameter to startExternalParse().
110 const OT_HTML
= 1; # like parse()
111 const OT_WIKI
= 2; # like preSaveTransform()
112 const OT_PREPROCESS
= 3; # like preprocess()
114 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
116 # Marker Suffix needs to be accessible staticly.
117 const MARKER_SUFFIX
= "-QINU\x7f";
120 var $mTagHooks = array();
121 var $mTransparentTagHooks = array();
122 var $mFunctionHooks = array();
123 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
124 var $mFunctionTagHooks = array();
125 var $mStripList = array();
126 var $mDefaultStripList = array();
127 var $mVarCache = array();
128 var $mImageParams = array();
129 var $mImageParamsMagicArray = array();
130 var $mMarkerIndex = 0;
131 var $mFirstCall = true;
133 # Initialised by initialiseVariables()
136 * @var MagicWordArray
141 * @var MagicWordArray
144 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
146 # Cleared with clearState():
151 var $mAutonumber, $mDTopen;
158 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
160 * @var LinkHolderArray
165 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
167 var $mTplExpandCache; # empty-frame expansion cache
168 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
169 var $mExpensiveFunctionCount; # number of expensive parser function calls
170 var $mShowToc, $mForceTocPosition;
175 var $mUser; # User object; only used when doing pre-save transform
178 # These are variables reset at least once per parse regardless of $clearState
188 var $mTitle; # Title context, used for self-link rendering and similar things
189 var $mOutputType; # Output type, one of the OT_xxx constants
190 var $ot; # Shortcut alias, see setOutputType()
191 var $mRevisionObject; # The revision object of the specified revision ID
192 var $mRevisionId; # ID to display in {{REVISIONID}} tags
193 var $mRevisionTimestamp; # The timestamp of the specified revision ID
194 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
195 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
203 * @var Array with the language name of each language link (i.e. the
204 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
205 * duplicate language links to the ParserOutput.
207 var $mLangLinkLanguages;
214 public function __construct( $conf = array() ) {
215 $this->mConf
= $conf;
216 $this->mUrlProtocols
= wfUrlProtocols();
217 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
218 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
219 if ( isset( $conf['preprocessorClass'] ) ) {
220 $this->mPreprocessorClass
= $conf['preprocessorClass'];
221 } elseif ( defined( 'MW_COMPILED' ) ) {
222 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
223 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 } elseif ( extension_loaded( 'domxml' ) ) {
225 # PECL extension that conflicts with the core DOM extension (bug 13770)
226 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
227 $this->mPreprocessorClass
= 'Preprocessor_Hash';
228 } elseif ( extension_loaded( 'dom' ) ) {
229 $this->mPreprocessorClass
= 'Preprocessor_DOM';
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
233 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
237 * Reduce memory usage to reduce the impact of circular references
239 function __destruct() {
240 if ( isset( $this->mLinkHolders
) ) {
241 unset( $this->mLinkHolders
);
243 foreach ( $this as $name => $value ) {
244 unset( $this->$name );
249 * Allow extensions to clean up when the parser is cloned
252 wfRunHooks( 'ParserCloned', array( $this ) );
256 * Do various kinds of initialisation on the first call of the parser
258 function firstCallInit() {
259 if ( !$this->mFirstCall
) {
262 $this->mFirstCall
= false;
264 wfProfileIn( __METHOD__
);
266 CoreParserFunctions
::register( $this );
267 CoreTagHooks
::register( $this );
268 $this->initialiseVariables();
270 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
271 wfProfileOut( __METHOD__
);
279 function clearState() {
280 wfProfileIn( __METHOD__
);
281 if ( $this->mFirstCall
) {
282 $this->firstCallInit();
284 $this->mOutput
= new ParserOutput
;
285 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
286 $this->mAutonumber
= 0;
287 $this->mLastSection
= '';
288 $this->mDTopen
= false;
289 $this->mIncludeCount
= array();
290 $this->mArgStack
= false;
291 $this->mInPre
= false;
292 $this->mLinkHolders
= new LinkHolderArray( $this );
294 $this->mRevisionObject
= $this->mRevisionTimestamp
=
295 $this->mRevisionId
= $this->mRevisionUser
= null;
296 $this->mVarCache
= array();
298 $this->mLangLinkLanguages
= array();
301 * Prefix for temporary replacement strings for the multipass parser.
302 * \x07 should never appear in input as it's disallowed in XML.
303 * Using it at the front also gives us a little extra robustness
304 * since it shouldn't match when butted up against identifier-like
307 * Must not consist of all title characters, or else it will change
308 * the behavior of <nowiki> in a link.
310 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
311 $this->mStripState
= new StripState( $this->mUniqPrefix
);
313 # Clear these on every parse, bug 4549
314 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
316 $this->mShowToc
= true;
317 $this->mForceTocPosition
= false;
318 $this->mIncludeSizes
= array(
322 $this->mPPNodeCount
= 0;
323 $this->mGeneratedPPNodeCount
= 0;
324 $this->mHighestExpansionDepth
= 0;
325 $this->mDefaultSort
= false;
326 $this->mHeadings
= array();
327 $this->mDoubleUnderscores
= array();
328 $this->mExpensiveFunctionCount
= 0;
331 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
332 $this->mPreprocessor
= null;
335 wfRunHooks( 'ParserClearState', array( &$this ) );
336 wfProfileOut( __METHOD__
);
340 * Convert wikitext to HTML
341 * Do not call this function recursively.
343 * @param string $text text we want to parse
344 * @param $title Title object
345 * @param $options ParserOptions
346 * @param $linestart boolean
347 * @param $clearState boolean
348 * @param int $revid number to pass in {{REVISIONID}}
349 * @return ParserOutput a ParserOutput
351 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
353 * First pass--just handle <nowiki> sections, pass the rest off
354 * to internalParse() which does all the real work.
357 global $wgUseTidy, $wgAlwaysUseTidy;
358 $fname = __METHOD__
. '-' . wfGetCaller();
359 wfProfileIn( __METHOD__
);
360 wfProfileIn( $fname );
362 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
364 # Remove the strip marker tag prefix from the input, if present.
366 $text = str_replace( $this->mUniqPrefix
, '', $text );
369 $oldRevisionId = $this->mRevisionId
;
370 $oldRevisionObject = $this->mRevisionObject
;
371 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
372 $oldRevisionUser = $this->mRevisionUser
;
373 if ( $revid !== null ) {
374 $this->mRevisionId
= $revid;
375 $this->mRevisionObject
= null;
376 $this->mRevisionTimestamp
= null;
377 $this->mRevisionUser
= null;
380 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
382 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
383 $text = $this->internalParse( $text );
384 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
386 $text = $this->mStripState
->unstripGeneral( $text );
388 # Clean up special characters, only run once, next-to-last before doBlockLevels
390 # french spaces, last one Guillemet-left
391 # only if there is something before the space
392 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
393 # french spaces, Guillemet-right
394 '/(\\302\\253) /' => '\\1 ',
395 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
397 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
399 $text = $this->doBlockLevels( $text, $linestart );
401 $this->replaceLinkHolders( $text );
404 * The input doesn't get language converted if
406 * b) Content isn't converted
407 * c) It's a conversion table
408 * d) it is an interface message (which is in the user language)
410 if ( !( $options->getDisableContentConversion()
411 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
413 if ( !$this->mOptions
->getInterfaceMessage() ) {
414 # The position of the convert() call should not be changed. it
415 # assumes that the links are all replaced and the only thing left
416 # is the <nowiki> mark.
417 $text = $this->getConverterLanguage()->convert( $text );
422 * A converted title will be provided in the output object if title and
423 * content conversion are enabled, the article text does not contain
424 * a conversion-suppressing double-underscore tag, and no
425 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
426 * automatic link conversion.
428 if ( !( $options->getDisableTitleConversion()
429 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
430 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
431 ||
$this->mOutput
->getDisplayTitle() !== false ) )
433 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
434 if ( $convruletitle ) {
435 $this->mOutput
->setTitleText( $convruletitle );
437 $titleText = $this->getConverterLanguage()->convertTitle( $title );
438 $this->mOutput
->setTitleText( $titleText );
442 $text = $this->mStripState
->unstripNoWiki( $text );
444 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
446 $text = $this->replaceTransparentTags( $text );
447 $text = $this->mStripState
->unstripGeneral( $text );
449 $text = Sanitizer
::normalizeCharReferences( $text );
451 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
452 $text = MWTidy
::tidy( $text );
454 # attempt to sanitize at least some nesting problems
455 # (bug #2702 and quite a few others)
457 # ''Something [http://www.cool.com cool''] -->
458 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
459 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
460 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
461 # fix up an anchor inside another anchor, only
462 # at least for a single single nested link (bug 3695)
463 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
464 '\\1\\2</a>\\3</a>\\1\\4</a>',
465 # fix div inside inline elements- doBlockLevels won't wrap a line which
466 # contains a div, so fix it up here; replace
467 # div with escaped text
468 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
469 '\\1\\3<div\\5>\\6</div>\\8\\9',
470 # remove empty italic or bold tag pairs, some
471 # introduced by rules above
472 '/<([bi])><\/\\1>/' => '',
475 $text = preg_replace(
476 array_keys( $tidyregs ),
477 array_values( $tidyregs ),
481 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
482 $this->limitationWarn( 'expensive-parserfunction',
483 $this->mExpensiveFunctionCount
,
484 $this->mOptions
->getExpensiveParserFunctionLimit()
488 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
490 # Information on include size limits, for the benefit of users who try to skirt them
491 if ( $this->mOptions
->getEnableLimitReport() ) {
492 $max = $this->mOptions
->getMaxIncludeSize();
493 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
495 "NewPP limit report\n" .
496 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
497 "Preprocessor generated node count: " .
498 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
499 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
500 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
501 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
503 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
505 // Sanitize for comment. Note '‐' in the replacement is U+2010,
506 // which looks much like the problematic '-'.
507 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
509 $text .= "\n<!-- \n$limitReport-->\n";
511 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
512 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
513 $this->mTitle
->getPrefixedDBkey() );
516 $this->mOutput
->setText( $text );
518 $this->mRevisionId
= $oldRevisionId;
519 $this->mRevisionObject
= $oldRevisionObject;
520 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
521 $this->mRevisionUser
= $oldRevisionUser;
522 wfProfileOut( $fname );
523 wfProfileOut( __METHOD__
);
525 return $this->mOutput
;
529 * Recursive parser entry point that can be called from an extension tag
532 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
534 * @param string $text text extension wants to have parsed
535 * @param $frame PPFrame: The frame to use for expanding any template variables
539 function recursiveTagParse( $text, $frame = false ) {
540 wfProfileIn( __METHOD__
);
541 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
542 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
543 $text = $this->internalParse( $text, false, $frame );
544 wfProfileOut( __METHOD__
);
549 * Expand templates and variables in the text, producing valid, static wikitext.
550 * Also removes comments.
551 * @return mixed|string
553 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
554 wfProfileIn( __METHOD__
);
555 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
556 if ( $revid !== null ) {
557 $this->mRevisionId
= $revid;
559 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
560 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
561 $text = $this->replaceVariables( $text );
562 $text = $this->mStripState
->unstripBoth( $text );
563 wfProfileOut( __METHOD__
);
568 * Recursive parser entry point that can be called from an extension tag
571 * @param string $text text to be expanded
572 * @param $frame PPFrame: The frame to use for expanding any template variables
576 public function recursivePreprocess( $text, $frame = false ) {
577 wfProfileIn( __METHOD__
);
578 $text = $this->replaceVariables( $text, $frame );
579 $text = $this->mStripState
->unstripBoth( $text );
580 wfProfileOut( __METHOD__
);
585 * Process the wikitext for the "?preload=" feature. (bug 5210)
587 * "<noinclude>", "<includeonly>" etc. are parsed as for template
588 * transclusion, comments, templates, arguments, tags hooks and parser
589 * functions are untouched.
591 * @param $text String
592 * @param $title Title
593 * @param $options ParserOptions
596 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
597 # Parser (re)initialisation
598 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
600 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
601 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
602 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
603 $text = $this->mStripState
->unstripBoth( $text );
608 * Get a random string
612 public static function getRandomString() {
613 return wfRandomString( 16 );
617 * Set the current user.
618 * Should only be used when doing pre-save transform.
620 * @param $user Mixed: User object or null (to reset)
622 function setUser( $user ) {
623 $this->mUser
= $user;
627 * Accessor for mUniqPrefix.
631 public function uniqPrefix() {
632 if ( !isset( $this->mUniqPrefix
) ) {
633 # @todo FIXME: This is probably *horribly wrong*
634 # LanguageConverter seems to want $wgParser's uniqPrefix, however
635 # if this is called for a parser cache hit, the parser may not
636 # have ever been initialized in the first place.
637 # Not really sure what the heck is supposed to be going on here.
639 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
641 return $this->mUniqPrefix
;
645 * Set the context title
649 function setTitle( $t ) {
650 if ( !$t ||
$t instanceof FakeTitle
) {
651 $t = Title
::newFromText( 'NO TITLE' );
654 if ( strval( $t->getFragment() ) !== '' ) {
655 # Strip the fragment to avoid various odd effects
656 $this->mTitle
= clone $t;
657 $this->mTitle
->setFragment( '' );
664 * Accessor for the Title object
666 * @return Title object
668 function getTitle() {
669 return $this->mTitle
;
673 * Accessor/mutator for the Title object
675 * @param $x Title object or null to just get the current one
676 * @return Title object
678 function Title( $x = null ) {
679 return wfSetVar( $this->mTitle
, $x );
683 * Set the output type
685 * @param $ot Integer: new value
687 function setOutputType( $ot ) {
688 $this->mOutputType
= $ot;
691 'html' => $ot == self
::OT_HTML
,
692 'wiki' => $ot == self
::OT_WIKI
,
693 'pre' => $ot == self
::OT_PREPROCESS
,
694 'plain' => $ot == self
::OT_PLAIN
,
699 * Accessor/mutator for the output type
701 * @param int|null $x New value or null to just get the current one
704 function OutputType( $x = null ) {
705 return wfSetVar( $this->mOutputType
, $x );
709 * Get the ParserOutput object
711 * @return ParserOutput object
713 function getOutput() {
714 return $this->mOutput
;
718 * Get the ParserOptions object
720 * @return ParserOptions object
722 function getOptions() {
723 return $this->mOptions
;
727 * Accessor/mutator for the ParserOptions object
729 * @param $x ParserOptions New value or null to just get the current one
730 * @return ParserOptions Current ParserOptions object
732 function Options( $x = null ) {
733 return wfSetVar( $this->mOptions
, $x );
739 function nextLinkID() {
740 return $this->mLinkID++
;
746 function setLinkID( $id ) {
747 $this->mLinkID
= $id;
751 * Get a language object for use in parser functions such as {{FORMATNUM:}}
754 function getFunctionLang() {
755 return $this->getTargetLanguage();
759 * Get the target language for the content being parsed. This is usually the
760 * language that the content is in.
764 * @throws MWException
765 * @return Language|null
767 public function getTargetLanguage() {
768 $target = $this->mOptions
->getTargetLanguage();
770 if ( $target !== null ) {
772 } elseif( $this->mOptions
->getInterfaceMessage() ) {
773 return $this->mOptions
->getUserLangObj();
774 } elseif( is_null( $this->mTitle
) ) {
775 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
778 return $this->mTitle
->getPageLanguage();
782 * Get the language object for language conversion
784 function getConverterLanguage() {
785 return $this->getTargetLanguage();
789 * Get a User object either from $this->mUser, if set, or from the
790 * ParserOptions object otherwise
792 * @return User object
795 if ( !is_null( $this->mUser
) ) {
798 return $this->mOptions
->getUser();
802 * Get a preprocessor object
804 * @return Preprocessor instance
806 function getPreprocessor() {
807 if ( !isset( $this->mPreprocessor
) ) {
808 $class = $this->mPreprocessorClass
;
809 $this->mPreprocessor
= new $class( $this );
811 return $this->mPreprocessor
;
815 * Replaces all occurrences of HTML-style comments and the given tags
816 * in the text with a random marker and returns the next text. The output
817 * parameter $matches will be an associative array filled with data in
821 * 'UNIQ-xxxxx' => array(
824 * array( 'param' => 'x' ),
825 * '<element param="x">tag content</element>' ) )
828 * @param array $elements list of element names. Comments are always extracted.
829 * @param string $text Source text string.
830 * @param array $matches Out parameter, Array: extracted tags
831 * @param $uniq_prefix string
832 * @return String: stripped text
834 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
839 $taglist = implode( '|', $elements );
840 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
842 while ( $text != '' ) {
843 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
845 if ( count( $p ) < 5 ) {
848 if ( count( $p ) > 5 ) {
862 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
863 $stripped .= $marker;
865 if ( $close === '/>' ) {
866 # Empty element tag, <tag />
871 if ( $element === '!--' ) {
874 $end = "/(<\\/$element\\s*>)/i";
876 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
878 if ( count( $q ) < 3 ) {
879 # No end tag -- let it run out to the end of the text.
888 $matches[$marker] = array( $element,
890 Sanitizer
::decodeTagAttributes( $attributes ),
891 "<$element$attributes$close$content$tail" );
897 * Get a list of strippable XML-like elements
901 function getStripList() {
902 return $this->mStripList
;
906 * Add an item to the strip state
907 * Returns the unique tag which must be inserted into the stripped text
908 * The tag will be replaced with the original text in unstrip()
910 * @param $text string
914 function insertStripItem( $text ) {
915 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
916 $this->mMarkerIndex++
;
917 $this->mStripState
->addGeneral( $rnd, $text );
922 * parse the wiki syntax used to render tables
927 function doTableStuff( $text ) {
928 wfProfileIn( __METHOD__
);
930 $lines = StringUtils
::explode( "\n", $text );
932 $td_history = array(); # Is currently a td tag open?
933 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
934 $tr_history = array(); # Is currently a tr tag open?
935 $tr_attributes = array(); # history of tr attributes
936 $has_opened_tr = array(); # Did this table open a <tr> element?
937 $indent_level = 0; # indent level of the table
939 foreach ( $lines as $outLine ) {
940 $line = trim( $outLine );
942 if ( $line === '' ) { # empty line, go to next line
943 $out .= $outLine . "\n";
947 $first_character = $line[0];
950 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
951 # First check if we are starting a new table
952 $indent_level = strlen( $matches[1] );
954 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
955 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
957 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
958 array_push( $td_history, false );
959 array_push( $last_tag_history, '' );
960 array_push( $tr_history, false );
961 array_push( $tr_attributes, '' );
962 array_push( $has_opened_tr, false );
963 } elseif ( count( $td_history ) == 0 ) {
964 # Don't do any of the following
965 $out .= $outLine . "\n";
967 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
968 # We are ending a table
969 $line = '</table>' . substr( $line, 2 );
970 $last_tag = array_pop( $last_tag_history );
972 if ( !array_pop( $has_opened_tr ) ) {
973 $line = "<tr><td></td></tr>{$line}";
976 if ( array_pop( $tr_history ) ) {
977 $line = "</tr>{$line}";
980 if ( array_pop( $td_history ) ) {
981 $line = "</{$last_tag}>{$line}";
983 array_pop( $tr_attributes );
984 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
985 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
986 # Now we have a table row
987 $line = preg_replace( '#^\|-+#', '', $line );
989 # Whats after the tag is now only attributes
990 $attributes = $this->mStripState
->unstripBoth( $line );
991 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
992 array_pop( $tr_attributes );
993 array_push( $tr_attributes, $attributes );
996 $last_tag = array_pop( $last_tag_history );
997 array_pop( $has_opened_tr );
998 array_push( $has_opened_tr, true );
1000 if ( array_pop( $tr_history ) ) {
1004 if ( array_pop( $td_history ) ) {
1005 $line = "</{$last_tag}>{$line}";
1009 array_push( $tr_history, false );
1010 array_push( $td_history, false );
1011 array_push( $last_tag_history, '' );
1012 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1013 # This might be cell elements, td, th or captions
1014 if ( substr( $line, 0, 2 ) === '|+' ) {
1015 $first_character = '+';
1016 $line = substr( $line, 1 );
1019 $line = substr( $line, 1 );
1021 if ( $first_character === '!' ) {
1022 $line = str_replace( '!!', '||', $line );
1025 # Split up multiple cells on the same line.
1026 # FIXME : This can result in improper nesting of tags processed
1027 # by earlier parser steps, but should avoid splitting up eg
1028 # attribute values containing literal "||".
1029 $cells = StringUtils
::explodeMarkup( '||', $line );
1033 # Loop through each table cell
1034 foreach ( $cells as $cell ) {
1036 if ( $first_character !== '+' ) {
1037 $tr_after = array_pop( $tr_attributes );
1038 if ( !array_pop( $tr_history ) ) {
1039 $previous = "<tr{$tr_after}>\n";
1041 array_push( $tr_history, true );
1042 array_push( $tr_attributes, '' );
1043 array_pop( $has_opened_tr );
1044 array_push( $has_opened_tr, true );
1047 $last_tag = array_pop( $last_tag_history );
1049 if ( array_pop( $td_history ) ) {
1050 $previous = "</{$last_tag}>\n{$previous}";
1053 if ( $first_character === '|' ) {
1055 } elseif ( $first_character === '!' ) {
1057 } elseif ( $first_character === '+' ) {
1058 $last_tag = 'caption';
1063 array_push( $last_tag_history, $last_tag );
1065 # A cell could contain both parameters and data
1066 $cell_data = explode( '|', $cell, 2 );
1068 # Bug 553: Note that a '|' inside an invalid link should not
1069 # be mistaken as delimiting cell parameters
1070 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1071 $cell = "{$previous}<{$last_tag}>{$cell}";
1072 } elseif ( count( $cell_data ) == 1 ) {
1073 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1075 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1076 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1077 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1081 array_push( $td_history, true );
1084 $out .= $outLine . "\n";
1087 # Closing open td, tr && table
1088 while ( count( $td_history ) > 0 ) {
1089 if ( array_pop( $td_history ) ) {
1092 if ( array_pop( $tr_history ) ) {
1095 if ( !array_pop( $has_opened_tr ) ) {
1096 $out .= "<tr><td></td></tr>\n";
1099 $out .= "</table>\n";
1102 # Remove trailing line-ending (b/c)
1103 if ( substr( $out, -1 ) === "\n" ) {
1104 $out = substr( $out, 0, -1 );
1107 # special case: don't return empty table
1108 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1112 wfProfileOut( __METHOD__
);
1118 * Helper function for parse() that transforms wiki markup into
1119 * HTML. Only called for $mOutputType == self::OT_HTML.
1123 * @param $text string
1124 * @param $isMain bool
1125 * @param $frame bool
1129 function internalParse( $text, $isMain = true, $frame = false ) {
1130 wfProfileIn( __METHOD__
);
1134 # Hook to suspend the parser in this state
1135 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1136 wfProfileOut( __METHOD__
);
1140 # if $frame is provided, then use $frame for replacing any variables
1142 # use frame depth to infer how include/noinclude tags should be handled
1143 # depth=0 means this is the top-level document; otherwise it's an included document
1144 if ( !$frame->depth
) {
1147 $flag = Parser
::PTD_FOR_INCLUSION
;
1149 $dom = $this->preprocessToDom( $text, $flag );
1150 $text = $frame->expand( $dom );
1152 # if $frame is not provided, then use old-style replaceVariables
1153 $text = $this->replaceVariables( $text );
1156 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1157 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1158 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1160 # Tables need to come after variable replacement for things to work
1161 # properly; putting them before other transformations should keep
1162 # exciting things like link expansions from showing up in surprising
1164 $text = $this->doTableStuff( $text );
1166 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1168 $text = $this->doDoubleUnderscore( $text );
1170 $text = $this->doHeadings( $text );
1171 $text = $this->replaceInternalLinks( $text );
1172 $text = $this->doAllQuotes( $text );
1173 $text = $this->replaceExternalLinks( $text );
1175 # replaceInternalLinks may sometimes leave behind
1176 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1177 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1179 $text = $this->doMagicLinks( $text );
1180 $text = $this->formatHeadings( $text, $origText, $isMain );
1182 wfProfileOut( __METHOD__
);
1187 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1188 * magic external links.
1193 * @param $text string
1197 function doMagicLinks( $text ) {
1198 wfProfileIn( __METHOD__
);
1199 $prots = wfUrlProtocolsWithoutProtRel();
1200 $urlChar = self
::EXT_LINK_URL_CLASS
;
1201 $text = preg_replace_callback(
1203 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1204 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1205 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1206 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1207 ISBN\s+(\b # m[5]: ISBN, capture number
1208 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1209 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1210 [0-9Xx] # check digit
1212 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1213 wfProfileOut( __METHOD__
);
1218 * @throws MWException
1220 * @return HTML|string
1222 function magicLinkCallback( $m ) {
1223 if ( isset( $m[1] ) && $m[1] !== '' ) {
1226 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1229 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1230 # Free external link
1231 return $this->makeFreeExternalLink( $m[0] );
1232 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1234 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1237 $CssClass = 'mw-magiclink-rfc';
1239 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1241 $urlmsg = 'pubmedurl';
1242 $CssClass = 'mw-magiclink-pmid';
1245 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1246 substr( $m[0], 0, 20 ) . '"' );
1248 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1249 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1250 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1253 $num = strtr( $isbn, array(
1258 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1260 htmlspecialchars( $titleObj->getLocalURL() ) .
1261 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1268 * Make a free external link, given a user-supplied URL
1270 * @param $url string
1272 * @return string HTML
1275 function makeFreeExternalLink( $url ) {
1276 wfProfileIn( __METHOD__
);
1280 # The characters '<' and '>' (which were escaped by
1281 # removeHTMLtags()) should not be included in
1282 # URLs, per RFC 2396.
1284 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1285 $trail = substr( $url, $m2[0][1] ) . $trail;
1286 $url = substr( $url, 0, $m2[0][1] );
1289 # Move trailing punctuation to $trail
1291 # If there is no left bracket, then consider right brackets fair game too
1292 if ( strpos( $url, '(' ) === false ) {
1296 $numSepChars = strspn( strrev( $url ), $sep );
1297 if ( $numSepChars ) {
1298 $trail = substr( $url, -$numSepChars ) . $trail;
1299 $url = substr( $url, 0, -$numSepChars );
1302 $url = Sanitizer
::cleanUrl( $url );
1304 # Is this an external image?
1305 $text = $this->maybeMakeExternalImage( $url );
1306 if ( $text === false ) {
1307 # Not an image, make a link
1308 $text = Linker
::makeExternalLink( $url,
1309 $this->getConverterLanguage()->markNoConversion( $url, true ),
1311 $this->getExternalLinkAttribs( $url ) );
1312 # Register it in the output object...
1313 # Replace unnecessary URL escape codes with their equivalent characters
1314 $pasteurized = self
::replaceUnusualEscapes( $url );
1315 $this->mOutput
->addExternalLink( $pasteurized );
1317 wfProfileOut( __METHOD__
);
1318 return $text . $trail;
1322 * Parse headers and return html
1326 * @param $text string
1330 function doHeadings( $text ) {
1331 wfProfileIn( __METHOD__
);
1332 for ( $i = 6; $i >= 1; --$i ) {
1333 $h = str_repeat( '=', $i );
1334 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1336 wfProfileOut( __METHOD__
);
1341 * Replace single quotes with HTML markup
1344 * @param $text string
1346 * @return string the altered text
1348 function doAllQuotes( $text ) {
1349 wfProfileIn( __METHOD__
);
1351 $lines = StringUtils
::explode( "\n", $text );
1352 foreach ( $lines as $line ) {
1353 $outtext .= $this->doQuotes( $line ) . "\n";
1355 $outtext = substr( $outtext, 0, -1 );
1356 wfProfileOut( __METHOD__
);
1361 * Helper function for doAllQuotes()
1363 * @param $text string
1367 public function doQuotes( $text ) {
1368 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1369 if ( count( $arr ) == 1 ) {
1372 # First, do some preliminary work. This may shift some apostrophes from
1373 # being mark-up to being text. It also counts the number of occurrences
1374 # of bold and italics mark-ups.
1377 for ( $i = 0; $i < count( $arr ); $i++
) {
1378 if ( ( $i %
2 ) == 1 ) {
1379 # If there are ever four apostrophes, assume the first is supposed to
1380 # be text, and the remaining three constitute mark-up for bold text.
1381 if ( strlen( $arr[$i] ) == 4 ) {
1382 $arr[$i - 1] .= "'";
1384 } elseif ( strlen( $arr[$i] ) > 5 ) {
1385 # If there are more than 5 apostrophes in a row, assume they're all
1386 # text except for the last 5.
1387 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1390 # Count the number of occurrences of bold and italics mark-ups.
1391 # We are not counting sequences of five apostrophes.
1392 if ( strlen( $arr[$i] ) == 2 ) {
1394 } elseif ( strlen( $arr[$i] ) == 3 ) {
1396 } elseif ( strlen( $arr[$i] ) == 5 ) {
1403 # If there is an odd number of both bold and italics, it is likely
1404 # that one of the bold ones was meant to be an apostrophe followed
1405 # by italics. Which one we cannot know for certain, but it is more
1406 # likely to be one that has a single-letter word before it.
1407 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1409 $firstsingleletterword = -1;
1410 $firstmultiletterword = -1;
1412 foreach ( $arr as $r ) {
1413 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1414 $x1 = substr( $arr[$i - 1], -1 );
1415 $x2 = substr( $arr[$i - 1], -2, 1 );
1416 if ( $x1 === ' ' ) {
1417 if ( $firstspace == -1 ) {
1420 } elseif ( $x2 === ' ' ) {
1421 if ( $firstsingleletterword == -1 ) {
1422 $firstsingleletterword = $i;
1425 if ( $firstmultiletterword == -1 ) {
1426 $firstmultiletterword = $i;
1433 # If there is a single-letter word, use it!
1434 if ( $firstsingleletterword > -1 ) {
1435 $arr[$firstsingleletterword] = "''";
1436 $arr[$firstsingleletterword - 1] .= "'";
1437 } elseif ( $firstmultiletterword > -1 ) {
1438 # If not, but there's a multi-letter word, use that one.
1439 $arr[$firstmultiletterword] = "''";
1440 $arr[$firstmultiletterword - 1] .= "'";
1441 } elseif ( $firstspace > -1 ) {
1442 # ... otherwise use the first one that has neither.
1443 # (notice that it is possible for all three to be -1 if, for example,
1444 # there is only one pentuple-apostrophe in the line)
1445 $arr[$firstspace] = "''";
1446 $arr[$firstspace - 1] .= "'";
1450 # Now let's actually convert our apostrophic mush to HTML!
1455 foreach ( $arr as $r ) {
1456 if ( ( $i %
2 ) == 0 ) {
1457 if ( $state === 'both' ) {
1463 if ( strlen( $r ) == 2 ) {
1464 if ( $state === 'i' ) {
1465 $output .= '</i>'; $state = '';
1466 } elseif ( $state === 'bi' ) {
1467 $output .= '</i>'; $state = 'b';
1468 } elseif ( $state === 'ib' ) {
1469 $output .= '</b></i><b>'; $state = 'b';
1470 } elseif ( $state === 'both' ) {
1471 $output .= '<b><i>' . $buffer . '</i>'; $state = 'b';
1472 } else { # $state can be 'b' or ''
1473 $output .= '<i>'; $state .= 'i';
1475 } elseif ( strlen( $r ) == 3 ) {
1476 if ( $state === 'b' ) {
1477 $output .= '</b>'; $state = '';
1478 } elseif ( $state === 'bi' ) {
1479 $output .= '</i></b><i>'; $state = 'i';
1480 } elseif ( $state === 'ib' ) {
1481 $output .= '</b>'; $state = 'i';
1482 } elseif ( $state === 'both' ) {
1483 $output .= '<i><b>' . $buffer . '</b>'; $state = 'i';
1484 } else { # $state can be 'i' or ''
1485 $output .= '<b>'; $state .= 'b';
1487 } elseif ( strlen( $r ) == 5 ) {
1488 if ( $state === 'b' ) {
1489 $output .= '</b><i>'; $state = 'i';
1490 } elseif ( $state === 'i' ) {
1491 $output .= '</i><b>'; $state = 'b';
1492 } elseif ( $state === 'bi' ) {
1493 $output .= '</i></b>'; $state = '';
1494 } elseif ( $state === 'ib' ) {
1495 $output .= '</b></i>'; $state = '';
1496 } elseif ( $state === 'both' ) {
1497 $output .= '<i><b>' . $buffer . '</b></i>'; $state = '';
1498 } else { # ($state == '')
1499 $buffer = ''; $state = 'both';
1505 # Now close all remaining tags. Notice that the order is important.
1506 if ( $state === 'b' ||
$state === 'ib' ) {
1509 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1512 if ( $state === 'bi' ) {
1515 # There might be lonely ''''', so make sure we have a buffer
1516 if ( $state === 'both' && $buffer ) {
1517 $output .= '<b><i>' . $buffer . '</i></b>';
1524 * Replace external links (REL)
1526 * Note: this is all very hackish and the order of execution matters a lot.
1527 * Make sure to run maintenance/parserTests.php if you change this code.
1531 * @param $text string
1533 * @throws MWException
1536 function replaceExternalLinks( $text ) {
1537 wfProfileIn( __METHOD__
);
1539 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1540 if ( $bits === false ) {
1541 wfProfileOut( __METHOD__
);
1542 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1544 $s = array_shift( $bits );
1547 while ( $i < count( $bits ) ) {
1550 $text = $bits[$i++
];
1551 $trail = $bits[$i++
];
1553 # The characters '<' and '>' (which were escaped by
1554 # removeHTMLtags()) should not be included in
1555 # URLs, per RFC 2396.
1557 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1558 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1559 $url = substr( $url, 0, $m2[0][1] );
1562 # If the link text is an image URL, replace it with an <img> tag
1563 # This happened by accident in the original parser, but some people used it extensively
1564 $img = $this->maybeMakeExternalImage( $text );
1565 if ( $img !== false ) {
1571 # Set linktype for CSS - if URL==text, link is essentially free
1572 $linktype = ( $text === $url ) ?
'free' : 'text';
1574 # No link text, e.g. [http://domain.tld/some.link]
1575 if ( $text == '' ) {
1577 $langObj = $this->getTargetLanguage();
1578 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1579 $linktype = 'autonumber';
1581 # Have link text, e.g. [http://domain.tld/some.link text]s
1583 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1586 $text = $this->getConverterLanguage()->markNoConversion( $text );
1588 $url = Sanitizer
::cleanUrl( $url );
1590 # Use the encoded URL
1591 # This means that users can paste URLs directly into the text
1592 # Funny characters like ö aren't valid in URLs anyway
1593 # This was changed in August 2004
1594 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1595 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1597 # Register link in the output object.
1598 # Replace unnecessary URL escape codes with the referenced character
1599 # This prevents spammers from hiding links from the filters
1600 $pasteurized = self
::replaceUnusualEscapes( $url );
1601 $this->mOutput
->addExternalLink( $pasteurized );
1604 wfProfileOut( __METHOD__
);
1608 * Get the rel attribute for a particular external link.
1611 * @param string|bool $url optional URL, to extract the domain from for rel =>
1612 * nofollow if appropriate
1613 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1614 * @return string|null rel attribute for $url
1616 public static function getExternalLinkRel( $url = false, $title = null ) {
1617 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1618 $ns = $title ?
$title->getNamespace() : false;
1619 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1620 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1627 * Get an associative array of additional HTML attributes appropriate for a
1628 * particular external link. This currently may include rel => nofollow
1629 * (depending on configuration, namespace, and the URL's domain) and/or a
1630 * target attribute (depending on configuration).
1632 * @param string|bool $url optional URL, to extract the domain from for rel =>
1633 * nofollow if appropriate
1634 * @return Array associative array of HTML attributes
1636 function getExternalLinkAttribs( $url = false ) {
1638 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1640 if ( $this->mOptions
->getExternalLinkTarget() ) {
1641 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1647 * Replace unusual URL escape codes with their equivalent characters
1649 * @param $url String
1652 * @todo This can merge genuinely required bits in the path or query string,
1653 * breaking legit URLs. A proper fix would treat the various parts of
1654 * the URL differently; as a workaround, just use the output for
1655 * statistical records, not for actual linking/output.
1657 static function replaceUnusualEscapes( $url ) {
1658 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1659 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1663 * Callback function used in replaceUnusualEscapes().
1664 * Replaces unusual URL escape codes with their equivalent character
1666 * @param $matches array
1670 private static function replaceUnusualEscapesCallback( $matches ) {
1671 $char = urldecode( $matches[0] );
1672 $ord = ord( $char );
1673 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1674 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1675 # No, shouldn't be escaped
1678 # Yes, leave it escaped
1684 * make an image if it's allowed, either through the global
1685 * option, through the exception, or through the on-wiki whitelist
1688 * $param $url string
1692 function maybeMakeExternalImage( $url ) {
1693 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1694 $imagesexception = !empty( $imagesfrom );
1696 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1697 if ( $imagesexception && is_array( $imagesfrom ) ) {
1698 $imagematch = false;
1699 foreach ( $imagesfrom as $match ) {
1700 if ( strpos( $url, $match ) === 0 ) {
1705 } elseif ( $imagesexception ) {
1706 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1708 $imagematch = false;
1710 if ( $this->mOptions
->getAllowExternalImages()
1711 ||
( $imagesexception && $imagematch ) ) {
1712 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1714 $text = Linker
::makeExternalImage( $url );
1717 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1718 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1719 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1720 foreach ( $whitelist as $entry ) {
1721 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1722 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1725 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1726 # Image matches a whitelist entry
1727 $text = Linker
::makeExternalImage( $url );
1736 * Process [[ ]] wikilinks
1740 * @return String: processed text
1744 function replaceInternalLinks( $s ) {
1745 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1750 * Process [[ ]] wikilinks (RIL)
1752 * @throws MWException
1753 * @return LinkHolderArray
1757 function replaceInternalLinks2( &$s ) {
1758 wfProfileIn( __METHOD__
);
1760 wfProfileIn( __METHOD__
. '-setup' );
1761 static $tc = false, $e1, $e1_img;
1762 # the % is needed to support urlencoded titles as well
1764 $tc = Title
::legalChars() . '#%';
1765 # Match a link having the form [[namespace:link|alternate]]trail
1766 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1767 # Match cases where there is no "]]", which might still be images
1768 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1771 $holders = new LinkHolderArray( $this );
1773 # split the entire text string on occurrences of [[
1774 $a = StringUtils
::explode( '[[', ' ' . $s );
1775 # get the first element (all text up to first [[), and remove the space we added
1778 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1779 $s = substr( $s, 1 );
1781 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1783 if ( $useLinkPrefixExtension ) {
1784 # Match the end of a line for a word that's not followed by whitespace,
1785 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1786 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1789 if ( is_null( $this->mTitle
) ) {
1790 wfProfileOut( __METHOD__
. '-setup' );
1791 wfProfileOut( __METHOD__
);
1792 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1794 $nottalk = !$this->mTitle
->isTalkPage();
1796 if ( $useLinkPrefixExtension ) {
1798 if ( preg_match( $e2, $s, $m ) ) {
1799 $first_prefix = $m[2];
1801 $first_prefix = false;
1807 $useSubpages = $this->areSubpagesAllowed();
1808 wfProfileOut( __METHOD__
. '-setup' );
1810 # Loop for each link
1811 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1812 # Check for excessive memory usage
1813 if ( $holders->isBig() ) {
1815 # Do the existence check, replace the link holders and clear the array
1816 $holders->replace( $s );
1820 if ( $useLinkPrefixExtension ) {
1821 wfProfileIn( __METHOD__
. '-prefixhandling' );
1822 if ( preg_match( $e2, $s, $m ) ) {
1829 if ( $first_prefix ) {
1830 $prefix = $first_prefix;
1831 $first_prefix = false;
1833 wfProfileOut( __METHOD__
. '-prefixhandling' );
1836 $might_be_img = false;
1838 wfProfileIn( __METHOD__
. "-e1" );
1839 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1841 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1842 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1843 # the real problem is with the $e1 regex
1846 # Still some problems for cases where the ] is meant to be outside punctuation,
1847 # and no image is in sight. See bug 2095.
1849 if ( $text !== '' &&
1850 substr( $m[3], 0, 1 ) === ']' &&
1851 strpos( $text, '[' ) !== false
1854 $text .= ']'; # so that replaceExternalLinks($text) works later
1855 $m[3] = substr( $m[3], 1 );
1857 # fix up urlencoded title texts
1858 if ( strpos( $m[1], '%' ) !== false ) {
1859 # Should anchors '#' also be rejected?
1860 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1863 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1864 $might_be_img = true;
1866 if ( strpos( $m[1], '%' ) !== false ) {
1867 $m[1] = rawurldecode( $m[1] );
1870 } else { # Invalid form; output directly
1871 $s .= $prefix . '[[' . $line;
1872 wfProfileOut( __METHOD__
. "-e1" );
1875 wfProfileOut( __METHOD__
. "-e1" );
1876 wfProfileIn( __METHOD__
. "-misc" );
1878 # Don't allow internal links to pages containing
1879 # PROTO: where PROTO is a valid URL protocol; these
1880 # should be external links.
1881 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1882 $s .= $prefix . '[[' . $line;
1883 wfProfileOut( __METHOD__
. "-misc" );
1887 # Make subpage if necessary
1888 if ( $useSubpages ) {
1889 $link = $this->maybeDoSubpageLink( $m[1], $text );
1894 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1896 # Strip off leading ':'
1897 $link = substr( $link, 1 );
1900 wfProfileOut( __METHOD__
. "-misc" );
1901 wfProfileIn( __METHOD__
. "-title" );
1902 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1903 if ( $nt === null ) {
1904 $s .= $prefix . '[[' . $line;
1905 wfProfileOut( __METHOD__
. "-title" );
1909 $ns = $nt->getNamespace();
1910 $iw = $nt->getInterWiki();
1911 wfProfileOut( __METHOD__
. "-title" );
1913 if ( $might_be_img ) { # if this is actually an invalid link
1914 wfProfileIn( __METHOD__
. "-might_be_img" );
1915 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1918 # look at the next 'line' to see if we can close it there
1920 $next_line = $a->current();
1921 if ( $next_line === false ||
$next_line === null ) {
1924 $m = explode( ']]', $next_line, 3 );
1925 if ( count( $m ) == 3 ) {
1926 # the first ]] closes the inner link, the second the image
1928 $text .= "[[{$m[0]}]]{$m[1]}";
1931 } elseif ( count( $m ) == 2 ) {
1932 # if there's exactly one ]] that's fine, we'll keep looking
1933 $text .= "[[{$m[0]}]]{$m[1]}";
1935 # if $next_line is invalid too, we need look no further
1936 $text .= '[[' . $next_line;
1941 # we couldn't find the end of this imageLink, so output it raw
1942 # but don't ignore what might be perfectly normal links in the text we've examined
1943 $holders->merge( $this->replaceInternalLinks2( $text ) );
1944 $s .= "{$prefix}[[$link|$text";
1945 # note: no $trail, because without an end, there *is* no trail
1946 wfProfileOut( __METHOD__
. "-might_be_img" );
1949 } else { # it's not an image, so output it raw
1950 $s .= "{$prefix}[[$link|$text";
1951 # note: no $trail, because without an end, there *is* no trail
1952 wfProfileOut( __METHOD__
. "-might_be_img" );
1955 wfProfileOut( __METHOD__
. "-might_be_img" );
1958 $wasblank = ( $text == '' );
1962 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1963 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1964 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1965 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1966 $text = $this->doQuotes( $text );
1969 # Link not escaped by : , create the various objects
1972 wfProfileIn( __METHOD__
. "-interwiki" );
1973 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1974 // XXX: the above check prevents links to sites with identifiers that are not language codes
1976 # Bug 24502: filter duplicates
1977 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1978 $this->mLangLinkLanguages
[$iw] = true;
1979 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1982 $s = rtrim( $s . $prefix );
1983 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1984 wfProfileOut( __METHOD__
. "-interwiki" );
1987 wfProfileOut( __METHOD__
. "-interwiki" );
1989 if ( $ns == NS_FILE
) {
1990 wfProfileIn( __METHOD__
. "-image" );
1991 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1993 # if no parameters were passed, $text
1994 # becomes something like "File:Foo.png",
1995 # which we don't want to pass on to the
1999 # recursively parse links inside the image caption
2000 # actually, this will parse them in any other parameters, too,
2001 # but it might be hard to fix that, and it doesn't matter ATM
2002 $text = $this->replaceExternalLinks( $text );
2003 $holders->merge( $this->replaceInternalLinks2( $text ) );
2005 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2006 $s .= $prefix . $this->armorLinks(
2007 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2009 $s .= $prefix . $trail;
2011 wfProfileOut( __METHOD__
. "-image" );
2015 if ( $ns == NS_CATEGORY
) {
2016 wfProfileIn( __METHOD__
. "-category" );
2017 $s = rtrim( $s . "\n" ); # bug 87
2020 $sortkey = $this->getDefaultSort();
2024 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2025 $sortkey = str_replace( "\n", '', $sortkey );
2026 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2027 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2030 * Strip the whitespace Category links produce, see bug 87
2031 * @todo We might want to use trim($tmp, "\n") here.
2033 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2035 wfProfileOut( __METHOD__
. "-category" );
2040 # Self-link checking
2041 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2042 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2043 $this->mTitle
->getPrefixedText(),
2044 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2047 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2052 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2053 # @todo FIXME: Should do batch file existence checks, see comment below
2054 if ( $ns == NS_MEDIA
) {
2055 wfProfileIn( __METHOD__
. "-media" );
2056 # Give extensions a chance to select the file revision for us
2059 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2060 array( $this, $nt, &$options, &$descQuery ) );
2061 # Fetch and register the file (file title may be different via hooks)
2062 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2063 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2064 $s .= $prefix . $this->armorLinks(
2065 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2066 wfProfileOut( __METHOD__
. "-media" );
2070 wfProfileIn( __METHOD__
. "-always_known" );
2071 # Some titles, such as valid special pages or files in foreign repos, should
2072 # be shown as bluelinks even though they're not included in the page table
2074 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2075 # batch file existence checks for NS_FILE and NS_MEDIA
2076 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2077 $this->mOutput
->addLink( $nt );
2078 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2080 # Links will be added to the output link list after checking
2081 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2083 wfProfileOut( __METHOD__
. "-always_known" );
2085 wfProfileOut( __METHOD__
);
2090 * Render a forced-blue link inline; protect against double expansion of
2091 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2092 * Since this little disaster has to split off the trail text to avoid
2093 * breaking URLs in the following text without breaking trails on the
2094 * wiki links, it's been made into a horrible function.
2097 * @param $text String
2098 * @param array $query or String
2099 * @param $trail String
2100 * @param $prefix String
2101 * @return String: HTML-wikitext mix oh yuck
2103 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2104 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2106 if ( is_string( $query ) ) {
2107 $query = wfCgiToArray( $query );
2109 if ( $text == '' ) {
2110 $text = htmlspecialchars( $nt->getPrefixedText() );
2113 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2115 return $this->armorLinks( $link ) . $trail;
2119 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2120 * going to go through further parsing steps before inline URL expansion.
2122 * Not needed quite as much as it used to be since free links are a bit
2123 * more sensible these days. But bracketed links are still an issue.
2125 * @param string $text more-or-less HTML
2126 * @return String: less-or-more HTML with NOPARSE bits
2128 function armorLinks( $text ) {
2129 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2130 "{$this->mUniqPrefix}NOPARSE$1", $text );
2134 * Return true if subpage links should be expanded on this page.
2137 function areSubpagesAllowed() {
2138 # Some namespaces don't allow subpages
2139 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2143 * Handle link to subpage if necessary
2145 * @param string $target the source of the link
2146 * @param &$text String: the link text, modified as necessary
2147 * @return string the full name of the link
2150 function maybeDoSubpageLink( $target, &$text ) {
2151 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2155 * Used by doBlockLevels()
2160 function closeParagraph() {
2162 if ( $this->mLastSection
!= '' ) {
2163 $result = '</' . $this->mLastSection
. ">\n";
2165 $this->mInPre
= false;
2166 $this->mLastSection
= '';
2171 * getCommon() returns the length of the longest common substring
2172 * of both arguments, starting at the beginning of both.
2175 * @param $st1 string
2176 * @param $st2 string
2180 function getCommon( $st1, $st2 ) {
2181 $fl = strlen( $st1 );
2182 $shorter = strlen( $st2 );
2183 if ( $fl < $shorter ) {
2187 for ( $i = 0; $i < $shorter; ++
$i ) {
2188 if ( $st1[$i] != $st2[$i] ) {
2196 * These next three functions open, continue, and close the list
2197 * element appropriate to the prefix character passed into them.
2200 * @param $char string
2204 function openList( $char ) {
2205 $result = $this->closeParagraph();
2207 if ( '*' === $char ) {
2208 $result .= '<ul><li>';
2209 } elseif ( '#' === $char ) {
2210 $result .= '<ol><li>';
2211 } elseif ( ':' === $char ) {
2212 $result .= '<dl><dd>';
2213 } elseif ( ';' === $char ) {
2214 $result .= '<dl><dt>';
2215 $this->mDTopen
= true;
2217 $result = '<!-- ERR 1 -->';
2225 * @param $char String
2230 function nextItem( $char ) {
2231 if ( '*' === $char ||
'#' === $char ) {
2233 } elseif ( ':' === $char ||
';' === $char ) {
2235 if ( $this->mDTopen
) {
2238 if ( ';' === $char ) {
2239 $this->mDTopen
= true;
2240 return $close . '<dt>';
2242 $this->mDTopen
= false;
2243 return $close . '<dd>';
2246 return '<!-- ERR 2 -->';
2251 * @param $char String
2256 function closeList( $char ) {
2257 if ( '*' === $char ) {
2258 $text = '</li></ul>';
2259 } elseif ( '#' === $char ) {
2260 $text = '</li></ol>';
2261 } elseif ( ':' === $char ) {
2262 if ( $this->mDTopen
) {
2263 $this->mDTopen
= false;
2264 $text = '</dt></dl>';
2266 $text = '</dd></dl>';
2269 return '<!-- ERR 3 -->';
2271 return $text . "\n";
2276 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2278 * @param $text String
2279 * @param $linestart Boolean: whether or not this is at the start of a line.
2281 * @return string the lists rendered as HTML
2283 function doBlockLevels( $text, $linestart ) {
2284 wfProfileIn( __METHOD__
);
2286 # Parsing through the text line by line. The main thing
2287 # happening here is handling of block-level elements p, pre,
2288 # and making lists from lines starting with * # : etc.
2290 $textLines = StringUtils
::explode( "\n", $text );
2292 $lastPrefix = $output = '';
2293 $this->mDTopen
= $inBlockElem = false;
2295 $paragraphStack = false;
2297 foreach ( $textLines as $oLine ) {
2299 if ( !$linestart ) {
2309 $lastPrefixLength = strlen( $lastPrefix );
2310 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2311 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2312 # If not in a <pre> element, scan for and figure out what prefixes are there.
2313 if ( !$this->mInPre
) {
2314 # Multiple prefixes may abut each other for nested lists.
2315 $prefixLength = strspn( $oLine, '*#:;' );
2316 $prefix = substr( $oLine, 0, $prefixLength );
2319 # ; and : are both from definition-lists, so they're equivalent
2320 # for the purposes of determining whether or not we need to open/close
2322 $prefix2 = str_replace( ';', ':', $prefix );
2323 $t = substr( $oLine, $prefixLength );
2324 $this->mInPre
= (bool)$preOpenMatch;
2326 # Don't interpret any other prefixes in preformatted text
2328 $prefix = $prefix2 = '';
2333 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2334 # Same as the last item, so no need to deal with nesting or opening stuff
2335 $output .= $this->nextItem( substr( $prefix, -1 ) );
2336 $paragraphStack = false;
2338 if ( substr( $prefix, -1 ) === ';' ) {
2339 # The one nasty exception: definition lists work like this:
2340 # ; title : definition text
2341 # So we check for : in the remainder text to split up the
2342 # title and definition, without b0rking links.
2344 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2346 $output .= $term . $this->nextItem( ':' );
2349 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2350 # We need to open or close prefixes, or both.
2352 # Either open or close a level...
2353 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2354 $paragraphStack = false;
2356 # Close all the prefixes which aren't shared.
2357 while ( $commonPrefixLength < $lastPrefixLength ) {
2358 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2359 --$lastPrefixLength;
2362 # Continue the current prefix if appropriate.
2363 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2364 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2367 # Open prefixes where appropriate.
2368 while ( $prefixLength > $commonPrefixLength ) {
2369 $char = substr( $prefix, $commonPrefixLength, 1 );
2370 $output .= $this->openList( $char );
2372 if ( ';' === $char ) {
2373 # @todo FIXME: This is dupe of code above
2374 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2376 $output .= $term . $this->nextItem( ':' );
2379 ++
$commonPrefixLength;
2381 $lastPrefix = $prefix2;
2384 # If we have no prefixes, go to paragraph mode.
2385 if ( 0 == $prefixLength ) {
2386 wfProfileIn( __METHOD__
. "-paragraph" );
2387 # No prefix (not in list)--go to paragraph mode
2388 # XXX: use a stack for nestable elements like span, table and div
2389 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2390 $closematch = preg_match(
2391 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2392 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2393 if ( $openmatch or $closematch ) {
2394 $paragraphStack = false;
2395 # TODO bug 5718: paragraph closed
2396 $output .= $this->closeParagraph();
2397 if ( $preOpenMatch and !$preCloseMatch ) {
2398 $this->mInPre
= true;
2400 $inBlockElem = !$closematch;
2401 } elseif ( !$inBlockElem && !$this->mInPre
) {
2402 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2404 if ( $this->mLastSection
!== 'pre' ) {
2405 $paragraphStack = false;
2406 $output .= $this->closeParagraph() . '<pre>';
2407 $this->mLastSection
= 'pre';
2409 $t = substr( $t, 1 );
2412 if ( trim( $t ) === '' ) {
2413 if ( $paragraphStack ) {
2414 $output .= $paragraphStack . '<br />';
2415 $paragraphStack = false;
2416 $this->mLastSection
= 'p';
2418 if ( $this->mLastSection
!== 'p' ) {
2419 $output .= $this->closeParagraph();
2420 $this->mLastSection
= '';
2421 $paragraphStack = '<p>';
2423 $paragraphStack = '</p><p>';
2427 if ( $paragraphStack ) {
2428 $output .= $paragraphStack;
2429 $paragraphStack = false;
2430 $this->mLastSection
= 'p';
2431 } elseif ( $this->mLastSection
!== 'p' ) {
2432 $output .= $this->closeParagraph() . '<p>';
2433 $this->mLastSection
= 'p';
2438 wfProfileOut( __METHOD__
. "-paragraph" );
2440 # somewhere above we forget to get out of pre block (bug 785)
2441 if ( $preCloseMatch && $this->mInPre
) {
2442 $this->mInPre
= false;
2444 if ( $paragraphStack === false ) {
2445 $output .= $t . "\n";
2448 while ( $prefixLength ) {
2449 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2452 if ( $this->mLastSection
!= '' ) {
2453 $output .= '</' . $this->mLastSection
. '>';
2454 $this->mLastSection
= '';
2457 wfProfileOut( __METHOD__
);
2462 * Split up a string on ':', ignoring any occurrences inside tags
2463 * to prevent illegal overlapping.
2465 * @param string $str the string to split
2466 * @param &$before String set to everything before the ':'
2467 * @param &$after String set to everything after the ':'
2468 * @throws MWException
2469 * @return String the position of the ':', or false if none found
2471 function findColonNoLinks( $str, &$before, &$after ) {
2472 wfProfileIn( __METHOD__
);
2474 $pos = strpos( $str, ':' );
2475 if ( $pos === false ) {
2477 wfProfileOut( __METHOD__
);
2481 $lt = strpos( $str, '<' );
2482 if ( $lt === false ||
$lt > $pos ) {
2483 # Easy; no tag nesting to worry about
2484 $before = substr( $str, 0, $pos );
2485 $after = substr( $str, $pos +
1 );
2486 wfProfileOut( __METHOD__
);
2490 # Ugly state machine to walk through avoiding tags.
2491 $state = self
::COLON_STATE_TEXT
;
2493 $len = strlen( $str );
2494 for( $i = 0; $i < $len; $i++
) {
2498 # (Using the number is a performance hack for common cases)
2499 case 0: # self::COLON_STATE_TEXT:
2502 # Could be either a <start> tag or an </end> tag
2503 $state = self
::COLON_STATE_TAGSTART
;
2506 if ( $stack == 0 ) {
2508 $before = substr( $str, 0, $i );
2509 $after = substr( $str, $i +
1 );
2510 wfProfileOut( __METHOD__
);
2513 # Embedded in a tag; don't break it.
2516 # Skip ahead looking for something interesting
2517 $colon = strpos( $str, ':', $i );
2518 if ( $colon === false ) {
2519 # Nothing else interesting
2520 wfProfileOut( __METHOD__
);
2523 $lt = strpos( $str, '<', $i );
2524 if ( $stack === 0 ) {
2525 if ( $lt === false ||
$colon < $lt ) {
2527 $before = substr( $str, 0, $colon );
2528 $after = substr( $str, $colon +
1 );
2529 wfProfileOut( __METHOD__
);
2533 if ( $lt === false ) {
2534 # Nothing else interesting to find; abort!
2535 # We're nested, but there's no close tags left. Abort!
2538 # Skip ahead to next tag start
2540 $state = self
::COLON_STATE_TAGSTART
;
2543 case 1: # self::COLON_STATE_TAG:
2548 $state = self
::COLON_STATE_TEXT
;
2551 # Slash may be followed by >?
2552 $state = self
::COLON_STATE_TAGSLASH
;
2558 case 2: # self::COLON_STATE_TAGSTART:
2561 $state = self
::COLON_STATE_CLOSETAG
;
2564 $state = self
::COLON_STATE_COMMENT
;
2567 # Illegal early close? This shouldn't happen D:
2568 $state = self
::COLON_STATE_TEXT
;
2571 $state = self
::COLON_STATE_TAG
;
2574 case 3: # self::COLON_STATE_CLOSETAG:
2579 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2580 wfProfileOut( __METHOD__
);
2583 $state = self
::COLON_STATE_TEXT
;
2586 case self
::COLON_STATE_TAGSLASH
:
2588 # Yes, a self-closed tag <blah/>
2589 $state = self
::COLON_STATE_TEXT
;
2591 # Probably we're jumping the gun, and this is an attribute
2592 $state = self
::COLON_STATE_TAG
;
2595 case 5: # self::COLON_STATE_COMMENT:
2597 $state = self
::COLON_STATE_COMMENTDASH
;
2600 case self
::COLON_STATE_COMMENTDASH
:
2602 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2604 $state = self
::COLON_STATE_COMMENT
;
2607 case self
::COLON_STATE_COMMENTDASHDASH
:
2609 $state = self
::COLON_STATE_TEXT
;
2611 $state = self
::COLON_STATE_COMMENT
;
2615 wfProfileOut( __METHOD__
);
2616 throw new MWException( "State machine error in " . __METHOD__
);
2620 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2621 wfProfileOut( __METHOD__
);
2624 wfProfileOut( __METHOD__
);
2629 * Return value of a magic variable (like PAGENAME)
2633 * @param $index integer
2634 * @param bool|\PPFrame $frame
2636 * @throws MWException
2639 function getVariableValue( $index, $frame = false ) {
2640 global $wgContLang, $wgSitename, $wgServer;
2641 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2643 if ( is_null( $this->mTitle
) ) {
2644 // If no title set, bad things are going to happen
2645 // later. Title should always be set since this
2646 // should only be called in the middle of a parse
2647 // operation (but the unit-tests do funky stuff)
2648 throw new MWException( __METHOD__
. ' Should only be '
2649 . ' called while parsing (no title set)' );
2653 * Some of these require message or data lookups and can be
2654 * expensive to check many times.
2656 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2657 if ( isset( $this->mVarCache
[$index] ) ) {
2658 return $this->mVarCache
[$index];
2662 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2663 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2666 global $wgLocaltimezone;
2667 if ( isset( $wgLocaltimezone ) ) {
2668 $oldtz = date_default_timezone_get();
2669 date_default_timezone_set( $wgLocaltimezone );
2672 $localTimestamp = date( 'YmdHis', $ts );
2673 $localMonth = date( 'm', $ts );
2674 $localMonth1 = date( 'n', $ts );
2675 $localMonthName = date( 'n', $ts );
2676 $localDay = date( 'j', $ts );
2677 $localDay2 = date( 'd', $ts );
2678 $localDayOfWeek = date( 'w', $ts );
2679 $localWeek = date( 'W', $ts );
2680 $localYear = date( 'Y', $ts );
2681 $localHour = date( 'H', $ts );
2682 if ( isset( $wgLocaltimezone ) ) {
2683 date_default_timezone_set( $oldtz );
2686 $pageLang = $this->getFunctionLang();
2689 case 'currentmonth':
2690 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2692 case 'currentmonth1':
2693 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2695 case 'currentmonthname':
2696 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2698 case 'currentmonthnamegen':
2699 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2701 case 'currentmonthabbrev':
2702 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2705 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2708 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2711 $value = $pageLang->formatNum( $localMonth );
2714 $value = $pageLang->formatNum( $localMonth1 );
2716 case 'localmonthname':
2717 $value = $pageLang->getMonthName( $localMonthName );
2719 case 'localmonthnamegen':
2720 $value = $pageLang->getMonthNameGen( $localMonthName );
2722 case 'localmonthabbrev':
2723 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2726 $value = $pageLang->formatNum( $localDay );
2729 $value = $pageLang->formatNum( $localDay2 );
2732 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2735 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2737 case 'fullpagename':
2738 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2740 case 'fullpagenamee':
2741 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2744 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2746 case 'subpagenamee':
2747 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2749 case 'basepagename':
2750 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2752 case 'basepagenamee':
2753 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2755 case 'talkpagename':
2756 if ( $this->mTitle
->canTalk() ) {
2757 $talkPage = $this->mTitle
->getTalkPage();
2758 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2763 case 'talkpagenamee':
2764 if ( $this->mTitle
->canTalk() ) {
2765 $talkPage = $this->mTitle
->getTalkPage();
2766 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2771 case 'subjectpagename':
2772 $subjPage = $this->mTitle
->getSubjectPage();
2773 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2775 case 'subjectpagenamee':
2776 $subjPage = $this->mTitle
->getSubjectPage();
2777 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2779 case 'pageid': // requested in bug 23427
2780 $pageid = $this->getTitle()->getArticleID();
2781 if( $pageid == 0 ) {
2782 # 0 means the page doesn't exist in the database,
2783 # which means the user is previewing a new page.
2784 # The vary-revision flag must be set, because the magic word
2785 # will have a different value once the page is saved.
2786 $this->mOutput
->setFlag( 'vary-revision' );
2787 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2789 $value = $pageid ?
$pageid : null;
2792 # Let the edit saving system know we should parse the page
2793 # *after* a revision ID has been assigned.
2794 $this->mOutput
->setFlag( 'vary-revision' );
2795 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2796 $value = $this->mRevisionId
;
2799 # Let the edit saving system know we should parse the page
2800 # *after* a revision ID has been assigned. This is for null edits.
2801 $this->mOutput
->setFlag( 'vary-revision' );
2802 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2803 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2805 case 'revisionday2':
2806 # Let the edit saving system know we should parse the page
2807 # *after* a revision ID has been assigned. This is for null edits.
2808 $this->mOutput
->setFlag( 'vary-revision' );
2809 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2810 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2812 case 'revisionmonth':
2813 # Let the edit saving system know we should parse the page
2814 # *after* a revision ID has been assigned. This is for null edits.
2815 $this->mOutput
->setFlag( 'vary-revision' );
2816 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2817 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2819 case 'revisionmonth1':
2820 # Let the edit saving system know we should parse the page
2821 # *after* a revision ID has been assigned. This is for null edits.
2822 $this->mOutput
->setFlag( 'vary-revision' );
2823 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2824 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2826 case 'revisionyear':
2827 # Let the edit saving system know we should parse the page
2828 # *after* a revision ID has been assigned. This is for null edits.
2829 $this->mOutput
->setFlag( 'vary-revision' );
2830 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2831 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2833 case 'revisiontimestamp':
2834 # Let the edit saving system know we should parse the page
2835 # *after* a revision ID has been assigned. This is for null edits.
2836 $this->mOutput
->setFlag( 'vary-revision' );
2837 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2838 $value = $this->getRevisionTimestamp();
2840 case 'revisionuser':
2841 # Let the edit saving system know we should parse the page
2842 # *after* a revision ID has been assigned. This is for null edits.
2843 $this->mOutput
->setFlag( 'vary-revision' );
2844 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2845 $value = $this->getRevisionUser();
2848 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2851 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2853 case 'namespacenumber':
2854 $value = $this->mTitle
->getNamespace();
2857 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2860 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2862 case 'subjectspace':
2863 $value = $this->mTitle
->getSubjectNsText();
2865 case 'subjectspacee':
2866 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2868 case 'currentdayname':
2869 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2872 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2875 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2878 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2881 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2882 # int to remove the padding
2883 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2886 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2888 case 'localdayname':
2889 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2892 $value = $pageLang->formatNum( $localYear, true );
2895 $value = $pageLang->time( $localTimestamp, false, false );
2898 $value = $pageLang->formatNum( $localHour, true );
2901 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2902 # int to remove the padding
2903 $value = $pageLang->formatNum( (int)$localWeek );
2906 $value = $pageLang->formatNum( $localDayOfWeek );
2908 case 'numberofarticles':
2909 $value = $pageLang->formatNum( SiteStats
::articles() );
2911 case 'numberoffiles':
2912 $value = $pageLang->formatNum( SiteStats
::images() );
2914 case 'numberofusers':
2915 $value = $pageLang->formatNum( SiteStats
::users() );
2917 case 'numberofactiveusers':
2918 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2920 case 'numberofpages':
2921 $value = $pageLang->formatNum( SiteStats
::pages() );
2923 case 'numberofadmins':
2924 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2926 case 'numberofedits':
2927 $value = $pageLang->formatNum( SiteStats
::edits() );
2929 case 'numberofviews':
2930 global $wgDisableCounters;
2931 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2933 case 'currenttimestamp':
2934 $value = wfTimestamp( TS_MW
, $ts );
2936 case 'localtimestamp':
2937 $value = $localTimestamp;
2939 case 'currentversion':
2940 $value = SpecialVersion
::getVersion();
2943 return $wgArticlePath;
2949 $serverParts = wfParseUrl( $wgServer );
2950 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2952 return $wgScriptPath;
2954 return $wgStylePath;
2955 case 'directionmark':
2956 return $pageLang->getDirMark();
2957 case 'contentlanguage':
2958 global $wgLanguageCode;
2959 return $wgLanguageCode;
2962 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2970 $this->mVarCache
[$index] = $value;
2977 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2981 function initialiseVariables() {
2982 wfProfileIn( __METHOD__
);
2983 $variableIDs = MagicWord
::getVariableIDs();
2984 $substIDs = MagicWord
::getSubstIDs();
2986 $this->mVariables
= new MagicWordArray( $variableIDs );
2987 $this->mSubstWords
= new MagicWordArray( $substIDs );
2988 wfProfileOut( __METHOD__
);
2992 * Preprocess some wikitext and return the document tree.
2993 * This is the ghost of replace_variables().
2995 * @param string $text The text to parse
2996 * @param $flags Integer: bitwise combination of:
2997 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2998 * included. Default is to assume a direct page view.
3000 * The generated DOM tree must depend only on the input text and the flags.
3001 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3003 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3004 * change in the DOM tree for a given text, must be passed through the section identifier
3005 * in the section edit link and thus back to extractSections().
3007 * The output of this function is currently only cached in process memory, but a persistent
3008 * cache may be implemented at a later date which takes further advantage of these strict
3009 * dependency requirements.
3015 function preprocessToDom( $text, $flags = 0 ) {
3016 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3021 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3027 public static function splitWhitespace( $s ) {
3028 $ltrimmed = ltrim( $s );
3029 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3030 $trimmed = rtrim( $ltrimmed );
3031 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3033 $w2 = substr( $ltrimmed, -$diff );
3037 return array( $w1, $trimmed, $w2 );
3041 * Replace magic variables, templates, and template arguments
3042 * with the appropriate text. Templates are substituted recursively,
3043 * taking care to avoid infinite loops.
3045 * Note that the substitution depends on value of $mOutputType:
3046 * self::OT_WIKI: only {{subst:}} templates
3047 * self::OT_PREPROCESS: templates but not extension tags
3048 * self::OT_HTML: all templates and extension tags
3050 * @param string $text the text to transform
3051 * @param $frame PPFrame Object describing the arguments passed to the template.
3052 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3053 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3054 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3059 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3060 # Is there any text? Also, Prevent too big inclusions!
3061 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3064 wfProfileIn( __METHOD__
);
3066 if ( $frame === false ) {
3067 $frame = $this->getPreprocessor()->newFrame();
3068 } elseif ( !( $frame instanceof PPFrame
) ) {
3069 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3070 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3073 $dom = $this->preprocessToDom( $text );
3074 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3075 $text = $frame->expand( $dom, $flags );
3077 wfProfileOut( __METHOD__
);
3082 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3084 * @param $args array
3088 static function createAssocArgs( $args ) {
3089 $assocArgs = array();
3091 foreach ( $args as $arg ) {
3092 $eqpos = strpos( $arg, '=' );
3093 if ( $eqpos === false ) {
3094 $assocArgs[$index++
] = $arg;
3096 $name = trim( substr( $arg, 0, $eqpos ) );
3097 $value = trim( substr( $arg, $eqpos +
1 ) );
3098 if ( $value === false ) {
3101 if ( $name !== false ) {
3102 $assocArgs[$name] = $value;
3111 * Warn the user when a parser limitation is reached
3112 * Will warn at most once the user per limitation type
3114 * @param string $limitationType should be one of:
3115 * 'expensive-parserfunction' (corresponding messages:
3116 * 'expensive-parserfunction-warning',
3117 * 'expensive-parserfunction-category')
3118 * 'post-expand-template-argument' (corresponding messages:
3119 * 'post-expand-template-argument-warning',
3120 * 'post-expand-template-argument-category')
3121 * 'post-expand-template-inclusion' (corresponding messages:
3122 * 'post-expand-template-inclusion-warning',
3123 * 'post-expand-template-inclusion-category')
3124 * @param int|null $current Current value
3125 * @param int|null $max Maximum allowed, when an explicit limit has been
3126 * exceeded, provide the values (optional)
3128 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3129 # does no harm if $current and $max are present but are unnecessary for the message
3130 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3131 ->inContentLanguage()->escaped();
3132 $this->mOutput
->addWarning( $warning );
3133 $this->addTrackingCategory( "$limitationType-category" );
3137 * Return the text of a template, after recursively
3138 * replacing any variables or templates within the template.
3140 * @param array $piece the parts of the template
3141 * $piece['title']: the title, i.e. the part before the |
3142 * $piece['parts']: the parameter array
3143 * $piece['lineStart']: whether the brace was at the start of a line
3144 * @param $frame PPFrame The current frame, contains template arguments
3145 * @throws MWException
3146 * @return String: the text of the template
3149 function braceSubstitution( $piece, $frame ) {
3150 wfProfileIn( __METHOD__
);
3151 wfProfileIn( __METHOD__
. '-setup' );
3154 $found = false; # $text has been filled
3155 $nowiki = false; # wiki markup in $text should be escaped
3156 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3157 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3158 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3159 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3161 # Title object, where $text came from
3164 # $part1 is the bit before the first |, and must contain only title characters.
3165 # Various prefixes will be stripped from it later.
3166 $titleWithSpaces = $frame->expand( $piece['title'] );
3167 $part1 = trim( $titleWithSpaces );
3170 # Original title text preserved for various purposes
3171 $originalTitle = $part1;
3173 # $args is a list of argument nodes, starting from index 0, not including $part1
3174 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3175 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3176 wfProfileOut( __METHOD__
. '-setup' );
3178 $titleProfileIn = null; // profile templates
3181 wfProfileIn( __METHOD__
. '-modifiers' );
3184 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3186 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3187 # Decide whether to expand template or keep wikitext as-is.
3188 if ( $this->ot
['wiki'] ) {
3189 if ( $substMatch === false ) {
3190 $literal = true; # literal when in PST with no prefix
3192 $literal = false; # expand when in PST with subst: or safesubst:
3195 if ( $substMatch == 'subst' ) {
3196 $literal = true; # literal when not in PST with plain subst:
3198 $literal = false; # expand when not in PST with safesubst: or no prefix
3202 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3209 if ( !$found && $args->getLength() == 0 ) {
3210 $id = $this->mVariables
->matchStartToEnd( $part1 );
3211 if ( $id !== false ) {
3212 $text = $this->getVariableValue( $id, $frame );
3213 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3214 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3220 # MSG, MSGNW and RAW
3223 $mwMsgnw = MagicWord
::get( 'msgnw' );
3224 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3227 # Remove obsolete MSG:
3228 $mwMsg = MagicWord
::get( 'msg' );
3229 $mwMsg->matchStartAndRemove( $part1 );
3233 $mwRaw = MagicWord
::get( 'raw' );
3234 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3235 $forceRawInterwiki = true;
3238 wfProfileOut( __METHOD__
. '-modifiers' );
3242 wfProfileIn( __METHOD__
. '-pfunc' );
3244 $colonPos = strpos( $part1, ':' );
3245 if ( $colonPos !== false ) {
3246 $func = substr( $part1, 0, $colonPos );
3247 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3248 for ( $i = 0; $i < $args->getLength(); $i++
) {
3249 $funcArgs[] = $args->item( $i );
3252 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3253 } catch ( Exception
$ex ) {
3254 wfProfileOut( __METHOD__
. '-pfunc' );
3255 wfProfileOut( __METHOD__
);
3259 # The interface for parser functions allows for extracting
3260 # flags into the local scope. Extract any forwarded flags
3264 wfProfileOut( __METHOD__
. '-pfunc' );
3267 # Finish mangling title and then check for loops.
3268 # Set $title to a Title object and $titleText to the PDBK
3271 # Split the title into page and subpage
3273 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3274 if ( $subpage !== '' ) {
3275 $ns = $this->mTitle
->getNamespace();
3277 $title = Title
::newFromText( $part1, $ns );
3279 $titleText = $title->getPrefixedText();
3280 # Check for language variants if the template is not found
3281 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3282 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3284 # Do recursion depth check
3285 $limit = $this->mOptions
->getMaxTemplateDepth();
3286 if ( $frame->depth
>= $limit ) {
3288 $text = '<span class="error">'
3289 . wfMessage( 'parser-template-recursion-depth-warning' )
3290 ->numParams( $limit )->inContentLanguage()->text()
3296 # Load from database
3297 if ( !$found && $title ) {
3298 if ( !Profiler
::instance()->isPersistent() ) {
3299 # Too many unique items can kill profiling DBs/collectors
3300 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBkey();
3301 wfProfileIn( $titleProfileIn ); // template in
3303 wfProfileIn( __METHOD__
. '-loadtpl' );
3304 if ( !$title->isExternal() ) {
3305 if ( $title->isSpecialPage()
3306 && $this->mOptions
->getAllowSpecialInclusion()
3307 && $this->ot
['html'] )
3309 // Pass the template arguments as URL parameters.
3310 // "uselang" will have no effect since the Language object
3311 // is forced to the one defined in ParserOptions.
3312 $pageArgs = array();
3313 for ( $i = 0; $i < $args->getLength(); $i++
) {
3314 $bits = $args->item( $i )->splitArg();
3315 if ( strval( $bits['index'] ) === '' ) {
3316 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3317 $value = trim( $frame->expand( $bits['value'] ) );
3318 $pageArgs[$name] = $value;
3322 // Create a new context to execute the special page
3323 $context = new RequestContext
;
3324 $context->setTitle( $title );
3325 $context->setRequest( new FauxRequest( $pageArgs ) );
3326 $context->setUser( $this->getUser() );
3327 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3328 $ret = SpecialPageFactory
::capturePath( $title, $context );
3330 $text = $context->getOutput()->getHTML();
3331 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3334 $this->disableCache();
3336 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3337 $found = false; # access denied
3338 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3340 list( $text, $title ) = $this->getTemplateDom( $title );
3341 if ( $text !== false ) {
3347 # If the title is valid but undisplayable, make a link to it
3348 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3349 $text = "[[:$titleText]]";
3352 } elseif ( $title->isTrans() ) {
3353 # Interwiki transclusion
3354 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3355 $text = $this->interwikiTransclude( $title, 'render' );
3358 $text = $this->interwikiTransclude( $title, 'raw' );
3359 # Preprocess it like a template
3360 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3366 # Do infinite loop check
3367 # This has to be done after redirect resolution to avoid infinite loops via redirects
3368 if ( !$frame->loopCheck( $title ) ) {
3370 $text = '<span class="error">'
3371 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3373 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3375 wfProfileOut( __METHOD__
. '-loadtpl' );
3378 # If we haven't found text to substitute by now, we're done
3379 # Recover the source wikitext and return it
3381 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3382 if ( $titleProfileIn ) {
3383 wfProfileOut( $titleProfileIn ); // template out
3385 wfProfileOut( __METHOD__
);
3386 return array( 'object' => $text );
3389 # Expand DOM-style return values in a child frame
3390 if ( $isChildObj ) {
3391 # Clean up argument array
3392 $newFrame = $frame->newChild( $args, $title );
3395 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3396 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3397 # Expansion is eligible for the empty-frame cache
3398 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3399 $text = $this->mTplExpandCache
[$titleText];
3401 $text = $newFrame->expand( $text );
3402 $this->mTplExpandCache
[$titleText] = $text;
3405 # Uncached expansion
3406 $text = $newFrame->expand( $text );
3409 if ( $isLocalObj && $nowiki ) {
3410 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3411 $isLocalObj = false;
3414 if ( $titleProfileIn ) {
3415 wfProfileOut( $titleProfileIn ); // template out
3418 # Replace raw HTML by a placeholder
3420 $text = $this->insertStripItem( $text );
3421 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3422 # Escape nowiki-style return values
3423 $text = wfEscapeWikiText( $text );
3424 } elseif ( is_string( $text )
3425 && !$piece['lineStart']
3426 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3428 # Bug 529: if the template begins with a table or block-level
3429 # element, it should be treated as beginning a new line.
3430 # This behavior is somewhat controversial.
3431 $text = "\n" . $text;
3434 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3435 # Error, oversize inclusion
3436 if ( $titleText !== false ) {
3437 # Make a working, properly escaped link if possible (bug 23588)
3438 $text = "[[:$titleText]]";
3440 # This will probably not be a working link, but at least it may
3441 # provide some hint of where the problem is
3442 preg_replace( '/^:/', '', $originalTitle );
3443 $text = "[[:$originalTitle]]";
3445 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3446 $this->limitationWarn( 'post-expand-template-inclusion' );
3449 if ( $isLocalObj ) {
3450 $ret = array( 'object' => $text );
3452 $ret = array( 'text' => $text );
3455 wfProfileOut( __METHOD__
);
3460 * Call a parser function and return an array with text and flags.
3462 * The returned array will always contain a boolean 'found', indicating
3463 * whether the parser function was found or not. It may also contain the
3465 * text: string|object, resulting wikitext or PP DOM object
3466 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3467 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3468 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3469 * nowiki: bool, wiki markup in $text should be escaped
3472 * @param $frame PPFrame The current frame, contains template arguments
3473 * @param $function string Function name
3474 * @param $args array Arguments to the function
3477 public function callParserFunction( $frame, $function, array $args = array() ) {
3480 wfProfileIn( __METHOD__
);
3482 # Case sensitive functions
3483 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3484 $function = $this->mFunctionSynonyms
[1][$function];
3486 # Case insensitive functions
3487 $function = $wgContLang->lc( $function );
3488 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3489 $function = $this->mFunctionSynonyms
[0][$function];
3491 wfProfileOut( __METHOD__
);
3492 return array( 'found' => false );
3496 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3497 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3499 # Workaround for PHP bug 35229 and similar
3500 if ( !is_callable( $callback ) ) {
3501 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3502 wfProfileOut( __METHOD__
);
3503 throw new MWException( "Tag hook for $function is not callable\n" );
3506 $allArgs = array( &$this );
3507 if ( $flags & SFH_OBJECT_ARGS
) {
3508 # Convert arguments to PPNodes and collect for appending to $allArgs
3509 $funcArgs = array();
3510 foreach ( $args as $k => $v ) {
3511 if ( $v instanceof PPNode ||
$k === 0 ) {
3514 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3518 # Add a frame parameter, and pass the arguments as an array
3519 $allArgs[] = $frame;
3520 $allArgs[] = $funcArgs;
3522 # Convert arguments to plain text and append to $allArgs
3523 foreach ( $args as $k => $v ) {
3524 if ( $v instanceof PPNode
) {
3525 $allArgs[] = trim( $frame->expand( $v ) );
3526 } elseif ( is_int( $k ) && $k >= 0 ) {
3527 $allArgs[] = trim( $v );
3529 $allArgs[] = trim( "$k=$v" );
3534 $result = call_user_func_array( $callback, $allArgs );
3536 # The interface for function hooks allows them to return a wikitext
3537 # string or an array containing the string and any flags. This mungs
3538 # things around to match what this method should return.
3539 if ( !is_array( $result ) ) {
3545 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3546 $result['text'] = $result[0];
3548 unset( $result[0] );
3555 $preprocessFlags = 0;
3556 if ( isset( $result['noparse'] ) ) {
3557 $noparse = $result['noparse'];
3559 if ( isset( $result['preprocessFlags'] ) ) {
3560 $preprocessFlags = $result['preprocessFlags'];
3564 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3565 $result['isChildObj'] = true;
3567 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3568 wfProfileOut( __METHOD__
);
3574 * Get the semi-parsed DOM representation of a template with a given title,
3575 * and its redirect destination title. Cached.
3577 * @param $title Title
3581 function getTemplateDom( $title ) {
3582 $cacheTitle = $title;
3583 $titleText = $title->getPrefixedDBkey();
3585 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3586 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3587 $title = Title
::makeTitle( $ns, $dbk );
3588 $titleText = $title->getPrefixedDBkey();
3590 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3591 return array( $this->mTplDomCache
[$titleText], $title );
3594 # Cache miss, go to the database
3595 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3597 if ( $text === false ) {
3598 $this->mTplDomCache
[$titleText] = false;
3599 return array( false, $title );
3602 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3603 $this->mTplDomCache
[$titleText] = $dom;
3605 if ( !$title->equals( $cacheTitle ) ) {
3606 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3607 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3610 return array( $dom, $title );
3614 * Fetch the unparsed text of a template and register a reference to it.
3615 * @param Title $title
3616 * @return Array ( string or false, Title )
3618 function fetchTemplateAndTitle( $title ) {
3619 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3620 $stuff = call_user_func( $templateCb, $title, $this );
3621 $text = $stuff['text'];
3622 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3623 if ( isset( $stuff['deps'] ) ) {
3624 foreach ( $stuff['deps'] as $dep ) {
3625 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3628 return array( $text, $finalTitle );
3632 * Fetch the unparsed text of a template and register a reference to it.
3633 * @param Title $title
3634 * @return mixed string or false
3636 function fetchTemplate( $title ) {
3637 $rv = $this->fetchTemplateAndTitle( $title );
3642 * Static function to get a template
3643 * Can be overridden via ParserOptions::setTemplateCallback().
3645 * @param $title Title
3646 * @param $parser Parser
3650 static function statelessFetchTemplate( $title, $parser = false ) {
3651 $text = $skip = false;
3652 $finalTitle = $title;
3655 # Loop to fetch the article, with up to 1 redirect
3656 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3657 # Give extensions a chance to select the revision instead
3658 $id = false; # Assume current
3659 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3660 array( $parser, $title, &$skip, &$id ) );
3666 'page_id' => $title->getArticleID(),
3673 ? Revision
::newFromId( $id )
3674 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3675 $rev_id = $rev ?
$rev->getId() : 0;
3676 # If there is no current revision, there is no page
3677 if ( $id === false && !$rev ) {
3678 $linkCache = LinkCache
::singleton();
3679 $linkCache->addBadLinkObj( $title );
3684 'page_id' => $title->getArticleID(),
3685 'rev_id' => $rev_id );
3686 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3687 # We fetched a rev from a different title; register it too...
3689 'title' => $rev->getTitle(),
3690 'page_id' => $rev->getPage(),
3691 'rev_id' => $rev_id );
3695 $content = $rev->getContent();
3696 $text = $content ?
$content->getWikitextForTransclusion() : null;
3698 if ( $text === false ||
$text === null ) {
3702 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3704 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3705 if ( !$message->exists() ) {
3709 $content = $message->content();
3710 $text = $message->plain();
3718 $finalTitle = $title;
3719 $title = $content->getRedirectTarget();
3723 'finalTitle' => $finalTitle,
3728 * Fetch a file and its title and register a reference to it.
3729 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3730 * @param Title $title
3731 * @param array $options Array of options to RepoGroup::findFile
3734 function fetchFile( $title, $options = array() ) {
3735 $res = $this->fetchFileAndTitle( $title, $options );
3740 * Fetch a file and its title and register a reference to it.
3741 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3742 * @param Title $title
3743 * @param array $options Array of options to RepoGroup::findFile
3744 * @return Array ( File or false, Title of file )
3746 function fetchFileAndTitle( $title, $options = array() ) {
3747 if ( isset( $options['broken'] ) ) {
3748 $file = false; // broken thumbnail forced by hook
3749 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3750 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3751 } else { // get by (name,timestamp)
3752 $file = wfFindFile( $title, $options );
3754 $time = $file ?
$file->getTimestamp() : false;
3755 $sha1 = $file ?
$file->getSha1() : false;
3756 # Register the file as a dependency...
3757 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3758 if ( $file && !$title->equals( $file->getTitle() ) ) {
3759 # Update fetched file title
3760 $title = $file->getTitle();
3761 if ( is_null( $file->getRedirectedTitle() ) ) {
3762 # This file was not a redirect, but the title does not match.
3763 # Register under the new name because otherwise the link will
3765 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3768 return array( $file, $title );
3772 * Transclude an interwiki link.
3774 * @param $title Title
3779 function interwikiTransclude( $title, $action ) {
3780 global $wgEnableScaryTranscluding;
3782 if ( !$wgEnableScaryTranscluding ) {
3783 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3786 $url = $title->getFullURL( "action=$action" );
3788 if ( strlen( $url ) > 255 ) {
3789 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3791 return $this->fetchScaryTemplateMaybeFromCache( $url );
3795 * @param $url string
3796 * @return Mixed|String
3798 function fetchScaryTemplateMaybeFromCache( $url ) {
3799 global $wgTranscludeCacheExpiry;
3800 $dbr = wfGetDB( DB_SLAVE
);
3801 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3802 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3803 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3805 return $obj->tc_contents
;
3808 $req = MWHttpRequest
::factory( $url );
3809 $status = $req->execute(); // Status object
3810 if ( $status->isOK() ) {
3811 $text = $req->getContent();
3812 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3813 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3815 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3818 $dbw = wfGetDB( DB_MASTER
);
3819 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3821 'tc_time' => $dbw->timestamp( time() ),
3822 'tc_contents' => $text
3828 * Triple brace replacement -- used for template arguments
3831 * @param $piece array
3832 * @param $frame PPFrame
3836 function argSubstitution( $piece, $frame ) {
3837 wfProfileIn( __METHOD__
);
3840 $parts = $piece['parts'];
3841 $nameWithSpaces = $frame->expand( $piece['title'] );
3842 $argName = trim( $nameWithSpaces );
3844 $text = $frame->getArgument( $argName );
3845 if ( $text === false && $parts->getLength() > 0
3849 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3852 # No match in frame, use the supplied default
3853 $object = $parts->item( 0 )->getChildren();
3855 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3856 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3857 $this->limitationWarn( 'post-expand-template-argument' );
3860 if ( $text === false && $object === false ) {
3862 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3864 if ( $error !== false ) {
3867 if ( $object !== false ) {
3868 $ret = array( 'object' => $object );
3870 $ret = array( 'text' => $text );
3873 wfProfileOut( __METHOD__
);
3878 * Return the text to be used for a given extension tag.
3879 * This is the ghost of strip().
3881 * @param array $params Associative array of parameters:
3882 * name PPNode for the tag name
3883 * attr PPNode for unparsed text where tag attributes are thought to be
3884 * attributes Optional associative array of parsed attributes
3885 * inner Contents of extension element
3886 * noClose Original text did not have a close tag
3887 * @param $frame PPFrame
3889 * @throws MWException
3892 function extensionSubstitution( $params, $frame ) {
3893 $name = $frame->expand( $params['name'] );
3894 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3895 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3896 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3898 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3899 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3900 if ( $isFunctionTag ) {
3901 $markerType = 'none';
3903 $markerType = 'general';
3905 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3906 $name = strtolower( $name );
3907 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3908 if ( isset( $params['attributes'] ) ) {
3909 $attributes = $attributes +
$params['attributes'];
3912 if ( isset( $this->mTagHooks
[$name] ) ) {
3913 # Workaround for PHP bug 35229 and similar
3914 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3915 throw new MWException( "Tag hook for $name is not callable\n" );
3917 $output = call_user_func_array( $this->mTagHooks
[$name],
3918 array( $content, $attributes, $this, $frame ) );
3919 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3920 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3921 if ( !is_callable( $callback ) ) {
3922 throw new MWException( "Tag hook for $name is not callable\n" );
3925 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3927 $output = '<span class="error">Invalid tag extension name: ' .
3928 htmlspecialchars( $name ) . '</span>';
3931 if ( is_array( $output ) ) {
3932 # Extract flags to local scope (to override $markerType)
3934 $output = $flags[0];
3939 if ( is_null( $attrText ) ) {
3942 if ( isset( $params['attributes'] ) ) {
3943 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3944 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3945 htmlspecialchars( $attrValue ) . '"';
3948 if ( $content === null ) {
3949 $output = "<$name$attrText/>";
3951 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3952 $output = "<$name$attrText>$content$close";
3956 if ( $markerType === 'none' ) {
3958 } elseif ( $markerType === 'nowiki' ) {
3959 $this->mStripState
->addNoWiki( $marker, $output );
3960 } elseif ( $markerType === 'general' ) {
3961 $this->mStripState
->addGeneral( $marker, $output );
3963 throw new MWException( __METHOD__
. ': invalid marker type' );
3969 * Increment an include size counter
3971 * @param string $type the type of expansion
3972 * @param $size Integer: the size of the text
3973 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3975 function incrementIncludeSize( $type, $size ) {
3976 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3979 $this->mIncludeSizes
[$type] +
= $size;
3985 * Increment the expensive function count
3987 * @return Boolean: false if the limit has been exceeded
3989 function incrementExpensiveFunctionCount() {
3990 $this->mExpensiveFunctionCount++
;
3991 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3995 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3996 * Fills $this->mDoubleUnderscores, returns the modified text
3998 * @param $text string
4002 function doDoubleUnderscore( $text ) {
4003 wfProfileIn( __METHOD__
);
4005 # The position of __TOC__ needs to be recorded
4006 $mw = MagicWord
::get( 'toc' );
4007 if ( $mw->match( $text ) ) {
4008 $this->mShowToc
= true;
4009 $this->mForceTocPosition
= true;
4011 # Set a placeholder. At the end we'll fill it in with the TOC.
4012 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4014 # Only keep the first one.
4015 $text = $mw->replace( '', $text );
4018 # Now match and remove the rest of them
4019 $mwa = MagicWord
::getDoubleUnderscoreArray();
4020 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4022 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4023 $this->mOutput
->mNoGallery
= true;
4025 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4026 $this->mShowToc
= false;
4028 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4029 $this->addTrackingCategory( 'hidden-category-category' );
4031 # (bug 8068) Allow control over whether robots index a page.
4033 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4034 # is not desirable, the last one on the page should win.
4035 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4036 $this->mOutput
->setIndexPolicy( 'noindex' );
4037 $this->addTrackingCategory( 'noindex-category' );
4039 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4040 $this->mOutput
->setIndexPolicy( 'index' );
4041 $this->addTrackingCategory( 'index-category' );
4044 # Cache all double underscores in the database
4045 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4046 $this->mOutput
->setProperty( $key, '' );
4049 wfProfileOut( __METHOD__
);
4054 * Add a tracking category, getting the title from a system message,
4055 * or print a debug message if the title is invalid.
4057 * @param string $msg message key
4058 * @return Boolean: whether the addition was successful
4060 public function addTrackingCategory( $msg ) {
4061 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4062 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4065 // Important to parse with correct title (bug 31469)
4066 $cat = wfMessage( $msg )
4067 ->title( $this->getTitle() )
4068 ->inContentLanguage()
4071 # Allow tracking categories to be disabled by setting them to "-"
4072 if ( $cat === '-' ) {
4076 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4077 if ( $containerCategory ) {
4078 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4081 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4087 * This function accomplishes several tasks:
4088 * 1) Auto-number headings if that option is enabled
4089 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4090 * 3) Add a Table of contents on the top for users who have enabled the option
4091 * 4) Auto-anchor headings
4093 * It loops through all headlines, collects the necessary data, then splits up the
4094 * string and re-inserts the newly formatted headlines.
4096 * @param $text String
4097 * @param string $origText original, untouched wikitext
4098 * @param $isMain Boolean
4099 * @return mixed|string
4102 function formatHeadings( $text, $origText, $isMain = true ) {
4103 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4105 # Inhibit editsection links if requested in the page
4106 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4107 $maybeShowEditLink = $showEditLink = false;
4109 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4110 $showEditLink = $this->mOptions
->getEditSection();
4112 if ( $showEditLink ) {
4113 $this->mOutput
->setEditSectionTokens( true );
4116 # Get all headlines for numbering them and adding funky stuff like [edit]
4117 # links - this is for later, but we need the number of headlines right now
4119 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4121 # if there are fewer than 4 headlines in the article, do not show TOC
4122 # unless it's been explicitly enabled.
4123 $enoughToc = $this->mShowToc
&&
4124 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4126 # Allow user to stipulate that a page should have a "new section"
4127 # link added via __NEWSECTIONLINK__
4128 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4129 $this->mOutput
->setNewSection( true );
4132 # Allow user to remove the "new section"
4133 # link via __NONEWSECTIONLINK__
4134 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4135 $this->mOutput
->hideNewSection( true );
4138 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4139 # override above conditions and always show TOC above first header
4140 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4141 $this->mShowToc
= true;
4149 # Ugh .. the TOC should have neat indentation levels which can be
4150 # passed to the skin functions. These are determined here
4154 $sublevelCount = array();
4155 $levelCount = array();
4160 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4161 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4162 $oldType = $this->mOutputType
;
4163 $this->setOutputType( self
::OT_WIKI
);
4164 $frame = $this->getPreprocessor()->newFrame();
4165 $root = $this->preprocessToDom( $origText );
4166 $node = $root->getFirstChild();
4171 foreach ( $matches[3] as $headline ) {
4172 $isTemplate = false;
4174 $sectionIndex = false;
4176 $markerMatches = array();
4177 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4178 $serial = $markerMatches[1];
4179 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4180 $isTemplate = ( $titleText != $baseTitleText );
4181 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4185 $prevlevel = $level;
4187 $level = $matches[1][$headlineCount];
4189 if ( $level > $prevlevel ) {
4190 # Increase TOC level
4192 $sublevelCount[$toclevel] = 0;
4193 if ( $toclevel < $wgMaxTocLevel ) {
4194 $prevtoclevel = $toclevel;
4195 $toc .= Linker
::tocIndent();
4198 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4199 # Decrease TOC level, find level to jump to
4201 for ( $i = $toclevel; $i > 0; $i-- ) {
4202 if ( $levelCount[$i] == $level ) {
4203 # Found last matching level
4206 } elseif ( $levelCount[$i] < $level ) {
4207 # Found first matching level below current level
4215 if ( $toclevel < $wgMaxTocLevel ) {
4216 if ( $prevtoclevel < $wgMaxTocLevel ) {
4217 # Unindent only if the previous toc level was shown :p
4218 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4219 $prevtoclevel = $toclevel;
4221 $toc .= Linker
::tocLineEnd();
4225 # No change in level, end TOC line
4226 if ( $toclevel < $wgMaxTocLevel ) {
4227 $toc .= Linker
::tocLineEnd();
4231 $levelCount[$toclevel] = $level;
4233 # count number of headlines for each level
4234 $sublevelCount[$toclevel]++
;
4236 for( $i = 1; $i <= $toclevel; $i++
) {
4237 if ( !empty( $sublevelCount[$i] ) ) {
4241 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4246 # The safe header is a version of the header text safe to use for links
4248 # Remove link placeholders by the link text.
4249 # <!--LINK number-->
4251 # link text with suffix
4252 # Do this before unstrip since link text can contain strip markers
4253 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4255 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4256 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4258 # Strip out HTML (first regex removes any tag not allowed)
4260 # * <sup> and <sub> (bug 8393)
4263 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4265 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4266 # to allow setting directionality in toc items.
4267 $tocline = preg_replace(
4268 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4269 array( '', '<$1>' ),
4272 $tocline = trim( $tocline );
4274 # For the anchor, strip out HTML-y stuff period
4275 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4276 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4278 # Save headline for section edit hint before it's escaped
4279 $headlineHint = $safeHeadline;
4281 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4282 # For reverse compatibility, provide an id that's
4283 # HTML4-compatible, like we used to.
4285 # It may be worth noting, academically, that it's possible for
4286 # the legacy anchor to conflict with a non-legacy headline
4287 # anchor on the page. In this case likely the "correct" thing
4288 # would be to either drop the legacy anchors or make sure
4289 # they're numbered first. However, this would require people
4290 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4291 # manually, so let's not bother worrying about it.
4292 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4293 array( 'noninitial', 'legacy' ) );
4294 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4296 if ( $legacyHeadline == $safeHeadline ) {
4297 # No reason to have both (in fact, we can't)
4298 $legacyHeadline = false;
4301 $legacyHeadline = false;
4302 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4306 # HTML names must be case-insensitively unique (bug 10721).
4307 # This does not apply to Unicode characters per
4308 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4309 # @todo FIXME: We may be changing them depending on the current locale.
4310 $arrayKey = strtolower( $safeHeadline );
4311 if ( $legacyHeadline === false ) {
4312 $legacyArrayKey = false;
4314 $legacyArrayKey = strtolower( $legacyHeadline );
4317 # count how many in assoc. array so we can track dupes in anchors
4318 if ( isset( $refers[$arrayKey] ) ) {
4319 $refers[$arrayKey]++
;
4321 $refers[$arrayKey] = 1;
4323 if ( isset( $refers[$legacyArrayKey] ) ) {
4324 $refers[$legacyArrayKey]++
;
4326 $refers[$legacyArrayKey] = 1;
4329 # Don't number the heading if it is the only one (looks silly)
4330 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4331 # the two are different if the line contains a link
4332 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4335 # Create the anchor for linking from the TOC to the section
4336 $anchor = $safeHeadline;
4337 $legacyAnchor = $legacyHeadline;
4338 if ( $refers[$arrayKey] > 1 ) {
4339 $anchor .= '_' . $refers[$arrayKey];
4341 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4342 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4344 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4345 $toc .= Linker
::tocLine( $anchor, $tocline,
4346 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4349 # Add the section to the section tree
4350 # Find the DOM node for this header
4351 while ( $node && !$isTemplate ) {
4352 if ( $node->getName() === 'h' ) {
4353 $bits = $node->splitHeading();
4354 if ( $bits['i'] == $sectionIndex ) {
4358 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4359 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4360 $node = $node->getNextSibling();
4363 'toclevel' => $toclevel,
4366 'number' => $numbering,
4367 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4368 'fromtitle' => $titleText,
4369 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4370 'anchor' => $anchor,
4373 # give headline the correct <h#> tag
4374 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4375 // Output edit section links as markers with styles that can be customized by skins
4376 if ( $isTemplate ) {
4377 # Put a T flag in the section identifier, to indicate to extractSections()
4378 # that sections inside <includeonly> should be counted.
4379 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4381 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4383 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4384 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4385 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4386 // so we don't have to worry about a user trying to input one of these markers directly.
4387 // We use a page and section attribute to stop the language converter from converting these important bits
4388 // of data, but put the headline hint inside a content block because the language converter is supposed to
4389 // be able to convert that piece of data.
4390 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4391 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4392 if ( isset( $editlinkArgs[2] ) ) {
4393 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4400 $head[$headlineCount] = Linker
::makeHeadline( $level,
4401 $matches['attrib'][$headlineCount], $anchor, $headline,
4402 $editlink, $legacyAnchor );
4407 $this->setOutputType( $oldType );
4409 # Never ever show TOC if no headers
4410 if ( $numVisible < 1 ) {
4415 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4416 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4418 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4419 $this->mOutput
->setTOCHTML( $toc );
4423 $this->mOutput
->setSections( $tocraw );
4426 # split up and insert constructed headlines
4427 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4430 // build an array of document sections
4431 $sections = array();
4432 foreach ( $blocks as $block ) {
4433 // $head is zero-based, sections aren't.
4434 if ( empty( $head[$i - 1] ) ) {
4435 $sections[$i] = $block;
4437 $sections[$i] = $head[$i - 1] . $block;
4441 * Send a hook, one per section.
4442 * The idea here is to be able to make section-level DIVs, but to do so in a
4443 * lower-impact, more correct way than r50769
4446 * $section : the section number
4447 * &$sectionContent : ref to the content of the section
4448 * $showEditLinks : boolean describing whether this section has an edit link
4450 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4455 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4456 // append the TOC at the beginning
4457 // Top anchor now in skin
4458 $sections[0] = $sections[0] . $toc . "\n";
4461 $full .= join( '', $sections );
4463 if ( $this->mForceTocPosition
) {
4464 return str_replace( '<!--MWTOC-->', $toc, $full );
4471 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4472 * conversion, substitting signatures, {{subst:}} templates, etc.
4474 * @param string $text the text to transform
4475 * @param $title Title: the Title object for the current article
4476 * @param $user User: the User object describing the current user
4477 * @param $options ParserOptions: parsing options
4478 * @param $clearState Boolean: whether to clear the parser state first
4479 * @return String: the altered wiki markup
4481 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4482 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4483 $this->setUser( $user );
4488 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4489 if( $options->getPreSaveTransform() ) {
4490 $text = $this->pstPass2( $text, $user );
4492 $text = $this->mStripState
->unstripBoth( $text );
4494 $this->setUser( null ); #Reset
4500 * Pre-save transform helper function
4503 * @param $text string
4508 function pstPass2( $text, $user ) {
4509 global $wgContLang, $wgLocaltimezone;
4511 # Note: This is the timestamp saved as hardcoded wikitext to
4512 # the database, we use $wgContLang here in order to give
4513 # everyone the same signature and use the default one rather
4514 # than the one selected in each user's preferences.
4515 # (see also bug 12815)
4516 $ts = $this->mOptions
->getTimestamp();
4517 if ( isset( $wgLocaltimezone ) ) {
4518 $tz = $wgLocaltimezone;
4520 $tz = date_default_timezone_get();
4523 $unixts = wfTimestamp( TS_UNIX
, $ts );
4524 $oldtz = date_default_timezone_get();
4525 date_default_timezone_set( $tz );
4526 $ts = date( 'YmdHis', $unixts );
4527 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4529 # Allow translation of timezones through wiki. date() can return
4530 # whatever crap the system uses, localised or not, so we cannot
4531 # ship premade translations.
4532 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4533 $msg = wfMessage( $key )->inContentLanguage();
4534 if ( $msg->exists() ) {
4535 $tzMsg = $msg->text();
4538 date_default_timezone_set( $oldtz );
4540 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4542 # Variable replacement
4543 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4544 $text = $this->replaceVariables( $text );
4546 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4547 # which may corrupt this parser instance via its wfMessage()->text() call-
4550 $sigText = $this->getUserSig( $user );
4551 $text = strtr( $text, array(
4553 '~~~~' => "$sigText $d",
4557 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4558 $tc = '[' . Title
::legalChars() . ']';
4559 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4561 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4562 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4563 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4564 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4566 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4567 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4568 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4569 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4571 $t = $this->mTitle
->getText();
4573 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4574 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4575 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4576 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4578 # if there's no context, don't bother duplicating the title
4579 $text = preg_replace( $p2, '[[\\1]]', $text );
4582 # Trim trailing whitespace
4583 $text = rtrim( $text );
4589 * Fetch the user's signature text, if any, and normalize to
4590 * validated, ready-to-insert wikitext.
4591 * If you have pre-fetched the nickname or the fancySig option, you can
4592 * specify them here to save a database query.
4593 * Do not reuse this parser instance after calling getUserSig(),
4594 * as it may have changed if it's the $wgParser.
4597 * @param string|bool $nickname nickname to use or false to use user's default nickname
4598 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4599 * or null to use default value
4602 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4603 global $wgMaxSigChars;
4605 $username = $user->getName();
4607 # If not given, retrieve from the user object.
4608 if ( $nickname === false )
4609 $nickname = $user->getOption( 'nickname' );
4611 if ( is_null( $fancySig ) ) {
4612 $fancySig = $user->getBoolOption( 'fancysig' );
4615 $nickname = $nickname == null ?
$username : $nickname;
4617 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4618 $nickname = $username;
4619 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4620 } elseif ( $fancySig !== false ) {
4621 # Sig. might contain markup; validate this
4622 if ( $this->validateSig( $nickname ) !== false ) {
4623 # Validated; clean up (if needed) and return it
4624 return $this->cleanSig( $nickname, true );
4626 # Failed to validate; fall back to the default
4627 $nickname = $username;
4628 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4632 # Make sure nickname doesnt get a sig in a sig
4633 $nickname = self
::cleanSigInSig( $nickname );
4635 # If we're still here, make it a link to the user page
4636 $userText = wfEscapeWikiText( $username );
4637 $nickText = wfEscapeWikiText( $nickname );
4638 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4640 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4644 * Check that the user's signature contains no bad XML
4646 * @param $text String
4647 * @return mixed An expanded string, or false if invalid.
4649 function validateSig( $text ) {
4650 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4654 * Clean up signature text
4656 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4657 * 2) Substitute all transclusions
4659 * @param $text String
4660 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4661 * @return String: signature text
4663 public function cleanSig( $text, $parsing = false ) {
4666 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4669 # Option to disable this feature
4670 if ( !$this->mOptions
->getCleanSignatures() ) {
4674 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4675 # => Move this logic to braceSubstitution()
4676 $substWord = MagicWord
::get( 'subst' );
4677 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4678 $substText = '{{' . $substWord->getSynonym( 0 );
4680 $text = preg_replace( $substRegex, $substText, $text );
4681 $text = self
::cleanSigInSig( $text );
4682 $dom = $this->preprocessToDom( $text );
4683 $frame = $this->getPreprocessor()->newFrame();
4684 $text = $frame->expand( $dom );
4687 $text = $this->mStripState
->unstripBoth( $text );
4694 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4696 * @param $text String
4697 * @return String: signature text with /~{3,5}/ removed
4699 public static function cleanSigInSig( $text ) {
4700 $text = preg_replace( '/~{3,5}/', '', $text );
4705 * Set up some variables which are usually set up in parse()
4706 * so that an external function can call some class members with confidence
4708 * @param $title Title|null
4709 * @param $options ParserOptions
4710 * @param $outputType
4711 * @param $clearState bool
4713 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4714 $this->startParse( $title, $options, $outputType, $clearState );
4718 * @param $title Title|null
4719 * @param $options ParserOptions
4720 * @param $outputType
4721 * @param $clearState bool
4723 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4724 $this->setTitle( $title );
4725 $this->mOptions
= $options;
4726 $this->setOutputType( $outputType );
4727 if ( $clearState ) {
4728 $this->clearState();
4733 * Wrapper for preprocess()
4735 * @param string $text the text to preprocess
4736 * @param $options ParserOptions: options
4737 * @param $title Title object or null to use $wgTitle
4740 public function transformMsg( $text, $options, $title = null ) {
4741 static $executing = false;
4743 # Guard against infinite recursion
4749 wfProfileIn( __METHOD__
);
4755 $text = $this->preprocess( $text, $title, $options );
4758 wfProfileOut( __METHOD__
);
4763 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4764 * The callback should have the following form:
4765 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4767 * Transform and return $text. Use $parser for any required context, e.g. use
4768 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4770 * Hooks may return extended information by returning an array, of which the
4771 * first numbered element (index 0) must be the return string, and all other
4772 * entries are extracted into local variables within an internal function
4773 * in the Parser class.
4775 * This interface (introduced r61913) appears to be undocumented, but
4776 * 'markerName' is used by some core tag hooks to override which strip
4777 * array their results are placed in. **Use great caution if attempting
4778 * this interface, as it is not documented and injudicious use could smash
4779 * private variables.**
4781 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4782 * @param $callback Mixed: the callback function (and object) to use for the tag
4783 * @throws MWException
4784 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4786 public function setHook( $tag, $callback ) {
4787 $tag = strtolower( $tag );
4788 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4789 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4791 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4792 $this->mTagHooks
[$tag] = $callback;
4793 if ( !in_array( $tag, $this->mStripList
) ) {
4794 $this->mStripList
[] = $tag;
4801 * As setHook(), but letting the contents be parsed.
4803 * Transparent tag hooks are like regular XML-style tag hooks, except they
4804 * operate late in the transformation sequence, on HTML instead of wikitext.
4806 * This is probably obsoleted by things dealing with parser frames?
4807 * The only extension currently using it is geoserver.
4810 * @todo better document or deprecate this
4812 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4813 * @param $callback Mixed: the callback function (and object) to use for the tag
4814 * @throws MWException
4815 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4817 function setTransparentTagHook( $tag, $callback ) {
4818 $tag = strtolower( $tag );
4819 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4820 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4822 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4823 $this->mTransparentTagHooks
[$tag] = $callback;
4829 * Remove all tag hooks
4831 function clearTagHooks() {
4832 $this->mTagHooks
= array();
4833 $this->mFunctionTagHooks
= array();
4834 $this->mStripList
= $this->mDefaultStripList
;
4838 * Create a function, e.g. {{sum:1|2|3}}
4839 * The callback function should have the form:
4840 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4842 * Or with SFH_OBJECT_ARGS:
4843 * function myParserFunction( $parser, $frame, $args ) { ... }
4845 * The callback may either return the text result of the function, or an array with the text
4846 * in element 0, and a number of flags in the other elements. The names of the flags are
4847 * specified in the keys. Valid flags are:
4848 * found The text returned is valid, stop processing the template. This
4850 * nowiki Wiki markup in the return value should be escaped
4851 * isHTML The returned text is HTML, armour it against wikitext transformation
4853 * @param string $id The magic word ID
4854 * @param $callback Mixed: the callback function (and object) to use
4855 * @param $flags Integer: a combination of the following flags:
4856 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4858 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4859 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4860 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4861 * the arguments, and to control the way they are expanded.
4863 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4864 * arguments, for instance:
4865 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4867 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4868 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4869 * working if/when this is changed.
4871 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4874 * Please read the documentation in includes/parser/Preprocessor.php for more information
4875 * about the methods available in PPFrame and PPNode.
4877 * @throws MWException
4878 * @return string|callback The old callback function for this name, if any
4880 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4883 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4884 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4886 # Add to function cache
4887 $mw = MagicWord
::get( $id );
4889 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4891 $synonyms = $mw->getSynonyms();
4892 $sensitive = intval( $mw->isCaseSensitive() );
4894 foreach ( $synonyms as $syn ) {
4896 if ( !$sensitive ) {
4897 $syn = $wgContLang->lc( $syn );
4900 if ( !( $flags & SFH_NO_HASH
) ) {
4903 # Remove trailing colon
4904 if ( substr( $syn, -1, 1 ) === ':' ) {
4905 $syn = substr( $syn, 0, -1 );
4907 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4913 * Get all registered function hook identifiers
4917 function getFunctionHooks() {
4918 return array_keys( $this->mFunctionHooks
);
4922 * Create a tag function, e.g. "<test>some stuff</test>".
4923 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4924 * Unlike parser functions, their content is not preprocessed.
4928 * @throws MWException
4931 function setFunctionTagHook( $tag, $callback, $flags ) {
4932 $tag = strtolower( $tag );
4933 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4934 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4935 $this->mFunctionTagHooks
[$tag] : null;
4936 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4938 if ( !in_array( $tag, $this->mStripList
) ) {
4939 $this->mStripList
[] = $tag;
4946 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4947 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4948 * Placeholders created in Skin::makeLinkObj()
4950 * @param $text string
4951 * @param $options int
4953 * @return array of link CSS classes, indexed by PDBK.
4955 function replaceLinkHolders( &$text, $options = 0 ) {
4956 return $this->mLinkHolders
->replace( $text );
4960 * Replace "<!--LINK-->" link placeholders with plain text of links
4961 * (not HTML-formatted).
4963 * @param $text String
4966 function replaceLinkHoldersText( $text ) {
4967 return $this->mLinkHolders
->replaceText( $text );
4971 * Renders an image gallery from a text with one line per image.
4972 * text labels may be given by using |-style alternative text. E.g.
4973 * Image:one.jpg|The number "1"
4974 * Image:tree.jpg|A tree
4975 * given as text will return the HTML of a gallery with two images,
4976 * labeled 'The number "1"' and
4979 * @param string $text
4980 * @param array $params
4981 * @return string HTML
4983 function renderImageGallery( $text, $params ) {
4984 $ig = new ImageGallery();
4985 $ig->setContextTitle( $this->mTitle
);
4986 $ig->setShowBytes( false );
4987 $ig->setShowFilename( false );
4988 $ig->setParser( $this );
4989 $ig->setHideBadImages();
4990 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4992 if ( isset( $params['showfilename'] ) ) {
4993 $ig->setShowFilename( true );
4995 $ig->setShowFilename( false );
4997 if ( isset( $params['caption'] ) ) {
4998 $caption = $params['caption'];
4999 $caption = htmlspecialchars( $caption );
5000 $caption = $this->replaceInternalLinks( $caption );
5001 $ig->setCaptionHtml( $caption );
5003 if ( isset( $params['perrow'] ) ) {
5004 $ig->setPerRow( $params['perrow'] );
5006 if ( isset( $params['widths'] ) ) {
5007 $ig->setWidths( $params['widths'] );
5009 if ( isset( $params['heights'] ) ) {
5010 $ig->setHeights( $params['heights'] );
5013 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5015 $lines = StringUtils
::explode( "\n", $text );
5016 foreach ( $lines as $line ) {
5017 # match lines like these:
5018 # Image:someimage.jpg|This is some image
5020 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5022 if ( count( $matches ) == 0 ) {
5026 if ( strpos( $matches[0], '%' ) !== false ) {
5027 $matches[1] = rawurldecode( $matches[1] );
5029 $title = Title
::newFromText( $matches[1], NS_FILE
);
5030 if ( is_null( $title ) ) {
5031 # Bogus title. Ignore these so we don't bomb out later.
5038 if ( isset( $matches[3] ) ) {
5039 // look for an |alt= definition while trying not to break existing
5040 // captions with multiple pipes (|) in it, until a more sensible grammar
5041 // is defined for images in galleries
5043 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5044 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5045 $magicWordAlt = MagicWord
::get( 'img_alt' );
5046 $magicWordLink = MagicWord
::get( 'img_link' );
5048 foreach ( $parameterMatches as $parameterMatch ) {
5049 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
5050 $alt = $this->stripAltText( $match, false );
5052 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
5053 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5054 $chars = self
::EXT_LINK_URL_CLASS
;
5055 $prots = $this->mUrlProtocols
;
5056 //check to see if link matches an absolute url, if not then it must be a wiki link.
5057 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5060 $localLinkTitle = Title
::newFromText( $linkValue );
5061 if ( $localLinkTitle !== null ) {
5062 $link = $localLinkTitle->getLocalURL();
5067 // concatenate all other pipes
5068 $label .= '|' . $parameterMatch;
5071 // remove the first pipe
5072 $label = substr( $label, 1 );
5075 $ig->add( $title, $label, $alt, $link );
5077 return $ig->toHTML();
5084 function getImageParams( $handler ) {
5086 $handlerClass = get_class( $handler );
5090 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5091 # Initialise static lists
5092 static $internalParamNames = array(
5093 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5094 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5095 'bottom', 'text-bottom' ),
5096 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5097 'upright', 'border', 'link', 'alt', 'class' ),
5099 static $internalParamMap;
5100 if ( !$internalParamMap ) {
5101 $internalParamMap = array();
5102 foreach ( $internalParamNames as $type => $names ) {
5103 foreach ( $names as $name ) {
5104 $magicName = str_replace( '-', '_', "img_$name" );
5105 $internalParamMap[$magicName] = array( $type, $name );
5110 # Add handler params
5111 $paramMap = $internalParamMap;
5113 $handlerParamMap = $handler->getParamMap();
5114 foreach ( $handlerParamMap as $magic => $paramName ) {
5115 $paramMap[$magic] = array( 'handler', $paramName );
5118 $this->mImageParams
[$handlerClass] = $paramMap;
5119 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5121 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5125 * Parse image options text and use it to make an image
5127 * @param $title Title
5128 * @param $options String
5129 * @param $holders LinkHolderArray|bool
5130 * @return string HTML
5132 function makeImage( $title, $options, $holders = false ) {
5133 # Check if the options text is of the form "options|alt text"
5135 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5136 # * left no resizing, just left align. label is used for alt= only
5137 # * right same, but right aligned
5138 # * none same, but not aligned
5139 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5140 # * center center the image
5141 # * frame Keep original image size, no magnify-button.
5142 # * framed Same as "frame"
5143 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5144 # * upright reduce width for upright images, rounded to full __0 px
5145 # * border draw a 1px border around the image
5146 # * alt Text for HTML alt attribute (defaults to empty)
5147 # * class Set a class for img node
5148 # * link Set the target of the image link. Can be external, interwiki, or local
5149 # vertical-align values (no % or length right now):
5159 $parts = StringUtils
::explode( "|", $options );
5161 # Give extensions a chance to select the file revision for us
5164 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5165 array( $this, $title, &$options, &$descQuery ) );
5166 # Fetch and register the file (file title may be different via hooks)
5167 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5170 $handler = $file ?
$file->getHandler() : false;
5172 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5175 $this->addTrackingCategory( 'broken-file-category' );
5178 # Process the input parameters
5180 $params = array( 'frame' => array(), 'handler' => array(),
5181 'horizAlign' => array(), 'vertAlign' => array() );
5182 foreach ( $parts as $part ) {
5183 $part = trim( $part );
5184 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5186 if ( isset( $paramMap[$magicName] ) ) {
5187 list( $type, $paramName ) = $paramMap[$magicName];
5189 # Special case; width and height come in one variable together
5190 if ( $type === 'handler' && $paramName === 'width' ) {
5191 $parsedWidthParam = $this->parseWidthParam( $value );
5192 if( isset( $parsedWidthParam['width'] ) ) {
5193 $width = $parsedWidthParam['width'];
5194 if ( $handler->validateParam( 'width', $width ) ) {
5195 $params[$type]['width'] = $width;
5199 if( isset( $parsedWidthParam['height'] ) ) {
5200 $height = $parsedWidthParam['height'];
5201 if ( $handler->validateParam( 'height', $height ) ) {
5202 $params[$type]['height'] = $height;
5206 # else no validation -- bug 13436
5208 if ( $type === 'handler' ) {
5209 # Validate handler parameter
5210 $validated = $handler->validateParam( $paramName, $value );
5212 # Validate internal parameters
5213 switch( $paramName ) {
5217 # @todo FIXME: Possibly check validity here for
5218 # manualthumb? downstream behavior seems odd with
5219 # missing manual thumbs.
5221 $value = $this->stripAltText( $value, $holders );
5224 $chars = self
::EXT_LINK_URL_CLASS
;
5225 $prots = $this->mUrlProtocols
;
5226 if ( $value === '' ) {
5227 $paramName = 'no-link';
5230 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5231 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5232 $paramName = 'link-url';
5233 $this->mOutput
->addExternalLink( $value );
5234 if ( $this->mOptions
->getExternalLinkTarget() ) {
5235 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5240 $linkTitle = Title
::newFromText( $value );
5242 $paramName = 'link-title';
5243 $value = $linkTitle;
5244 $this->mOutput
->addLink( $linkTitle );
5250 # Most other things appear to be empty or numeric...
5251 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5256 $params[$type][$paramName] = $value;
5260 if ( !$validated ) {
5265 # Process alignment parameters
5266 if ( $params['horizAlign'] ) {
5267 $params['frame']['align'] = key( $params['horizAlign'] );
5269 if ( $params['vertAlign'] ) {
5270 $params['frame']['valign'] = key( $params['vertAlign'] );
5273 $params['frame']['caption'] = $caption;
5275 # Will the image be presented in a frame, with the caption below?
5276 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5277 isset( $params['frame']['framed'] ) ||
5278 isset( $params['frame']['thumbnail'] ) ||
5279 isset( $params['frame']['manualthumb'] );
5281 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5282 # came to also set the caption, ordinary text after the image -- which
5283 # makes no sense, because that just repeats the text multiple times in
5284 # screen readers. It *also* came to set the title attribute.
5286 # Now that we have an alt attribute, we should not set the alt text to
5287 # equal the caption: that's worse than useless, it just repeats the
5288 # text. This is the framed/thumbnail case. If there's no caption, we
5289 # use the unnamed parameter for alt text as well, just for the time be-
5290 # ing, if the unnamed param is set and the alt param is not.
5292 # For the future, we need to figure out if we want to tweak this more,
5293 # e.g., introducing a title= parameter for the title; ignoring the un-
5294 # named parameter entirely for images without a caption; adding an ex-
5295 # plicit caption= parameter and preserving the old magic unnamed para-
5297 if ( $imageIsFramed ) { # Framed image
5298 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5299 # No caption or alt text, add the filename as the alt text so
5300 # that screen readers at least get some description of the image
5301 $params['frame']['alt'] = $title->getText();
5303 # Do not set $params['frame']['title'] because tooltips don't make sense
5305 } else { # Inline image
5306 if ( !isset( $params['frame']['alt'] ) ) {
5307 # No alt text, use the "caption" for the alt text
5308 if ( $caption !== '' ) {
5309 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5311 # No caption, fall back to using the filename for the
5313 $params['frame']['alt'] = $title->getText();
5316 # Use the "caption" for the tooltip text
5317 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5320 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5322 # Linker does the rest
5323 $time = isset( $options['time'] ) ?
$options['time'] : false;
5324 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5325 $time, $descQuery, $this->mOptions
->getThumbSize() );
5327 # Give the handler a chance to modify the parser object
5329 $handler->parserTransformHook( $this, $file );
5337 * @param $holders LinkHolderArray
5338 * @return mixed|String
5340 protected function stripAltText( $caption, $holders ) {
5341 # Strip bad stuff out of the title (tooltip). We can't just use
5342 # replaceLinkHoldersText() here, because if this function is called
5343 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5345 $tooltip = $holders->replaceText( $caption );
5347 $tooltip = $this->replaceLinkHoldersText( $caption );
5350 # make sure there are no placeholders in thumbnail attributes
5351 # that are later expanded to html- so expand them now and
5353 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5354 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5360 * Set a flag in the output object indicating that the content is dynamic and
5361 * shouldn't be cached.
5363 function disableCache() {
5364 wfDebug( "Parser output marked as uncacheable.\n" );
5365 if ( !$this->mOutput
) {
5366 throw new MWException( __METHOD__
.
5367 " can only be called when actually parsing something" );
5369 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5370 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5374 * Callback from the Sanitizer for expanding items found in HTML attribute
5375 * values, so they can be safely tested and escaped.
5377 * @param $text String
5378 * @param $frame PPFrame
5381 function attributeStripCallback( &$text, $frame = false ) {
5382 $text = $this->replaceVariables( $text, $frame );
5383 $text = $this->mStripState
->unstripBoth( $text );
5392 function getTags() {
5393 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5397 * Replace transparent tags in $text with the values given by the callbacks.
5399 * Transparent tag hooks are like regular XML-style tag hooks, except they
5400 * operate late in the transformation sequence, on HTML instead of wikitext.
5402 * @param $text string
5406 function replaceTransparentTags( $text ) {
5408 $elements = array_keys( $this->mTransparentTagHooks
);
5409 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5410 $replacements = array();
5412 foreach ( $matches as $marker => $data ) {
5413 list( $element, $content, $params, $tag ) = $data;
5414 $tagName = strtolower( $element );
5415 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5416 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5420 $replacements[$marker] = $output;
5422 return strtr( $text, $replacements );
5426 * Break wikitext input into sections, and either pull or replace
5427 * some particular section's text.
5429 * External callers should use the getSection and replaceSection methods.
5431 * @param string $text Page wikitext
5432 * @param string $section a section identifier string of the form:
5433 * "<flag1> - <flag2> - ... - <section number>"
5435 * Currently the only recognised flag is "T", which means the target section number
5436 * was derived during a template inclusion parse, in other words this is a template
5437 * section edit link. If no flags are given, it was an ordinary section edit link.
5438 * This flag is required to avoid a section numbering mismatch when a section is
5439 * enclosed by "<includeonly>" (bug 6563).
5441 * The section number 0 pulls the text before the first heading; other numbers will
5442 * pull the given section along with its lower-level subsections. If the section is
5443 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5445 * Section 0 is always considered to exist, even if it only contains the empty
5446 * string. If $text is the empty string and section 0 is replaced, $newText is
5449 * @param string $mode one of "get" or "replace"
5450 * @param string $newText replacement text for section data.
5451 * @return String: for "get", the extracted section text.
5452 * for "replace", the whole page with the section replaced.
5454 private function extractSections( $text, $section, $mode, $newText = '' ) {
5455 global $wgTitle; # not generally used but removes an ugly failure mode
5456 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5458 $frame = $this->getPreprocessor()->newFrame();
5460 # Process section extraction flags
5462 $sectionParts = explode( '-', $section );
5463 $sectionIndex = array_pop( $sectionParts );
5464 foreach ( $sectionParts as $part ) {
5465 if ( $part === 'T' ) {
5466 $flags |
= self
::PTD_FOR_INCLUSION
;
5470 # Check for empty input
5471 if ( strval( $text ) === '' ) {
5472 # Only sections 0 and T-0 exist in an empty document
5473 if ( $sectionIndex == 0 ) {
5474 if ( $mode === 'get' ) {
5480 if ( $mode === 'get' ) {
5488 # Preprocess the text
5489 $root = $this->preprocessToDom( $text, $flags );
5491 # <h> nodes indicate section breaks
5492 # They can only occur at the top level, so we can find them by iterating the root's children
5493 $node = $root->getFirstChild();
5495 # Find the target section
5496 if ( $sectionIndex == 0 ) {
5497 # Section zero doesn't nest, level=big
5498 $targetLevel = 1000;
5501 if ( $node->getName() === 'h' ) {
5502 $bits = $node->splitHeading();
5503 if ( $bits['i'] == $sectionIndex ) {
5504 $targetLevel = $bits['level'];
5508 if ( $mode === 'replace' ) {
5509 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5511 $node = $node->getNextSibling();
5517 if ( $mode === 'get' ) {
5524 # Find the end of the section, including nested sections
5526 if ( $node->getName() === 'h' ) {
5527 $bits = $node->splitHeading();
5528 $curLevel = $bits['level'];
5529 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5533 if ( $mode === 'get' ) {
5534 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5536 $node = $node->getNextSibling();
5539 # Write out the remainder (in replace mode only)
5540 if ( $mode === 'replace' ) {
5541 # Output the replacement text
5542 # Add two newlines on -- trailing whitespace in $newText is conventionally
5543 # stripped by the editor, so we need both newlines to restore the paragraph gap
5544 # Only add trailing whitespace if there is newText
5545 if ( $newText != "" ) {
5546 $outText .= $newText . "\n\n";
5550 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5551 $node = $node->getNextSibling();
5555 if ( is_string( $outText ) ) {
5556 # Re-insert stripped tags
5557 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5564 * This function returns the text of a section, specified by a number ($section).
5565 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5566 * the first section before any such heading (section 0).
5568 * If a section contains subsections, these are also returned.
5570 * @param string $text text to look in
5571 * @param string $section section identifier
5572 * @param string $deftext default to return if section is not found
5573 * @return string text of the requested section
5575 public function getSection( $text, $section, $deftext = '' ) {
5576 return $this->extractSections( $text, $section, "get", $deftext );
5580 * This function returns $oldtext after the content of the section
5581 * specified by $section has been replaced with $text. If the target
5582 * section does not exist, $oldtext is returned unchanged.
5584 * @param string $oldtext former text of the article
5585 * @param int $section section identifier
5586 * @param string $text replacing text
5587 * @return String: modified text
5589 public function replaceSection( $oldtext, $section, $text ) {
5590 return $this->extractSections( $oldtext, $section, "replace", $text );
5594 * Get the ID of the revision we are parsing
5596 * @return Mixed: integer or null
5598 function getRevisionId() {
5599 return $this->mRevisionId
;
5603 * Get the revision object for $this->mRevisionId
5605 * @return Revision|null either a Revision object or null
5607 protected function getRevisionObject() {
5608 if ( !is_null( $this->mRevisionObject
) ) {
5609 return $this->mRevisionObject
;
5611 if ( is_null( $this->mRevisionId
) ) {
5615 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5616 return $this->mRevisionObject
;
5620 * Get the timestamp associated with the current revision, adjusted for
5621 * the default server-local timestamp
5623 function getRevisionTimestamp() {
5624 if ( is_null( $this->mRevisionTimestamp
) ) {
5625 wfProfileIn( __METHOD__
);
5629 $revObject = $this->getRevisionObject();
5630 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5632 # The cryptic '' timezone parameter tells to use the site-default
5633 # timezone offset instead of the user settings.
5635 # Since this value will be saved into the parser cache, served
5636 # to other users, and potentially even used inside links and such,
5637 # it needs to be consistent for all visitors.
5638 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5640 wfProfileOut( __METHOD__
);
5642 return $this->mRevisionTimestamp
;
5646 * Get the name of the user that edited the last revision
5648 * @return String: user name
5650 function getRevisionUser() {
5651 if( is_null( $this->mRevisionUser
) ) {
5652 $revObject = $this->getRevisionObject();
5654 # if this template is subst: the revision id will be blank,
5655 # so just use the current user's name
5657 $this->mRevisionUser
= $revObject->getUserText();
5658 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5659 $this->mRevisionUser
= $this->getUser()->getName();
5662 return $this->mRevisionUser
;
5666 * Mutator for $mDefaultSort
5668 * @param string $sort New value
5670 public function setDefaultSort( $sort ) {
5671 $this->mDefaultSort
= $sort;
5672 $this->mOutput
->setProperty( 'defaultsort', $sort );
5676 * Accessor for $mDefaultSort
5677 * Will use the empty string if none is set.
5679 * This value is treated as a prefix, so the
5680 * empty string is equivalent to sorting by
5685 public function getDefaultSort() {
5686 if ( $this->mDefaultSort
!== false ) {
5687 return $this->mDefaultSort
;
5694 * Accessor for $mDefaultSort
5695 * Unlike getDefaultSort(), will return false if none is set
5697 * @return string or false
5699 public function getCustomDefaultSort() {
5700 return $this->mDefaultSort
;
5704 * Try to guess the section anchor name based on a wikitext fragment
5705 * presumably extracted from a heading, for example "Header" from
5708 * @param $text string
5712 public function guessSectionNameFromWikiText( $text ) {
5713 # Strip out wikitext links(they break the anchor)
5714 $text = $this->stripSectionName( $text );
5715 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5716 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5720 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5721 * instead. For use in redirects, since IE6 interprets Redirect: headers
5722 * as something other than UTF-8 (apparently?), resulting in breakage.
5724 * @param string $text The section name
5725 * @return string An anchor
5727 public function guessLegacySectionNameFromWikiText( $text ) {
5728 # Strip out wikitext links(they break the anchor)
5729 $text = $this->stripSectionName( $text );
5730 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5731 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5735 * Strips a text string of wikitext for use in a section anchor
5737 * Accepts a text string and then removes all wikitext from the
5738 * string and leaves only the resultant text (i.e. the result of
5739 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5740 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5741 * to create valid section anchors by mimicing the output of the
5742 * parser when headings are parsed.
5744 * @param string $text text string to be stripped of wikitext
5745 * for use in a Section anchor
5746 * @return string Filtered text string
5748 public function stripSectionName( $text ) {
5749 # Strip internal link markup
5750 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5751 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5753 # Strip external link markup
5754 # @todo FIXME: Not tolerant to blank link text
5755 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5756 # on how many empty links there are on the page - need to figure that out.
5757 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5759 # Parse wikitext quotes (italics & bold)
5760 $text = $this->doQuotes( $text );
5763 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5768 * strip/replaceVariables/unstrip for preprocessor regression testing
5770 * @param $text string
5771 * @param $title Title
5772 * @param $options ParserOptions
5773 * @param $outputType int
5777 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5778 $this->startParse( $title, $options, $outputType, true );
5780 $text = $this->replaceVariables( $text );
5781 $text = $this->mStripState
->unstripBoth( $text );
5782 $text = Sanitizer
::removeHTMLtags( $text );
5787 * @param $text string
5788 * @param $title Title
5789 * @param $options ParserOptions
5792 function testPst( $text, Title
$title, ParserOptions
$options ) {
5793 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5798 * @param $title Title
5799 * @param $options ParserOptions
5802 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5803 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5807 * Call a callback function on all regions of the given text that are not
5808 * inside strip markers, and replace those regions with the return value
5809 * of the callback. For example, with input:
5813 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5814 * two strings will be replaced with the value returned by the callback in
5822 function markerSkipCallback( $s, $callback ) {
5825 while ( $i < strlen( $s ) ) {
5826 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5827 if ( $markerStart === false ) {
5828 $out .= call_user_func( $callback, substr( $s, $i ) );
5831 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5832 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5833 if ( $markerEnd === false ) {
5834 $out .= substr( $s, $markerStart );
5837 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5838 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5847 * Remove any strip markers found in the given text.
5849 * @param $text Input string
5852 function killMarkers( $text ) {
5853 return $this->mStripState
->killMarkers( $text );
5857 * Save the parser state required to convert the given half-parsed text to
5858 * HTML. "Half-parsed" in this context means the output of
5859 * recursiveTagParse() or internalParse(). This output has strip markers
5860 * from replaceVariables (extensionSubstitution() etc.), and link
5861 * placeholders from replaceLinkHolders().
5863 * Returns an array which can be serialized and stored persistently. This
5864 * array can later be loaded into another parser instance with
5865 * unserializeHalfParsedText(). The text can then be safely incorporated into
5866 * the return value of a parser hook.
5868 * @param $text string
5872 function serializeHalfParsedText( $text ) {
5873 wfProfileIn( __METHOD__
);
5876 'version' => self
::HALF_PARSED_VERSION
,
5877 'stripState' => $this->mStripState
->getSubState( $text ),
5878 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5880 wfProfileOut( __METHOD__
);
5885 * Load the parser state given in the $data array, which is assumed to
5886 * have been generated by serializeHalfParsedText(). The text contents is
5887 * extracted from the array, and its markers are transformed into markers
5888 * appropriate for the current Parser instance. This transformed text is
5889 * returned, and can be safely included in the return value of a parser
5892 * If the $data array has been stored persistently, the caller should first
5893 * check whether it is still valid, by calling isValidHalfParsedText().
5895 * @param array $data Serialized data
5896 * @throws MWException
5899 function unserializeHalfParsedText( $data ) {
5900 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5901 throw new MWException( __METHOD__
. ': invalid version' );
5904 # First, extract the strip state.
5905 $texts = array( $data['text'] );
5906 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5908 # Now renumber links
5909 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5911 # Should be good to go.
5916 * Returns true if the given array, presumed to be generated by
5917 * serializeHalfParsedText(), is compatible with the current version of the
5920 * @param $data Array
5924 function isValidHalfParsedText( $data ) {
5925 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5929 * Parsed a width param of imagelink like 300px or 200x300px
5931 * @param $value String
5936 public function parseWidthParam( $value ) {
5937 $parsedWidthParam = array();
5938 if( $value === '' ) {
5939 return $parsedWidthParam;
5942 # (bug 13500) In both cases (width/height and width only),
5943 # permit trailing "px" for backward compatibility.
5944 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5945 $width = intval( $m[1] );
5946 $height = intval( $m[2] );
5947 $parsedWidthParam['width'] = $width;
5948 $parsedWidthParam['height'] = $height;
5949 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5950 $width = intval( $value );
5951 $parsedWidthParam['width'] = $width;
5953 return $parsedWidthParam;