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 ) );
504 $text .= "\n<!-- \n$limitReport-->\n";
506 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
507 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
508 $this->mTitle
->getPrefixedDBkey() );
511 $this->mOutput
->setText( $text );
513 $this->mRevisionId
= $oldRevisionId;
514 $this->mRevisionObject
= $oldRevisionObject;
515 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
516 $this->mRevisionUser
= $oldRevisionUser;
517 wfProfileOut( $fname );
518 wfProfileOut( __METHOD__
);
520 return $this->mOutput
;
524 * Recursive parser entry point that can be called from an extension tag
527 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
529 * @param string $text text extension wants to have parsed
530 * @param $frame PPFrame: The frame to use for expanding any template variables
534 function recursiveTagParse( $text, $frame=false ) {
535 wfProfileIn( __METHOD__
);
536 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
537 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
538 $text = $this->internalParse( $text, false, $frame );
539 wfProfileOut( __METHOD__
);
544 * Expand templates and variables in the text, producing valid, static wikitext.
545 * Also removes comments.
546 * @return mixed|string
548 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
549 wfProfileIn( __METHOD__
);
550 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
551 if ( $revid !== null ) {
552 $this->mRevisionId
= $revid;
554 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
555 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
556 $text = $this->replaceVariables( $text );
557 $text = $this->mStripState
->unstripBoth( $text );
558 wfProfileOut( __METHOD__
);
563 * Recursive parser entry point that can be called from an extension tag
566 * @param string $text text to be expanded
567 * @param $frame PPFrame: The frame to use for expanding any template variables
571 public function recursivePreprocess( $text, $frame = false ) {
572 wfProfileIn( __METHOD__
);
573 $text = $this->replaceVariables( $text, $frame );
574 $text = $this->mStripState
->unstripBoth( $text );
575 wfProfileOut( __METHOD__
);
580 * Process the wikitext for the "?preload=" feature. (bug 5210)
582 * "<noinclude>", "<includeonly>" etc. are parsed as for template
583 * transclusion, comments, templates, arguments, tags hooks and parser
584 * functions are untouched.
586 * @param $text String
587 * @param $title Title
588 * @param $options ParserOptions
591 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
592 # Parser (re)initialisation
593 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
595 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
596 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
597 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
598 $text = $this->mStripState
->unstripBoth( $text );
603 * Get a random string
607 public static function getRandomString() {
608 return wfRandomString( 16 );
612 * Set the current user.
613 * Should only be used when doing pre-save transform.
615 * @param $user Mixed: User object or null (to reset)
617 function setUser( $user ) {
618 $this->mUser
= $user;
622 * Accessor for mUniqPrefix.
626 public function uniqPrefix() {
627 if ( !isset( $this->mUniqPrefix
) ) {
628 # @todo FIXME: This is probably *horribly wrong*
629 # LanguageConverter seems to want $wgParser's uniqPrefix, however
630 # if this is called for a parser cache hit, the parser may not
631 # have ever been initialized in the first place.
632 # Not really sure what the heck is supposed to be going on here.
634 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
636 return $this->mUniqPrefix
;
640 * Set the context title
644 function setTitle( $t ) {
645 if ( !$t ||
$t instanceof FakeTitle
) {
646 $t = Title
::newFromText( 'NO TITLE' );
649 if ( strval( $t->getFragment() ) !== '' ) {
650 # Strip the fragment to avoid various odd effects
651 $this->mTitle
= clone $t;
652 $this->mTitle
->setFragment( '' );
659 * Accessor for the Title object
661 * @return Title object
663 function getTitle() {
664 return $this->mTitle
;
668 * Accessor/mutator for the Title object
670 * @param $x Title object or null to just get the current one
671 * @return Title object
673 function Title( $x = null ) {
674 return wfSetVar( $this->mTitle
, $x );
678 * Set the output type
680 * @param $ot Integer: new value
682 function setOutputType( $ot ) {
683 $this->mOutputType
= $ot;
686 'html' => $ot == self
::OT_HTML
,
687 'wiki' => $ot == self
::OT_WIKI
,
688 'pre' => $ot == self
::OT_PREPROCESS
,
689 'plain' => $ot == self
::OT_PLAIN
,
694 * Accessor/mutator for the output type
696 * @param int|null $x New value or null to just get the current one
699 function OutputType( $x = null ) {
700 return wfSetVar( $this->mOutputType
, $x );
704 * Get the ParserOutput object
706 * @return ParserOutput object
708 function getOutput() {
709 return $this->mOutput
;
713 * Get the ParserOptions object
715 * @return ParserOptions object
717 function getOptions() {
718 return $this->mOptions
;
722 * Accessor/mutator for the ParserOptions object
724 * @param $x ParserOptions New value or null to just get the current one
725 * @return ParserOptions Current ParserOptions object
727 function Options( $x = null ) {
728 return wfSetVar( $this->mOptions
, $x );
734 function nextLinkID() {
735 return $this->mLinkID++
;
741 function setLinkID( $id ) {
742 $this->mLinkID
= $id;
746 * Get a language object for use in parser functions such as {{FORMATNUM:}}
749 function getFunctionLang() {
750 return $this->getTargetLanguage();
754 * Get the target language for the content being parsed. This is usually the
755 * language that the content is in.
759 * @throws MWException
760 * @return Language|null
762 public function getTargetLanguage() {
763 $target = $this->mOptions
->getTargetLanguage();
765 if ( $target !== null ) {
767 } elseif( $this->mOptions
->getInterfaceMessage() ) {
768 return $this->mOptions
->getUserLangObj();
769 } elseif( is_null( $this->mTitle
) ) {
770 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
773 return $this->mTitle
->getPageLanguage();
777 * Get the language object for language conversion
779 function getConverterLanguage() {
780 return $this->getTargetLanguage();
784 * Get a User object either from $this->mUser, if set, or from the
785 * ParserOptions object otherwise
787 * @return User object
790 if ( !is_null( $this->mUser
) ) {
793 return $this->mOptions
->getUser();
797 * Get a preprocessor object
799 * @return Preprocessor instance
801 function getPreprocessor() {
802 if ( !isset( $this->mPreprocessor
) ) {
803 $class = $this->mPreprocessorClass
;
804 $this->mPreprocessor
= new $class( $this );
806 return $this->mPreprocessor
;
810 * Replaces all occurrences of HTML-style comments and the given tags
811 * in the text with a random marker and returns the next text. The output
812 * parameter $matches will be an associative array filled with data in
816 * 'UNIQ-xxxxx' => array(
819 * array( 'param' => 'x' ),
820 * '<element param="x">tag content</element>' ) )
823 * @param array $elements list of element names. Comments are always extracted.
824 * @param string $text Source text string.
825 * @param array $matches Out parameter, Array: extracted tags
826 * @param $uniq_prefix string
827 * @return String: stripped text
829 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
834 $taglist = implode( '|', $elements );
835 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
837 while ( $text != '' ) {
838 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
840 if ( count( $p ) < 5 ) {
843 if ( count( $p ) > 5 ) {
857 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
858 $stripped .= $marker;
860 if ( $close === '/>' ) {
861 # Empty element tag, <tag />
866 if ( $element === '!--' ) {
869 $end = "/(<\\/$element\\s*>)/i";
871 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
873 if ( count( $q ) < 3 ) {
874 # No end tag -- let it run out to the end of the text.
883 $matches[$marker] = array( $element,
885 Sanitizer
::decodeTagAttributes( $attributes ),
886 "<$element$attributes$close$content$tail" );
892 * Get a list of strippable XML-like elements
896 function getStripList() {
897 return $this->mStripList
;
901 * Add an item to the strip state
902 * Returns the unique tag which must be inserted into the stripped text
903 * The tag will be replaced with the original text in unstrip()
905 * @param $text string
909 function insertStripItem( $text ) {
910 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
911 $this->mMarkerIndex++
;
912 $this->mStripState
->addGeneral( $rnd, $text );
917 * parse the wiki syntax used to render tables
922 function doTableStuff( $text ) {
923 wfProfileIn( __METHOD__
);
925 $lines = StringUtils
::explode( "\n", $text );
927 $td_history = array(); # Is currently a td tag open?
928 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
929 $tr_history = array(); # Is currently a tr tag open?
930 $tr_attributes = array(); # history of tr attributes
931 $has_opened_tr = array(); # Did this table open a <tr> element?
932 $indent_level = 0; # indent level of the table
934 foreach ( $lines as $outLine ) {
935 $line = trim( $outLine );
937 if ( $line === '' ) { # empty line, go to next line
938 $out .= $outLine . "\n";
942 $first_character = $line[0];
945 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
946 # First check if we are starting a new table
947 $indent_level = strlen( $matches[1] );
949 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
950 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
952 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
953 array_push( $td_history, false );
954 array_push( $last_tag_history, '' );
955 array_push( $tr_history, false );
956 array_push( $tr_attributes, '' );
957 array_push( $has_opened_tr, false );
958 } elseif ( count( $td_history ) == 0 ) {
959 # Don't do any of the following
960 $out .= $outLine . "\n";
962 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
963 # We are ending a table
964 $line = '</table>' . substr( $line, 2 );
965 $last_tag = array_pop( $last_tag_history );
967 if ( !array_pop( $has_opened_tr ) ) {
968 $line = "<tr><td></td></tr>{$line}";
971 if ( array_pop( $tr_history ) ) {
972 $line = "</tr>{$line}";
975 if ( array_pop( $td_history ) ) {
976 $line = "</{$last_tag}>{$line}";
978 array_pop( $tr_attributes );
979 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
980 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
981 # Now we have a table row
982 $line = preg_replace( '#^\|-+#', '', $line );
984 # Whats after the tag is now only attributes
985 $attributes = $this->mStripState
->unstripBoth( $line );
986 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
987 array_pop( $tr_attributes );
988 array_push( $tr_attributes, $attributes );
991 $last_tag = array_pop( $last_tag_history );
992 array_pop( $has_opened_tr );
993 array_push( $has_opened_tr, true );
995 if ( array_pop( $tr_history ) ) {
999 if ( array_pop( $td_history ) ) {
1000 $line = "</{$last_tag}>{$line}";
1004 array_push( $tr_history, false );
1005 array_push( $td_history, false );
1006 array_push( $last_tag_history, '' );
1007 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1008 # This might be cell elements, td, th or captions
1009 if ( substr( $line, 0, 2 ) === '|+' ) {
1010 $first_character = '+';
1011 $line = substr( $line, 1 );
1014 $line = substr( $line, 1 );
1016 if ( $first_character === '!' ) {
1017 $line = str_replace( '!!', '||', $line );
1020 # Split up multiple cells on the same line.
1021 # FIXME : This can result in improper nesting of tags processed
1022 # by earlier parser steps, but should avoid splitting up eg
1023 # attribute values containing literal "||".
1024 $cells = StringUtils
::explodeMarkup( '||', $line );
1028 # Loop through each table cell
1029 foreach ( $cells as $cell ) {
1031 if ( $first_character !== '+' ) {
1032 $tr_after = array_pop( $tr_attributes );
1033 if ( !array_pop( $tr_history ) ) {
1034 $previous = "<tr{$tr_after}>\n";
1036 array_push( $tr_history, true );
1037 array_push( $tr_attributes, '' );
1038 array_pop( $has_opened_tr );
1039 array_push( $has_opened_tr, true );
1042 $last_tag = array_pop( $last_tag_history );
1044 if ( array_pop( $td_history ) ) {
1045 $previous = "</{$last_tag}>\n{$previous}";
1048 if ( $first_character === '|' ) {
1050 } elseif ( $first_character === '!' ) {
1052 } elseif ( $first_character === '+' ) {
1053 $last_tag = 'caption';
1058 array_push( $last_tag_history, $last_tag );
1060 # A cell could contain both parameters and data
1061 $cell_data = explode( '|', $cell, 2 );
1063 # Bug 553: Note that a '|' inside an invalid link should not
1064 # be mistaken as delimiting cell parameters
1065 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1066 $cell = "{$previous}<{$last_tag}>{$cell}";
1067 } elseif ( count( $cell_data ) == 1 ) {
1068 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1070 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1071 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1072 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1076 array_push( $td_history, true );
1079 $out .= $outLine . "\n";
1082 # Closing open td, tr && table
1083 while ( count( $td_history ) > 0 ) {
1084 if ( array_pop( $td_history ) ) {
1087 if ( array_pop( $tr_history ) ) {
1090 if ( !array_pop( $has_opened_tr ) ) {
1091 $out .= "<tr><td></td></tr>\n";
1094 $out .= "</table>\n";
1097 # Remove trailing line-ending (b/c)
1098 if ( substr( $out, -1 ) === "\n" ) {
1099 $out = substr( $out, 0, -1 );
1102 # special case: don't return empty table
1103 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1107 wfProfileOut( __METHOD__
);
1113 * Helper function for parse() that transforms wiki markup into
1114 * HTML. Only called for $mOutputType == self::OT_HTML.
1118 * @param $text string
1119 * @param $isMain bool
1120 * @param $frame bool
1124 function internalParse( $text, $isMain = true, $frame = false ) {
1125 wfProfileIn( __METHOD__
);
1129 # Hook to suspend the parser in this state
1130 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1131 wfProfileOut( __METHOD__
);
1135 # if $frame is provided, then use $frame for replacing any variables
1137 # use frame depth to infer how include/noinclude tags should be handled
1138 # depth=0 means this is the top-level document; otherwise it's an included document
1139 if ( !$frame->depth
) {
1142 $flag = Parser
::PTD_FOR_INCLUSION
;
1144 $dom = $this->preprocessToDom( $text, $flag );
1145 $text = $frame->expand( $dom );
1147 # if $frame is not provided, then use old-style replaceVariables
1148 $text = $this->replaceVariables( $text );
1151 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1152 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1153 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1155 # Tables need to come after variable replacement for things to work
1156 # properly; putting them before other transformations should keep
1157 # exciting things like link expansions from showing up in surprising
1159 $text = $this->doTableStuff( $text );
1161 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1163 $text = $this->doDoubleUnderscore( $text );
1165 $text = $this->doHeadings( $text );
1166 $text = $this->replaceInternalLinks( $text );
1167 $text = $this->doAllQuotes( $text );
1168 $text = $this->replaceExternalLinks( $text );
1170 # replaceInternalLinks may sometimes leave behind
1171 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1172 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1174 $text = $this->doMagicLinks( $text );
1175 $text = $this->formatHeadings( $text, $origText, $isMain );
1177 wfProfileOut( __METHOD__
);
1182 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1183 * magic external links.
1188 * @param $text string
1192 function doMagicLinks( $text ) {
1193 wfProfileIn( __METHOD__
);
1194 $prots = wfUrlProtocolsWithoutProtRel();
1195 $urlChar = self
::EXT_LINK_URL_CLASS
;
1196 $text = preg_replace_callback(
1198 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1199 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1200 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1201 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1202 ISBN\s+(\b # m[5]: ISBN, capture number
1203 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1204 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1205 [0-9Xx] # check digit
1207 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1208 wfProfileOut( __METHOD__
);
1213 * @throws MWException
1215 * @return HTML|string
1217 function magicLinkCallback( $m ) {
1218 if ( isset( $m[1] ) && $m[1] !== '' ) {
1221 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1224 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1225 # Free external link
1226 return $this->makeFreeExternalLink( $m[0] );
1227 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1229 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1232 $CssClass = 'mw-magiclink-rfc';
1234 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1236 $urlmsg = 'pubmedurl';
1237 $CssClass = 'mw-magiclink-pmid';
1240 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1241 substr( $m[0], 0, 20 ) . '"' );
1243 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1244 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1245 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1248 $num = strtr( $isbn, array(
1253 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1255 htmlspecialchars( $titleObj->getLocalUrl() ) .
1256 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1263 * Make a free external link, given a user-supplied URL
1265 * @param $url string
1267 * @return string HTML
1270 function makeFreeExternalLink( $url ) {
1271 wfProfileIn( __METHOD__
);
1275 # The characters '<' and '>' (which were escaped by
1276 # removeHTMLtags()) should not be included in
1277 # URLs, per RFC 2396.
1279 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1280 $trail = substr( $url, $m2[0][1] ) . $trail;
1281 $url = substr( $url, 0, $m2[0][1] );
1284 # Move trailing punctuation to $trail
1286 # If there is no left bracket, then consider right brackets fair game too
1287 if ( strpos( $url, '(' ) === false ) {
1291 $numSepChars = strspn( strrev( $url ), $sep );
1292 if ( $numSepChars ) {
1293 $trail = substr( $url, -$numSepChars ) . $trail;
1294 $url = substr( $url, 0, -$numSepChars );
1297 $url = Sanitizer
::cleanUrl( $url );
1299 # Is this an external image?
1300 $text = $this->maybeMakeExternalImage( $url );
1301 if ( $text === false ) {
1302 # Not an image, make a link
1303 $text = Linker
::makeExternalLink( $url,
1304 $this->getConverterLanguage()->markNoConversion( $url, true ),
1306 $this->getExternalLinkAttribs( $url ) );
1307 # Register it in the output object...
1308 # Replace unnecessary URL escape codes with their equivalent characters
1309 $pasteurized = self
::replaceUnusualEscapes( $url );
1310 $this->mOutput
->addExternalLink( $pasteurized );
1312 wfProfileOut( __METHOD__
);
1313 return $text . $trail;
1317 * Parse headers and return html
1321 * @param $text string
1325 function doHeadings( $text ) {
1326 wfProfileIn( __METHOD__
);
1327 for ( $i = 6; $i >= 1; --$i ) {
1328 $h = str_repeat( '=', $i );
1329 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1331 wfProfileOut( __METHOD__
);
1336 * Replace single quotes with HTML markup
1339 * @param $text string
1341 * @return string the altered text
1343 function doAllQuotes( $text ) {
1344 wfProfileIn( __METHOD__
);
1346 $lines = StringUtils
::explode( "\n", $text );
1347 foreach ( $lines as $line ) {
1348 $outtext .= $this->doQuotes( $line ) . "\n";
1350 $outtext = substr( $outtext, 0, -1 );
1351 wfProfileOut( __METHOD__
);
1356 * Helper function for doAllQuotes()
1358 * @param $text string
1362 public function doQuotes( $text ) {
1363 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1364 if ( count( $arr ) == 1 ) {
1367 # First, do some preliminary work. This may shift some apostrophes from
1368 # being mark-up to being text. It also counts the number of occurrences
1369 # of bold and italics mark-ups.
1372 for ( $i = 0; $i < count( $arr ); $i++
) {
1373 if ( ( $i %
2 ) == 1 ) {
1374 # If there are ever four apostrophes, assume the first is supposed to
1375 # be text, and the remaining three constitute mark-up for bold text.
1376 if ( strlen( $arr[$i] ) == 4 ) {
1379 } elseif ( strlen( $arr[$i] ) > 5 ) {
1380 # If there are more than 5 apostrophes in a row, assume they're all
1381 # text except for the last 5.
1382 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1385 # Count the number of occurrences of bold and italics mark-ups.
1386 # We are not counting sequences of five apostrophes.
1387 if ( strlen( $arr[$i] ) == 2 ) {
1389 } elseif ( strlen( $arr[$i] ) == 3 ) {
1391 } elseif ( strlen( $arr[$i] ) == 5 ) {
1398 # If there is an odd number of both bold and italics, it is likely
1399 # that one of the bold ones was meant to be an apostrophe followed
1400 # by italics. Which one we cannot know for certain, but it is more
1401 # likely to be one that has a single-letter word before it.
1402 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1404 $firstsingleletterword = -1;
1405 $firstmultiletterword = -1;
1407 foreach ( $arr as $r ) {
1408 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1409 $x1 = substr( $arr[$i-1], -1 );
1410 $x2 = substr( $arr[$i-1], -2, 1 );
1411 if ( $x1 === ' ' ) {
1412 if ( $firstspace == -1 ) {
1415 } elseif ( $x2 === ' ' ) {
1416 if ( $firstsingleletterword == -1 ) {
1417 $firstsingleletterword = $i;
1420 if ( $firstmultiletterword == -1 ) {
1421 $firstmultiletterword = $i;
1428 # If there is a single-letter word, use it!
1429 if ( $firstsingleletterword > -1 ) {
1430 $arr[$firstsingleletterword] = "''";
1431 $arr[$firstsingleletterword-1] .= "'";
1432 } elseif ( $firstmultiletterword > -1 ) {
1433 # If not, but there's a multi-letter word, use that one.
1434 $arr[$firstmultiletterword] = "''";
1435 $arr[$firstmultiletterword-1] .= "'";
1436 } elseif ( $firstspace > -1 ) {
1437 # ... otherwise use the first one that has neither.
1438 # (notice that it is possible for all three to be -1 if, for example,
1439 # there is only one pentuple-apostrophe in the line)
1440 $arr[$firstspace] = "''";
1441 $arr[$firstspace-1] .= "'";
1445 # Now let's actually convert our apostrophic mush to HTML!
1450 foreach ( $arr as $r ) {
1451 if ( ( $i %
2 ) == 0 ) {
1452 if ( $state === 'both' ) {
1458 if ( strlen( $r ) == 2 ) {
1459 if ( $state === 'i' ) {
1460 $output .= '</i>'; $state = '';
1461 } elseif ( $state === 'bi' ) {
1462 $output .= '</i>'; $state = 'b';
1463 } elseif ( $state === 'ib' ) {
1464 $output .= '</b></i><b>'; $state = 'b';
1465 } elseif ( $state === 'both' ) {
1466 $output .= '<b><i>' . $buffer . '</i>'; $state = 'b';
1467 } else { # $state can be 'b' or ''
1468 $output .= '<i>'; $state .= 'i';
1470 } elseif ( strlen( $r ) == 3 ) {
1471 if ( $state === 'b' ) {
1472 $output .= '</b>'; $state = '';
1473 } elseif ( $state === 'bi' ) {
1474 $output .= '</i></b><i>'; $state = 'i';
1475 } elseif ( $state === 'ib' ) {
1476 $output .= '</b>'; $state = 'i';
1477 } elseif ( $state === 'both' ) {
1478 $output .= '<i><b>' . $buffer . '</b>'; $state = 'i';
1479 } else { # $state can be 'i' or ''
1480 $output .= '<b>'; $state .= 'b';
1482 } elseif ( strlen( $r ) == 5 ) {
1483 if ( $state === 'b' ) {
1484 $output .= '</b><i>'; $state = 'i';
1485 } elseif ( $state === 'i' ) {
1486 $output .= '</i><b>'; $state = 'b';
1487 } elseif ( $state === 'bi' ) {
1488 $output .= '</i></b>'; $state = '';
1489 } elseif ( $state === 'ib' ) {
1490 $output .= '</b></i>'; $state = '';
1491 } elseif ( $state === 'both' ) {
1492 $output .= '<i><b>' . $buffer . '</b></i>'; $state = '';
1493 } else { # ($state == '')
1494 $buffer = ''; $state = 'both';
1500 # Now close all remaining tags. Notice that the order is important.
1501 if ( $state === 'b' ||
$state === 'ib' ) {
1504 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1507 if ( $state === 'bi' ) {
1510 # There might be lonely ''''', so make sure we have a buffer
1511 if ( $state === 'both' && $buffer ) {
1512 $output .= '<b><i>' . $buffer . '</i></b>';
1519 * Replace external links (REL)
1521 * Note: this is all very hackish and the order of execution matters a lot.
1522 * Make sure to run maintenance/parserTests.php if you change this code.
1526 * @param $text string
1528 * @throws MWException
1531 function replaceExternalLinks( $text ) {
1532 wfProfileIn( __METHOD__
);
1534 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1535 if ( $bits === false ) {
1536 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1538 $s = array_shift( $bits );
1541 while ( $i<count( $bits ) ) {
1544 $text = $bits[$i++
];
1545 $trail = $bits[$i++
];
1547 # The characters '<' and '>' (which were escaped by
1548 # removeHTMLtags()) should not be included in
1549 # URLs, per RFC 2396.
1551 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1552 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1553 $url = substr( $url, 0, $m2[0][1] );
1556 # If the link text is an image URL, replace it with an <img> tag
1557 # This happened by accident in the original parser, but some people used it extensively
1558 $img = $this->maybeMakeExternalImage( $text );
1559 if ( $img !== false ) {
1565 # Set linktype for CSS - if URL==text, link is essentially free
1566 $linktype = ( $text === $url ) ?
'free' : 'text';
1568 # No link text, e.g. [http://domain.tld/some.link]
1569 if ( $text == '' ) {
1571 $langObj = $this->getTargetLanguage();
1572 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1573 $linktype = 'autonumber';
1575 # Have link text, e.g. [http://domain.tld/some.link text]s
1577 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1580 $text = $this->getConverterLanguage()->markNoConversion( $text );
1582 $url = Sanitizer
::cleanUrl( $url );
1584 # Use the encoded URL
1585 # This means that users can paste URLs directly into the text
1586 # Funny characters like ö aren't valid in URLs anyway
1587 # This was changed in August 2004
1588 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1589 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1591 # Register link in the output object.
1592 # Replace unnecessary URL escape codes with the referenced character
1593 # This prevents spammers from hiding links from the filters
1594 $pasteurized = self
::replaceUnusualEscapes( $url );
1595 $this->mOutput
->addExternalLink( $pasteurized );
1598 wfProfileOut( __METHOD__
);
1602 * Get the rel attribute for a particular external link.
1605 * @param string|bool $url optional URL, to extract the domain from for rel =>
1606 * nofollow if appropriate
1607 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1608 * @return string|null rel attribute for $url
1610 public static function getExternalLinkRel( $url = false, $title = null ) {
1611 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1612 $ns = $title ?
$title->getNamespace() : false;
1613 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1614 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1621 * Get an associative array of additional HTML attributes appropriate for a
1622 * particular external link. This currently may include rel => nofollow
1623 * (depending on configuration, namespace, and the URL's domain) and/or a
1624 * target attribute (depending on configuration).
1626 * @param string|bool $url optional URL, to extract the domain from for rel =>
1627 * nofollow if appropriate
1628 * @return Array associative array of HTML attributes
1630 function getExternalLinkAttribs( $url = false ) {
1632 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1634 if ( $this->mOptions
->getExternalLinkTarget() ) {
1635 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1641 * Replace unusual URL escape codes with their equivalent characters
1643 * @param $url String
1646 * @todo This can merge genuinely required bits in the path or query string,
1647 * breaking legit URLs. A proper fix would treat the various parts of
1648 * the URL differently; as a workaround, just use the output for
1649 * statistical records, not for actual linking/output.
1651 static function replaceUnusualEscapes( $url ) {
1652 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1653 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1657 * Callback function used in replaceUnusualEscapes().
1658 * Replaces unusual URL escape codes with their equivalent character
1660 * @param $matches array
1664 private static function replaceUnusualEscapesCallback( $matches ) {
1665 $char = urldecode( $matches[0] );
1666 $ord = ord( $char );
1667 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1668 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1669 # No, shouldn't be escaped
1672 # Yes, leave it escaped
1678 * make an image if it's allowed, either through the global
1679 * option, through the exception, or through the on-wiki whitelist
1682 * $param $url string
1686 function maybeMakeExternalImage( $url ) {
1687 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1688 $imagesexception = !empty( $imagesfrom );
1690 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1691 if ( $imagesexception && is_array( $imagesfrom ) ) {
1692 $imagematch = false;
1693 foreach ( $imagesfrom as $match ) {
1694 if ( strpos( $url, $match ) === 0 ) {
1699 } elseif ( $imagesexception ) {
1700 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1702 $imagematch = false;
1704 if ( $this->mOptions
->getAllowExternalImages()
1705 ||
( $imagesexception && $imagematch ) ) {
1706 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1708 $text = Linker
::makeExternalImage( $url );
1711 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1712 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1713 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1714 foreach ( $whitelist as $entry ) {
1715 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1716 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1719 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1720 # Image matches a whitelist entry
1721 $text = Linker
::makeExternalImage( $url );
1730 * Process [[ ]] wikilinks
1734 * @return String: processed text
1738 function replaceInternalLinks( $s ) {
1739 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1744 * Process [[ ]] wikilinks (RIL)
1746 * @throws MWException
1747 * @return LinkHolderArray
1751 function replaceInternalLinks2( &$s ) {
1752 wfProfileIn( __METHOD__
);
1754 wfProfileIn( __METHOD__
. '-setup' );
1755 static $tc = false, $e1, $e1_img;
1756 # the % is needed to support urlencoded titles as well
1758 $tc = Title
::legalChars() . '#%';
1759 # Match a link having the form [[namespace:link|alternate]]trail
1760 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1761 # Match cases where there is no "]]", which might still be images
1762 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1765 $holders = new LinkHolderArray( $this );
1767 # split the entire text string on occurrences of [[
1768 $a = StringUtils
::explode( '[[', ' ' . $s );
1769 # get the first element (all text up to first [[), and remove the space we added
1772 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1773 $s = substr( $s, 1 );
1775 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1777 if ( $useLinkPrefixExtension ) {
1778 # Match the end of a line for a word that's not followed by whitespace,
1779 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1780 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1783 if ( is_null( $this->mTitle
) ) {
1784 wfProfileOut( __METHOD__
. '-setup' );
1785 wfProfileOut( __METHOD__
);
1786 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1788 $nottalk = !$this->mTitle
->isTalkPage();
1790 if ( $useLinkPrefixExtension ) {
1792 if ( preg_match( $e2, $s, $m ) ) {
1793 $first_prefix = $m[2];
1795 $first_prefix = false;
1801 $useSubpages = $this->areSubpagesAllowed();
1802 wfProfileOut( __METHOD__
. '-setup' );
1804 # Loop for each link
1805 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1806 # Check for excessive memory usage
1807 if ( $holders->isBig() ) {
1809 # Do the existence check, replace the link holders and clear the array
1810 $holders->replace( $s );
1814 if ( $useLinkPrefixExtension ) {
1815 wfProfileIn( __METHOD__
. '-prefixhandling' );
1816 if ( preg_match( $e2, $s, $m ) ) {
1823 if ( $first_prefix ) {
1824 $prefix = $first_prefix;
1825 $first_prefix = false;
1827 wfProfileOut( __METHOD__
. '-prefixhandling' );
1830 $might_be_img = false;
1832 wfProfileIn( __METHOD__
. "-e1" );
1833 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1835 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1836 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1837 # the real problem is with the $e1 regex
1840 # Still some problems for cases where the ] is meant to be outside punctuation,
1841 # and no image is in sight. See bug 2095.
1843 if ( $text !== '' &&
1844 substr( $m[3], 0, 1 ) === ']' &&
1845 strpos( $text, '[' ) !== false
1848 $text .= ']'; # so that replaceExternalLinks($text) works later
1849 $m[3] = substr( $m[3], 1 );
1851 # fix up urlencoded title texts
1852 if ( strpos( $m[1], '%' ) !== false ) {
1853 # Should anchors '#' also be rejected?
1854 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1857 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1858 $might_be_img = true;
1860 if ( strpos( $m[1], '%' ) !== false ) {
1861 $m[1] = rawurldecode( $m[1] );
1864 } else { # Invalid form; output directly
1865 $s .= $prefix . '[[' . $line;
1866 wfProfileOut( __METHOD__
. "-e1" );
1869 wfProfileOut( __METHOD__
. "-e1" );
1870 wfProfileIn( __METHOD__
. "-misc" );
1872 # Don't allow internal links to pages containing
1873 # PROTO: where PROTO is a valid URL protocol; these
1874 # should be external links.
1875 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1876 $s .= $prefix . '[[' . $line;
1877 wfProfileOut( __METHOD__
. "-misc" );
1881 # Make subpage if necessary
1882 if ( $useSubpages ) {
1883 $link = $this->maybeDoSubpageLink( $m[1], $text );
1888 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1890 # Strip off leading ':'
1891 $link = substr( $link, 1 );
1894 wfProfileOut( __METHOD__
. "-misc" );
1895 wfProfileIn( __METHOD__
. "-title" );
1896 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1897 if ( $nt === null ) {
1898 $s .= $prefix . '[[' . $line;
1899 wfProfileOut( __METHOD__
. "-title" );
1903 $ns = $nt->getNamespace();
1904 $iw = $nt->getInterWiki();
1905 wfProfileOut( __METHOD__
. "-title" );
1907 if ( $might_be_img ) { # if this is actually an invalid link
1908 wfProfileIn( __METHOD__
. "-might_be_img" );
1909 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1912 # look at the next 'line' to see if we can close it there
1914 $next_line = $a->current();
1915 if ( $next_line === false ||
$next_line === null ) {
1918 $m = explode( ']]', $next_line, 3 );
1919 if ( count( $m ) == 3 ) {
1920 # the first ]] closes the inner link, the second the image
1922 $text .= "[[{$m[0]}]]{$m[1]}";
1925 } elseif ( count( $m ) == 2 ) {
1926 # if there's exactly one ]] that's fine, we'll keep looking
1927 $text .= "[[{$m[0]}]]{$m[1]}";
1929 # if $next_line is invalid too, we need look no further
1930 $text .= '[[' . $next_line;
1935 # we couldn't find the end of this imageLink, so output it raw
1936 # but don't ignore what might be perfectly normal links in the text we've examined
1937 $holders->merge( $this->replaceInternalLinks2( $text ) );
1938 $s .= "{$prefix}[[$link|$text";
1939 # note: no $trail, because without an end, there *is* no trail
1940 wfProfileOut( __METHOD__
. "-might_be_img" );
1943 } else { # it's not an image, so output it raw
1944 $s .= "{$prefix}[[$link|$text";
1945 # note: no $trail, because without an end, there *is* no trail
1946 wfProfileOut( __METHOD__
. "-might_be_img" );
1949 wfProfileOut( __METHOD__
. "-might_be_img" );
1952 $wasblank = ( $text == '' );
1956 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1957 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1958 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1959 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1960 $text = $this->doQuotes( $text );
1963 # Link not escaped by : , create the various objects
1966 wfProfileIn( __METHOD__
. "-interwiki" );
1967 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1968 // XXX: the above check prevents links to sites with identifiers that are not language codes
1970 # Bug 24502: filter duplicates
1971 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1972 $this->mLangLinkLanguages
[$iw] = true;
1973 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1976 $s = rtrim( $s . $prefix );
1977 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1978 wfProfileOut( __METHOD__
. "-interwiki" );
1981 wfProfileOut( __METHOD__
. "-interwiki" );
1983 if ( $ns == NS_FILE
) {
1984 wfProfileIn( __METHOD__
. "-image" );
1985 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1987 # if no parameters were passed, $text
1988 # becomes something like "File:Foo.png",
1989 # which we don't want to pass on to the
1993 # recursively parse links inside the image caption
1994 # actually, this will parse them in any other parameters, too,
1995 # but it might be hard to fix that, and it doesn't matter ATM
1996 $text = $this->replaceExternalLinks( $text );
1997 $holders->merge( $this->replaceInternalLinks2( $text ) );
1999 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2000 $s .= $prefix . $this->armorLinks(
2001 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2003 $s .= $prefix . $trail;
2005 wfProfileOut( __METHOD__
. "-image" );
2009 if ( $ns == NS_CATEGORY
) {
2010 wfProfileIn( __METHOD__
. "-category" );
2011 $s = rtrim( $s . "\n" ); # bug 87
2014 $sortkey = $this->getDefaultSort();
2018 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2019 $sortkey = str_replace( "\n", '', $sortkey );
2020 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2021 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2024 * Strip the whitespace Category links produce, see bug 87
2025 * @todo We might want to use trim($tmp, "\n") here.
2027 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2029 wfProfileOut( __METHOD__
. "-category" );
2034 # Self-link checking
2035 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2036 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2037 $this->mTitle
->getPrefixedText(),
2038 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2041 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2046 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2047 # @todo FIXME: Should do batch file existence checks, see comment below
2048 if ( $ns == NS_MEDIA
) {
2049 wfProfileIn( __METHOD__
. "-media" );
2050 # Give extensions a chance to select the file revision for us
2053 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2054 array( $this, $nt, &$options, &$descQuery ) );
2055 # Fetch and register the file (file title may be different via hooks)
2056 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2057 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2058 $s .= $prefix . $this->armorLinks(
2059 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2060 wfProfileOut( __METHOD__
. "-media" );
2064 wfProfileIn( __METHOD__
. "-always_known" );
2065 # Some titles, such as valid special pages or files in foreign repos, should
2066 # be shown as bluelinks even though they're not included in the page table
2068 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2069 # batch file existence checks for NS_FILE and NS_MEDIA
2070 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2071 $this->mOutput
->addLink( $nt );
2072 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2074 # Links will be added to the output link list after checking
2075 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2077 wfProfileOut( __METHOD__
. "-always_known" );
2079 wfProfileOut( __METHOD__
);
2084 * Render a forced-blue link inline; protect against double expansion of
2085 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2086 * Since this little disaster has to split off the trail text to avoid
2087 * breaking URLs in the following text without breaking trails on the
2088 * wiki links, it's been made into a horrible function.
2091 * @param $text String
2092 * @param array $query or String
2093 * @param $trail String
2094 * @param $prefix String
2095 * @return String: HTML-wikitext mix oh yuck
2097 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2098 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2100 if ( is_string( $query ) ) {
2101 $query = wfCgiToArray( $query );
2103 if ( $text == '' ) {
2104 $text = htmlspecialchars( $nt->getPrefixedText() );
2107 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2109 return $this->armorLinks( $link ) . $trail;
2113 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2114 * going to go through further parsing steps before inline URL expansion.
2116 * Not needed quite as much as it used to be since free links are a bit
2117 * more sensible these days. But bracketed links are still an issue.
2119 * @param string $text more-or-less HTML
2120 * @return String: less-or-more HTML with NOPARSE bits
2122 function armorLinks( $text ) {
2123 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2124 "{$this->mUniqPrefix}NOPARSE$1", $text );
2128 * Return true if subpage links should be expanded on this page.
2131 function areSubpagesAllowed() {
2132 # Some namespaces don't allow subpages
2133 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2137 * Handle link to subpage if necessary
2139 * @param string $target the source of the link
2140 * @param &$text String: the link text, modified as necessary
2141 * @return string the full name of the link
2144 function maybeDoSubpageLink( $target, &$text ) {
2145 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2149 * Used by doBlockLevels()
2154 function closeParagraph() {
2156 if ( $this->mLastSection
!= '' ) {
2157 $result = '</' . $this->mLastSection
. ">\n";
2159 $this->mInPre
= false;
2160 $this->mLastSection
= '';
2165 * getCommon() returns the length of the longest common substring
2166 * of both arguments, starting at the beginning of both.
2169 * @param $st1 string
2170 * @param $st2 string
2174 function getCommon( $st1, $st2 ) {
2175 $fl = strlen( $st1 );
2176 $shorter = strlen( $st2 );
2177 if ( $fl < $shorter ) {
2181 for ( $i = 0; $i < $shorter; ++
$i ) {
2182 if ( $st1[$i] != $st2[$i] ) {
2190 * These next three functions open, continue, and close the list
2191 * element appropriate to the prefix character passed into them.
2194 * @param $char string
2198 function openList( $char ) {
2199 $result = $this->closeParagraph();
2201 if ( '*' === $char ) {
2202 $result .= '<ul><li>';
2203 } elseif ( '#' === $char ) {
2204 $result .= '<ol><li>';
2205 } elseif ( ':' === $char ) {
2206 $result .= '<dl><dd>';
2207 } elseif ( ';' === $char ) {
2208 $result .= '<dl><dt>';
2209 $this->mDTopen
= true;
2211 $result = '<!-- ERR 1 -->';
2219 * @param $char String
2224 function nextItem( $char ) {
2225 if ( '*' === $char ||
'#' === $char ) {
2227 } elseif ( ':' === $char ||
';' === $char ) {
2229 if ( $this->mDTopen
) {
2232 if ( ';' === $char ) {
2233 $this->mDTopen
= true;
2234 return $close . '<dt>';
2236 $this->mDTopen
= false;
2237 return $close . '<dd>';
2240 return '<!-- ERR 2 -->';
2245 * @param $char String
2250 function closeList( $char ) {
2251 if ( '*' === $char ) {
2252 $text = '</li></ul>';
2253 } elseif ( '#' === $char ) {
2254 $text = '</li></ol>';
2255 } elseif ( ':' === $char ) {
2256 if ( $this->mDTopen
) {
2257 $this->mDTopen
= false;
2258 $text = '</dt></dl>';
2260 $text = '</dd></dl>';
2263 return '<!-- ERR 3 -->';
2265 return $text . "\n";
2270 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2272 * @param $text String
2273 * @param $linestart Boolean: whether or not this is at the start of a line.
2275 * @return string the lists rendered as HTML
2277 function doBlockLevels( $text, $linestart ) {
2278 wfProfileIn( __METHOD__
);
2280 # Parsing through the text line by line. The main thing
2281 # happening here is handling of block-level elements p, pre,
2282 # and making lists from lines starting with * # : etc.
2284 $textLines = StringUtils
::explode( "\n", $text );
2286 $lastPrefix = $output = '';
2287 $this->mDTopen
= $inBlockElem = false;
2289 $paragraphStack = false;
2291 foreach ( $textLines as $oLine ) {
2293 if ( !$linestart ) {
2303 $lastPrefixLength = strlen( $lastPrefix );
2304 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2305 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2306 # If not in a <pre> element, scan for and figure out what prefixes are there.
2307 if ( !$this->mInPre
) {
2308 # Multiple prefixes may abut each other for nested lists.
2309 $prefixLength = strspn( $oLine, '*#:;' );
2310 $prefix = substr( $oLine, 0, $prefixLength );
2313 # ; and : are both from definition-lists, so they're equivalent
2314 # for the purposes of determining whether or not we need to open/close
2316 $prefix2 = str_replace( ';', ':', $prefix );
2317 $t = substr( $oLine, $prefixLength );
2318 $this->mInPre
= (bool)$preOpenMatch;
2320 # Don't interpret any other prefixes in preformatted text
2322 $prefix = $prefix2 = '';
2327 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2328 # Same as the last item, so no need to deal with nesting or opening stuff
2329 $output .= $this->nextItem( substr( $prefix, -1 ) );
2330 $paragraphStack = false;
2332 if ( substr( $prefix, -1 ) === ';' ) {
2333 # The one nasty exception: definition lists work like this:
2334 # ; title : definition text
2335 # So we check for : in the remainder text to split up the
2336 # title and definition, without b0rking links.
2338 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2340 $output .= $term . $this->nextItem( ':' );
2343 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2344 # We need to open or close prefixes, or both.
2346 # Either open or close a level...
2347 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2348 $paragraphStack = false;
2350 # Close all the prefixes which aren't shared.
2351 while ( $commonPrefixLength < $lastPrefixLength ) {
2352 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2353 --$lastPrefixLength;
2356 # Continue the current prefix if appropriate.
2357 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2358 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2361 # Open prefixes where appropriate.
2362 while ( $prefixLength > $commonPrefixLength ) {
2363 $char = substr( $prefix, $commonPrefixLength, 1 );
2364 $output .= $this->openList( $char );
2366 if ( ';' === $char ) {
2367 # @todo FIXME: This is dupe of code above
2368 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2370 $output .= $term . $this->nextItem( ':' );
2373 ++
$commonPrefixLength;
2375 $lastPrefix = $prefix2;
2378 # If we have no prefixes, go to paragraph mode.
2379 if ( 0 == $prefixLength ) {
2380 wfProfileIn( __METHOD__
. "-paragraph" );
2381 # No prefix (not in list)--go to paragraph mode
2382 # XXX: use a stack for nestable elements like span, table and div
2383 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2384 $closematch = preg_match(
2385 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2386 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2387 if ( $openmatch or $closematch ) {
2388 $paragraphStack = false;
2389 # TODO bug 5718: paragraph closed
2390 $output .= $this->closeParagraph();
2391 if ( $preOpenMatch and !$preCloseMatch ) {
2392 $this->mInPre
= true;
2394 $inBlockElem = !$closematch;
2395 } elseif ( !$inBlockElem && !$this->mInPre
) {
2396 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2398 if ( $this->mLastSection
!== 'pre' ) {
2399 $paragraphStack = false;
2400 $output .= $this->closeParagraph() . '<pre>';
2401 $this->mLastSection
= 'pre';
2403 $t = substr( $t, 1 );
2406 if ( trim( $t ) === '' ) {
2407 if ( $paragraphStack ) {
2408 $output .= $paragraphStack . '<br />';
2409 $paragraphStack = false;
2410 $this->mLastSection
= 'p';
2412 if ( $this->mLastSection
!== 'p' ) {
2413 $output .= $this->closeParagraph();
2414 $this->mLastSection
= '';
2415 $paragraphStack = '<p>';
2417 $paragraphStack = '</p><p>';
2421 if ( $paragraphStack ) {
2422 $output .= $paragraphStack;
2423 $paragraphStack = false;
2424 $this->mLastSection
= 'p';
2425 } elseif ( $this->mLastSection
!== 'p' ) {
2426 $output .= $this->closeParagraph() . '<p>';
2427 $this->mLastSection
= 'p';
2432 wfProfileOut( __METHOD__
. "-paragraph" );
2434 # somewhere above we forget to get out of pre block (bug 785)
2435 if ( $preCloseMatch && $this->mInPre
) {
2436 $this->mInPre
= false;
2438 if ( $paragraphStack === false ) {
2439 $output .= $t . "\n";
2442 while ( $prefixLength ) {
2443 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2446 if ( $this->mLastSection
!= '' ) {
2447 $output .= '</' . $this->mLastSection
. '>';
2448 $this->mLastSection
= '';
2451 wfProfileOut( __METHOD__
);
2456 * Split up a string on ':', ignoring any occurrences inside tags
2457 * to prevent illegal overlapping.
2459 * @param string $str the string to split
2460 * @param &$before String set to everything before the ':'
2461 * @param &$after String set to everything after the ':'
2462 * @throws MWException
2463 * @return String the position of the ':', or false if none found
2465 function findColonNoLinks( $str, &$before, &$after ) {
2466 wfProfileIn( __METHOD__
);
2468 $pos = strpos( $str, ':' );
2469 if ( $pos === false ) {
2471 wfProfileOut( __METHOD__
);
2475 $lt = strpos( $str, '<' );
2476 if ( $lt === false ||
$lt > $pos ) {
2477 # Easy; no tag nesting to worry about
2478 $before = substr( $str, 0, $pos );
2479 $after = substr( $str, $pos+
1 );
2480 wfProfileOut( __METHOD__
);
2484 # Ugly state machine to walk through avoiding tags.
2485 $state = self
::COLON_STATE_TEXT
;
2487 $len = strlen( $str );
2488 for( $i = 0; $i < $len; $i++
) {
2492 # (Using the number is a performance hack for common cases)
2493 case 0: # self::COLON_STATE_TEXT:
2496 # Could be either a <start> tag or an </end> tag
2497 $state = self
::COLON_STATE_TAGSTART
;
2500 if ( $stack == 0 ) {
2502 $before = substr( $str, 0, $i );
2503 $after = substr( $str, $i +
1 );
2504 wfProfileOut( __METHOD__
);
2507 # Embedded in a tag; don't break it.
2510 # Skip ahead looking for something interesting
2511 $colon = strpos( $str, ':', $i );
2512 if ( $colon === false ) {
2513 # Nothing else interesting
2514 wfProfileOut( __METHOD__
);
2517 $lt = strpos( $str, '<', $i );
2518 if ( $stack === 0 ) {
2519 if ( $lt === false ||
$colon < $lt ) {
2521 $before = substr( $str, 0, $colon );
2522 $after = substr( $str, $colon +
1 );
2523 wfProfileOut( __METHOD__
);
2527 if ( $lt === false ) {
2528 # Nothing else interesting to find; abort!
2529 # We're nested, but there's no close tags left. Abort!
2532 # Skip ahead to next tag start
2534 $state = self
::COLON_STATE_TAGSTART
;
2537 case 1: # self::COLON_STATE_TAG:
2542 $state = self
::COLON_STATE_TEXT
;
2545 # Slash may be followed by >?
2546 $state = self
::COLON_STATE_TAGSLASH
;
2552 case 2: # self::COLON_STATE_TAGSTART:
2555 $state = self
::COLON_STATE_CLOSETAG
;
2558 $state = self
::COLON_STATE_COMMENT
;
2561 # Illegal early close? This shouldn't happen D:
2562 $state = self
::COLON_STATE_TEXT
;
2565 $state = self
::COLON_STATE_TAG
;
2568 case 3: # self::COLON_STATE_CLOSETAG:
2573 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2574 wfProfileOut( __METHOD__
);
2577 $state = self
::COLON_STATE_TEXT
;
2580 case self
::COLON_STATE_TAGSLASH
:
2582 # Yes, a self-closed tag <blah/>
2583 $state = self
::COLON_STATE_TEXT
;
2585 # Probably we're jumping the gun, and this is an attribute
2586 $state = self
::COLON_STATE_TAG
;
2589 case 5: # self::COLON_STATE_COMMENT:
2591 $state = self
::COLON_STATE_COMMENTDASH
;
2594 case self
::COLON_STATE_COMMENTDASH
:
2596 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2598 $state = self
::COLON_STATE_COMMENT
;
2601 case self
::COLON_STATE_COMMENTDASHDASH
:
2603 $state = self
::COLON_STATE_TEXT
;
2605 $state = self
::COLON_STATE_COMMENT
;
2609 throw new MWException( "State machine error in " . __METHOD__
);
2613 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2614 wfProfileOut( __METHOD__
);
2617 wfProfileOut( __METHOD__
);
2622 * Return value of a magic variable (like PAGENAME)
2626 * @param $index integer
2627 * @param bool|\PPFrame $frame
2629 * @throws MWException
2632 function getVariableValue( $index, $frame = false ) {
2633 global $wgContLang, $wgSitename, $wgServer;
2634 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2636 if ( is_null( $this->mTitle
) ) {
2637 // If no title set, bad things are going to happen
2638 // later. Title should always be set since this
2639 // should only be called in the middle of a parse
2640 // operation (but the unit-tests do funky stuff)
2641 throw new MWException( __METHOD__
. ' Should only be '
2642 . ' called while parsing (no title set)' );
2646 * Some of these require message or data lookups and can be
2647 * expensive to check many times.
2649 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2650 if ( isset( $this->mVarCache
[$index] ) ) {
2651 return $this->mVarCache
[$index];
2655 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2656 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2659 global $wgLocaltimezone;
2660 if ( isset( $wgLocaltimezone ) ) {
2661 $oldtz = date_default_timezone_get();
2662 date_default_timezone_set( $wgLocaltimezone );
2665 $localTimestamp = date( 'YmdHis', $ts );
2666 $localMonth = date( 'm', $ts );
2667 $localMonth1 = date( 'n', $ts );
2668 $localMonthName = date( 'n', $ts );
2669 $localDay = date( 'j', $ts );
2670 $localDay2 = date( 'd', $ts );
2671 $localDayOfWeek = date( 'w', $ts );
2672 $localWeek = date( 'W', $ts );
2673 $localYear = date( 'Y', $ts );
2674 $localHour = date( 'H', $ts );
2675 if ( isset( $wgLocaltimezone ) ) {
2676 date_default_timezone_set( $oldtz );
2679 $pageLang = $this->getFunctionLang();
2682 case 'currentmonth':
2683 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2685 case 'currentmonth1':
2686 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2688 case 'currentmonthname':
2689 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2691 case 'currentmonthnamegen':
2692 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2694 case 'currentmonthabbrev':
2695 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2698 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2701 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2704 $value = $pageLang->formatNum( $localMonth );
2707 $value = $pageLang->formatNum( $localMonth1 );
2709 case 'localmonthname':
2710 $value = $pageLang->getMonthName( $localMonthName );
2712 case 'localmonthnamegen':
2713 $value = $pageLang->getMonthNameGen( $localMonthName );
2715 case 'localmonthabbrev':
2716 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2719 $value = $pageLang->formatNum( $localDay );
2722 $value = $pageLang->formatNum( $localDay2 );
2725 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2728 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2730 case 'fullpagename':
2731 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2733 case 'fullpagenamee':
2734 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2737 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2739 case 'subpagenamee':
2740 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2742 case 'basepagename':
2743 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2745 case 'basepagenamee':
2746 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2748 case 'talkpagename':
2749 if ( $this->mTitle
->canTalk() ) {
2750 $talkPage = $this->mTitle
->getTalkPage();
2751 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2756 case 'talkpagenamee':
2757 if ( $this->mTitle
->canTalk() ) {
2758 $talkPage = $this->mTitle
->getTalkPage();
2759 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2764 case 'subjectpagename':
2765 $subjPage = $this->mTitle
->getSubjectPage();
2766 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2768 case 'subjectpagenamee':
2769 $subjPage = $this->mTitle
->getSubjectPage();
2770 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2772 case 'pageid': // requested in bug 23427
2773 $pageid = $this->getTitle()->getArticleId();
2774 if( $pageid == 0 ) {
2775 # 0 means the page doesn't exist in the database,
2776 # which means the user is previewing a new page.
2777 # The vary-revision flag must be set, because the magic word
2778 # will have a different value once the page is saved.
2779 $this->mOutput
->setFlag( 'vary-revision' );
2780 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2782 $value = $pageid ?
$pageid : null;
2785 # Let the edit saving system know we should parse the page
2786 # *after* a revision ID has been assigned.
2787 $this->mOutput
->setFlag( 'vary-revision' );
2788 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2789 $value = $this->mRevisionId
;
2792 # Let the edit saving system know we should parse the page
2793 # *after* a revision ID has been assigned. This is for null edits.
2794 $this->mOutput
->setFlag( 'vary-revision' );
2795 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2796 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2798 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2803 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2805 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2810 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2812 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2817 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2819 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2824 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2826 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2831 $value = $this->getRevisionTimestamp();
2833 case 'revisionuser':
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__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2838 $value = $this->getRevisionUser();
2841 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2844 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2846 case 'namespacenumber':
2847 $value = $this->mTitle
->getNamespace();
2850 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2853 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2855 case 'subjectspace':
2856 $value = $this->mTitle
->getSubjectNsText();
2858 case 'subjectspacee':
2859 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2861 case 'currentdayname':
2862 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2865 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2868 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2871 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2874 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2875 # int to remove the padding
2876 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2879 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2881 case 'localdayname':
2882 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2885 $value = $pageLang->formatNum( $localYear, true );
2888 $value = $pageLang->time( $localTimestamp, false, false );
2891 $value = $pageLang->formatNum( $localHour, true );
2894 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2895 # int to remove the padding
2896 $value = $pageLang->formatNum( (int)$localWeek );
2899 $value = $pageLang->formatNum( $localDayOfWeek );
2901 case 'numberofarticles':
2902 $value = $pageLang->formatNum( SiteStats
::articles() );
2904 case 'numberoffiles':
2905 $value = $pageLang->formatNum( SiteStats
::images() );
2907 case 'numberofusers':
2908 $value = $pageLang->formatNum( SiteStats
::users() );
2910 case 'numberofactiveusers':
2911 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2913 case 'numberofpages':
2914 $value = $pageLang->formatNum( SiteStats
::pages() );
2916 case 'numberofadmins':
2917 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2919 case 'numberofedits':
2920 $value = $pageLang->formatNum( SiteStats
::edits() );
2922 case 'numberofviews':
2923 global $wgDisableCounters;
2924 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2926 case 'currenttimestamp':
2927 $value = wfTimestamp( TS_MW
, $ts );
2929 case 'localtimestamp':
2930 $value = $localTimestamp;
2932 case 'currentversion':
2933 $value = SpecialVersion
::getVersion();
2936 return $wgArticlePath;
2942 $serverParts = wfParseUrl( $wgServer );
2943 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2945 return $wgScriptPath;
2947 return $wgStylePath;
2948 case 'directionmark':
2949 return $pageLang->getDirMark();
2950 case 'contentlanguage':
2951 global $wgLanguageCode;
2952 return $wgLanguageCode;
2955 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2963 $this->mVarCache
[$index] = $value;
2970 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2974 function initialiseVariables() {
2975 wfProfileIn( __METHOD__
);
2976 $variableIDs = MagicWord
::getVariableIDs();
2977 $substIDs = MagicWord
::getSubstIDs();
2979 $this->mVariables
= new MagicWordArray( $variableIDs );
2980 $this->mSubstWords
= new MagicWordArray( $substIDs );
2981 wfProfileOut( __METHOD__
);
2985 * Preprocess some wikitext and return the document tree.
2986 * This is the ghost of replace_variables().
2988 * @param string $text The text to parse
2989 * @param $flags Integer: bitwise combination of:
2990 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2991 * included. Default is to assume a direct page view.
2993 * The generated DOM tree must depend only on the input text and the flags.
2994 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2996 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2997 * change in the DOM tree for a given text, must be passed through the section identifier
2998 * in the section edit link and thus back to extractSections().
3000 * The output of this function is currently only cached in process memory, but a persistent
3001 * cache may be implemented at a later date which takes further advantage of these strict
3002 * dependency requirements.
3008 function preprocessToDom( $text, $flags = 0 ) {
3009 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3014 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3020 public static function splitWhitespace( $s ) {
3021 $ltrimmed = ltrim( $s );
3022 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3023 $trimmed = rtrim( $ltrimmed );
3024 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3026 $w2 = substr( $ltrimmed, -$diff );
3030 return array( $w1, $trimmed, $w2 );
3034 * Replace magic variables, templates, and template arguments
3035 * with the appropriate text. Templates are substituted recursively,
3036 * taking care to avoid infinite loops.
3038 * Note that the substitution depends on value of $mOutputType:
3039 * self::OT_WIKI: only {{subst:}} templates
3040 * self::OT_PREPROCESS: templates but not extension tags
3041 * self::OT_HTML: all templates and extension tags
3043 * @param string $text the text to transform
3044 * @param $frame PPFrame Object describing the arguments passed to the template.
3045 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3046 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3047 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3052 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3053 # Is there any text? Also, Prevent too big inclusions!
3054 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3057 wfProfileIn( __METHOD__
);
3059 if ( $frame === false ) {
3060 $frame = $this->getPreprocessor()->newFrame();
3061 } elseif ( !( $frame instanceof PPFrame
) ) {
3062 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3063 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3066 $dom = $this->preprocessToDom( $text );
3067 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3068 $text = $frame->expand( $dom, $flags );
3070 wfProfileOut( __METHOD__
);
3075 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3077 * @param $args array
3081 static function createAssocArgs( $args ) {
3082 $assocArgs = array();
3084 foreach ( $args as $arg ) {
3085 $eqpos = strpos( $arg, '=' );
3086 if ( $eqpos === false ) {
3087 $assocArgs[$index++
] = $arg;
3089 $name = trim( substr( $arg, 0, $eqpos ) );
3090 $value = trim( substr( $arg, $eqpos+
1 ) );
3091 if ( $value === false ) {
3094 if ( $name !== false ) {
3095 $assocArgs[$name] = $value;
3104 * Warn the user when a parser limitation is reached
3105 * Will warn at most once the user per limitation type
3107 * @param string $limitationType should be one of:
3108 * 'expensive-parserfunction' (corresponding messages:
3109 * 'expensive-parserfunction-warning',
3110 * 'expensive-parserfunction-category')
3111 * 'post-expand-template-argument' (corresponding messages:
3112 * 'post-expand-template-argument-warning',
3113 * 'post-expand-template-argument-category')
3114 * 'post-expand-template-inclusion' (corresponding messages:
3115 * 'post-expand-template-inclusion-warning',
3116 * 'post-expand-template-inclusion-category')
3117 * @param int|null $current Current value
3118 * @param int|null $max Maximum allowed, when an explicit limit has been
3119 * exceeded, provide the values (optional)
3121 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3122 # does no harm if $current and $max are present but are unnecessary for the message
3123 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3124 ->inContentLanguage()->escaped();
3125 $this->mOutput
->addWarning( $warning );
3126 $this->addTrackingCategory( "$limitationType-category" );
3130 * Return the text of a template, after recursively
3131 * replacing any variables or templates within the template.
3133 * @param array $piece the parts of the template
3134 * $piece['title']: the title, i.e. the part before the |
3135 * $piece['parts']: the parameter array
3136 * $piece['lineStart']: whether the brace was at the start of a line
3137 * @param $frame PPFrame The current frame, contains template arguments
3138 * @throws MWException
3139 * @return String: the text of the template
3142 function braceSubstitution( $piece, $frame ) {
3143 wfProfileIn( __METHOD__
);
3144 wfProfileIn( __METHOD__
. '-setup' );
3147 $found = false; # $text has been filled
3148 $nowiki = false; # wiki markup in $text should be escaped
3149 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3150 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3151 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3152 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3154 # Title object, where $text came from
3157 # $part1 is the bit before the first |, and must contain only title characters.
3158 # Various prefixes will be stripped from it later.
3159 $titleWithSpaces = $frame->expand( $piece['title'] );
3160 $part1 = trim( $titleWithSpaces );
3163 # Original title text preserved for various purposes
3164 $originalTitle = $part1;
3166 # $args is a list of argument nodes, starting from index 0, not including $part1
3167 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3168 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3169 wfProfileOut( __METHOD__
. '-setup' );
3171 $titleProfileIn = null; // profile templates
3174 wfProfileIn( __METHOD__
. '-modifiers' );
3177 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3179 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3180 # Decide whether to expand template or keep wikitext as-is.
3181 if ( $this->ot
['wiki'] ) {
3182 if ( $substMatch === false ) {
3183 $literal = true; # literal when in PST with no prefix
3185 $literal = false; # expand when in PST with subst: or safesubst:
3188 if ( $substMatch == 'subst' ) {
3189 $literal = true; # literal when not in PST with plain subst:
3191 $literal = false; # expand when not in PST with safesubst: or no prefix
3195 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3202 if ( !$found && $args->getLength() == 0 ) {
3203 $id = $this->mVariables
->matchStartToEnd( $part1 );
3204 if ( $id !== false ) {
3205 $text = $this->getVariableValue( $id, $frame );
3206 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3207 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3213 # MSG, MSGNW and RAW
3216 $mwMsgnw = MagicWord
::get( 'msgnw' );
3217 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3220 # Remove obsolete MSG:
3221 $mwMsg = MagicWord
::get( 'msg' );
3222 $mwMsg->matchStartAndRemove( $part1 );
3226 $mwRaw = MagicWord
::get( 'raw' );
3227 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3228 $forceRawInterwiki = true;
3231 wfProfileOut( __METHOD__
. '-modifiers' );
3235 wfProfileIn( __METHOD__
. '-pfunc' );
3237 $colonPos = strpos( $part1, ':' );
3238 if ( $colonPos !== false ) {
3239 $func = substr( $part1, 0, $colonPos );
3240 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3241 for ( $i = 0; $i < $args->getLength(); $i++
) {
3242 $funcArgs[] = $args->item( $i );
3245 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3246 } catch ( Exception
$ex ) {
3247 wfProfileOut( __METHOD__
. '-pfunc' );
3251 # The interface for parser functions allows for extracting
3252 # flags into the local scope. Extract any forwarded flags
3256 wfProfileOut( __METHOD__
. '-pfunc' );
3259 # Finish mangling title and then check for loops.
3260 # Set $title to a Title object and $titleText to the PDBK
3263 # Split the title into page and subpage
3265 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3266 if ( $subpage !== '' ) {
3267 $ns = $this->mTitle
->getNamespace();
3269 $title = Title
::newFromText( $part1, $ns );
3271 $titleText = $title->getPrefixedText();
3272 # Check for language variants if the template is not found
3273 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3274 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3276 # Do recursion depth check
3277 $limit = $this->mOptions
->getMaxTemplateDepth();
3278 if ( $frame->depth
>= $limit ) {
3280 $text = '<span class="error">'
3281 . wfMessage( 'parser-template-recursion-depth-warning' )
3282 ->numParams( $limit )->inContentLanguage()->text()
3288 # Load from database
3289 if ( !$found && $title ) {
3290 if ( !Profiler
::instance()->isPersistent() ) {
3291 # Too many unique items can kill profiling DBs/collectors
3292 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3293 wfProfileIn( $titleProfileIn ); // template in
3295 wfProfileIn( __METHOD__
. '-loadtpl' );
3296 if ( !$title->isExternal() ) {
3297 if ( $title->isSpecialPage()
3298 && $this->mOptions
->getAllowSpecialInclusion()
3299 && $this->ot
['html'] )
3301 // Pass the template arguments as URL parameters.
3302 // "uselang" will have no effect since the Language object
3303 // is forced to the one defined in ParserOptions.
3304 $pageArgs = array();
3305 for ( $i = 0; $i < $args->getLength(); $i++
) {
3306 $bits = $args->item( $i )->splitArg();
3307 if ( strval( $bits['index'] ) === '' ) {
3308 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3309 $value = trim( $frame->expand( $bits['value'] ) );
3310 $pageArgs[$name] = $value;
3314 // Create a new context to execute the special page
3315 $context = new RequestContext
;
3316 $context->setTitle( $title );
3317 $context->setRequest( new FauxRequest( $pageArgs ) );
3318 $context->setUser( $this->getUser() );
3319 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3320 $ret = SpecialPageFactory
::capturePath( $title, $context );
3322 $text = $context->getOutput()->getHTML();
3323 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3326 $this->disableCache();
3328 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3329 $found = false; # access denied
3330 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3332 list( $text, $title ) = $this->getTemplateDom( $title );
3333 if ( $text !== false ) {
3339 # If the title is valid but undisplayable, make a link to it
3340 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3341 $text = "[[:$titleText]]";
3344 } elseif ( $title->isTrans() ) {
3345 # Interwiki transclusion
3346 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3347 $text = $this->interwikiTransclude( $title, 'render' );
3350 $text = $this->interwikiTransclude( $title, 'raw' );
3351 # Preprocess it like a template
3352 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3358 # Do infinite loop check
3359 # This has to be done after redirect resolution to avoid infinite loops via redirects
3360 if ( !$frame->loopCheck( $title ) ) {
3362 $text = '<span class="error">'
3363 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3365 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3367 wfProfileOut( __METHOD__
. '-loadtpl' );
3370 # If we haven't found text to substitute by now, we're done
3371 # Recover the source wikitext and return it
3373 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3374 if ( $titleProfileIn ) {
3375 wfProfileOut( $titleProfileIn ); // template out
3377 wfProfileOut( __METHOD__
);
3378 return array( 'object' => $text );
3381 # Expand DOM-style return values in a child frame
3382 if ( $isChildObj ) {
3383 # Clean up argument array
3384 $newFrame = $frame->newChild( $args, $title );
3387 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3388 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3389 # Expansion is eligible for the empty-frame cache
3390 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3391 $text = $this->mTplExpandCache
[$titleText];
3393 $text = $newFrame->expand( $text );
3394 $this->mTplExpandCache
[$titleText] = $text;
3397 # Uncached expansion
3398 $text = $newFrame->expand( $text );
3401 if ( $isLocalObj && $nowiki ) {
3402 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3403 $isLocalObj = false;
3406 if ( $titleProfileIn ) {
3407 wfProfileOut( $titleProfileIn ); // template out
3410 # Replace raw HTML by a placeholder
3412 $text = $this->insertStripItem( $text );
3413 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3414 # Escape nowiki-style return values
3415 $text = wfEscapeWikiText( $text );
3416 } elseif ( is_string( $text )
3417 && !$piece['lineStart']
3418 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3420 # Bug 529: if the template begins with a table or block-level
3421 # element, it should be treated as beginning a new line.
3422 # This behavior is somewhat controversial.
3423 $text = "\n" . $text;
3426 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3427 # Error, oversize inclusion
3428 if ( $titleText !== false ) {
3429 # Make a working, properly escaped link if possible (bug 23588)
3430 $text = "[[:$titleText]]";
3432 # This will probably not be a working link, but at least it may
3433 # provide some hint of where the problem is
3434 preg_replace( '/^:/', '', $originalTitle );
3435 $text = "[[:$originalTitle]]";
3437 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3438 $this->limitationWarn( 'post-expand-template-inclusion' );
3441 if ( $isLocalObj ) {
3442 $ret = array( 'object' => $text );
3444 $ret = array( 'text' => $text );
3447 wfProfileOut( __METHOD__
);
3452 * Call a parser function and return an array with text and flags.
3454 * The returned array will always contain a boolean 'found', indicating
3455 * whether the parser function was found or not. It may also contain the
3457 * text: string|object, resulting wikitext or PP DOM object
3458 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3459 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3460 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3461 * nowiki: bool, wiki markup in $text should be escaped
3464 * @param $frame PPFrame The current frame, contains template arguments
3465 * @param $function string Function name
3466 * @param $args array Arguments to the function
3469 public function callParserFunction( $frame, $function, array $args = array() ) {
3472 wfProfileIn( __METHOD__
);
3474 # Case sensitive functions
3475 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3476 $function = $this->mFunctionSynonyms
[1][$function];
3478 # Case insensitive functions
3479 $function = $wgContLang->lc( $function );
3480 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3481 $function = $this->mFunctionSynonyms
[0][$function];
3483 wfProfileOut( __METHOD__
);
3484 return array( 'found' => false );
3488 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3489 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3491 # Workaround for PHP bug 35229 and similar
3492 if ( !is_callable( $callback ) ) {
3493 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3494 wfProfileOut( __METHOD__
);
3495 throw new MWException( "Tag hook for $function is not callable\n" );
3498 $allArgs = array( &$this );
3499 if ( $flags & SFH_OBJECT_ARGS
) {
3500 # Convert arguments to PPNodes and collect for appending to $allArgs
3501 $funcArgs = array();
3502 foreach ( $args as $k => $v ) {
3503 if ( $v instanceof PPNode ||
$k === 0 ) {
3506 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3510 # Add a frame parameter, and pass the arguments as an array
3511 $allArgs[] = $frame;
3512 $allArgs[] = $funcArgs;
3514 # Convert arguments to plain text and append to $allArgs
3515 foreach ( $args as $k => $v ) {
3516 if ( $v instanceof PPNode
) {
3517 $allArgs[] = trim( $frame->expand( $v ) );
3518 } elseif ( is_int( $k ) && $k >= 0 ) {
3519 $allArgs[] = trim( $v );
3521 $allArgs[] = trim( "$k=$v" );
3526 $result = call_user_func_array( $callback, $allArgs );
3528 # The interface for function hooks allows them to return a wikitext
3529 # string or an array containing the string and any flags. This mungs
3530 # things around to match what this method should return.
3531 if ( !is_array( $result ) ) {
3537 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3538 $result['text'] = $result[0];
3540 unset( $result[0] );
3547 $preprocessFlags = 0;
3548 if ( isset( $result['noparse'] ) ) {
3549 $noparse = $result['noparse'];
3551 if ( isset( $result['preprocessFlags'] ) ) {
3552 $preprocessFlags = $result['preprocessFlags'];
3556 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3557 $result['isChildObj'] = true;
3559 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3560 wfProfileOut( __METHOD__
);
3566 * Get the semi-parsed DOM representation of a template with a given title,
3567 * and its redirect destination title. Cached.
3569 * @param $title Title
3573 function getTemplateDom( $title ) {
3574 $cacheTitle = $title;
3575 $titleText = $title->getPrefixedDBkey();
3577 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3578 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3579 $title = Title
::makeTitle( $ns, $dbk );
3580 $titleText = $title->getPrefixedDBkey();
3582 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3583 return array( $this->mTplDomCache
[$titleText], $title );
3586 # Cache miss, go to the database
3587 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3589 if ( $text === false ) {
3590 $this->mTplDomCache
[$titleText] = false;
3591 return array( false, $title );
3594 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3595 $this->mTplDomCache
[ $titleText ] = $dom;
3597 if ( !$title->equals( $cacheTitle ) ) {
3598 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3599 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3602 return array( $dom, $title );
3606 * Fetch the unparsed text of a template and register a reference to it.
3607 * @param Title $title
3608 * @return Array ( string or false, Title )
3610 function fetchTemplateAndTitle( $title ) {
3611 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3612 $stuff = call_user_func( $templateCb, $title, $this );
3613 $text = $stuff['text'];
3614 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3615 if ( isset( $stuff['deps'] ) ) {
3616 foreach ( $stuff['deps'] as $dep ) {
3617 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3620 return array( $text, $finalTitle );
3624 * Fetch the unparsed text of a template and register a reference to it.
3625 * @param Title $title
3626 * @return mixed string or false
3628 function fetchTemplate( $title ) {
3629 $rv = $this->fetchTemplateAndTitle( $title );
3634 * Static function to get a template
3635 * Can be overridden via ParserOptions::setTemplateCallback().
3637 * @param $title Title
3638 * @param $parser Parser
3642 static function statelessFetchTemplate( $title, $parser = false ) {
3643 $text = $skip = false;
3644 $finalTitle = $title;
3647 # Loop to fetch the article, with up to 1 redirect
3648 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3649 # Give extensions a chance to select the revision instead
3650 $id = false; # Assume current
3651 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3652 array( $parser, $title, &$skip, &$id ) );
3658 'page_id' => $title->getArticleID(),
3665 ? Revision
::newFromId( $id )
3666 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3667 $rev_id = $rev ?
$rev->getId() : 0;
3668 # If there is no current revision, there is no page
3669 if ( $id === false && !$rev ) {
3670 $linkCache = LinkCache
::singleton();
3671 $linkCache->addBadLinkObj( $title );
3676 'page_id' => $title->getArticleID(),
3677 'rev_id' => $rev_id );
3678 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3679 # We fetched a rev from a different title; register it too...
3681 'title' => $rev->getTitle(),
3682 'page_id' => $rev->getPage(),
3683 'rev_id' => $rev_id );
3687 $content = $rev->getContent();
3688 $text = $content ?
$content->getWikitextForTransclusion() : null;
3690 if ( $text === false ||
$text === null ) {
3694 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3696 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3697 if ( !$message->exists() ) {
3701 $content = $message->content();
3702 $text = $message->plain();
3710 $finalTitle = $title;
3711 $title = $content->getRedirectTarget();
3715 'finalTitle' => $finalTitle,
3720 * Fetch a file and its title and register a reference to it.
3721 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3722 * @param Title $title
3723 * @param array $options Array of options to RepoGroup::findFile
3726 function fetchFile( $title, $options = array() ) {
3727 $res = $this->fetchFileAndTitle( $title, $options );
3732 * Fetch a file and its title and register a reference to it.
3733 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3734 * @param Title $title
3735 * @param array $options Array of options to RepoGroup::findFile
3736 * @return Array ( File or false, Title of file )
3738 function fetchFileAndTitle( $title, $options = array() ) {
3739 if ( isset( $options['broken'] ) ) {
3740 $file = false; // broken thumbnail forced by hook
3741 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3742 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3743 } else { // get by (name,timestamp)
3744 $file = wfFindFile( $title, $options );
3746 $time = $file ?
$file->getTimestamp() : false;
3747 $sha1 = $file ?
$file->getSha1() : false;
3748 # Register the file as a dependency...
3749 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3750 if ( $file && !$title->equals( $file->getTitle() ) ) {
3751 # Update fetched file title
3752 $title = $file->getTitle();
3753 if ( is_null( $file->getRedirectedTitle() ) ) {
3754 # This file was not a redirect, but the title does not match.
3755 # Register under the new name because otherwise the link will
3757 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3760 return array( $file, $title );
3764 * Transclude an interwiki link.
3766 * @param $title Title
3771 function interwikiTransclude( $title, $action ) {
3772 global $wgEnableScaryTranscluding;
3774 if ( !$wgEnableScaryTranscluding ) {
3775 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3778 $url = $title->getFullUrl( "action=$action" );
3780 if ( strlen( $url ) > 255 ) {
3781 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3783 return $this->fetchScaryTemplateMaybeFromCache( $url );
3787 * @param $url string
3788 * @return Mixed|String
3790 function fetchScaryTemplateMaybeFromCache( $url ) {
3791 global $wgTranscludeCacheExpiry;
3792 $dbr = wfGetDB( DB_SLAVE
);
3793 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3794 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3795 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3797 return $obj->tc_contents
;
3800 $req = MWHttpRequest
::factory( $url );
3801 $status = $req->execute(); // Status object
3802 if ( $status->isOK() ) {
3803 $text = $req->getContent();
3804 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3805 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3807 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3810 $dbw = wfGetDB( DB_MASTER
);
3811 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3813 'tc_time' => $dbw->timestamp( time() ),
3814 'tc_contents' => $text)
3820 * Triple brace replacement -- used for template arguments
3823 * @param $piece array
3824 * @param $frame PPFrame
3828 function argSubstitution( $piece, $frame ) {
3829 wfProfileIn( __METHOD__
);
3832 $parts = $piece['parts'];
3833 $nameWithSpaces = $frame->expand( $piece['title'] );
3834 $argName = trim( $nameWithSpaces );
3836 $text = $frame->getArgument( $argName );
3837 if ( $text === false && $parts->getLength() > 0
3841 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3844 # No match in frame, use the supplied default
3845 $object = $parts->item( 0 )->getChildren();
3847 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3848 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3849 $this->limitationWarn( 'post-expand-template-argument' );
3852 if ( $text === false && $object === false ) {
3854 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3856 if ( $error !== false ) {
3859 if ( $object !== false ) {
3860 $ret = array( 'object' => $object );
3862 $ret = array( 'text' => $text );
3865 wfProfileOut( __METHOD__
);
3870 * Return the text to be used for a given extension tag.
3871 * This is the ghost of strip().
3873 * @param array $params Associative array of parameters:
3874 * name PPNode for the tag name
3875 * attr PPNode for unparsed text where tag attributes are thought to be
3876 * attributes Optional associative array of parsed attributes
3877 * inner Contents of extension element
3878 * noClose Original text did not have a close tag
3879 * @param $frame PPFrame
3881 * @throws MWException
3884 function extensionSubstitution( $params, $frame ) {
3885 $name = $frame->expand( $params['name'] );
3886 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3887 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3888 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3890 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3891 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3892 if ( $isFunctionTag ) {
3893 $markerType = 'none';
3895 $markerType = 'general';
3897 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3898 $name = strtolower( $name );
3899 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3900 if ( isset( $params['attributes'] ) ) {
3901 $attributes = $attributes +
$params['attributes'];
3904 if ( isset( $this->mTagHooks
[$name] ) ) {
3905 # Workaround for PHP bug 35229 and similar
3906 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3907 throw new MWException( "Tag hook for $name is not callable\n" );
3909 $output = call_user_func_array( $this->mTagHooks
[$name],
3910 array( $content, $attributes, $this, $frame ) );
3911 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3912 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3913 if ( !is_callable( $callback ) ) {
3914 throw new MWException( "Tag hook for $name is not callable\n" );
3917 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3919 $output = '<span class="error">Invalid tag extension name: ' .
3920 htmlspecialchars( $name ) . '</span>';
3923 if ( is_array( $output ) ) {
3924 # Extract flags to local scope (to override $markerType)
3926 $output = $flags[0];
3931 if ( is_null( $attrText ) ) {
3934 if ( isset( $params['attributes'] ) ) {
3935 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3936 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3937 htmlspecialchars( $attrValue ) . '"';
3940 if ( $content === null ) {
3941 $output = "<$name$attrText/>";
3943 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3944 $output = "<$name$attrText>$content$close";
3948 if ( $markerType === 'none' ) {
3950 } elseif ( $markerType === 'nowiki' ) {
3951 $this->mStripState
->addNoWiki( $marker, $output );
3952 } elseif ( $markerType === 'general' ) {
3953 $this->mStripState
->addGeneral( $marker, $output );
3955 throw new MWException( __METHOD__
. ': invalid marker type' );
3961 * Increment an include size counter
3963 * @param string $type the type of expansion
3964 * @param $size Integer: the size of the text
3965 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3967 function incrementIncludeSize( $type, $size ) {
3968 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3971 $this->mIncludeSizes
[$type] +
= $size;
3977 * Increment the expensive function count
3979 * @return Boolean: false if the limit has been exceeded
3981 function incrementExpensiveFunctionCount() {
3982 $this->mExpensiveFunctionCount++
;
3983 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3987 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3988 * Fills $this->mDoubleUnderscores, returns the modified text
3990 * @param $text string
3994 function doDoubleUnderscore( $text ) {
3995 wfProfileIn( __METHOD__
);
3997 # The position of __TOC__ needs to be recorded
3998 $mw = MagicWord
::get( 'toc' );
3999 if ( $mw->match( $text ) ) {
4000 $this->mShowToc
= true;
4001 $this->mForceTocPosition
= true;
4003 # Set a placeholder. At the end we'll fill it in with the TOC.
4004 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4006 # Only keep the first one.
4007 $text = $mw->replace( '', $text );
4010 # Now match and remove the rest of them
4011 $mwa = MagicWord
::getDoubleUnderscoreArray();
4012 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4014 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4015 $this->mOutput
->mNoGallery
= true;
4017 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4018 $this->mShowToc
= false;
4020 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4021 $this->addTrackingCategory( 'hidden-category-category' );
4023 # (bug 8068) Allow control over whether robots index a page.
4025 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4026 # is not desirable, the last one on the page should win.
4027 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4028 $this->mOutput
->setIndexPolicy( 'noindex' );
4029 $this->addTrackingCategory( 'noindex-category' );
4031 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4032 $this->mOutput
->setIndexPolicy( 'index' );
4033 $this->addTrackingCategory( 'index-category' );
4036 # Cache all double underscores in the database
4037 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4038 $this->mOutput
->setProperty( $key, '' );
4041 wfProfileOut( __METHOD__
);
4046 * Add a tracking category, getting the title from a system message,
4047 * or print a debug message if the title is invalid.
4049 * @param string $msg message key
4050 * @return Boolean: whether the addition was successful
4052 public function addTrackingCategory( $msg ) {
4053 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4054 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4057 // Important to parse with correct title (bug 31469)
4058 $cat = wfMessage( $msg )
4059 ->title( $this->getTitle() )
4060 ->inContentLanguage()
4063 # Allow tracking categories to be disabled by setting them to "-"
4064 if ( $cat === '-' ) {
4068 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4069 if ( $containerCategory ) {
4070 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4073 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4079 * This function accomplishes several tasks:
4080 * 1) Auto-number headings if that option is enabled
4081 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4082 * 3) Add a Table of contents on the top for users who have enabled the option
4083 * 4) Auto-anchor headings
4085 * It loops through all headlines, collects the necessary data, then splits up the
4086 * string and re-inserts the newly formatted headlines.
4088 * @param $text String
4089 * @param string $origText original, untouched wikitext
4090 * @param $isMain Boolean
4091 * @return mixed|string
4094 function formatHeadings( $text, $origText, $isMain=true ) {
4095 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4097 # Inhibit editsection links if requested in the page
4098 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4099 $maybeShowEditLink = $showEditLink = false;
4101 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4102 $showEditLink = $this->mOptions
->getEditSection();
4104 if ( $showEditLink ) {
4105 $this->mOutput
->setEditSectionTokens( true );
4108 # Get all headlines for numbering them and adding funky stuff like [edit]
4109 # links - this is for later, but we need the number of headlines right now
4111 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4113 # if there are fewer than 4 headlines in the article, do not show TOC
4114 # unless it's been explicitly enabled.
4115 $enoughToc = $this->mShowToc
&&
4116 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4118 # Allow user to stipulate that a page should have a "new section"
4119 # link added via __NEWSECTIONLINK__
4120 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4121 $this->mOutput
->setNewSection( true );
4124 # Allow user to remove the "new section"
4125 # link via __NONEWSECTIONLINK__
4126 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4127 $this->mOutput
->hideNewSection( true );
4130 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4131 # override above conditions and always show TOC above first header
4132 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4133 $this->mShowToc
= true;
4141 # Ugh .. the TOC should have neat indentation levels which can be
4142 # passed to the skin functions. These are determined here
4146 $sublevelCount = array();
4147 $levelCount = array();
4152 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4153 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4154 $oldType = $this->mOutputType
;
4155 $this->setOutputType( self
::OT_WIKI
);
4156 $frame = $this->getPreprocessor()->newFrame();
4157 $root = $this->preprocessToDom( $origText );
4158 $node = $root->getFirstChild();
4163 foreach ( $matches[3] as $headline ) {
4164 $isTemplate = false;
4166 $sectionIndex = false;
4168 $markerMatches = array();
4169 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4170 $serial = $markerMatches[1];
4171 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4172 $isTemplate = ( $titleText != $baseTitleText );
4173 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4177 $prevlevel = $level;
4179 $level = $matches[1][$headlineCount];
4181 if ( $level > $prevlevel ) {
4182 # Increase TOC level
4184 $sublevelCount[$toclevel] = 0;
4185 if ( $toclevel < $wgMaxTocLevel ) {
4186 $prevtoclevel = $toclevel;
4187 $toc .= Linker
::tocIndent();
4190 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4191 # Decrease TOC level, find level to jump to
4193 for ( $i = $toclevel; $i > 0; $i-- ) {
4194 if ( $levelCount[$i] == $level ) {
4195 # Found last matching level
4198 } elseif ( $levelCount[$i] < $level ) {
4199 # Found first matching level below current level
4207 if ( $toclevel < $wgMaxTocLevel ) {
4208 if ( $prevtoclevel < $wgMaxTocLevel ) {
4209 # Unindent only if the previous toc level was shown :p
4210 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4211 $prevtoclevel = $toclevel;
4213 $toc .= Linker
::tocLineEnd();
4217 # No change in level, end TOC line
4218 if ( $toclevel < $wgMaxTocLevel ) {
4219 $toc .= Linker
::tocLineEnd();
4223 $levelCount[$toclevel] = $level;
4225 # count number of headlines for each level
4226 $sublevelCount[$toclevel]++
;
4228 for( $i = 1; $i <= $toclevel; $i++
) {
4229 if ( !empty( $sublevelCount[$i] ) ) {
4233 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4238 # The safe header is a version of the header text safe to use for links
4240 # Remove link placeholders by the link text.
4241 # <!--LINK number-->
4243 # link text with suffix
4244 # Do this before unstrip since link text can contain strip markers
4245 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4247 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4248 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4250 # Strip out HTML (first regex removes any tag not allowed)
4252 # * <sup> and <sub> (bug 8393)
4255 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4257 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4258 # to allow setting directionality in toc items.
4259 $tocline = preg_replace(
4260 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4261 array( '', '<$1>' ),
4264 $tocline = trim( $tocline );
4266 # For the anchor, strip out HTML-y stuff period
4267 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4268 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4270 # Save headline for section edit hint before it's escaped
4271 $headlineHint = $safeHeadline;
4273 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4274 # For reverse compatibility, provide an id that's
4275 # HTML4-compatible, like we used to.
4277 # It may be worth noting, academically, that it's possible for
4278 # the legacy anchor to conflict with a non-legacy headline
4279 # anchor on the page. In this case likely the "correct" thing
4280 # would be to either drop the legacy anchors or make sure
4281 # they're numbered first. However, this would require people
4282 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4283 # manually, so let's not bother worrying about it.
4284 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4285 array( 'noninitial', 'legacy' ) );
4286 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4288 if ( $legacyHeadline == $safeHeadline ) {
4289 # No reason to have both (in fact, we can't)
4290 $legacyHeadline = false;
4293 $legacyHeadline = false;
4294 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4298 # HTML names must be case-insensitively unique (bug 10721).
4299 # This does not apply to Unicode characters per
4300 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4301 # @todo FIXME: We may be changing them depending on the current locale.
4302 $arrayKey = strtolower( $safeHeadline );
4303 if ( $legacyHeadline === false ) {
4304 $legacyArrayKey = false;
4306 $legacyArrayKey = strtolower( $legacyHeadline );
4309 # count how many in assoc. array so we can track dupes in anchors
4310 if ( isset( $refers[$arrayKey] ) ) {
4311 $refers[$arrayKey]++
;
4313 $refers[$arrayKey] = 1;
4315 if ( isset( $refers[$legacyArrayKey] ) ) {
4316 $refers[$legacyArrayKey]++
;
4318 $refers[$legacyArrayKey] = 1;
4321 # Don't number the heading if it is the only one (looks silly)
4322 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4323 # the two are different if the line contains a link
4324 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4327 # Create the anchor for linking from the TOC to the section
4328 $anchor = $safeHeadline;
4329 $legacyAnchor = $legacyHeadline;
4330 if ( $refers[$arrayKey] > 1 ) {
4331 $anchor .= '_' . $refers[$arrayKey];
4333 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4334 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4336 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4337 $toc .= Linker
::tocLine( $anchor, $tocline,
4338 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4341 # Add the section to the section tree
4342 # Find the DOM node for this header
4343 while ( $node && !$isTemplate ) {
4344 if ( $node->getName() === 'h' ) {
4345 $bits = $node->splitHeading();
4346 if ( $bits['i'] == $sectionIndex ) {
4350 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4351 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4352 $node = $node->getNextSibling();
4355 'toclevel' => $toclevel,
4358 'number' => $numbering,
4359 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4360 'fromtitle' => $titleText,
4361 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4362 'anchor' => $anchor,
4365 # give headline the correct <h#> tag
4366 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4367 // Output edit section links as markers with styles that can be customized by skins
4368 if ( $isTemplate ) {
4369 # Put a T flag in the section identifier, to indicate to extractSections()
4370 # that sections inside <includeonly> should be counted.
4371 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4373 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4375 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4376 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4377 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4378 // so we don't have to worry about a user trying to input one of these markers directly.
4379 // We use a page and section attribute to stop the language converter from converting these important bits
4380 // of data, but put the headline hint inside a content block because the language converter is supposed to
4381 // be able to convert that piece of data.
4382 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4383 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4384 if ( isset( $editlinkArgs[2] ) ) {
4385 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4392 $head[$headlineCount] = Linker
::makeHeadline( $level,
4393 $matches['attrib'][$headlineCount], $anchor, $headline,
4394 $editlink, $legacyAnchor );
4399 $this->setOutputType( $oldType );
4401 # Never ever show TOC if no headers
4402 if ( $numVisible < 1 ) {
4407 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4408 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4410 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4411 $this->mOutput
->setTOCHTML( $toc );
4415 $this->mOutput
->setSections( $tocraw );
4418 # split up and insert constructed headlines
4419 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4422 // build an array of document sections
4423 $sections = array();
4424 foreach ( $blocks as $block ) {
4425 // $head is zero-based, sections aren't.
4426 if ( empty( $head[$i - 1] ) ) {
4427 $sections[$i] = $block;
4429 $sections[$i] = $head[$i - 1] . $block;
4433 * Send a hook, one per section.
4434 * The idea here is to be able to make section-level DIVs, but to do so in a
4435 * lower-impact, more correct way than r50769
4438 * $section : the section number
4439 * &$sectionContent : ref to the content of the section
4440 * $showEditLinks : boolean describing whether this section has an edit link
4442 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4447 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4448 // append the TOC at the beginning
4449 // Top anchor now in skin
4450 $sections[0] = $sections[0] . $toc . "\n";
4453 $full .= join( '', $sections );
4455 if ( $this->mForceTocPosition
) {
4456 return str_replace( '<!--MWTOC-->', $toc, $full );
4463 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4464 * conversion, substitting signatures, {{subst:}} templates, etc.
4466 * @param string $text the text to transform
4467 * @param $title Title: the Title object for the current article
4468 * @param $user User: the User object describing the current user
4469 * @param $options ParserOptions: parsing options
4470 * @param $clearState Boolean: whether to clear the parser state first
4471 * @return String: the altered wiki markup
4473 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4474 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4475 $this->setUser( $user );
4480 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4481 if( $options->getPreSaveTransform() ) {
4482 $text = $this->pstPass2( $text, $user );
4484 $text = $this->mStripState
->unstripBoth( $text );
4486 $this->setUser( null ); #Reset
4492 * Pre-save transform helper function
4495 * @param $text string
4500 function pstPass2( $text, $user ) {
4501 global $wgContLang, $wgLocaltimezone;
4503 # Note: This is the timestamp saved as hardcoded wikitext to
4504 # the database, we use $wgContLang here in order to give
4505 # everyone the same signature and use the default one rather
4506 # than the one selected in each user's preferences.
4507 # (see also bug 12815)
4508 $ts = $this->mOptions
->getTimestamp();
4509 if ( isset( $wgLocaltimezone ) ) {
4510 $tz = $wgLocaltimezone;
4512 $tz = date_default_timezone_get();
4515 $unixts = wfTimestamp( TS_UNIX
, $ts );
4516 $oldtz = date_default_timezone_get();
4517 date_default_timezone_set( $tz );
4518 $ts = date( 'YmdHis', $unixts );
4519 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4521 # Allow translation of timezones through wiki. date() can return
4522 # whatever crap the system uses, localised or not, so we cannot
4523 # ship premade translations.
4524 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4525 $msg = wfMessage( $key )->inContentLanguage();
4526 if ( $msg->exists() ) {
4527 $tzMsg = $msg->text();
4530 date_default_timezone_set( $oldtz );
4532 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4534 # Variable replacement
4535 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4536 $text = $this->replaceVariables( $text );
4538 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4539 # which may corrupt this parser instance via its wfMessage()->text() call-
4542 $sigText = $this->getUserSig( $user );
4543 $text = strtr( $text, array(
4545 '~~~~' => "$sigText $d",
4549 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4550 $tc = '[' . Title
::legalChars() . ']';
4551 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4553 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4554 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4555 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4556 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4558 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4559 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4560 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4561 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4563 $t = $this->mTitle
->getText();
4565 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4566 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4567 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4568 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4570 # if there's no context, don't bother duplicating the title
4571 $text = preg_replace( $p2, '[[\\1]]', $text );
4574 # Trim trailing whitespace
4575 $text = rtrim( $text );
4581 * Fetch the user's signature text, if any, and normalize to
4582 * validated, ready-to-insert wikitext.
4583 * If you have pre-fetched the nickname or the fancySig option, you can
4584 * specify them here to save a database query.
4585 * Do not reuse this parser instance after calling getUserSig(),
4586 * as it may have changed if it's the $wgParser.
4589 * @param string|bool $nickname nickname to use or false to use user's default nickname
4590 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4591 * or null to use default value
4594 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4595 global $wgMaxSigChars;
4597 $username = $user->getName();
4599 # If not given, retrieve from the user object.
4600 if ( $nickname === false )
4601 $nickname = $user->getOption( 'nickname' );
4603 if ( is_null( $fancySig ) ) {
4604 $fancySig = $user->getBoolOption( 'fancysig' );
4607 $nickname = $nickname == null ?
$username : $nickname;
4609 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4610 $nickname = $username;
4611 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4612 } elseif ( $fancySig !== false ) {
4613 # Sig. might contain markup; validate this
4614 if ( $this->validateSig( $nickname ) !== false ) {
4615 # Validated; clean up (if needed) and return it
4616 return $this->cleanSig( $nickname, true );
4618 # Failed to validate; fall back to the default
4619 $nickname = $username;
4620 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4624 # Make sure nickname doesnt get a sig in a sig
4625 $nickname = self
::cleanSigInSig( $nickname );
4627 # If we're still here, make it a link to the user page
4628 $userText = wfEscapeWikiText( $username );
4629 $nickText = wfEscapeWikiText( $nickname );
4630 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4632 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4636 * Check that the user's signature contains no bad XML
4638 * @param $text String
4639 * @return mixed An expanded string, or false if invalid.
4641 function validateSig( $text ) {
4642 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4646 * Clean up signature text
4648 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4649 * 2) Substitute all transclusions
4651 * @param $text String
4652 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4653 * @return String: signature text
4655 public function cleanSig( $text, $parsing = false ) {
4658 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4661 # Option to disable this feature
4662 if ( !$this->mOptions
->getCleanSignatures() ) {
4666 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4667 # => Move this logic to braceSubstitution()
4668 $substWord = MagicWord
::get( 'subst' );
4669 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4670 $substText = '{{' . $substWord->getSynonym( 0 );
4672 $text = preg_replace( $substRegex, $substText, $text );
4673 $text = self
::cleanSigInSig( $text );
4674 $dom = $this->preprocessToDom( $text );
4675 $frame = $this->getPreprocessor()->newFrame();
4676 $text = $frame->expand( $dom );
4679 $text = $this->mStripState
->unstripBoth( $text );
4686 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4688 * @param $text String
4689 * @return String: signature text with /~{3,5}/ removed
4691 public static function cleanSigInSig( $text ) {
4692 $text = preg_replace( '/~{3,5}/', '', $text );
4697 * Set up some variables which are usually set up in parse()
4698 * so that an external function can call some class members with confidence
4700 * @param $title Title|null
4701 * @param $options ParserOptions
4702 * @param $outputType
4703 * @param $clearState bool
4705 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4706 $this->startParse( $title, $options, $outputType, $clearState );
4710 * @param $title Title|null
4711 * @param $options ParserOptions
4712 * @param $outputType
4713 * @param $clearState bool
4715 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4716 $this->setTitle( $title );
4717 $this->mOptions
= $options;
4718 $this->setOutputType( $outputType );
4719 if ( $clearState ) {
4720 $this->clearState();
4725 * Wrapper for preprocess()
4727 * @param string $text the text to preprocess
4728 * @param $options ParserOptions: options
4729 * @param $title Title object or null to use $wgTitle
4732 public function transformMsg( $text, $options, $title = null ) {
4733 static $executing = false;
4735 # Guard against infinite recursion
4741 wfProfileIn( __METHOD__
);
4747 $text = $this->preprocess( $text, $title, $options );
4750 wfProfileOut( __METHOD__
);
4755 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4756 * The callback should have the following form:
4757 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4759 * Transform and return $text. Use $parser for any required context, e.g. use
4760 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4762 * Hooks may return extended information by returning an array, of which the
4763 * first numbered element (index 0) must be the return string, and all other
4764 * entries are extracted into local variables within an internal function
4765 * in the Parser class.
4767 * This interface (introduced r61913) appears to be undocumented, but
4768 * 'markerName' is used by some core tag hooks to override which strip
4769 * array their results are placed in. **Use great caution if attempting
4770 * this interface, as it is not documented and injudicious use could smash
4771 * private variables.**
4773 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4774 * @param $callback Mixed: the callback function (and object) to use for the tag
4775 * @throws MWException
4776 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4778 public function setHook( $tag, $callback ) {
4779 $tag = strtolower( $tag );
4780 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4781 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4783 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4784 $this->mTagHooks
[$tag] = $callback;
4785 if ( !in_array( $tag, $this->mStripList
) ) {
4786 $this->mStripList
[] = $tag;
4793 * As setHook(), but letting the contents be parsed.
4795 * Transparent tag hooks are like regular XML-style tag hooks, except they
4796 * operate late in the transformation sequence, on HTML instead of wikitext.
4798 * This is probably obsoleted by things dealing with parser frames?
4799 * The only extension currently using it is geoserver.
4802 * @todo better document or deprecate this
4804 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4805 * @param $callback Mixed: the callback function (and object) to use for the tag
4806 * @throws MWException
4807 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4809 function setTransparentTagHook( $tag, $callback ) {
4810 $tag = strtolower( $tag );
4811 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4812 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4814 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4815 $this->mTransparentTagHooks
[$tag] = $callback;
4821 * Remove all tag hooks
4823 function clearTagHooks() {
4824 $this->mTagHooks
= array();
4825 $this->mFunctionTagHooks
= array();
4826 $this->mStripList
= $this->mDefaultStripList
;
4830 * Create a function, e.g. {{sum:1|2|3}}
4831 * The callback function should have the form:
4832 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4834 * Or with SFH_OBJECT_ARGS:
4835 * function myParserFunction( $parser, $frame, $args ) { ... }
4837 * The callback may either return the text result of the function, or an array with the text
4838 * in element 0, and a number of flags in the other elements. The names of the flags are
4839 * specified in the keys. Valid flags are:
4840 * found The text returned is valid, stop processing the template. This
4842 * nowiki Wiki markup in the return value should be escaped
4843 * isHTML The returned text is HTML, armour it against wikitext transformation
4845 * @param string $id The magic word ID
4846 * @param $callback Mixed: the callback function (and object) to use
4847 * @param $flags Integer: a combination of the following flags:
4848 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4850 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4851 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4852 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4853 * the arguments, and to control the way they are expanded.
4855 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4856 * arguments, for instance:
4857 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4859 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4860 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4861 * working if/when this is changed.
4863 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4866 * Please read the documentation in includes/parser/Preprocessor.php for more information
4867 * about the methods available in PPFrame and PPNode.
4869 * @throws MWException
4870 * @return string|callback The old callback function for this name, if any
4872 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4875 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4876 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4878 # Add to function cache
4879 $mw = MagicWord
::get( $id );
4881 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4883 $synonyms = $mw->getSynonyms();
4884 $sensitive = intval( $mw->isCaseSensitive() );
4886 foreach ( $synonyms as $syn ) {
4888 if ( !$sensitive ) {
4889 $syn = $wgContLang->lc( $syn );
4892 if ( !( $flags & SFH_NO_HASH
) ) {
4895 # Remove trailing colon
4896 if ( substr( $syn, -1, 1 ) === ':' ) {
4897 $syn = substr( $syn, 0, -1 );
4899 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4905 * Get all registered function hook identifiers
4909 function getFunctionHooks() {
4910 return array_keys( $this->mFunctionHooks
);
4914 * Create a tag function, e.g. "<test>some stuff</test>".
4915 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4916 * Unlike parser functions, their content is not preprocessed.
4920 * @throws MWException
4923 function setFunctionTagHook( $tag, $callback, $flags ) {
4924 $tag = strtolower( $tag );
4925 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4926 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4927 $this->mFunctionTagHooks
[$tag] : null;
4928 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4930 if ( !in_array( $tag, $this->mStripList
) ) {
4931 $this->mStripList
[] = $tag;
4938 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4939 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4940 * Placeholders created in Skin::makeLinkObj()
4942 * @param $text string
4943 * @param $options int
4945 * @return array of link CSS classes, indexed by PDBK.
4947 function replaceLinkHolders( &$text, $options = 0 ) {
4948 return $this->mLinkHolders
->replace( $text );
4952 * Replace "<!--LINK-->" link placeholders with plain text of links
4953 * (not HTML-formatted).
4955 * @param $text String
4958 function replaceLinkHoldersText( $text ) {
4959 return $this->mLinkHolders
->replaceText( $text );
4963 * Renders an image gallery from a text with one line per image.
4964 * text labels may be given by using |-style alternative text. E.g.
4965 * Image:one.jpg|The number "1"
4966 * Image:tree.jpg|A tree
4967 * given as text will return the HTML of a gallery with two images,
4968 * labeled 'The number "1"' and
4971 * @param string $text
4972 * @param array $params
4973 * @return string HTML
4975 function renderImageGallery( $text, $params ) {
4976 $ig = new ImageGallery();
4977 $ig->setContextTitle( $this->mTitle
);
4978 $ig->setShowBytes( false );
4979 $ig->setShowFilename( false );
4980 $ig->setParser( $this );
4981 $ig->setHideBadImages();
4982 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4984 if ( isset( $params['showfilename'] ) ) {
4985 $ig->setShowFilename( true );
4987 $ig->setShowFilename( false );
4989 if ( isset( $params['caption'] ) ) {
4990 $caption = $params['caption'];
4991 $caption = htmlspecialchars( $caption );
4992 $caption = $this->replaceInternalLinks( $caption );
4993 $ig->setCaptionHtml( $caption );
4995 if ( isset( $params['perrow'] ) ) {
4996 $ig->setPerRow( $params['perrow'] );
4998 if ( isset( $params['widths'] ) ) {
4999 $ig->setWidths( $params['widths'] );
5001 if ( isset( $params['heights'] ) ) {
5002 $ig->setHeights( $params['heights'] );
5005 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5007 $lines = StringUtils
::explode( "\n", $text );
5008 foreach ( $lines as $line ) {
5009 # match lines like these:
5010 # Image:someimage.jpg|This is some image
5012 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5014 if ( count( $matches ) == 0 ) {
5018 if ( strpos( $matches[0], '%' ) !== false ) {
5019 $matches[1] = rawurldecode( $matches[1] );
5021 $title = Title
::newFromText( $matches[1], NS_FILE
);
5022 if ( is_null( $title ) ) {
5023 # Bogus title. Ignore these so we don't bomb out later.
5030 if ( isset( $matches[3] ) ) {
5031 // look for an |alt= definition while trying not to break existing
5032 // captions with multiple pipes (|) in it, until a more sensible grammar
5033 // is defined for images in galleries
5035 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5036 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5037 $magicWordAlt = MagicWord
::get( 'img_alt' );
5038 $magicWordLink = MagicWord
::get( 'img_link' );
5040 foreach ( $parameterMatches as $parameterMatch ) {
5041 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
5042 $alt = $this->stripAltText( $match, false );
5044 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
5045 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5046 $chars = self
::EXT_LINK_URL_CLASS
;
5047 $prots = $this->mUrlProtocols
;
5048 //check to see if link matches an absolute url, if not then it must be a wiki link.
5049 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5052 $localLinkTitle = Title
::newFromText( $linkValue );
5053 if ( $localLinkTitle !== null ) {
5054 $link = $localLinkTitle->getLocalURL();
5059 // concatenate all other pipes
5060 $label .= '|' . $parameterMatch;
5063 // remove the first pipe
5064 $label = substr( $label, 1 );
5067 $ig->add( $title, $label, $alt, $link );
5069 return $ig->toHTML();
5076 function getImageParams( $handler ) {
5078 $handlerClass = get_class( $handler );
5082 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5083 # Initialise static lists
5084 static $internalParamNames = array(
5085 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5086 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5087 'bottom', 'text-bottom' ),
5088 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5089 'upright', 'border', 'link', 'alt', 'class' ),
5091 static $internalParamMap;
5092 if ( !$internalParamMap ) {
5093 $internalParamMap = array();
5094 foreach ( $internalParamNames as $type => $names ) {
5095 foreach ( $names as $name ) {
5096 $magicName = str_replace( '-', '_', "img_$name" );
5097 $internalParamMap[$magicName] = array( $type, $name );
5102 # Add handler params
5103 $paramMap = $internalParamMap;
5105 $handlerParamMap = $handler->getParamMap();
5106 foreach ( $handlerParamMap as $magic => $paramName ) {
5107 $paramMap[$magic] = array( 'handler', $paramName );
5110 $this->mImageParams
[$handlerClass] = $paramMap;
5111 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5113 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5117 * Parse image options text and use it to make an image
5119 * @param $title Title
5120 * @param $options String
5121 * @param $holders LinkHolderArray|bool
5122 * @return string HTML
5124 function makeImage( $title, $options, $holders = false ) {
5125 # Check if the options text is of the form "options|alt text"
5127 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5128 # * left no resizing, just left align. label is used for alt= only
5129 # * right same, but right aligned
5130 # * none same, but not aligned
5131 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5132 # * center center the image
5133 # * frame Keep original image size, no magnify-button.
5134 # * framed Same as "frame"
5135 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5136 # * upright reduce width for upright images, rounded to full __0 px
5137 # * border draw a 1px border around the image
5138 # * alt Text for HTML alt attribute (defaults to empty)
5139 # * class Set a class for img node
5140 # * link Set the target of the image link. Can be external, interwiki, or local
5141 # vertical-align values (no % or length right now):
5151 $parts = StringUtils
::explode( "|", $options );
5153 # Give extensions a chance to select the file revision for us
5156 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5157 array( $this, $title, &$options, &$descQuery ) );
5158 # Fetch and register the file (file title may be different via hooks)
5159 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5162 $handler = $file ?
$file->getHandler() : false;
5164 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5167 $this->addTrackingCategory( 'broken-file-category' );
5170 # Process the input parameters
5172 $params = array( 'frame' => array(), 'handler' => array(),
5173 'horizAlign' => array(), 'vertAlign' => array() );
5174 foreach ( $parts as $part ) {
5175 $part = trim( $part );
5176 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5178 if ( isset( $paramMap[$magicName] ) ) {
5179 list( $type, $paramName ) = $paramMap[$magicName];
5181 # Special case; width and height come in one variable together
5182 if ( $type === 'handler' && $paramName === 'width' ) {
5183 $parsedWidthParam = $this->parseWidthParam( $value );
5184 if( isset( $parsedWidthParam['width'] ) ) {
5185 $width = $parsedWidthParam['width'];
5186 if ( $handler->validateParam( 'width', $width ) ) {
5187 $params[$type]['width'] = $width;
5191 if( isset( $parsedWidthParam['height'] ) ) {
5192 $height = $parsedWidthParam['height'];
5193 if ( $handler->validateParam( 'height', $height ) ) {
5194 $params[$type]['height'] = $height;
5198 # else no validation -- bug 13436
5200 if ( $type === 'handler' ) {
5201 # Validate handler parameter
5202 $validated = $handler->validateParam( $paramName, $value );
5204 # Validate internal parameters
5205 switch( $paramName ) {
5209 # @todo FIXME: Possibly check validity here for
5210 # manualthumb? downstream behavior seems odd with
5211 # missing manual thumbs.
5213 $value = $this->stripAltText( $value, $holders );
5216 $chars = self
::EXT_LINK_URL_CLASS
;
5217 $prots = $this->mUrlProtocols
;
5218 if ( $value === '' ) {
5219 $paramName = 'no-link';
5222 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5223 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5224 $paramName = 'link-url';
5225 $this->mOutput
->addExternalLink( $value );
5226 if ( $this->mOptions
->getExternalLinkTarget() ) {
5227 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5232 $linkTitle = Title
::newFromText( $value );
5234 $paramName = 'link-title';
5235 $value = $linkTitle;
5236 $this->mOutput
->addLink( $linkTitle );
5242 # Most other things appear to be empty or numeric...
5243 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5248 $params[$type][$paramName] = $value;
5252 if ( !$validated ) {
5257 # Process alignment parameters
5258 if ( $params['horizAlign'] ) {
5259 $params['frame']['align'] = key( $params['horizAlign'] );
5261 if ( $params['vertAlign'] ) {
5262 $params['frame']['valign'] = key( $params['vertAlign'] );
5265 $params['frame']['caption'] = $caption;
5267 # Will the image be presented in a frame, with the caption below?
5268 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5269 isset( $params['frame']['framed'] ) ||
5270 isset( $params['frame']['thumbnail'] ) ||
5271 isset( $params['frame']['manualthumb'] );
5273 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5274 # came to also set the caption, ordinary text after the image -- which
5275 # makes no sense, because that just repeats the text multiple times in
5276 # screen readers. It *also* came to set the title attribute.
5278 # Now that we have an alt attribute, we should not set the alt text to
5279 # equal the caption: that's worse than useless, it just repeats the
5280 # text. This is the framed/thumbnail case. If there's no caption, we
5281 # use the unnamed parameter for alt text as well, just for the time be-
5282 # ing, if the unnamed param is set and the alt param is not.
5284 # For the future, we need to figure out if we want to tweak this more,
5285 # e.g., introducing a title= parameter for the title; ignoring the un-
5286 # named parameter entirely for images without a caption; adding an ex-
5287 # plicit caption= parameter and preserving the old magic unnamed para-
5289 if ( $imageIsFramed ) { # Framed image
5290 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5291 # No caption or alt text, add the filename as the alt text so
5292 # that screen readers at least get some description of the image
5293 $params['frame']['alt'] = $title->getText();
5295 # Do not set $params['frame']['title'] because tooltips don't make sense
5297 } else { # Inline image
5298 if ( !isset( $params['frame']['alt'] ) ) {
5299 # No alt text, use the "caption" for the alt text
5300 if ( $caption !== '' ) {
5301 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5303 # No caption, fall back to using the filename for the
5305 $params['frame']['alt'] = $title->getText();
5308 # Use the "caption" for the tooltip text
5309 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5312 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5314 # Linker does the rest
5315 $time = isset( $options['time'] ) ?
$options['time'] : false;
5316 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5317 $time, $descQuery, $this->mOptions
->getThumbSize() );
5319 # Give the handler a chance to modify the parser object
5321 $handler->parserTransformHook( $this, $file );
5329 * @param $holders LinkHolderArray
5330 * @return mixed|String
5332 protected function stripAltText( $caption, $holders ) {
5333 # Strip bad stuff out of the title (tooltip). We can't just use
5334 # replaceLinkHoldersText() here, because if this function is called
5335 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5337 $tooltip = $holders->replaceText( $caption );
5339 $tooltip = $this->replaceLinkHoldersText( $caption );
5342 # make sure there are no placeholders in thumbnail attributes
5343 # that are later expanded to html- so expand them now and
5345 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5346 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5352 * Set a flag in the output object indicating that the content is dynamic and
5353 * shouldn't be cached.
5355 function disableCache() {
5356 wfDebug( "Parser output marked as uncacheable.\n" );
5357 if ( !$this->mOutput
) {
5358 throw new MWException( __METHOD__
.
5359 " can only be called when actually parsing something" );
5361 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5362 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5366 * Callback from the Sanitizer for expanding items found in HTML attribute
5367 * values, so they can be safely tested and escaped.
5369 * @param $text String
5370 * @param $frame PPFrame
5373 function attributeStripCallback( &$text, $frame = false ) {
5374 $text = $this->replaceVariables( $text, $frame );
5375 $text = $this->mStripState
->unstripBoth( $text );
5384 function getTags() {
5385 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5389 * Replace transparent tags in $text with the values given by the callbacks.
5391 * Transparent tag hooks are like regular XML-style tag hooks, except they
5392 * operate late in the transformation sequence, on HTML instead of wikitext.
5394 * @param $text string
5398 function replaceTransparentTags( $text ) {
5400 $elements = array_keys( $this->mTransparentTagHooks
);
5401 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5402 $replacements = array();
5404 foreach ( $matches as $marker => $data ) {
5405 list( $element, $content, $params, $tag ) = $data;
5406 $tagName = strtolower( $element );
5407 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5408 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5412 $replacements[$marker] = $output;
5414 return strtr( $text, $replacements );
5418 * Break wikitext input into sections, and either pull or replace
5419 * some particular section's text.
5421 * External callers should use the getSection and replaceSection methods.
5423 * @param string $text Page wikitext
5424 * @param string $section a section identifier string of the form:
5425 * "<flag1> - <flag2> - ... - <section number>"
5427 * Currently the only recognised flag is "T", which means the target section number
5428 * was derived during a template inclusion parse, in other words this is a template
5429 * section edit link. If no flags are given, it was an ordinary section edit link.
5430 * This flag is required to avoid a section numbering mismatch when a section is
5431 * enclosed by "<includeonly>" (bug 6563).
5433 * The section number 0 pulls the text before the first heading; other numbers will
5434 * pull the given section along with its lower-level subsections. If the section is
5435 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5437 * Section 0 is always considered to exist, even if it only contains the empty
5438 * string. If $text is the empty string and section 0 is replaced, $newText is
5441 * @param string $mode one of "get" or "replace"
5442 * @param string $newText replacement text for section data.
5443 * @return String: for "get", the extracted section text.
5444 * for "replace", the whole page with the section replaced.
5446 private function extractSections( $text, $section, $mode, $newText = '' ) {
5447 global $wgTitle; # not generally used but removes an ugly failure mode
5448 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5450 $frame = $this->getPreprocessor()->newFrame();
5452 # Process section extraction flags
5454 $sectionParts = explode( '-', $section );
5455 $sectionIndex = array_pop( $sectionParts );
5456 foreach ( $sectionParts as $part ) {
5457 if ( $part === 'T' ) {
5458 $flags |
= self
::PTD_FOR_INCLUSION
;
5462 # Check for empty input
5463 if ( strval( $text ) === '' ) {
5464 # Only sections 0 and T-0 exist in an empty document
5465 if ( $sectionIndex == 0 ) {
5466 if ( $mode === 'get' ) {
5472 if ( $mode === 'get' ) {
5480 # Preprocess the text
5481 $root = $this->preprocessToDom( $text, $flags );
5483 # <h> nodes indicate section breaks
5484 # They can only occur at the top level, so we can find them by iterating the root's children
5485 $node = $root->getFirstChild();
5487 # Find the target section
5488 if ( $sectionIndex == 0 ) {
5489 # Section zero doesn't nest, level=big
5490 $targetLevel = 1000;
5493 if ( $node->getName() === 'h' ) {
5494 $bits = $node->splitHeading();
5495 if ( $bits['i'] == $sectionIndex ) {
5496 $targetLevel = $bits['level'];
5500 if ( $mode === 'replace' ) {
5501 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5503 $node = $node->getNextSibling();
5509 if ( $mode === 'get' ) {
5516 # Find the end of the section, including nested sections
5518 if ( $node->getName() === 'h' ) {
5519 $bits = $node->splitHeading();
5520 $curLevel = $bits['level'];
5521 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5525 if ( $mode === 'get' ) {
5526 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5528 $node = $node->getNextSibling();
5531 # Write out the remainder (in replace mode only)
5532 if ( $mode === 'replace' ) {
5533 # Output the replacement text
5534 # Add two newlines on -- trailing whitespace in $newText is conventionally
5535 # stripped by the editor, so we need both newlines to restore the paragraph gap
5536 # Only add trailing whitespace if there is newText
5537 if ( $newText != "" ) {
5538 $outText .= $newText . "\n\n";
5542 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5543 $node = $node->getNextSibling();
5547 if ( is_string( $outText ) ) {
5548 # Re-insert stripped tags
5549 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5556 * This function returns the text of a section, specified by a number ($section).
5557 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5558 * the first section before any such heading (section 0).
5560 * If a section contains subsections, these are also returned.
5562 * @param string $text text to look in
5563 * @param string $section section identifier
5564 * @param string $deftext default to return if section is not found
5565 * @return string text of the requested section
5567 public function getSection( $text, $section, $deftext = '' ) {
5568 return $this->extractSections( $text, $section, "get", $deftext );
5572 * This function returns $oldtext after the content of the section
5573 * specified by $section has been replaced with $text. If the target
5574 * section does not exist, $oldtext is returned unchanged.
5576 * @param string $oldtext former text of the article
5577 * @param int $section section identifier
5578 * @param string $text replacing text
5579 * @return String: modified text
5581 public function replaceSection( $oldtext, $section, $text ) {
5582 return $this->extractSections( $oldtext, $section, "replace", $text );
5586 * Get the ID of the revision we are parsing
5588 * @return Mixed: integer or null
5590 function getRevisionId() {
5591 return $this->mRevisionId
;
5595 * Get the revision object for $this->mRevisionId
5597 * @return Revision|null either a Revision object or null
5599 protected function getRevisionObject() {
5600 if ( !is_null( $this->mRevisionObject
) ) {
5601 return $this->mRevisionObject
;
5603 if ( is_null( $this->mRevisionId
) ) {
5607 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5608 return $this->mRevisionObject
;
5612 * Get the timestamp associated with the current revision, adjusted for
5613 * the default server-local timestamp
5615 function getRevisionTimestamp() {
5616 if ( is_null( $this->mRevisionTimestamp
) ) {
5617 wfProfileIn( __METHOD__
);
5621 $revObject = $this->getRevisionObject();
5622 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5624 # The cryptic '' timezone parameter tells to use the site-default
5625 # timezone offset instead of the user settings.
5627 # Since this value will be saved into the parser cache, served
5628 # to other users, and potentially even used inside links and such,
5629 # it needs to be consistent for all visitors.
5630 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5632 wfProfileOut( __METHOD__
);
5634 return $this->mRevisionTimestamp
;
5638 * Get the name of the user that edited the last revision
5640 * @return String: user name
5642 function getRevisionUser() {
5643 if( is_null( $this->mRevisionUser
) ) {
5644 $revObject = $this->getRevisionObject();
5646 # if this template is subst: the revision id will be blank,
5647 # so just use the current user's name
5649 $this->mRevisionUser
= $revObject->getUserText();
5650 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5651 $this->mRevisionUser
= $this->getUser()->getName();
5654 return $this->mRevisionUser
;
5658 * Mutator for $mDefaultSort
5660 * @param string $sort New value
5662 public function setDefaultSort( $sort ) {
5663 $this->mDefaultSort
= $sort;
5664 $this->mOutput
->setProperty( 'defaultsort', $sort );
5668 * Accessor for $mDefaultSort
5669 * Will use the empty string if none is set.
5671 * This value is treated as a prefix, so the
5672 * empty string is equivalent to sorting by
5677 public function getDefaultSort() {
5678 if ( $this->mDefaultSort
!== false ) {
5679 return $this->mDefaultSort
;
5686 * Accessor for $mDefaultSort
5687 * Unlike getDefaultSort(), will return false if none is set
5689 * @return string or false
5691 public function getCustomDefaultSort() {
5692 return $this->mDefaultSort
;
5696 * Try to guess the section anchor name based on a wikitext fragment
5697 * presumably extracted from a heading, for example "Header" from
5700 * @param $text string
5704 public function guessSectionNameFromWikiText( $text ) {
5705 # Strip out wikitext links(they break the anchor)
5706 $text = $this->stripSectionName( $text );
5707 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5708 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5712 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5713 * instead. For use in redirects, since IE6 interprets Redirect: headers
5714 * as something other than UTF-8 (apparently?), resulting in breakage.
5716 * @param string $text The section name
5717 * @return string An anchor
5719 public function guessLegacySectionNameFromWikiText( $text ) {
5720 # Strip out wikitext links(they break the anchor)
5721 $text = $this->stripSectionName( $text );
5722 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5723 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5727 * Strips a text string of wikitext for use in a section anchor
5729 * Accepts a text string and then removes all wikitext from the
5730 * string and leaves only the resultant text (i.e. the result of
5731 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5732 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5733 * to create valid section anchors by mimicing the output of the
5734 * parser when headings are parsed.
5736 * @param string $text text string to be stripped of wikitext
5737 * for use in a Section anchor
5738 * @return string Filtered text string
5740 public function stripSectionName( $text ) {
5741 # Strip internal link markup
5742 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5743 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5745 # Strip external link markup
5746 # @todo FIXME: Not tolerant to blank link text
5747 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5748 # on how many empty links there are on the page - need to figure that out.
5749 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5751 # Parse wikitext quotes (italics & bold)
5752 $text = $this->doQuotes( $text );
5755 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5760 * strip/replaceVariables/unstrip for preprocessor regression testing
5762 * @param $text string
5763 * @param $title Title
5764 * @param $options ParserOptions
5765 * @param $outputType int
5769 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5770 $this->startParse( $title, $options, $outputType, true );
5772 $text = $this->replaceVariables( $text );
5773 $text = $this->mStripState
->unstripBoth( $text );
5774 $text = Sanitizer
::removeHTMLtags( $text );
5779 * @param $text string
5780 * @param $title Title
5781 * @param $options ParserOptions
5784 function testPst( $text, Title
$title, ParserOptions
$options ) {
5785 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5790 * @param $title Title
5791 * @param $options ParserOptions
5794 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5795 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5799 * Call a callback function on all regions of the given text that are not
5800 * inside strip markers, and replace those regions with the return value
5801 * of the callback. For example, with input:
5805 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5806 * two strings will be replaced with the value returned by the callback in
5814 function markerSkipCallback( $s, $callback ) {
5817 while ( $i < strlen( $s ) ) {
5818 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5819 if ( $markerStart === false ) {
5820 $out .= call_user_func( $callback, substr( $s, $i ) );
5823 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5824 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5825 if ( $markerEnd === false ) {
5826 $out .= substr( $s, $markerStart );
5829 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5830 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5839 * Remove any strip markers found in the given text.
5841 * @param $text Input string
5844 function killMarkers( $text ) {
5845 return $this->mStripState
->killMarkers( $text );
5849 * Save the parser state required to convert the given half-parsed text to
5850 * HTML. "Half-parsed" in this context means the output of
5851 * recursiveTagParse() or internalParse(). This output has strip markers
5852 * from replaceVariables (extensionSubstitution() etc.), and link
5853 * placeholders from replaceLinkHolders().
5855 * Returns an array which can be serialized and stored persistently. This
5856 * array can later be loaded into another parser instance with
5857 * unserializeHalfParsedText(). The text can then be safely incorporated into
5858 * the return value of a parser hook.
5860 * @param $text string
5864 function serializeHalfParsedText( $text ) {
5865 wfProfileIn( __METHOD__
);
5868 'version' => self
::HALF_PARSED_VERSION
,
5869 'stripState' => $this->mStripState
->getSubState( $text ),
5870 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5872 wfProfileOut( __METHOD__
);
5877 * Load the parser state given in the $data array, which is assumed to
5878 * have been generated by serializeHalfParsedText(). The text contents is
5879 * extracted from the array, and its markers are transformed into markers
5880 * appropriate for the current Parser instance. This transformed text is
5881 * returned, and can be safely included in the return value of a parser
5884 * If the $data array has been stored persistently, the caller should first
5885 * check whether it is still valid, by calling isValidHalfParsedText().
5887 * @param array $data Serialized data
5888 * @throws MWException
5891 function unserializeHalfParsedText( $data ) {
5892 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5893 throw new MWException( __METHOD__
. ': invalid version' );
5896 # First, extract the strip state.
5897 $texts = array( $data['text'] );
5898 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5900 # Now renumber links
5901 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5903 # Should be good to go.
5908 * Returns true if the given array, presumed to be generated by
5909 * serializeHalfParsedText(), is compatible with the current version of the
5912 * @param $data Array
5916 function isValidHalfParsedText( $data ) {
5917 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5921 * Parsed a width param of imagelink like 300px or 200x300px
5923 * @param $value String
5928 public function parseWidthParam( $value ) {
5929 $parsedWidthParam = array();
5930 if( $value === '' ) {
5931 return $parsedWidthParam;
5934 # (bug 13500) In both cases (width/height and width only),
5935 # permit trailing "px" for backward compatibility.
5936 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5937 $width = intval( $m[1] );
5938 $height = intval( $m[2] );
5939 $parsedWidthParam['width'] = $width;
5940 $parsedWidthParam['height'] = $height;
5941 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5942 $width = intval( $value );
5943 $parsedWidthParam['width'] = $width;
5945 return $parsedWidthParam;