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 (X)HTML 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
196 var $mInputSize = false; # For {{PAGESIZE}} on current page.
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
208 var $mLangLinkLanguages;
215 public function __construct( $conf = array() ) {
216 $this->mConf
= $conf;
217 $this->mUrlProtocols
= wfUrlProtocols();
218 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
219 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass
= $conf['preprocessorClass'];
222 } elseif ( defined( 'HPHP_VERSION' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass
= 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass
= 'Preprocessor_DOM';
232 $this->mPreprocessorClass
= 'Preprocessor_Hash';
234 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
238 * Reduce memory usage to reduce the impact of circular references
240 function __destruct() {
241 if ( isset( $this->mLinkHolders
) ) {
242 unset( $this->mLinkHolders
);
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
250 * Allow extensions to clean up when the parser is cloned
253 wfRunHooks( 'ParserCloned', array( $this ) );
257 * Do various kinds of initialisation on the first call of the parser
259 function firstCallInit() {
260 if ( !$this->mFirstCall
) {
263 $this->mFirstCall
= false;
265 wfProfileIn( __METHOD__
);
267 CoreParserFunctions
::register( $this );
268 CoreTagHooks
::register( $this );
269 $this->initialiseVariables();
271 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
272 wfProfileOut( __METHOD__
);
280 function clearState() {
281 wfProfileIn( __METHOD__
);
282 if ( $this->mFirstCall
) {
283 $this->firstCallInit();
285 $this->mOutput
= new ParserOutput
;
286 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
287 $this->mAutonumber
= 0;
288 $this->mLastSection
= '';
289 $this->mDTopen
= false;
290 $this->mIncludeCount
= array();
291 $this->mArgStack
= false;
292 $this->mInPre
= false;
293 $this->mLinkHolders
= new LinkHolderArray( $this );
295 $this->mRevisionObject
= $this->mRevisionTimestamp
=
296 $this->mRevisionId
= $this->mRevisionUser
= null;
297 $this->mVarCache
= array();
299 $this->mLangLinkLanguages
= array();
302 * Prefix for temporary replacement strings for the multipass parser.
303 * \x07 should never appear in input as it's disallowed in XML.
304 * Using it at the front also gives us a little extra robustness
305 * since it shouldn't match when butted up against identifier-like
308 * Must not consist of all title characters, or else it will change
309 * the behavior of <nowiki> in a link.
311 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
312 $this->mStripState
= new StripState( $this->mUniqPrefix
);
314 # Clear these on every parse, bug 4549
315 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
317 $this->mShowToc
= true;
318 $this->mForceTocPosition
= false;
319 $this->mIncludeSizes
= array(
323 $this->mPPNodeCount
= 0;
324 $this->mGeneratedPPNodeCount
= 0;
325 $this->mHighestExpansionDepth
= 0;
326 $this->mDefaultSort
= false;
327 $this->mHeadings
= array();
328 $this->mDoubleUnderscores
= array();
329 $this->mExpensiveFunctionCount
= 0;
332 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
333 $this->mPreprocessor
= null;
336 wfRunHooks( 'ParserClearState', array( &$this ) );
337 wfProfileOut( __METHOD__
);
341 * Convert wikitext to HTML
342 * Do not call this function recursively.
344 * @param string $text text we want to parse
345 * @param $title Title object
346 * @param $options ParserOptions
347 * @param $linestart boolean
348 * @param $clearState boolean
349 * @param int $revid number to pass in {{REVISIONID}}
350 * @return ParserOutput a ParserOutput
352 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
354 * First pass--just handle <nowiki> sections, pass the rest off
355 * to internalParse() which does all the real work.
358 global $wgUseTidy, $wgAlwaysUseTidy;
359 $fname = __METHOD__
. '-' . wfGetCaller();
360 wfProfileIn( __METHOD__
);
361 wfProfileIn( $fname );
363 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
365 $this->mInputSize
= strlen( $text );
367 # Remove the strip marker tag prefix from the input, if present.
369 $text = str_replace( $this->mUniqPrefix
, '', $text );
372 $oldRevisionId = $this->mRevisionId
;
373 $oldRevisionObject = $this->mRevisionObject
;
374 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
375 $oldRevisionUser = $this->mRevisionUser
;
376 if ( $revid !== null ) {
377 $this->mRevisionId
= $revid;
378 $this->mRevisionObject
= null;
379 $this->mRevisionTimestamp
= null;
380 $this->mRevisionUser
= null;
383 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
385 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
386 $text = $this->internalParse( $text );
387 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
389 $text = $this->mStripState
->unstripGeneral( $text );
391 # Clean up special characters, only run once, next-to-last before doBlockLevels
393 # french spaces, last one Guillemet-left
394 # only if there is something before the space
395 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
396 # french spaces, Guillemet-right
397 '/(\\302\\253) /' => '\\1 ',
398 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
400 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
402 $text = $this->doBlockLevels( $text, $linestart );
404 $this->replaceLinkHolders( $text );
407 * The input doesn't get language converted if
409 * b) Content isn't converted
410 * c) It's a conversion table
411 * d) it is an interface message (which is in the user language)
413 if ( !( $options->getDisableContentConversion()
414 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
416 if ( !$this->mOptions
->getInterfaceMessage() ) {
417 # The position of the convert() call should not be changed. it
418 # assumes that the links are all replaced and the only thing left
419 # is the <nowiki> mark.
420 $text = $this->getConverterLanguage()->convert( $text );
425 * A converted title will be provided in the output object if title and
426 * content conversion are enabled, the article text does not contain
427 * a conversion-suppressing double-underscore tag, and no
428 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
429 * automatic link conversion.
431 if ( !( $options->getDisableTitleConversion()
432 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
433 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
434 ||
$this->mOutput
->getDisplayTitle() !== false ) )
436 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
437 if ( $convruletitle ) {
438 $this->mOutput
->setTitleText( $convruletitle );
440 $titleText = $this->getConverterLanguage()->convertTitle( $title );
441 $this->mOutput
->setTitleText( $titleText );
445 $text = $this->mStripState
->unstripNoWiki( $text );
447 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
449 $text = $this->replaceTransparentTags( $text );
450 $text = $this->mStripState
->unstripGeneral( $text );
452 $text = Sanitizer
::normalizeCharReferences( $text );
454 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
455 $text = MWTidy
::tidy( $text );
457 # attempt to sanitize at least some nesting problems
458 # (bug #2702 and quite a few others)
460 # ''Something [http://www.cool.com cool''] -->
461 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
462 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
463 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
464 # fix up an anchor inside another anchor, only
465 # at least for a single single nested link (bug 3695)
466 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
467 '\\1\\2</a>\\3</a>\\1\\4</a>',
468 # fix div inside inline elements- doBlockLevels won't wrap a line which
469 # contains a div, so fix it up here; replace
470 # div with escaped text
471 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
472 '\\1\\3<div\\5>\\6</div>\\8\\9',
473 # remove empty italic or bold tag pairs, some
474 # introduced by rules above
475 '/<([bi])><\/\\1>/' => '',
478 $text = preg_replace(
479 array_keys( $tidyregs ),
480 array_values( $tidyregs ),
484 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
485 $this->limitationWarn( 'expensive-parserfunction',
486 $this->mExpensiveFunctionCount
,
487 $this->mOptions
->getExpensiveParserFunctionLimit()
491 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
493 # Information on include size limits, for the benefit of users who try to skirt them
494 if ( $this->mOptions
->getEnableLimitReport() ) {
495 $max = $this->mOptions
->getMaxIncludeSize();
496 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
498 "NewPP limit report\n" .
499 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
500 "Preprocessor generated node count: " .
501 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
502 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
503 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n" .
504 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n" .
506 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
508 // Sanitize for comment. Note '‐' in the replacement is U+2010,
509 // which looks much like the problematic '-'.
510 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
512 $text .= "\n<!-- \n$limitReport-->\n";
514 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
515 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
516 $this->mTitle
->getPrefixedDBkey() );
519 $this->mOutput
->setText( $text );
521 $this->mRevisionId
= $oldRevisionId;
522 $this->mRevisionObject
= $oldRevisionObject;
523 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
524 $this->mRevisionUser
= $oldRevisionUser;
525 $this->mInputSize
= false;
526 wfProfileOut( $fname );
527 wfProfileOut( __METHOD__
);
529 return $this->mOutput
;
533 * Recursive parser entry point that can be called from an extension tag
536 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
538 * @param string $text text extension wants to have parsed
539 * @param $frame PPFrame: The frame to use for expanding any template variables
543 function recursiveTagParse( $text, $frame = false ) {
544 wfProfileIn( __METHOD__
);
545 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
546 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
547 $text = $this->internalParse( $text, false, $frame );
548 wfProfileOut( __METHOD__
);
553 * Expand templates and variables in the text, producing valid, static wikitext.
554 * Also removes comments.
555 * @return mixed|string
557 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
558 wfProfileIn( __METHOD__
);
559 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
560 if ( $revid !== null ) {
561 $this->mRevisionId
= $revid;
563 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
564 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
565 $text = $this->replaceVariables( $text );
566 $text = $this->mStripState
->unstripBoth( $text );
567 wfProfileOut( __METHOD__
);
572 * Recursive parser entry point that can be called from an extension tag
575 * @param string $text text to be expanded
576 * @param $frame PPFrame: The frame to use for expanding any template variables
580 public function recursivePreprocess( $text, $frame = false ) {
581 wfProfileIn( __METHOD__
);
582 $text = $this->replaceVariables( $text, $frame );
583 $text = $this->mStripState
->unstripBoth( $text );
584 wfProfileOut( __METHOD__
);
589 * Process the wikitext for the "?preload=" feature. (bug 5210)
591 * "<noinclude>", "<includeonly>" etc. are parsed as for template
592 * transclusion, comments, templates, arguments, tags hooks and parser
593 * functions are untouched.
595 * @param $text String
596 * @param $title Title
597 * @param $options ParserOptions
600 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
601 # Parser (re)initialisation
602 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
604 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
605 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
606 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
607 $text = $this->mStripState
->unstripBoth( $text );
612 * Get a random string
616 public static function getRandomString() {
617 return wfRandomString( 16 );
621 * Set the current user.
622 * Should only be used when doing pre-save transform.
624 * @param $user Mixed: User object or null (to reset)
626 function setUser( $user ) {
627 $this->mUser
= $user;
631 * Accessor for mUniqPrefix.
635 public function uniqPrefix() {
636 if ( !isset( $this->mUniqPrefix
) ) {
637 # @todo FIXME: This is probably *horribly wrong*
638 # LanguageConverter seems to want $wgParser's uniqPrefix, however
639 # if this is called for a parser cache hit, the parser may not
640 # have ever been initialized in the first place.
641 # Not really sure what the heck is supposed to be going on here.
643 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
645 return $this->mUniqPrefix
;
649 * Set the context title
653 function setTitle( $t ) {
654 if ( !$t ||
$t instanceof FakeTitle
) {
655 $t = Title
::newFromText( 'NO TITLE' );
658 if ( strval( $t->getFragment() ) !== '' ) {
659 # Strip the fragment to avoid various odd effects
660 $this->mTitle
= clone $t;
661 $this->mTitle
->setFragment( '' );
668 * Accessor for the Title object
670 * @return Title object
672 function getTitle() {
673 return $this->mTitle
;
677 * Accessor/mutator for the Title object
679 * @param $x Title object or null to just get the current one
680 * @return Title object
682 function Title( $x = null ) {
683 return wfSetVar( $this->mTitle
, $x );
687 * Set the output type
689 * @param $ot Integer: new value
691 function setOutputType( $ot ) {
692 $this->mOutputType
= $ot;
695 'html' => $ot == self
::OT_HTML
,
696 'wiki' => $ot == self
::OT_WIKI
,
697 'pre' => $ot == self
::OT_PREPROCESS
,
698 'plain' => $ot == self
::OT_PLAIN
,
703 * Accessor/mutator for the output type
705 * @param int|null $x New value or null to just get the current one
708 function OutputType( $x = null ) {
709 return wfSetVar( $this->mOutputType
, $x );
713 * Get the ParserOutput object
715 * @return ParserOutput object
717 function getOutput() {
718 return $this->mOutput
;
722 * Get the ParserOptions object
724 * @return ParserOptions object
726 function getOptions() {
727 return $this->mOptions
;
731 * Accessor/mutator for the ParserOptions object
733 * @param $x ParserOptions New value or null to just get the current one
734 * @return ParserOptions Current ParserOptions object
736 function Options( $x = null ) {
737 return wfSetVar( $this->mOptions
, $x );
743 function nextLinkID() {
744 return $this->mLinkID++
;
750 function setLinkID( $id ) {
751 $this->mLinkID
= $id;
755 * Get a language object for use in parser functions such as {{FORMATNUM:}}
758 function getFunctionLang() {
759 return $this->getTargetLanguage();
763 * Get the target language for the content being parsed. This is usually the
764 * language that the content is in.
768 * @throws MWException
769 * @return Language|null
771 public function getTargetLanguage() {
772 $target = $this->mOptions
->getTargetLanguage();
774 if ( $target !== null ) {
776 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
777 return $this->mOptions
->getUserLangObj();
778 } elseif ( is_null( $this->mTitle
) ) {
779 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
782 return $this->mTitle
->getPageLanguage();
786 * Get the language object for language conversion
788 function getConverterLanguage() {
789 return $this->getTargetLanguage();
793 * Get a User object either from $this->mUser, if set, or from the
794 * ParserOptions object otherwise
796 * @return User object
799 if ( !is_null( $this->mUser
) ) {
802 return $this->mOptions
->getUser();
806 * Get a preprocessor object
808 * @return Preprocessor instance
810 function getPreprocessor() {
811 if ( !isset( $this->mPreprocessor
) ) {
812 $class = $this->mPreprocessorClass
;
813 $this->mPreprocessor
= new $class( $this );
815 return $this->mPreprocessor
;
819 * Replaces all occurrences of HTML-style comments and the given tags
820 * in the text with a random marker and returns the next text. The output
821 * parameter $matches will be an associative array filled with data in
825 * 'UNIQ-xxxxx' => array(
828 * array( 'param' => 'x' ),
829 * '<element param="x">tag content</element>' ) )
832 * @param array $elements list of element names. Comments are always extracted.
833 * @param string $text Source text string.
834 * @param array $matches Out parameter, Array: extracted tags
835 * @param $uniq_prefix string
836 * @return String: stripped text
838 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
843 $taglist = implode( '|', $elements );
844 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
846 while ( $text != '' ) {
847 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
849 if ( count( $p ) < 5 ) {
852 if ( count( $p ) > 5 ) {
866 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
867 $stripped .= $marker;
869 if ( $close === '/>' ) {
870 # Empty element tag, <tag />
875 if ( $element === '!--' ) {
878 $end = "/(<\\/$element\\s*>)/i";
880 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
882 if ( count( $q ) < 3 ) {
883 # No end tag -- let it run out to the end of the text.
892 $matches[$marker] = array( $element,
894 Sanitizer
::decodeTagAttributes( $attributes ),
895 "<$element$attributes$close$content$tail" );
901 * Get a list of strippable XML-like elements
905 function getStripList() {
906 return $this->mStripList
;
910 * Add an item to the strip state
911 * Returns the unique tag which must be inserted into the stripped text
912 * The tag will be replaced with the original text in unstrip()
914 * @param $text string
918 function insertStripItem( $text ) {
919 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
920 $this->mMarkerIndex++
;
921 $this->mStripState
->addGeneral( $rnd, $text );
926 * parse the wiki syntax used to render tables
931 function doTableStuff( $text ) {
932 wfProfileIn( __METHOD__
);
934 $lines = StringUtils
::explode( "\n", $text );
936 $td_history = array(); # Is currently a td tag open?
937 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
938 $tr_history = array(); # Is currently a tr tag open?
939 $tr_attributes = array(); # history of tr attributes
940 $has_opened_tr = array(); # Did this table open a <tr> element?
941 $indent_level = 0; # indent level of the table
943 foreach ( $lines as $outLine ) {
944 $line = trim( $outLine );
946 if ( $line === '' ) { # empty line, go to next line
947 $out .= $outLine . "\n";
951 $first_character = $line[0];
954 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
955 # First check if we are starting a new table
956 $indent_level = strlen( $matches[1] );
958 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
959 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
961 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
962 array_push( $td_history, false );
963 array_push( $last_tag_history, '' );
964 array_push( $tr_history, false );
965 array_push( $tr_attributes, '' );
966 array_push( $has_opened_tr, false );
967 } elseif ( count( $td_history ) == 0 ) {
968 # Don't do any of the following
969 $out .= $outLine . "\n";
971 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
972 # We are ending a table
973 $line = '</table>' . substr( $line, 2 );
974 $last_tag = array_pop( $last_tag_history );
976 if ( !array_pop( $has_opened_tr ) ) {
977 $line = "<tr><td></td></tr>{$line}";
980 if ( array_pop( $tr_history ) ) {
981 $line = "</tr>{$line}";
984 if ( array_pop( $td_history ) ) {
985 $line = "</{$last_tag}>{$line}";
987 array_pop( $tr_attributes );
988 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
989 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
990 # Now we have a table row
991 $line = preg_replace( '#^\|-+#', '', $line );
993 # Whats after the tag is now only attributes
994 $attributes = $this->mStripState
->unstripBoth( $line );
995 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
996 array_pop( $tr_attributes );
997 array_push( $tr_attributes, $attributes );
1000 $last_tag = array_pop( $last_tag_history );
1001 array_pop( $has_opened_tr );
1002 array_push( $has_opened_tr, true );
1004 if ( array_pop( $tr_history ) ) {
1008 if ( array_pop( $td_history ) ) {
1009 $line = "</{$last_tag}>{$line}";
1013 array_push( $tr_history, false );
1014 array_push( $td_history, false );
1015 array_push( $last_tag_history, '' );
1016 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1017 # This might be cell elements, td, th or captions
1018 if ( substr( $line, 0, 2 ) === '|+' ) {
1019 $first_character = '+';
1020 $line = substr( $line, 1 );
1023 $line = substr( $line, 1 );
1025 if ( $first_character === '!' ) {
1026 $line = str_replace( '!!', '||', $line );
1029 # Split up multiple cells on the same line.
1030 # FIXME : This can result in improper nesting of tags processed
1031 # by earlier parser steps, but should avoid splitting up eg
1032 # attribute values containing literal "||".
1033 $cells = StringUtils
::explodeMarkup( '||', $line );
1037 # Loop through each table cell
1038 foreach ( $cells as $cell ) {
1040 if ( $first_character !== '+' ) {
1041 $tr_after = array_pop( $tr_attributes );
1042 if ( !array_pop( $tr_history ) ) {
1043 $previous = "<tr{$tr_after}>\n";
1045 array_push( $tr_history, true );
1046 array_push( $tr_attributes, '' );
1047 array_pop( $has_opened_tr );
1048 array_push( $has_opened_tr, true );
1051 $last_tag = array_pop( $last_tag_history );
1053 if ( array_pop( $td_history ) ) {
1054 $previous = "</{$last_tag}>\n{$previous}";
1057 if ( $first_character === '|' ) {
1059 } elseif ( $first_character === '!' ) {
1061 } elseif ( $first_character === '+' ) {
1062 $last_tag = 'caption';
1067 array_push( $last_tag_history, $last_tag );
1069 # A cell could contain both parameters and data
1070 $cell_data = explode( '|', $cell, 2 );
1072 # Bug 553: Note that a '|' inside an invalid link should not
1073 # be mistaken as delimiting cell parameters
1074 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1075 $cell = "{$previous}<{$last_tag}>{$cell}";
1076 } elseif ( count( $cell_data ) == 1 ) {
1077 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1079 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1080 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1081 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1085 array_push( $td_history, true );
1088 $out .= $outLine . "\n";
1091 # Closing open td, tr && table
1092 while ( count( $td_history ) > 0 ) {
1093 if ( array_pop( $td_history ) ) {
1096 if ( array_pop( $tr_history ) ) {
1099 if ( !array_pop( $has_opened_tr ) ) {
1100 $out .= "<tr><td></td></tr>\n";
1103 $out .= "</table>\n";
1106 # Remove trailing line-ending (b/c)
1107 if ( substr( $out, -1 ) === "\n" ) {
1108 $out = substr( $out, 0, -1 );
1111 # special case: don't return empty table
1112 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1116 wfProfileOut( __METHOD__
);
1122 * Helper function for parse() that transforms wiki markup into
1123 * HTML. Only called for $mOutputType == self::OT_HTML.
1127 * @param $text string
1128 * @param $isMain bool
1129 * @param $frame bool
1133 function internalParse( $text, $isMain = true, $frame = false ) {
1134 wfProfileIn( __METHOD__
);
1138 # Hook to suspend the parser in this state
1139 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1140 wfProfileOut( __METHOD__
);
1144 # if $frame is provided, then use $frame for replacing any variables
1146 # use frame depth to infer how include/noinclude tags should be handled
1147 # depth=0 means this is the top-level document; otherwise it's an included document
1148 if ( !$frame->depth
) {
1151 $flag = Parser
::PTD_FOR_INCLUSION
;
1153 $dom = $this->preprocessToDom( $text, $flag );
1154 $text = $frame->expand( $dom );
1156 # if $frame is not provided, then use old-style replaceVariables
1157 $text = $this->replaceVariables( $text );
1160 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1161 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1162 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1164 # Tables need to come after variable replacement for things to work
1165 # properly; putting them before other transformations should keep
1166 # exciting things like link expansions from showing up in surprising
1168 $text = $this->doTableStuff( $text );
1170 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1172 $text = $this->doDoubleUnderscore( $text );
1174 $text = $this->doHeadings( $text );
1175 $text = $this->replaceInternalLinks( $text );
1176 $text = $this->doAllQuotes( $text );
1177 $text = $this->replaceExternalLinks( $text );
1179 # replaceInternalLinks may sometimes leave behind
1180 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1181 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1183 $text = $this->doMagicLinks( $text );
1184 $text = $this->formatHeadings( $text, $origText, $isMain );
1186 wfProfileOut( __METHOD__
);
1191 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1192 * magic external links.
1197 * @param $text string
1201 function doMagicLinks( $text ) {
1202 wfProfileIn( __METHOD__
);
1203 $prots = wfUrlProtocolsWithoutProtRel();
1204 $urlChar = self
::EXT_LINK_URL_CLASS
;
1205 $text = preg_replace_callback(
1207 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1208 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1209 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1210 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1211 ISBN\s+(\b # m[5]: ISBN, capture number
1212 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1213 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1214 [0-9Xx] # check digit
1216 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1217 wfProfileOut( __METHOD__
);
1222 * @throws MWException
1224 * @return HTML|string
1226 function magicLinkCallback( $m ) {
1227 if ( isset( $m[1] ) && $m[1] !== '' ) {
1230 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1233 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1234 # Free external link
1235 return $this->makeFreeExternalLink( $m[0] );
1236 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1238 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1241 $CssClass = 'mw-magiclink-rfc';
1243 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1245 $urlmsg = 'pubmedurl';
1246 $CssClass = 'mw-magiclink-pmid';
1249 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1250 substr( $m[0], 0, 20 ) . '"' );
1252 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1253 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1254 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1257 $num = strtr( $isbn, array(
1262 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1263 return '<a href="' .
1264 htmlspecialchars( $titleObj->getLocalURL() ) .
1265 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1272 * Make a free external link, given a user-supplied URL
1274 * @param $url string
1276 * @return string HTML
1279 function makeFreeExternalLink( $url ) {
1280 wfProfileIn( __METHOD__
);
1284 # The characters '<' and '>' (which were escaped by
1285 # removeHTMLtags()) should not be included in
1286 # URLs, per RFC 2396.
1288 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1289 $trail = substr( $url, $m2[0][1] ) . $trail;
1290 $url = substr( $url, 0, $m2[0][1] );
1293 # Move trailing punctuation to $trail
1295 # If there is no left bracket, then consider right brackets fair game too
1296 if ( strpos( $url, '(' ) === false ) {
1300 $numSepChars = strspn( strrev( $url ), $sep );
1301 if ( $numSepChars ) {
1302 $trail = substr( $url, -$numSepChars ) . $trail;
1303 $url = substr( $url, 0, -$numSepChars );
1306 $url = Sanitizer
::cleanUrl( $url );
1308 # Is this an external image?
1309 $text = $this->maybeMakeExternalImage( $url );
1310 if ( $text === false ) {
1311 # Not an image, make a link
1312 $text = Linker
::makeExternalLink( $url,
1313 $this->getConverterLanguage()->markNoConversion( $url, true ),
1315 $this->getExternalLinkAttribs( $url ) );
1316 # Register it in the output object...
1317 # Replace unnecessary URL escape codes with their equivalent characters
1318 $pasteurized = self
::replaceUnusualEscapes( $url );
1319 $this->mOutput
->addExternalLink( $pasteurized );
1321 wfProfileOut( __METHOD__
);
1322 return $text . $trail;
1326 * Parse headers and return html
1330 * @param $text string
1334 function doHeadings( $text ) {
1335 wfProfileIn( __METHOD__
);
1336 for ( $i = 6; $i >= 1; --$i ) {
1337 $h = str_repeat( '=', $i );
1338 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1340 wfProfileOut( __METHOD__
);
1345 * Replace single quotes with HTML markup
1348 * @param $text string
1350 * @return string the altered text
1352 function doAllQuotes( $text ) {
1353 wfProfileIn( __METHOD__
);
1355 $lines = StringUtils
::explode( "\n", $text );
1356 foreach ( $lines as $line ) {
1357 $outtext .= $this->doQuotes( $line ) . "\n";
1359 $outtext = substr( $outtext, 0, -1 );
1360 wfProfileOut( __METHOD__
);
1365 * Helper function for doAllQuotes()
1367 * @param $text string
1371 public function doQuotes( $text ) {
1372 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1373 if ( count( $arr ) == 1 ) {
1376 # First, do some preliminary work. This may shift some apostrophes from
1377 # being mark-up to being text. It also counts the number of occurrences
1378 # of bold and italics mark-ups.
1381 for ( $i = 0; $i < count( $arr ); $i++
) {
1382 if ( ( $i %
2 ) == 1 ) {
1383 # If there are ever four apostrophes, assume the first is supposed to
1384 # be text, and the remaining three constitute mark-up for bold text.
1385 if ( strlen( $arr[$i] ) == 4 ) {
1386 $arr[$i - 1] .= "'";
1388 } elseif ( strlen( $arr[$i] ) > 5 ) {
1389 # If there are more than 5 apostrophes in a row, assume they're all
1390 # text except for the last 5.
1391 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1394 # Count the number of occurrences of bold and italics mark-ups.
1395 # We are not counting sequences of five apostrophes.
1396 if ( strlen( $arr[$i] ) == 2 ) {
1398 } elseif ( strlen( $arr[$i] ) == 3 ) {
1400 } elseif ( strlen( $arr[$i] ) == 5 ) {
1407 # If there is an odd number of both bold and italics, it is likely
1408 # that one of the bold ones was meant to be an apostrophe followed
1409 # by italics. Which one we cannot know for certain, but it is more
1410 # likely to be one that has a single-letter word before it.
1411 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1413 $firstsingleletterword = -1;
1414 $firstmultiletterword = -1;
1416 foreach ( $arr as $r ) {
1417 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1418 $x1 = substr( $arr[$i - 1], -1 );
1419 $x2 = substr( $arr[$i - 1], -2, 1 );
1420 if ( $x1 === ' ' ) {
1421 if ( $firstspace == -1 ) {
1424 } elseif ( $x2 === ' ' ) {
1425 if ( $firstsingleletterword == -1 ) {
1426 $firstsingleletterword = $i;
1429 if ( $firstmultiletterword == -1 ) {
1430 $firstmultiletterword = $i;
1437 # If there is a single-letter word, use it!
1438 if ( $firstsingleletterword > -1 ) {
1439 $arr[$firstsingleletterword] = "''";
1440 $arr[$firstsingleletterword - 1] .= "'";
1441 } elseif ( $firstmultiletterword > -1 ) {
1442 # If not, but there's a multi-letter word, use that one.
1443 $arr[$firstmultiletterword] = "''";
1444 $arr[$firstmultiletterword - 1] .= "'";
1445 } elseif ( $firstspace > -1 ) {
1446 # ... otherwise use the first one that has neither.
1447 # (notice that it is possible for all three to be -1 if, for example,
1448 # there is only one pentuple-apostrophe in the line)
1449 $arr[$firstspace] = "''";
1450 $arr[$firstspace - 1] .= "'";
1454 # Now let's actually convert our apostrophic mush to HTML!
1459 foreach ( $arr as $r ) {
1460 if ( ( $i %
2 ) == 0 ) {
1461 if ( $state === 'both' ) {
1467 if ( strlen( $r ) == 2 ) {
1468 if ( $state === 'i' ) {
1471 } elseif ( $state === 'bi' ) {
1474 } elseif ( $state === 'ib' ) {
1475 $output .= '</b></i><b>';
1477 } elseif ( $state === 'both' ) {
1478 $output .= '<b><i>' . $buffer . '</i>';
1480 } else { # $state can be 'b' or ''
1484 } elseif ( strlen( $r ) == 3 ) {
1485 if ( $state === 'b' ) {
1488 } elseif ( $state === 'bi' ) {
1489 $output .= '</i></b><i>';
1491 } elseif ( $state === 'ib' ) {
1494 } elseif ( $state === 'both' ) {
1495 $output .= '<i><b>' . $buffer . '</b>';
1497 } else { # $state can be 'i' or ''
1501 } elseif ( strlen( $r ) == 5 ) {
1502 if ( $state === 'b' ) {
1503 $output .= '</b><i>';
1505 } elseif ( $state === 'i' ) {
1506 $output .= '</i><b>';
1508 } elseif ( $state === 'bi' ) {
1509 $output .= '</i></b>';
1511 } elseif ( $state === 'ib' ) {
1512 $output .= '</b></i>';
1514 } elseif ( $state === 'both' ) {
1515 $output .= '<i><b>' . $buffer . '</b></i>';
1517 } else { # ($state == '')
1525 # Now close all remaining tags. Notice that the order is important.
1526 if ( $state === 'b' ||
$state === 'ib' ) {
1529 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1532 if ( $state === 'bi' ) {
1535 # There might be lonely ''''', so make sure we have a buffer
1536 if ( $state === 'both' && $buffer ) {
1537 $output .= '<b><i>' . $buffer . '</i></b>';
1544 * Replace external links (REL)
1546 * Note: this is all very hackish and the order of execution matters a lot.
1547 * Make sure to run maintenance/parserTests.php if you change this code.
1551 * @param $text string
1553 * @throws MWException
1556 function replaceExternalLinks( $text ) {
1557 wfProfileIn( __METHOD__
);
1559 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1560 if ( $bits === false ) {
1561 wfProfileOut( __METHOD__
);
1562 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1564 $s = array_shift( $bits );
1567 while ( $i < count( $bits ) ) {
1570 $text = $bits[$i++
];
1571 $trail = $bits[$i++
];
1573 # The characters '<' and '>' (which were escaped by
1574 # removeHTMLtags()) should not be included in
1575 # URLs, per RFC 2396.
1577 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1578 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1579 $url = substr( $url, 0, $m2[0][1] );
1582 # If the link text is an image URL, replace it with an <img> tag
1583 # This happened by accident in the original parser, but some people used it extensively
1584 $img = $this->maybeMakeExternalImage( $text );
1585 if ( $img !== false ) {
1591 # Set linktype for CSS - if URL==text, link is essentially free
1592 $linktype = ( $text === $url ) ?
'free' : 'text';
1594 # No link text, e.g. [http://domain.tld/some.link]
1595 if ( $text == '' ) {
1597 $langObj = $this->getTargetLanguage();
1598 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1599 $linktype = 'autonumber';
1601 # Have link text, e.g. [http://domain.tld/some.link text]s
1603 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1606 $text = $this->getConverterLanguage()->markNoConversion( $text );
1608 $url = Sanitizer
::cleanUrl( $url );
1610 # Use the encoded URL
1611 # This means that users can paste URLs directly into the text
1612 # Funny characters like ö aren't valid in URLs anyway
1613 # This was changed in August 2004
1614 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1615 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1617 # Register link in the output object.
1618 # Replace unnecessary URL escape codes with the referenced character
1619 # This prevents spammers from hiding links from the filters
1620 $pasteurized = self
::replaceUnusualEscapes( $url );
1621 $this->mOutput
->addExternalLink( $pasteurized );
1624 wfProfileOut( __METHOD__
);
1628 * Get the rel attribute for a particular external link.
1631 * @param string|bool $url optional URL, to extract the domain from for rel =>
1632 * nofollow if appropriate
1633 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1634 * @return string|null rel attribute for $url
1636 public static function getExternalLinkRel( $url = false, $title = null ) {
1637 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1638 $ns = $title ?
$title->getNamespace() : false;
1639 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1640 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1647 * Get an associative array of additional HTML attributes appropriate for a
1648 * particular external link. This currently may include rel => nofollow
1649 * (depending on configuration, namespace, and the URL's domain) and/or a
1650 * target attribute (depending on configuration).
1652 * @param string|bool $url optional URL, to extract the domain from for rel =>
1653 * nofollow if appropriate
1654 * @return Array associative array of HTML attributes
1656 function getExternalLinkAttribs( $url = false ) {
1658 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1660 if ( $this->mOptions
->getExternalLinkTarget() ) {
1661 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1667 * Replace unusual URL escape codes with their equivalent characters
1669 * @param $url String
1672 * @todo This can merge genuinely required bits in the path or query string,
1673 * breaking legit URLs. A proper fix would treat the various parts of
1674 * the URL differently; as a workaround, just use the output for
1675 * statistical records, not for actual linking/output.
1677 static function replaceUnusualEscapes( $url ) {
1678 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1679 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1683 * Callback function used in replaceUnusualEscapes().
1684 * Replaces unusual URL escape codes with their equivalent character
1686 * @param $matches array
1690 private static function replaceUnusualEscapesCallback( $matches ) {
1691 $char = urldecode( $matches[0] );
1692 $ord = ord( $char );
1693 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1694 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1695 # No, shouldn't be escaped
1698 # Yes, leave it escaped
1704 * make an image if it's allowed, either through the global
1705 * option, through the exception, or through the on-wiki whitelist
1708 * $param $url string
1712 function maybeMakeExternalImage( $url ) {
1713 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1714 $imagesexception = !empty( $imagesfrom );
1716 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1717 if ( $imagesexception && is_array( $imagesfrom ) ) {
1718 $imagematch = false;
1719 foreach ( $imagesfrom as $match ) {
1720 if ( strpos( $url, $match ) === 0 ) {
1725 } elseif ( $imagesexception ) {
1726 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1728 $imagematch = false;
1730 if ( $this->mOptions
->getAllowExternalImages()
1731 ||
( $imagesexception && $imagematch ) ) {
1732 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1734 $text = Linker
::makeExternalImage( $url );
1737 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1738 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1739 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1740 foreach ( $whitelist as $entry ) {
1741 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1742 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1745 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1746 # Image matches a whitelist entry
1747 $text = Linker
::makeExternalImage( $url );
1756 * Process [[ ]] wikilinks
1760 * @return String: processed text
1764 function replaceInternalLinks( $s ) {
1765 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1770 * Process [[ ]] wikilinks (RIL)
1772 * @throws MWException
1773 * @return LinkHolderArray
1777 function replaceInternalLinks2( &$s ) {
1778 wfProfileIn( __METHOD__
);
1780 wfProfileIn( __METHOD__
. '-setup' );
1781 static $tc = false, $e1, $e1_img;
1782 # the % is needed to support urlencoded titles as well
1784 $tc = Title
::legalChars() . '#%';
1785 # Match a link having the form [[namespace:link|alternate]]trail
1786 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1787 # Match cases where there is no "]]", which might still be images
1788 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1791 $holders = new LinkHolderArray( $this );
1793 # split the entire text string on occurrences of [[
1794 $a = StringUtils
::explode( '[[', ' ' . $s );
1795 # get the first element (all text up to first [[), and remove the space we added
1798 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1799 $s = substr( $s, 1 );
1801 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1803 if ( $useLinkPrefixExtension ) {
1804 # Match the end of a line for a word that's not followed by whitespace,
1805 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1806 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1809 if ( is_null( $this->mTitle
) ) {
1810 wfProfileOut( __METHOD__
. '-setup' );
1811 wfProfileOut( __METHOD__
);
1812 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1814 $nottalk = !$this->mTitle
->isTalkPage();
1816 if ( $useLinkPrefixExtension ) {
1818 if ( preg_match( $e2, $s, $m ) ) {
1819 $first_prefix = $m[2];
1821 $first_prefix = false;
1827 $useSubpages = $this->areSubpagesAllowed();
1828 wfProfileOut( __METHOD__
. '-setup' );
1830 # Loop for each link
1831 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1832 # Check for excessive memory usage
1833 if ( $holders->isBig() ) {
1835 # Do the existence check, replace the link holders and clear the array
1836 $holders->replace( $s );
1840 if ( $useLinkPrefixExtension ) {
1841 wfProfileIn( __METHOD__
. '-prefixhandling' );
1842 if ( preg_match( $e2, $s, $m ) ) {
1849 if ( $first_prefix ) {
1850 $prefix = $first_prefix;
1851 $first_prefix = false;
1853 wfProfileOut( __METHOD__
. '-prefixhandling' );
1856 $might_be_img = false;
1858 wfProfileIn( __METHOD__
. "-e1" );
1859 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1861 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1862 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1863 # the real problem is with the $e1 regex
1866 # Still some problems for cases where the ] is meant to be outside punctuation,
1867 # and no image is in sight. See bug 2095.
1869 if ( $text !== '' &&
1870 substr( $m[3], 0, 1 ) === ']' &&
1871 strpos( $text, '[' ) !== false
1874 $text .= ']'; # so that replaceExternalLinks($text) works later
1875 $m[3] = substr( $m[3], 1 );
1877 # fix up urlencoded title texts
1878 if ( strpos( $m[1], '%' ) !== false ) {
1879 # Should anchors '#' also be rejected?
1880 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1883 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1884 $might_be_img = true;
1886 if ( strpos( $m[1], '%' ) !== false ) {
1887 $m[1] = rawurldecode( $m[1] );
1890 } else { # Invalid form; output directly
1891 $s .= $prefix . '[[' . $line;
1892 wfProfileOut( __METHOD__
. "-e1" );
1895 wfProfileOut( __METHOD__
. "-e1" );
1896 wfProfileIn( __METHOD__
. "-misc" );
1898 # Don't allow internal links to pages containing
1899 # PROTO: where PROTO is a valid URL protocol; these
1900 # should be external links.
1901 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1902 $s .= $prefix . '[[' . $line;
1903 wfProfileOut( __METHOD__
. "-misc" );
1907 # Make subpage if necessary
1908 if ( $useSubpages ) {
1909 $link = $this->maybeDoSubpageLink( $m[1], $text );
1914 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1916 # Strip off leading ':'
1917 $link = substr( $link, 1 );
1920 wfProfileOut( __METHOD__
. "-misc" );
1921 wfProfileIn( __METHOD__
. "-title" );
1922 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1923 if ( $nt === null ) {
1924 $s .= $prefix . '[[' . $line;
1925 wfProfileOut( __METHOD__
. "-title" );
1929 $ns = $nt->getNamespace();
1930 $iw = $nt->getInterWiki();
1931 wfProfileOut( __METHOD__
. "-title" );
1933 if ( $might_be_img ) { # if this is actually an invalid link
1934 wfProfileIn( __METHOD__
. "-might_be_img" );
1935 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1938 # look at the next 'line' to see if we can close it there
1940 $next_line = $a->current();
1941 if ( $next_line === false ||
$next_line === null ) {
1944 $m = explode( ']]', $next_line, 3 );
1945 if ( count( $m ) == 3 ) {
1946 # the first ]] closes the inner link, the second the image
1948 $text .= "[[{$m[0]}]]{$m[1]}";
1951 } elseif ( count( $m ) == 2 ) {
1952 # if there's exactly one ]] that's fine, we'll keep looking
1953 $text .= "[[{$m[0]}]]{$m[1]}";
1955 # if $next_line is invalid too, we need look no further
1956 $text .= '[[' . $next_line;
1961 # we couldn't find the end of this imageLink, so output it raw
1962 # but don't ignore what might be perfectly normal links in the text we've examined
1963 $holders->merge( $this->replaceInternalLinks2( $text ) );
1964 $s .= "{$prefix}[[$link|$text";
1965 # note: no $trail, because without an end, there *is* no trail
1966 wfProfileOut( __METHOD__
. "-might_be_img" );
1969 } else { # it's not an image, so output it raw
1970 $s .= "{$prefix}[[$link|$text";
1971 # note: no $trail, because without an end, there *is* no trail
1972 wfProfileOut( __METHOD__
. "-might_be_img" );
1975 wfProfileOut( __METHOD__
. "-might_be_img" );
1978 $wasblank = ( $text == '' );
1982 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1983 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1984 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1985 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1986 $text = $this->doQuotes( $text );
1989 # Link not escaped by : , create the various objects
1992 wfProfileIn( __METHOD__
. "-interwiki" );
1993 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1994 // XXX: the above check prevents links to sites with identifiers that are not language codes
1996 # Bug 24502: filter duplicates
1997 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1998 $this->mLangLinkLanguages
[$iw] = true;
1999 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2002 $s = rtrim( $s . $prefix );
2003 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2004 wfProfileOut( __METHOD__
. "-interwiki" );
2007 wfProfileOut( __METHOD__
. "-interwiki" );
2009 if ( $ns == NS_FILE
) {
2010 wfProfileIn( __METHOD__
. "-image" );
2011 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2013 # if no parameters were passed, $text
2014 # becomes something like "File:Foo.png",
2015 # which we don't want to pass on to the
2019 # recursively parse links inside the image caption
2020 # actually, this will parse them in any other parameters, too,
2021 # but it might be hard to fix that, and it doesn't matter ATM
2022 $text = $this->replaceExternalLinks( $text );
2023 $holders->merge( $this->replaceInternalLinks2( $text ) );
2025 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2026 $s .= $prefix . $this->armorLinks(
2027 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2029 $s .= $prefix . $trail;
2031 wfProfileOut( __METHOD__
. "-image" );
2035 if ( $ns == NS_CATEGORY
) {
2036 wfProfileIn( __METHOD__
. "-category" );
2037 $s = rtrim( $s . "\n" ); # bug 87
2040 $sortkey = $this->getDefaultSort();
2044 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2045 $sortkey = str_replace( "\n", '', $sortkey );
2046 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2047 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2050 * Strip the whitespace Category links produce, see bug 87
2051 * @todo We might want to use trim($tmp, "\n") here.
2053 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2055 wfProfileOut( __METHOD__
. "-category" );
2060 # Self-link checking
2061 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2062 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2063 $this->mTitle
->getPrefixedText(),
2064 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2067 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2072 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2073 # @todo FIXME: Should do batch file existence checks, see comment below
2074 if ( $ns == NS_MEDIA
) {
2075 wfProfileIn( __METHOD__
. "-media" );
2076 # Give extensions a chance to select the file revision for us
2079 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2080 array( $this, $nt, &$options, &$descQuery ) );
2081 # Fetch and register the file (file title may be different via hooks)
2082 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2083 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2084 $s .= $prefix . $this->armorLinks(
2085 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2086 wfProfileOut( __METHOD__
. "-media" );
2090 wfProfileIn( __METHOD__
. "-always_known" );
2091 # Some titles, such as valid special pages or files in foreign repos, should
2092 # be shown as bluelinks even though they're not included in the page table
2094 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2095 # batch file existence checks for NS_FILE and NS_MEDIA
2096 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2097 $this->mOutput
->addLink( $nt );
2098 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2100 # Links will be added to the output link list after checking
2101 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2103 wfProfileOut( __METHOD__
. "-always_known" );
2105 wfProfileOut( __METHOD__
);
2110 * Render a forced-blue link inline; protect against double expansion of
2111 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2112 * Since this little disaster has to split off the trail text to avoid
2113 * breaking URLs in the following text without breaking trails on the
2114 * wiki links, it's been made into a horrible function.
2117 * @param $text String
2118 * @param array $query or String
2119 * @param $trail String
2120 * @param $prefix String
2121 * @return String: HTML-wikitext mix oh yuck
2123 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2124 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2126 if ( is_string( $query ) ) {
2127 $query = wfCgiToArray( $query );
2129 if ( $text == '' ) {
2130 $text = htmlspecialchars( $nt->getPrefixedText() );
2133 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2135 return $this->armorLinks( $link ) . $trail;
2139 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2140 * going to go through further parsing steps before inline URL expansion.
2142 * Not needed quite as much as it used to be since free links are a bit
2143 * more sensible these days. But bracketed links are still an issue.
2145 * @param string $text more-or-less HTML
2146 * @return String: less-or-more HTML with NOPARSE bits
2148 function armorLinks( $text ) {
2149 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2150 "{$this->mUniqPrefix}NOPARSE$1", $text );
2154 * Return true if subpage links should be expanded on this page.
2157 function areSubpagesAllowed() {
2158 # Some namespaces don't allow subpages
2159 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2163 * Handle link to subpage if necessary
2165 * @param string $target the source of the link
2166 * @param &$text String: the link text, modified as necessary
2167 * @return string the full name of the link
2170 function maybeDoSubpageLink( $target, &$text ) {
2171 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2175 * Used by doBlockLevels()
2180 function closeParagraph() {
2182 if ( $this->mLastSection
!= '' ) {
2183 $result = '</' . $this->mLastSection
. ">\n";
2185 $this->mInPre
= false;
2186 $this->mLastSection
= '';
2191 * getCommon() returns the length of the longest common substring
2192 * of both arguments, starting at the beginning of both.
2195 * @param $st1 string
2196 * @param $st2 string
2200 function getCommon( $st1, $st2 ) {
2201 $fl = strlen( $st1 );
2202 $shorter = strlen( $st2 );
2203 if ( $fl < $shorter ) {
2207 for ( $i = 0; $i < $shorter; ++
$i ) {
2208 if ( $st1[$i] != $st2[$i] ) {
2216 * These next three functions open, continue, and close the list
2217 * element appropriate to the prefix character passed into them.
2220 * @param $char string
2224 function openList( $char ) {
2225 $result = $this->closeParagraph();
2227 if ( '*' === $char ) {
2228 $result .= '<ul><li>';
2229 } elseif ( '#' === $char ) {
2230 $result .= '<ol><li>';
2231 } elseif ( ':' === $char ) {
2232 $result .= '<dl><dd>';
2233 } elseif ( ';' === $char ) {
2234 $result .= '<dl><dt>';
2235 $this->mDTopen
= true;
2237 $result = '<!-- ERR 1 -->';
2245 * @param $char String
2250 function nextItem( $char ) {
2251 if ( '*' === $char ||
'#' === $char ) {
2253 } elseif ( ':' === $char ||
';' === $char ) {
2255 if ( $this->mDTopen
) {
2258 if ( ';' === $char ) {
2259 $this->mDTopen
= true;
2260 return $close . '<dt>';
2262 $this->mDTopen
= false;
2263 return $close . '<dd>';
2266 return '<!-- ERR 2 -->';
2271 * @param $char String
2276 function closeList( $char ) {
2277 if ( '*' === $char ) {
2278 $text = '</li></ul>';
2279 } elseif ( '#' === $char ) {
2280 $text = '</li></ol>';
2281 } elseif ( ':' === $char ) {
2282 if ( $this->mDTopen
) {
2283 $this->mDTopen
= false;
2284 $text = '</dt></dl>';
2286 $text = '</dd></dl>';
2289 return '<!-- ERR 3 -->';
2291 return $text . "\n";
2296 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2298 * @param $text String
2299 * @param $linestart Boolean: whether or not this is at the start of a line.
2301 * @return string the lists rendered as HTML
2303 function doBlockLevels( $text, $linestart ) {
2304 wfProfileIn( __METHOD__
);
2306 # Parsing through the text line by line. The main thing
2307 # happening here is handling of block-level elements p, pre,
2308 # and making lists from lines starting with * # : etc.
2310 $textLines = StringUtils
::explode( "\n", $text );
2312 $lastPrefix = $output = '';
2313 $this->mDTopen
= $inBlockElem = false;
2315 $paragraphStack = false;
2317 foreach ( $textLines as $oLine ) {
2319 if ( !$linestart ) {
2329 $lastPrefixLength = strlen( $lastPrefix );
2330 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2331 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2332 # If not in a <pre> element, scan for and figure out what prefixes are there.
2333 if ( !$this->mInPre
) {
2334 # Multiple prefixes may abut each other for nested lists.
2335 $prefixLength = strspn( $oLine, '*#:;' );
2336 $prefix = substr( $oLine, 0, $prefixLength );
2339 # ; and : are both from definition-lists, so they're equivalent
2340 # for the purposes of determining whether or not we need to open/close
2342 $prefix2 = str_replace( ';', ':', $prefix );
2343 $t = substr( $oLine, $prefixLength );
2344 $this->mInPre
= (bool)$preOpenMatch;
2346 # Don't interpret any other prefixes in preformatted text
2348 $prefix = $prefix2 = '';
2353 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2354 # Same as the last item, so no need to deal with nesting or opening stuff
2355 $output .= $this->nextItem( substr( $prefix, -1 ) );
2356 $paragraphStack = false;
2358 if ( substr( $prefix, -1 ) === ';' ) {
2359 # The one nasty exception: definition lists work like this:
2360 # ; title : definition text
2361 # So we check for : in the remainder text to split up the
2362 # title and definition, without b0rking links.
2364 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2366 $output .= $term . $this->nextItem( ':' );
2369 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2370 # We need to open or close prefixes, or both.
2372 # Either open or close a level...
2373 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2374 $paragraphStack = false;
2376 # Close all the prefixes which aren't shared.
2377 while ( $commonPrefixLength < $lastPrefixLength ) {
2378 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2379 --$lastPrefixLength;
2382 # Continue the current prefix if appropriate.
2383 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2384 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2387 # Open prefixes where appropriate.
2388 while ( $prefixLength > $commonPrefixLength ) {
2389 $char = substr( $prefix, $commonPrefixLength, 1 );
2390 $output .= $this->openList( $char );
2392 if ( ';' === $char ) {
2393 # @todo FIXME: This is dupe of code above
2394 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2396 $output .= $term . $this->nextItem( ':' );
2399 ++
$commonPrefixLength;
2401 $lastPrefix = $prefix2;
2404 # If we have no prefixes, go to paragraph mode.
2405 if ( 0 == $prefixLength ) {
2406 wfProfileIn( __METHOD__
. "-paragraph" );
2407 # No prefix (not in list)--go to paragraph mode
2408 # XXX: use a stack for nestable elements like span, table and div
2409 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2410 $closematch = preg_match(
2411 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2412 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2413 if ( $openmatch or $closematch ) {
2414 $paragraphStack = false;
2415 # TODO bug 5718: paragraph closed
2416 $output .= $this->closeParagraph();
2417 if ( $preOpenMatch and !$preCloseMatch ) {
2418 $this->mInPre
= true;
2420 $inBlockElem = !$closematch;
2421 } elseif ( !$inBlockElem && !$this->mInPre
) {
2422 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2424 if ( $this->mLastSection
!== 'pre' ) {
2425 $paragraphStack = false;
2426 $output .= $this->closeParagraph() . '<pre>';
2427 $this->mLastSection
= 'pre';
2429 $t = substr( $t, 1 );
2432 if ( trim( $t ) === '' ) {
2433 if ( $paragraphStack ) {
2434 $output .= $paragraphStack . '<br />';
2435 $paragraphStack = false;
2436 $this->mLastSection
= 'p';
2438 if ( $this->mLastSection
!== 'p' ) {
2439 $output .= $this->closeParagraph();
2440 $this->mLastSection
= '';
2441 $paragraphStack = '<p>';
2443 $paragraphStack = '</p><p>';
2447 if ( $paragraphStack ) {
2448 $output .= $paragraphStack;
2449 $paragraphStack = false;
2450 $this->mLastSection
= 'p';
2451 } elseif ( $this->mLastSection
!== 'p' ) {
2452 $output .= $this->closeParagraph() . '<p>';
2453 $this->mLastSection
= 'p';
2458 wfProfileOut( __METHOD__
. "-paragraph" );
2460 # somewhere above we forget to get out of pre block (bug 785)
2461 if ( $preCloseMatch && $this->mInPre
) {
2462 $this->mInPre
= false;
2464 if ( $paragraphStack === false ) {
2465 $output .= $t . "\n";
2468 while ( $prefixLength ) {
2469 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2472 if ( $this->mLastSection
!= '' ) {
2473 $output .= '</' . $this->mLastSection
. '>';
2474 $this->mLastSection
= '';
2477 wfProfileOut( __METHOD__
);
2482 * Split up a string on ':', ignoring any occurrences inside tags
2483 * to prevent illegal overlapping.
2485 * @param string $str the string to split
2486 * @param &$before String set to everything before the ':'
2487 * @param &$after String set to everything after the ':'
2488 * @throws MWException
2489 * @return String the position of the ':', or false if none found
2491 function findColonNoLinks( $str, &$before, &$after ) {
2492 wfProfileIn( __METHOD__
);
2494 $pos = strpos( $str, ':' );
2495 if ( $pos === false ) {
2497 wfProfileOut( __METHOD__
);
2501 $lt = strpos( $str, '<' );
2502 if ( $lt === false ||
$lt > $pos ) {
2503 # Easy; no tag nesting to worry about
2504 $before = substr( $str, 0, $pos );
2505 $after = substr( $str, $pos +
1 );
2506 wfProfileOut( __METHOD__
);
2510 # Ugly state machine to walk through avoiding tags.
2511 $state = self
::COLON_STATE_TEXT
;
2513 $len = strlen( $str );
2514 for ( $i = 0; $i < $len; $i++
) {
2518 # (Using the number is a performance hack for common cases)
2519 case 0: # self::COLON_STATE_TEXT:
2522 # Could be either a <start> tag or an </end> tag
2523 $state = self
::COLON_STATE_TAGSTART
;
2526 if ( $stack == 0 ) {
2528 $before = substr( $str, 0, $i );
2529 $after = substr( $str, $i +
1 );
2530 wfProfileOut( __METHOD__
);
2533 # Embedded in a tag; don't break it.
2536 # Skip ahead looking for something interesting
2537 $colon = strpos( $str, ':', $i );
2538 if ( $colon === false ) {
2539 # Nothing else interesting
2540 wfProfileOut( __METHOD__
);
2543 $lt = strpos( $str, '<', $i );
2544 if ( $stack === 0 ) {
2545 if ( $lt === false ||
$colon < $lt ) {
2547 $before = substr( $str, 0, $colon );
2548 $after = substr( $str, $colon +
1 );
2549 wfProfileOut( __METHOD__
);
2553 if ( $lt === false ) {
2554 # Nothing else interesting to find; abort!
2555 # We're nested, but there's no close tags left. Abort!
2558 # Skip ahead to next tag start
2560 $state = self
::COLON_STATE_TAGSTART
;
2563 case 1: # self::COLON_STATE_TAG:
2568 $state = self
::COLON_STATE_TEXT
;
2571 # Slash may be followed by >?
2572 $state = self
::COLON_STATE_TAGSLASH
;
2578 case 2: # self::COLON_STATE_TAGSTART:
2581 $state = self
::COLON_STATE_CLOSETAG
;
2584 $state = self
::COLON_STATE_COMMENT
;
2587 # Illegal early close? This shouldn't happen D:
2588 $state = self
::COLON_STATE_TEXT
;
2591 $state = self
::COLON_STATE_TAG
;
2594 case 3: # self::COLON_STATE_CLOSETAG:
2599 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2600 wfProfileOut( __METHOD__
);
2603 $state = self
::COLON_STATE_TEXT
;
2606 case self
::COLON_STATE_TAGSLASH
:
2608 # Yes, a self-closed tag <blah/>
2609 $state = self
::COLON_STATE_TEXT
;
2611 # Probably we're jumping the gun, and this is an attribute
2612 $state = self
::COLON_STATE_TAG
;
2615 case 5: # self::COLON_STATE_COMMENT:
2617 $state = self
::COLON_STATE_COMMENTDASH
;
2620 case self
::COLON_STATE_COMMENTDASH
:
2622 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2624 $state = self
::COLON_STATE_COMMENT
;
2627 case self
::COLON_STATE_COMMENTDASHDASH
:
2629 $state = self
::COLON_STATE_TEXT
;
2631 $state = self
::COLON_STATE_COMMENT
;
2635 wfProfileOut( __METHOD__
);
2636 throw new MWException( "State machine error in " . __METHOD__
);
2640 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2641 wfProfileOut( __METHOD__
);
2644 wfProfileOut( __METHOD__
);
2649 * Return value of a magic variable (like PAGENAME)
2653 * @param $index integer
2654 * @param bool|\PPFrame $frame
2656 * @throws MWException
2659 function getVariableValue( $index, $frame = false ) {
2660 global $wgContLang, $wgSitename, $wgServer;
2661 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2663 if ( is_null( $this->mTitle
) ) {
2664 // If no title set, bad things are going to happen
2665 // later. Title should always be set since this
2666 // should only be called in the middle of a parse
2667 // operation (but the unit-tests do funky stuff)
2668 throw new MWException( __METHOD__
. ' Should only be '
2669 . ' called while parsing (no title set)' );
2673 * Some of these require message or data lookups and can be
2674 * expensive to check many times.
2676 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2677 if ( isset( $this->mVarCache
[$index] ) ) {
2678 return $this->mVarCache
[$index];
2682 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2683 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2686 global $wgLocaltimezone;
2687 if ( isset( $wgLocaltimezone ) ) {
2688 $oldtz = date_default_timezone_get();
2689 date_default_timezone_set( $wgLocaltimezone );
2692 $localTimestamp = date( 'YmdHis', $ts );
2693 $localMonth = date( 'm', $ts );
2694 $localMonth1 = date( 'n', $ts );
2695 $localMonthName = date( 'n', $ts );
2696 $localDay = date( 'j', $ts );
2697 $localDay2 = date( 'd', $ts );
2698 $localDayOfWeek = date( 'w', $ts );
2699 $localWeek = date( 'W', $ts );
2700 $localYear = date( 'Y', $ts );
2701 $localHour = date( 'H', $ts );
2702 if ( isset( $wgLocaltimezone ) ) {
2703 date_default_timezone_set( $oldtz );
2706 $pageLang = $this->getFunctionLang();
2709 case 'currentmonth':
2710 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2712 case 'currentmonth1':
2713 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2715 case 'currentmonthname':
2716 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2718 case 'currentmonthnamegen':
2719 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2721 case 'currentmonthabbrev':
2722 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2725 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2728 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2731 $value = $pageLang->formatNum( $localMonth );
2734 $value = $pageLang->formatNum( $localMonth1 );
2736 case 'localmonthname':
2737 $value = $pageLang->getMonthName( $localMonthName );
2739 case 'localmonthnamegen':
2740 $value = $pageLang->getMonthNameGen( $localMonthName );
2742 case 'localmonthabbrev':
2743 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2746 $value = $pageLang->formatNum( $localDay );
2749 $value = $pageLang->formatNum( $localDay2 );
2752 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2755 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2757 case 'fullpagename':
2758 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2760 case 'fullpagenamee':
2761 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2764 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2766 case 'subpagenamee':
2767 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2769 case 'rootpagename':
2770 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2772 case 'rootpagenamee':
2773 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2775 case 'basepagename':
2776 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2778 case 'basepagenamee':
2779 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2781 case 'talkpagename':
2782 if ( $this->mTitle
->canTalk() ) {
2783 $talkPage = $this->mTitle
->getTalkPage();
2784 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2789 case 'talkpagenamee':
2790 if ( $this->mTitle
->canTalk() ) {
2791 $talkPage = $this->mTitle
->getTalkPage();
2792 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2797 case 'subjectpagename':
2798 $subjPage = $this->mTitle
->getSubjectPage();
2799 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2801 case 'subjectpagenamee':
2802 $subjPage = $this->mTitle
->getSubjectPage();
2803 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2805 case 'pageid': // requested in bug 23427
2806 $pageid = $this->getTitle()->getArticleID();
2807 if ( $pageid == 0 ) {
2808 # 0 means the page doesn't exist in the database,
2809 # which means the user is previewing a new page.
2810 # The vary-revision flag must be set, because the magic word
2811 # will have a different value once the page is saved.
2812 $this->mOutput
->setFlag( 'vary-revision' );
2813 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2815 $value = $pageid ?
$pageid : null;
2818 # Let the edit saving system know we should parse the page
2819 # *after* a revision ID has been assigned.
2820 $this->mOutput
->setFlag( 'vary-revision' );
2821 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2822 $value = $this->mRevisionId
;
2825 # Let the edit saving system know we should parse the page
2826 # *after* a revision ID has been assigned. This is for null edits.
2827 $this->mOutput
->setFlag( 'vary-revision' );
2828 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2829 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2831 case 'revisionday2':
2832 # Let the edit saving system know we should parse the page
2833 # *after* a revision ID has been assigned. This is for null edits.
2834 $this->mOutput
->setFlag( 'vary-revision' );
2835 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2836 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2838 case 'revisionmonth':
2839 # Let the edit saving system know we should parse the page
2840 # *after* a revision ID has been assigned. This is for null edits.
2841 $this->mOutput
->setFlag( 'vary-revision' );
2842 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2843 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2845 case 'revisionmonth1':
2846 # Let the edit saving system know we should parse the page
2847 # *after* a revision ID has been assigned. This is for null edits.
2848 $this->mOutput
->setFlag( 'vary-revision' );
2849 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2850 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2852 case 'revisionyear':
2853 # Let the edit saving system know we should parse the page
2854 # *after* a revision ID has been assigned. This is for null edits.
2855 $this->mOutput
->setFlag( 'vary-revision' );
2856 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2857 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2859 case 'revisiontimestamp':
2860 # Let the edit saving system know we should parse the page
2861 # *after* a revision ID has been assigned. This is for null edits.
2862 $this->mOutput
->setFlag( 'vary-revision' );
2863 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2864 $value = $this->getRevisionTimestamp();
2866 case 'revisionuser':
2867 # Let the edit saving system know we should parse the page
2868 # *after* a revision ID has been assigned. This is for null edits.
2869 $this->mOutput
->setFlag( 'vary-revision' );
2870 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2871 $value = $this->getRevisionUser();
2874 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2877 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2879 case 'namespacenumber':
2880 $value = $this->mTitle
->getNamespace();
2883 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2886 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2888 case 'subjectspace':
2889 $value = $this->mTitle
->getSubjectNsText();
2891 case 'subjectspacee':
2892 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2894 case 'currentdayname':
2895 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2898 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2901 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2904 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2907 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2908 # int to remove the padding
2909 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2912 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2914 case 'localdayname':
2915 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2918 $value = $pageLang->formatNum( $localYear, true );
2921 $value = $pageLang->time( $localTimestamp, false, false );
2924 $value = $pageLang->formatNum( $localHour, true );
2927 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2928 # int to remove the padding
2929 $value = $pageLang->formatNum( (int)$localWeek );
2932 $value = $pageLang->formatNum( $localDayOfWeek );
2934 case 'numberofarticles':
2935 $value = $pageLang->formatNum( SiteStats
::articles() );
2937 case 'numberoffiles':
2938 $value = $pageLang->formatNum( SiteStats
::images() );
2940 case 'numberofusers':
2941 $value = $pageLang->formatNum( SiteStats
::users() );
2943 case 'numberofactiveusers':
2944 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2946 case 'numberofpages':
2947 $value = $pageLang->formatNum( SiteStats
::pages() );
2949 case 'numberofadmins':
2950 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2952 case 'numberofedits':
2953 $value = $pageLang->formatNum( SiteStats
::edits() );
2955 case 'numberofviews':
2956 global $wgDisableCounters;
2957 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2959 case 'currenttimestamp':
2960 $value = wfTimestamp( TS_MW
, $ts );
2962 case 'localtimestamp':
2963 $value = $localTimestamp;
2965 case 'currentversion':
2966 $value = SpecialVersion
::getVersion();
2969 return $wgArticlePath;
2975 $serverParts = wfParseUrl( $wgServer );
2976 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2978 return $wgScriptPath;
2980 return $wgStylePath;
2981 case 'directionmark':
2982 return $pageLang->getDirMark();
2983 case 'contentlanguage':
2984 global $wgLanguageCode;
2985 return $wgLanguageCode;
2988 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2996 $this->mVarCache
[$index] = $value;
3003 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3007 function initialiseVariables() {
3008 wfProfileIn( __METHOD__
);
3009 $variableIDs = MagicWord
::getVariableIDs();
3010 $substIDs = MagicWord
::getSubstIDs();
3012 $this->mVariables
= new MagicWordArray( $variableIDs );
3013 $this->mSubstWords
= new MagicWordArray( $substIDs );
3014 wfProfileOut( __METHOD__
);
3018 * Preprocess some wikitext and return the document tree.
3019 * This is the ghost of replace_variables().
3021 * @param string $text The text to parse
3022 * @param $flags Integer: bitwise combination of:
3023 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3024 * included. Default is to assume a direct page view.
3026 * The generated DOM tree must depend only on the input text and the flags.
3027 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3029 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3030 * change in the DOM tree for a given text, must be passed through the section identifier
3031 * in the section edit link and thus back to extractSections().
3033 * The output of this function is currently only cached in process memory, but a persistent
3034 * cache may be implemented at a later date which takes further advantage of these strict
3035 * dependency requirements.
3041 function preprocessToDom( $text, $flags = 0 ) {
3042 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3047 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3053 public static function splitWhitespace( $s ) {
3054 $ltrimmed = ltrim( $s );
3055 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3056 $trimmed = rtrim( $ltrimmed );
3057 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3059 $w2 = substr( $ltrimmed, -$diff );
3063 return array( $w1, $trimmed, $w2 );
3067 * Replace magic variables, templates, and template arguments
3068 * with the appropriate text. Templates are substituted recursively,
3069 * taking care to avoid infinite loops.
3071 * Note that the substitution depends on value of $mOutputType:
3072 * self::OT_WIKI: only {{subst:}} templates
3073 * self::OT_PREPROCESS: templates but not extension tags
3074 * self::OT_HTML: all templates and extension tags
3076 * @param string $text the text to transform
3077 * @param $frame PPFrame Object describing the arguments passed to the template.
3078 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3079 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3080 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3085 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3086 # Is there any text? Also, Prevent too big inclusions!
3087 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3090 wfProfileIn( __METHOD__
);
3092 if ( $frame === false ) {
3093 $frame = $this->getPreprocessor()->newFrame();
3094 } elseif ( !( $frame instanceof PPFrame
) ) {
3095 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3096 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3099 $dom = $this->preprocessToDom( $text );
3100 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3101 $text = $frame->expand( $dom, $flags );
3103 wfProfileOut( __METHOD__
);
3108 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3110 * @param $args array
3114 static function createAssocArgs( $args ) {
3115 $assocArgs = array();
3117 foreach ( $args as $arg ) {
3118 $eqpos = strpos( $arg, '=' );
3119 if ( $eqpos === false ) {
3120 $assocArgs[$index++
] = $arg;
3122 $name = trim( substr( $arg, 0, $eqpos ) );
3123 $value = trim( substr( $arg, $eqpos +
1 ) );
3124 if ( $value === false ) {
3127 if ( $name !== false ) {
3128 $assocArgs[$name] = $value;
3137 * Warn the user when a parser limitation is reached
3138 * Will warn at most once the user per limitation type
3140 * @param string $limitationType should be one of:
3141 * 'expensive-parserfunction' (corresponding messages:
3142 * 'expensive-parserfunction-warning',
3143 * 'expensive-parserfunction-category')
3144 * 'post-expand-template-argument' (corresponding messages:
3145 * 'post-expand-template-argument-warning',
3146 * 'post-expand-template-argument-category')
3147 * 'post-expand-template-inclusion' (corresponding messages:
3148 * 'post-expand-template-inclusion-warning',
3149 * 'post-expand-template-inclusion-category')
3150 * @param int|null $current Current value
3151 * @param int|null $max Maximum allowed, when an explicit limit has been
3152 * exceeded, provide the values (optional)
3154 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3155 # does no harm if $current and $max are present but are unnecessary for the message
3156 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3157 ->inContentLanguage()->escaped();
3158 $this->mOutput
->addWarning( $warning );
3159 $this->addTrackingCategory( "$limitationType-category" );
3163 * Return the text of a template, after recursively
3164 * replacing any variables or templates within the template.
3166 * @param array $piece the parts of the template
3167 * $piece['title']: the title, i.e. the part before the |
3168 * $piece['parts']: the parameter array
3169 * $piece['lineStart']: whether the brace was at the start of a line
3170 * @param $frame PPFrame The current frame, contains template arguments
3171 * @throws MWException
3172 * @return String: the text of the template
3175 function braceSubstitution( $piece, $frame ) {
3176 wfProfileIn( __METHOD__
);
3177 wfProfileIn( __METHOD__
. '-setup' );
3180 $found = false; # $text has been filled
3181 $nowiki = false; # wiki markup in $text should be escaped
3182 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3183 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3184 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3185 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3187 # Title object, where $text came from
3190 # $part1 is the bit before the first |, and must contain only title characters.
3191 # Various prefixes will be stripped from it later.
3192 $titleWithSpaces = $frame->expand( $piece['title'] );
3193 $part1 = trim( $titleWithSpaces );
3196 # Original title text preserved for various purposes
3197 $originalTitle = $part1;
3199 # $args is a list of argument nodes, starting from index 0, not including $part1
3200 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3201 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3202 wfProfileOut( __METHOD__
. '-setup' );
3204 $titleProfileIn = null; // profile templates
3207 wfProfileIn( __METHOD__
. '-modifiers' );
3210 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3212 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3213 # Decide whether to expand template or keep wikitext as-is.
3214 if ( $this->ot
['wiki'] ) {
3215 if ( $substMatch === false ) {
3216 $literal = true; # literal when in PST with no prefix
3218 $literal = false; # expand when in PST with subst: or safesubst:
3221 if ( $substMatch == 'subst' ) {
3222 $literal = true; # literal when not in PST with plain subst:
3224 $literal = false; # expand when not in PST with safesubst: or no prefix
3228 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3235 if ( !$found && $args->getLength() == 0 ) {
3236 $id = $this->mVariables
->matchStartToEnd( $part1 );
3237 if ( $id !== false ) {
3238 $text = $this->getVariableValue( $id, $frame );
3239 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3240 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3246 # MSG, MSGNW and RAW
3249 $mwMsgnw = MagicWord
::get( 'msgnw' );
3250 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3253 # Remove obsolete MSG:
3254 $mwMsg = MagicWord
::get( 'msg' );
3255 $mwMsg->matchStartAndRemove( $part1 );
3259 $mwRaw = MagicWord
::get( 'raw' );
3260 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3261 $forceRawInterwiki = true;
3264 wfProfileOut( __METHOD__
. '-modifiers' );
3268 wfProfileIn( __METHOD__
. '-pfunc' );
3270 $colonPos = strpos( $part1, ':' );
3271 if ( $colonPos !== false ) {
3272 $func = substr( $part1, 0, $colonPos );
3273 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3274 for ( $i = 0; $i < $args->getLength(); $i++
) {
3275 $funcArgs[] = $args->item( $i );
3278 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3279 } catch ( Exception
$ex ) {
3280 wfProfileOut( __METHOD__
. '-pfunc' );
3281 wfProfileOut( __METHOD__
);
3285 # The interface for parser functions allows for extracting
3286 # flags into the local scope. Extract any forwarded flags
3290 wfProfileOut( __METHOD__
. '-pfunc' );
3293 # Finish mangling title and then check for loops.
3294 # Set $title to a Title object and $titleText to the PDBK
3297 # Split the title into page and subpage
3299 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3300 if ( $subpage !== '' ) {
3301 $ns = $this->mTitle
->getNamespace();
3303 $title = Title
::newFromText( $part1, $ns );
3305 $titleText = $title->getPrefixedText();
3306 # Check for language variants if the template is not found
3307 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3308 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3310 # Do recursion depth check
3311 $limit = $this->mOptions
->getMaxTemplateDepth();
3312 if ( $frame->depth
>= $limit ) {
3314 $text = '<span class="error">'
3315 . wfMessage( 'parser-template-recursion-depth-warning' )
3316 ->numParams( $limit )->inContentLanguage()->text()
3322 # Load from database
3323 if ( !$found && $title ) {
3324 if ( !Profiler
::instance()->isPersistent() ) {
3325 # Too many unique items can kill profiling DBs/collectors
3326 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3327 wfProfileIn( $titleProfileIn ); // template in
3329 wfProfileIn( __METHOD__
. '-loadtpl' );
3330 if ( !$title->isExternal() ) {
3331 if ( $title->isSpecialPage()
3332 && $this->mOptions
->getAllowSpecialInclusion()
3333 && $this->ot
['html'] )
3335 // Pass the template arguments as URL parameters.
3336 // "uselang" will have no effect since the Language object
3337 // is forced to the one defined in ParserOptions.
3338 $pageArgs = array();
3339 for ( $i = 0; $i < $args->getLength(); $i++
) {
3340 $bits = $args->item( $i )->splitArg();
3341 if ( strval( $bits['index'] ) === '' ) {
3342 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3343 $value = trim( $frame->expand( $bits['value'] ) );
3344 $pageArgs[$name] = $value;
3348 // Create a new context to execute the special page
3349 $context = new RequestContext
;
3350 $context->setTitle( $title );
3351 $context->setRequest( new FauxRequest( $pageArgs ) );
3352 $context->setUser( $this->getUser() );
3353 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3354 $ret = SpecialPageFactory
::capturePath( $title, $context );
3356 $text = $context->getOutput()->getHTML();
3357 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3360 $this->disableCache();
3362 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3363 $found = false; # access denied
3364 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3366 list( $text, $title ) = $this->getTemplateDom( $title );
3367 if ( $text !== false ) {
3373 # If the title is valid but undisplayable, make a link to it
3374 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3375 $text = "[[:$titleText]]";
3378 } elseif ( $title->isTrans() ) {
3379 # Interwiki transclusion
3380 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3381 $text = $this->interwikiTransclude( $title, 'render' );
3384 $text = $this->interwikiTransclude( $title, 'raw' );
3385 # Preprocess it like a template
3386 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3392 # Do infinite loop check
3393 # This has to be done after redirect resolution to avoid infinite loops via redirects
3394 if ( !$frame->loopCheck( $title ) ) {
3396 $text = '<span class="error">'
3397 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3399 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3401 wfProfileOut( __METHOD__
. '-loadtpl' );
3404 # If we haven't found text to substitute by now, we're done
3405 # Recover the source wikitext and return it
3407 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3408 if ( $titleProfileIn ) {
3409 wfProfileOut( $titleProfileIn ); // template out
3411 wfProfileOut( __METHOD__
);
3412 return array( 'object' => $text );
3415 # Expand DOM-style return values in a child frame
3416 if ( $isChildObj ) {
3417 # Clean up argument array
3418 $newFrame = $frame->newChild( $args, $title );
3421 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3422 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3423 # Expansion is eligible for the empty-frame cache
3424 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3425 $text = $this->mTplExpandCache
[$titleText];
3427 $text = $newFrame->expand( $text );
3428 $this->mTplExpandCache
[$titleText] = $text;
3431 # Uncached expansion
3432 $text = $newFrame->expand( $text );
3435 if ( $isLocalObj && $nowiki ) {
3436 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3437 $isLocalObj = false;
3440 if ( $titleProfileIn ) {
3441 wfProfileOut( $titleProfileIn ); // template out
3444 # Replace raw HTML by a placeholder
3446 $text = $this->insertStripItem( $text );
3447 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3448 # Escape nowiki-style return values
3449 $text = wfEscapeWikiText( $text );
3450 } elseif ( is_string( $text )
3451 && !$piece['lineStart']
3452 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3454 # Bug 529: if the template begins with a table or block-level
3455 # element, it should be treated as beginning a new line.
3456 # This behavior is somewhat controversial.
3457 $text = "\n" . $text;
3460 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3461 # Error, oversize inclusion
3462 if ( $titleText !== false ) {
3463 # Make a working, properly escaped link if possible (bug 23588)
3464 $text = "[[:$titleText]]";
3466 # This will probably not be a working link, but at least it may
3467 # provide some hint of where the problem is
3468 preg_replace( '/^:/', '', $originalTitle );
3469 $text = "[[:$originalTitle]]";
3471 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3472 $this->limitationWarn( 'post-expand-template-inclusion' );
3475 if ( $isLocalObj ) {
3476 $ret = array( 'object' => $text );
3478 $ret = array( 'text' => $text );
3481 wfProfileOut( __METHOD__
);
3486 * Call a parser function and return an array with text and flags.
3488 * The returned array will always contain a boolean 'found', indicating
3489 * whether the parser function was found or not. It may also contain the
3491 * text: string|object, resulting wikitext or PP DOM object
3492 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3493 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3494 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3495 * nowiki: bool, wiki markup in $text should be escaped
3498 * @param $frame PPFrame The current frame, contains template arguments
3499 * @param $function string Function name
3500 * @param $args array Arguments to the function
3503 public function callParserFunction( $frame, $function, array $args = array() ) {
3506 wfProfileIn( __METHOD__
);
3508 # Case sensitive functions
3509 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3510 $function = $this->mFunctionSynonyms
[1][$function];
3512 # Case insensitive functions
3513 $function = $wgContLang->lc( $function );
3514 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3515 $function = $this->mFunctionSynonyms
[0][$function];
3517 wfProfileOut( __METHOD__
);
3518 return array( 'found' => false );
3522 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3523 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3525 # Workaround for PHP bug 35229 and similar
3526 if ( !is_callable( $callback ) ) {
3527 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3528 wfProfileOut( __METHOD__
);
3529 throw new MWException( "Tag hook for $function is not callable\n" );
3532 $allArgs = array( &$this );
3533 if ( $flags & SFH_OBJECT_ARGS
) {
3534 # Convert arguments to PPNodes and collect for appending to $allArgs
3535 $funcArgs = array();
3536 foreach ( $args as $k => $v ) {
3537 if ( $v instanceof PPNode ||
$k === 0 ) {
3540 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3544 # Add a frame parameter, and pass the arguments as an array
3545 $allArgs[] = $frame;
3546 $allArgs[] = $funcArgs;
3548 # Convert arguments to plain text and append to $allArgs
3549 foreach ( $args as $k => $v ) {
3550 if ( $v instanceof PPNode
) {
3551 $allArgs[] = trim( $frame->expand( $v ) );
3552 } elseif ( is_int( $k ) && $k >= 0 ) {
3553 $allArgs[] = trim( $v );
3555 $allArgs[] = trim( "$k=$v" );
3560 $result = call_user_func_array( $callback, $allArgs );
3562 # The interface for function hooks allows them to return a wikitext
3563 # string or an array containing the string and any flags. This mungs
3564 # things around to match what this method should return.
3565 if ( !is_array( $result ) ) {
3571 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3572 $result['text'] = $result[0];
3574 unset( $result[0] );
3581 $preprocessFlags = 0;
3582 if ( isset( $result['noparse'] ) ) {
3583 $noparse = $result['noparse'];
3585 if ( isset( $result['preprocessFlags'] ) ) {
3586 $preprocessFlags = $result['preprocessFlags'];
3590 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3591 $result['isChildObj'] = true;
3593 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3594 wfProfileOut( __METHOD__
);
3600 * Get the semi-parsed DOM representation of a template with a given title,
3601 * and its redirect destination title. Cached.
3603 * @param $title Title
3607 function getTemplateDom( $title ) {
3608 $cacheTitle = $title;
3609 $titleText = $title->getPrefixedDBkey();
3611 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3612 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3613 $title = Title
::makeTitle( $ns, $dbk );
3614 $titleText = $title->getPrefixedDBkey();
3616 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3617 return array( $this->mTplDomCache
[$titleText], $title );
3620 # Cache miss, go to the database
3621 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3623 if ( $text === false ) {
3624 $this->mTplDomCache
[$titleText] = false;
3625 return array( false, $title );
3628 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3629 $this->mTplDomCache
[$titleText] = $dom;
3631 if ( !$title->equals( $cacheTitle ) ) {
3632 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3633 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3636 return array( $dom, $title );
3640 * Fetch the unparsed text of a template and register a reference to it.
3641 * @param Title $title
3642 * @return Array ( string or false, Title )
3644 function fetchTemplateAndTitle( $title ) {
3645 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3646 $stuff = call_user_func( $templateCb, $title, $this );
3647 $text = $stuff['text'];
3648 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3649 if ( isset( $stuff['deps'] ) ) {
3650 foreach ( $stuff['deps'] as $dep ) {
3651 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3652 if ( $dep['title']->equals( $this->getTitle() ) ) {
3653 // If we transclude ourselves, the final result
3654 // will change based on the new version of the page
3655 $this->mOutput
->setFlag( 'vary-revision' );
3659 return array( $text, $finalTitle );
3663 * Fetch the unparsed text of a template and register a reference to it.
3664 * @param Title $title
3665 * @return mixed string or false
3667 function fetchTemplate( $title ) {
3668 $rv = $this->fetchTemplateAndTitle( $title );
3673 * Static function to get a template
3674 * Can be overridden via ParserOptions::setTemplateCallback().
3676 * @param $title Title
3677 * @param $parser Parser
3681 static function statelessFetchTemplate( $title, $parser = false ) {
3682 $text = $skip = false;
3683 $finalTitle = $title;
3686 # Loop to fetch the article, with up to 1 redirect
3687 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3688 # Give extensions a chance to select the revision instead
3689 $id = false; # Assume current
3690 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3691 array( $parser, $title, &$skip, &$id ) );
3697 'page_id' => $title->getArticleID(),
3704 ? Revision
::newFromId( $id )
3705 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3706 $rev_id = $rev ?
$rev->getId() : 0;
3707 # If there is no current revision, there is no page
3708 if ( $id === false && !$rev ) {
3709 $linkCache = LinkCache
::singleton();
3710 $linkCache->addBadLinkObj( $title );
3715 'page_id' => $title->getArticleID(),
3716 'rev_id' => $rev_id );
3717 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3718 # We fetched a rev from a different title; register it too...
3720 'title' => $rev->getTitle(),
3721 'page_id' => $rev->getPage(),
3722 'rev_id' => $rev_id );
3726 $content = $rev->getContent();
3727 $text = $content ?
$content->getWikitextForTransclusion() : null;
3729 if ( $text === false ||
$text === null ) {
3733 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3735 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3736 if ( !$message->exists() ) {
3740 $content = $message->content();
3741 $text = $message->plain();
3749 $finalTitle = $title;
3750 $title = $content->getRedirectTarget();
3754 'finalTitle' => $finalTitle,
3759 * Fetch a file and its title and register a reference to it.
3760 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3761 * @param Title $title
3762 * @param array $options Array of options to RepoGroup::findFile
3765 function fetchFile( $title, $options = array() ) {
3766 $res = $this->fetchFileAndTitle( $title, $options );
3771 * Fetch a file and its title and register a reference to it.
3772 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3773 * @param Title $title
3774 * @param array $options Array of options to RepoGroup::findFile
3775 * @return Array ( File or false, Title of file )
3777 function fetchFileAndTitle( $title, $options = array() ) {
3778 if ( isset( $options['broken'] ) ) {
3779 $file = false; // broken thumbnail forced by hook
3780 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3781 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3782 } else { // get by (name,timestamp)
3783 $file = wfFindFile( $title, $options );
3785 $time = $file ?
$file->getTimestamp() : false;
3786 $sha1 = $file ?
$file->getSha1() : false;
3787 # Register the file as a dependency...
3788 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3789 if ( $file && !$title->equals( $file->getTitle() ) ) {
3790 # Update fetched file title
3791 $title = $file->getTitle();
3792 if ( is_null( $file->getRedirectedTitle() ) ) {
3793 # This file was not a redirect, but the title does not match.
3794 # Register under the new name because otherwise the link will
3796 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3799 return array( $file, $title );
3803 * Transclude an interwiki link.
3805 * @param $title Title
3810 function interwikiTransclude( $title, $action ) {
3811 global $wgEnableScaryTranscluding;
3813 if ( !$wgEnableScaryTranscluding ) {
3814 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3817 $url = $title->getFullURL( array( 'action' => $action ) );
3819 if ( strlen( $url ) > 255 ) {
3820 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3822 return $this->fetchScaryTemplateMaybeFromCache( $url );
3826 * @param $url string
3827 * @return Mixed|String
3829 function fetchScaryTemplateMaybeFromCache( $url ) {
3830 global $wgTranscludeCacheExpiry;
3831 $dbr = wfGetDB( DB_SLAVE
);
3832 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3833 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3834 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3836 return $obj->tc_contents
;
3839 $req = MWHttpRequest
::factory( $url );
3840 $status = $req->execute(); // Status object
3841 if ( $status->isOK() ) {
3842 $text = $req->getContent();
3843 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3844 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3846 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3849 $dbw = wfGetDB( DB_MASTER
);
3850 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3852 'tc_time' => $dbw->timestamp( time() ),
3853 'tc_contents' => $text
3859 * Triple brace replacement -- used for template arguments
3862 * @param $piece array
3863 * @param $frame PPFrame
3867 function argSubstitution( $piece, $frame ) {
3868 wfProfileIn( __METHOD__
);
3871 $parts = $piece['parts'];
3872 $nameWithSpaces = $frame->expand( $piece['title'] );
3873 $argName = trim( $nameWithSpaces );
3875 $text = $frame->getArgument( $argName );
3876 if ( $text === false && $parts->getLength() > 0
3880 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3883 # No match in frame, use the supplied default
3884 $object = $parts->item( 0 )->getChildren();
3886 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3887 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3888 $this->limitationWarn( 'post-expand-template-argument' );
3891 if ( $text === false && $object === false ) {
3893 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3895 if ( $error !== false ) {
3898 if ( $object !== false ) {
3899 $ret = array( 'object' => $object );
3901 $ret = array( 'text' => $text );
3904 wfProfileOut( __METHOD__
);
3909 * Return the text to be used for a given extension tag.
3910 * This is the ghost of strip().
3912 * @param array $params Associative array of parameters:
3913 * name PPNode for the tag name
3914 * attr PPNode for unparsed text where tag attributes are thought to be
3915 * attributes Optional associative array of parsed attributes
3916 * inner Contents of extension element
3917 * noClose Original text did not have a close tag
3918 * @param $frame PPFrame
3920 * @throws MWException
3923 function extensionSubstitution( $params, $frame ) {
3924 $name = $frame->expand( $params['name'] );
3925 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3926 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3927 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3929 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3930 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3931 if ( $isFunctionTag ) {
3932 $markerType = 'none';
3934 $markerType = 'general';
3936 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3937 $name = strtolower( $name );
3938 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3939 if ( isset( $params['attributes'] ) ) {
3940 $attributes = $attributes +
$params['attributes'];
3943 if ( isset( $this->mTagHooks
[$name] ) ) {
3944 # Workaround for PHP bug 35229 and similar
3945 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3946 throw new MWException( "Tag hook for $name is not callable\n" );
3948 $output = call_user_func_array( $this->mTagHooks
[$name],
3949 array( $content, $attributes, $this, $frame ) );
3950 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3951 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3952 if ( !is_callable( $callback ) ) {
3953 throw new MWException( "Tag hook for $name is not callable\n" );
3956 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3958 $output = '<span class="error">Invalid tag extension name: ' .
3959 htmlspecialchars( $name ) . '</span>';
3962 if ( is_array( $output ) ) {
3963 # Extract flags to local scope (to override $markerType)
3965 $output = $flags[0];
3970 if ( is_null( $attrText ) ) {
3973 if ( isset( $params['attributes'] ) ) {
3974 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3975 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3976 htmlspecialchars( $attrValue ) . '"';
3979 if ( $content === null ) {
3980 $output = "<$name$attrText/>";
3982 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3983 $output = "<$name$attrText>$content$close";
3987 if ( $markerType === 'none' ) {
3989 } elseif ( $markerType === 'nowiki' ) {
3990 $this->mStripState
->addNoWiki( $marker, $output );
3991 } elseif ( $markerType === 'general' ) {
3992 $this->mStripState
->addGeneral( $marker, $output );
3994 throw new MWException( __METHOD__
. ': invalid marker type' );
4000 * Increment an include size counter
4002 * @param string $type the type of expansion
4003 * @param $size Integer: the size of the text
4004 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4006 function incrementIncludeSize( $type, $size ) {
4007 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4010 $this->mIncludeSizes
[$type] +
= $size;
4016 * Increment the expensive function count
4018 * @return Boolean: false if the limit has been exceeded
4020 function incrementExpensiveFunctionCount() {
4021 $this->mExpensiveFunctionCount++
;
4022 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4026 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4027 * Fills $this->mDoubleUnderscores, returns the modified text
4029 * @param $text string
4033 function doDoubleUnderscore( $text ) {
4034 wfProfileIn( __METHOD__
);
4036 # The position of __TOC__ needs to be recorded
4037 $mw = MagicWord
::get( 'toc' );
4038 if ( $mw->match( $text ) ) {
4039 $this->mShowToc
= true;
4040 $this->mForceTocPosition
= true;
4042 # Set a placeholder. At the end we'll fill it in with the TOC.
4043 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4045 # Only keep the first one.
4046 $text = $mw->replace( '', $text );
4049 # Now match and remove the rest of them
4050 $mwa = MagicWord
::getDoubleUnderscoreArray();
4051 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4053 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4054 $this->mOutput
->mNoGallery
= true;
4056 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4057 $this->mShowToc
= false;
4059 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4060 $this->addTrackingCategory( 'hidden-category-category' );
4062 # (bug 8068) Allow control over whether robots index a page.
4064 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4065 # is not desirable, the last one on the page should win.
4066 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4067 $this->mOutput
->setIndexPolicy( 'noindex' );
4068 $this->addTrackingCategory( 'noindex-category' );
4070 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4071 $this->mOutput
->setIndexPolicy( 'index' );
4072 $this->addTrackingCategory( 'index-category' );
4075 # Cache all double underscores in the database
4076 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4077 $this->mOutput
->setProperty( $key, '' );
4080 wfProfileOut( __METHOD__
);
4085 * Add a tracking category, getting the title from a system message,
4086 * or print a debug message if the title is invalid.
4088 * @param string $msg message key
4089 * @return Boolean: whether the addition was successful
4091 public function addTrackingCategory( $msg ) {
4092 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4093 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4096 // Important to parse with correct title (bug 31469)
4097 $cat = wfMessage( $msg )
4098 ->title( $this->getTitle() )
4099 ->inContentLanguage()
4102 # Allow tracking categories to be disabled by setting them to "-"
4103 if ( $cat === '-' ) {
4107 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4108 if ( $containerCategory ) {
4109 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4112 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4118 * This function accomplishes several tasks:
4119 * 1) Auto-number headings if that option is enabled
4120 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4121 * 3) Add a Table of contents on the top for users who have enabled the option
4122 * 4) Auto-anchor headings
4124 * It loops through all headlines, collects the necessary data, then splits up the
4125 * string and re-inserts the newly formatted headlines.
4127 * @param $text String
4128 * @param string $origText original, untouched wikitext
4129 * @param $isMain Boolean
4130 * @return mixed|string
4133 function formatHeadings( $text, $origText, $isMain = true ) {
4134 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4136 # Inhibit editsection links if requested in the page
4137 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4138 $maybeShowEditLink = $showEditLink = false;
4140 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4141 $showEditLink = $this->mOptions
->getEditSection();
4143 if ( $showEditLink ) {
4144 $this->mOutput
->setEditSectionTokens( true );
4147 # Get all headlines for numbering them and adding funky stuff like [edit]
4148 # links - this is for later, but we need the number of headlines right now
4150 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4152 # if there are fewer than 4 headlines in the article, do not show TOC
4153 # unless it's been explicitly enabled.
4154 $enoughToc = $this->mShowToc
&&
4155 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4157 # Allow user to stipulate that a page should have a "new section"
4158 # link added via __NEWSECTIONLINK__
4159 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4160 $this->mOutput
->setNewSection( true );
4163 # Allow user to remove the "new section"
4164 # link via __NONEWSECTIONLINK__
4165 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4166 $this->mOutput
->hideNewSection( true );
4169 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4170 # override above conditions and always show TOC above first header
4171 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4172 $this->mShowToc
= true;
4180 # Ugh .. the TOC should have neat indentation levels which can be
4181 # passed to the skin functions. These are determined here
4185 $sublevelCount = array();
4186 $levelCount = array();
4191 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4192 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4193 $oldType = $this->mOutputType
;
4194 $this->setOutputType( self
::OT_WIKI
);
4195 $frame = $this->getPreprocessor()->newFrame();
4196 $root = $this->preprocessToDom( $origText );
4197 $node = $root->getFirstChild();
4202 foreach ( $matches[3] as $headline ) {
4203 $isTemplate = false;
4205 $sectionIndex = false;
4207 $markerMatches = array();
4208 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4209 $serial = $markerMatches[1];
4210 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4211 $isTemplate = ( $titleText != $baseTitleText );
4212 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4216 $prevlevel = $level;
4218 $level = $matches[1][$headlineCount];
4220 if ( $level > $prevlevel ) {
4221 # Increase TOC level
4223 $sublevelCount[$toclevel] = 0;
4224 if ( $toclevel < $wgMaxTocLevel ) {
4225 $prevtoclevel = $toclevel;
4226 $toc .= Linker
::tocIndent();
4229 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4230 # Decrease TOC level, find level to jump to
4232 for ( $i = $toclevel; $i > 0; $i-- ) {
4233 if ( $levelCount[$i] == $level ) {
4234 # Found last matching level
4237 } elseif ( $levelCount[$i] < $level ) {
4238 # Found first matching level below current level
4246 if ( $toclevel < $wgMaxTocLevel ) {
4247 if ( $prevtoclevel < $wgMaxTocLevel ) {
4248 # Unindent only if the previous toc level was shown :p
4249 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4250 $prevtoclevel = $toclevel;
4252 $toc .= Linker
::tocLineEnd();
4256 # No change in level, end TOC line
4257 if ( $toclevel < $wgMaxTocLevel ) {
4258 $toc .= Linker
::tocLineEnd();
4262 $levelCount[$toclevel] = $level;
4264 # count number of headlines for each level
4265 $sublevelCount[$toclevel]++
;
4267 for ( $i = 1; $i <= $toclevel; $i++
) {
4268 if ( !empty( $sublevelCount[$i] ) ) {
4272 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4277 # The safe header is a version of the header text safe to use for links
4279 # Remove link placeholders by the link text.
4280 # <!--LINK number-->
4282 # link text with suffix
4283 # Do this before unstrip since link text can contain strip markers
4284 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4286 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4287 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4289 # Strip out HTML (first regex removes any tag not allowed)
4291 # * <sup> and <sub> (bug 8393)
4294 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4296 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4297 # to allow setting directionality in toc items.
4298 $tocline = preg_replace(
4299 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4300 array( '', '<$1>' ),
4303 $tocline = trim( $tocline );
4305 # For the anchor, strip out HTML-y stuff period
4306 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4307 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4309 # Save headline for section edit hint before it's escaped
4310 $headlineHint = $safeHeadline;
4312 if ( $wgExperimentalHtmlIds ) {
4313 # For reverse compatibility, provide an id that's
4314 # HTML4-compatible, like we used to.
4316 # It may be worth noting, academically, that it's possible for
4317 # the legacy anchor to conflict with a non-legacy headline
4318 # anchor on the page. In this case likely the "correct" thing
4319 # would be to either drop the legacy anchors or make sure
4320 # they're numbered first. However, this would require people
4321 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4322 # manually, so let's not bother worrying about it.
4323 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4324 array( 'noninitial', 'legacy' ) );
4325 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4327 if ( $legacyHeadline == $safeHeadline ) {
4328 # No reason to have both (in fact, we can't)
4329 $legacyHeadline = false;
4332 $legacyHeadline = false;
4333 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4337 # HTML names must be case-insensitively unique (bug 10721).
4338 # This does not apply to Unicode characters per
4339 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4340 # @todo FIXME: We may be changing them depending on the current locale.
4341 $arrayKey = strtolower( $safeHeadline );
4342 if ( $legacyHeadline === false ) {
4343 $legacyArrayKey = false;
4345 $legacyArrayKey = strtolower( $legacyHeadline );
4348 # count how many in assoc. array so we can track dupes in anchors
4349 if ( isset( $refers[$arrayKey] ) ) {
4350 $refers[$arrayKey]++
;
4352 $refers[$arrayKey] = 1;
4354 if ( isset( $refers[$legacyArrayKey] ) ) {
4355 $refers[$legacyArrayKey]++
;
4357 $refers[$legacyArrayKey] = 1;
4360 # Don't number the heading if it is the only one (looks silly)
4361 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4362 # the two are different if the line contains a link
4363 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4366 # Create the anchor for linking from the TOC to the section
4367 $anchor = $safeHeadline;
4368 $legacyAnchor = $legacyHeadline;
4369 if ( $refers[$arrayKey] > 1 ) {
4370 $anchor .= '_' . $refers[$arrayKey];
4372 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4373 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4375 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4376 $toc .= Linker
::tocLine( $anchor, $tocline,
4377 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4380 # Add the section to the section tree
4381 # Find the DOM node for this header
4382 while ( $node && !$isTemplate ) {
4383 if ( $node->getName() === 'h' ) {
4384 $bits = $node->splitHeading();
4385 if ( $bits['i'] == $sectionIndex ) {
4389 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4390 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4391 $node = $node->getNextSibling();
4394 'toclevel' => $toclevel,
4397 'number' => $numbering,
4398 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4399 'fromtitle' => $titleText,
4400 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4401 'anchor' => $anchor,
4404 # give headline the correct <h#> tag
4405 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4406 // Output edit section links as markers with styles that can be customized by skins
4407 if ( $isTemplate ) {
4408 # Put a T flag in the section identifier, to indicate to extractSections()
4409 # that sections inside <includeonly> should be counted.
4410 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4412 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4414 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4415 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4416 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4417 // so we don't have to worry about a user trying to input one of these markers directly.
4418 // We use a page and section attribute to stop the language converter from converting these important bits
4419 // of data, but put the headline hint inside a content block because the language converter is supposed to
4420 // be able to convert that piece of data.
4421 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4422 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4423 if ( isset( $editlinkArgs[2] ) ) {
4424 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4431 $head[$headlineCount] = Linker
::makeHeadline( $level,
4432 $matches['attrib'][$headlineCount], $anchor, $headline,
4433 $editlink, $legacyAnchor );
4438 $this->setOutputType( $oldType );
4440 # Never ever show TOC if no headers
4441 if ( $numVisible < 1 ) {
4446 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4447 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4449 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4450 $this->mOutput
->setTOCHTML( $toc );
4454 $this->mOutput
->setSections( $tocraw );
4457 # split up and insert constructed headlines
4458 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4461 // build an array of document sections
4462 $sections = array();
4463 foreach ( $blocks as $block ) {
4464 // $head is zero-based, sections aren't.
4465 if ( empty( $head[$i - 1] ) ) {
4466 $sections[$i] = $block;
4468 $sections[$i] = $head[$i - 1] . $block;
4472 * Send a hook, one per section.
4473 * The idea here is to be able to make section-level DIVs, but to do so in a
4474 * lower-impact, more correct way than r50769
4477 * $section : the section number
4478 * &$sectionContent : ref to the content of the section
4479 * $showEditLinks : boolean describing whether this section has an edit link
4481 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4486 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4487 // append the TOC at the beginning
4488 // Top anchor now in skin
4489 $sections[0] = $sections[0] . $toc . "\n";
4492 $full .= join( '', $sections );
4494 if ( $this->mForceTocPosition
) {
4495 return str_replace( '<!--MWTOC-->', $toc, $full );
4502 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4503 * conversion, substitting signatures, {{subst:}} templates, etc.
4505 * @param string $text the text to transform
4506 * @param $title Title: the Title object for the current article
4507 * @param $user User: the User object describing the current user
4508 * @param $options ParserOptions: parsing options
4509 * @param $clearState Boolean: whether to clear the parser state first
4510 * @return String: the altered wiki markup
4512 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4513 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4514 $this->setUser( $user );
4519 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4520 if ( $options->getPreSaveTransform() ) {
4521 $text = $this->pstPass2( $text, $user );
4523 $text = $this->mStripState
->unstripBoth( $text );
4525 $this->setUser( null ); #Reset
4531 * Pre-save transform helper function
4534 * @param $text string
4539 function pstPass2( $text, $user ) {
4540 global $wgContLang, $wgLocaltimezone;
4542 # Note: This is the timestamp saved as hardcoded wikitext to
4543 # the database, we use $wgContLang here in order to give
4544 # everyone the same signature and use the default one rather
4545 # than the one selected in each user's preferences.
4546 # (see also bug 12815)
4547 $ts = $this->mOptions
->getTimestamp();
4548 if ( isset( $wgLocaltimezone ) ) {
4549 $tz = $wgLocaltimezone;
4551 $tz = date_default_timezone_get();
4554 $unixts = wfTimestamp( TS_UNIX
, $ts );
4555 $oldtz = date_default_timezone_get();
4556 date_default_timezone_set( $tz );
4557 $ts = date( 'YmdHis', $unixts );
4558 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4560 # Allow translation of timezones through wiki. date() can return
4561 # whatever crap the system uses, localised or not, so we cannot
4562 # ship premade translations.
4563 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4564 $msg = wfMessage( $key )->inContentLanguage();
4565 if ( $msg->exists() ) {
4566 $tzMsg = $msg->text();
4569 date_default_timezone_set( $oldtz );
4571 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4573 # Variable replacement
4574 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4575 $text = $this->replaceVariables( $text );
4577 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4578 # which may corrupt this parser instance via its wfMessage()->text() call-
4581 $sigText = $this->getUserSig( $user );
4582 $text = strtr( $text, array(
4584 '~~~~' => "$sigText $d",
4588 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4589 $tc = '[' . Title
::legalChars() . ']';
4590 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4592 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4593 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4594 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4595 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4597 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4598 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4599 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4600 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4602 $t = $this->mTitle
->getText();
4604 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4605 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4606 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4607 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4609 # if there's no context, don't bother duplicating the title
4610 $text = preg_replace( $p2, '[[\\1]]', $text );
4613 # Trim trailing whitespace
4614 $text = rtrim( $text );
4620 * Fetch the user's signature text, if any, and normalize to
4621 * validated, ready-to-insert wikitext.
4622 * If you have pre-fetched the nickname or the fancySig option, you can
4623 * specify them here to save a database query.
4624 * Do not reuse this parser instance after calling getUserSig(),
4625 * as it may have changed if it's the $wgParser.
4628 * @param string|bool $nickname nickname to use or false to use user's default nickname
4629 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4630 * or null to use default value
4633 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4634 global $wgMaxSigChars;
4636 $username = $user->getName();
4638 # If not given, retrieve from the user object.
4639 if ( $nickname === false ) {
4640 $nickname = $user->getOption( 'nickname' );
4643 if ( is_null( $fancySig ) ) {
4644 $fancySig = $user->getBoolOption( 'fancysig' );
4647 $nickname = $nickname == null ?
$username : $nickname;
4649 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4650 $nickname = $username;
4651 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4652 } elseif ( $fancySig !== false ) {
4653 # Sig. might contain markup; validate this
4654 if ( $this->validateSig( $nickname ) !== false ) {
4655 # Validated; clean up (if needed) and return it
4656 return $this->cleanSig( $nickname, true );
4658 # Failed to validate; fall back to the default
4659 $nickname = $username;
4660 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4664 # Make sure nickname doesnt get a sig in a sig
4665 $nickname = self
::cleanSigInSig( $nickname );
4667 # If we're still here, make it a link to the user page
4668 $userText = wfEscapeWikiText( $username );
4669 $nickText = wfEscapeWikiText( $nickname );
4670 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4672 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4676 * Check that the user's signature contains no bad XML
4678 * @param $text String
4679 * @return mixed An expanded string, or false if invalid.
4681 function validateSig( $text ) {
4682 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4686 * Clean up signature text
4688 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4689 * 2) Substitute all transclusions
4691 * @param $text String
4692 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4693 * @return String: signature text
4695 public function cleanSig( $text, $parsing = false ) {
4698 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4701 # Option to disable this feature
4702 if ( !$this->mOptions
->getCleanSignatures() ) {
4706 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4707 # => Move this logic to braceSubstitution()
4708 $substWord = MagicWord
::get( 'subst' );
4709 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4710 $substText = '{{' . $substWord->getSynonym( 0 );
4712 $text = preg_replace( $substRegex, $substText, $text );
4713 $text = self
::cleanSigInSig( $text );
4714 $dom = $this->preprocessToDom( $text );
4715 $frame = $this->getPreprocessor()->newFrame();
4716 $text = $frame->expand( $dom );
4719 $text = $this->mStripState
->unstripBoth( $text );
4726 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4728 * @param $text String
4729 * @return String: signature text with /~{3,5}/ removed
4731 public static function cleanSigInSig( $text ) {
4732 $text = preg_replace( '/~{3,5}/', '', $text );
4737 * Set up some variables which are usually set up in parse()
4738 * so that an external function can call some class members with confidence
4740 * @param $title Title|null
4741 * @param $options ParserOptions
4742 * @param $outputType
4743 * @param $clearState bool
4745 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4746 $this->startParse( $title, $options, $outputType, $clearState );
4750 * @param $title Title|null
4751 * @param $options ParserOptions
4752 * @param $outputType
4753 * @param $clearState bool
4755 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4756 $this->setTitle( $title );
4757 $this->mOptions
= $options;
4758 $this->setOutputType( $outputType );
4759 if ( $clearState ) {
4760 $this->clearState();
4765 * Wrapper for preprocess()
4767 * @param string $text the text to preprocess
4768 * @param $options ParserOptions: options
4769 * @param $title Title object or null to use $wgTitle
4772 public function transformMsg( $text, $options, $title = null ) {
4773 static $executing = false;
4775 # Guard against infinite recursion
4781 wfProfileIn( __METHOD__
);
4787 $text = $this->preprocess( $text, $title, $options );
4790 wfProfileOut( __METHOD__
);
4795 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4796 * The callback should have the following form:
4797 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4799 * Transform and return $text. Use $parser for any required context, e.g. use
4800 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4802 * Hooks may return extended information by returning an array, of which the
4803 * first numbered element (index 0) must be the return string, and all other
4804 * entries are extracted into local variables within an internal function
4805 * in the Parser class.
4807 * This interface (introduced r61913) appears to be undocumented, but
4808 * 'markerName' is used by some core tag hooks to override which strip
4809 * array their results are placed in. **Use great caution if attempting
4810 * this interface, as it is not documented and injudicious use could smash
4811 * private variables.**
4813 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4814 * @param $callback Mixed: the callback function (and object) to use for the tag
4815 * @throws MWException
4816 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4818 public function setHook( $tag, $callback ) {
4819 $tag = strtolower( $tag );
4820 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4821 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4823 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4824 $this->mTagHooks
[$tag] = $callback;
4825 if ( !in_array( $tag, $this->mStripList
) ) {
4826 $this->mStripList
[] = $tag;
4833 * As setHook(), but letting the contents be parsed.
4835 * Transparent tag hooks are like regular XML-style tag hooks, except they
4836 * operate late in the transformation sequence, on HTML instead of wikitext.
4838 * This is probably obsoleted by things dealing with parser frames?
4839 * The only extension currently using it is geoserver.
4842 * @todo better document or deprecate this
4844 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4845 * @param $callback Mixed: the callback function (and object) to use for the tag
4846 * @throws MWException
4847 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4849 function setTransparentTagHook( $tag, $callback ) {
4850 $tag = strtolower( $tag );
4851 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4852 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4854 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4855 $this->mTransparentTagHooks
[$tag] = $callback;
4861 * Remove all tag hooks
4863 function clearTagHooks() {
4864 $this->mTagHooks
= array();
4865 $this->mFunctionTagHooks
= array();
4866 $this->mStripList
= $this->mDefaultStripList
;
4870 * Create a function, e.g. {{sum:1|2|3}}
4871 * The callback function should have the form:
4872 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4874 * Or with SFH_OBJECT_ARGS:
4875 * function myParserFunction( $parser, $frame, $args ) { ... }
4877 * The callback may either return the text result of the function, or an array with the text
4878 * in element 0, and a number of flags in the other elements. The names of the flags are
4879 * specified in the keys. Valid flags are:
4880 * found The text returned is valid, stop processing the template. This
4882 * nowiki Wiki markup in the return value should be escaped
4883 * isHTML The returned text is HTML, armour it against wikitext transformation
4885 * @param string $id The magic word ID
4886 * @param $callback Mixed: the callback function (and object) to use
4887 * @param $flags Integer: a combination of the following flags:
4888 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4890 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4891 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4892 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4893 * the arguments, and to control the way they are expanded.
4895 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4896 * arguments, for instance:
4897 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4899 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4900 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4901 * working if/when this is changed.
4903 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4906 * Please read the documentation in includes/parser/Preprocessor.php for more information
4907 * about the methods available in PPFrame and PPNode.
4909 * @throws MWException
4910 * @return string|callback The old callback function for this name, if any
4912 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4915 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4916 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4918 # Add to function cache
4919 $mw = MagicWord
::get( $id );
4921 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4924 $synonyms = $mw->getSynonyms();
4925 $sensitive = intval( $mw->isCaseSensitive() );
4927 foreach ( $synonyms as $syn ) {
4929 if ( !$sensitive ) {
4930 $syn = $wgContLang->lc( $syn );
4933 if ( !( $flags & SFH_NO_HASH
) ) {
4936 # Remove trailing colon
4937 if ( substr( $syn, -1, 1 ) === ':' ) {
4938 $syn = substr( $syn, 0, -1 );
4940 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4946 * Get all registered function hook identifiers
4950 function getFunctionHooks() {
4951 return array_keys( $this->mFunctionHooks
);
4955 * Create a tag function, e.g. "<test>some stuff</test>".
4956 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4957 * Unlike parser functions, their content is not preprocessed.
4961 * @throws MWException
4964 function setFunctionTagHook( $tag, $callback, $flags ) {
4965 $tag = strtolower( $tag );
4966 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4967 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4969 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4970 $this->mFunctionTagHooks
[$tag] : null;
4971 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4973 if ( !in_array( $tag, $this->mStripList
) ) {
4974 $this->mStripList
[] = $tag;
4981 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4982 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4983 * Placeholders created in Skin::makeLinkObj()
4985 * @param $text string
4986 * @param $options int
4988 * @return array of link CSS classes, indexed by PDBK.
4990 function replaceLinkHolders( &$text, $options = 0 ) {
4991 return $this->mLinkHolders
->replace( $text );
4995 * Replace "<!--LINK-->" link placeholders with plain text of links
4996 * (not HTML-formatted).
4998 * @param $text String
5001 function replaceLinkHoldersText( $text ) {
5002 return $this->mLinkHolders
->replaceText( $text );
5006 * Renders an image gallery from a text with one line per image.
5007 * text labels may be given by using |-style alternative text. E.g.
5008 * Image:one.jpg|The number "1"
5009 * Image:tree.jpg|A tree
5010 * given as text will return the HTML of a gallery with two images,
5011 * labeled 'The number "1"' and
5014 * @param string $text
5015 * @param array $params
5016 * @return string HTML
5018 function renderImageGallery( $text, $params ) {
5019 $ig = new ImageGallery();
5020 $ig->setContextTitle( $this->mTitle
);
5021 $ig->setShowBytes( false );
5022 $ig->setShowFilename( false );
5023 $ig->setParser( $this );
5024 $ig->setHideBadImages();
5025 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5027 if ( isset( $params['showfilename'] ) ) {
5028 $ig->setShowFilename( true );
5030 $ig->setShowFilename( false );
5032 if ( isset( $params['caption'] ) ) {
5033 $caption = $params['caption'];
5034 $caption = htmlspecialchars( $caption );
5035 $caption = $this->replaceInternalLinks( $caption );
5036 $ig->setCaptionHtml( $caption );
5038 if ( isset( $params['perrow'] ) ) {
5039 $ig->setPerRow( $params['perrow'] );
5041 if ( isset( $params['widths'] ) ) {
5042 $ig->setWidths( $params['widths'] );
5044 if ( isset( $params['heights'] ) ) {
5045 $ig->setHeights( $params['heights'] );
5048 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5050 $lines = StringUtils
::explode( "\n", $text );
5051 foreach ( $lines as $line ) {
5052 # match lines like these:
5053 # Image:someimage.jpg|This is some image
5055 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5057 if ( count( $matches ) == 0 ) {
5061 if ( strpos( $matches[0], '%' ) !== false ) {
5062 $matches[1] = rawurldecode( $matches[1] );
5064 $title = Title
::newFromText( $matches[1], NS_FILE
);
5065 if ( is_null( $title ) ) {
5066 # Bogus title. Ignore these so we don't bomb out later.
5073 if ( isset( $matches[3] ) ) {
5074 // look for an |alt= definition while trying not to break existing
5075 // captions with multiple pipes (|) in it, until a more sensible grammar
5076 // is defined for images in galleries
5078 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5079 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5080 $magicWordAlt = MagicWord
::get( 'img_alt' );
5081 $magicWordLink = MagicWord
::get( 'img_link' );
5083 foreach ( $parameterMatches as $parameterMatch ) {
5084 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
5085 $alt = $this->stripAltText( $match, false );
5087 elseif ( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ) {
5088 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5089 $chars = self
::EXT_LINK_URL_CLASS
;
5090 $prots = $this->mUrlProtocols
;
5091 //check to see if link matches an absolute url, if not then it must be a wiki link.
5092 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5095 $localLinkTitle = Title
::newFromText( $linkValue );
5096 if ( $localLinkTitle !== null ) {
5097 $link = $localLinkTitle->getLocalURL();
5102 // concatenate all other pipes
5103 $label .= '|' . $parameterMatch;
5106 // remove the first pipe
5107 $label = substr( $label, 1 );
5110 $ig->add( $title, $label, $alt, $link );
5112 return $ig->toHTML();
5119 function getImageParams( $handler ) {
5121 $handlerClass = get_class( $handler );
5125 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5126 # Initialise static lists
5127 static $internalParamNames = array(
5128 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5129 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5130 'bottom', 'text-bottom' ),
5131 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5132 'upright', 'border', 'link', 'alt', 'class' ),
5134 static $internalParamMap;
5135 if ( !$internalParamMap ) {
5136 $internalParamMap = array();
5137 foreach ( $internalParamNames as $type => $names ) {
5138 foreach ( $names as $name ) {
5139 $magicName = str_replace( '-', '_', "img_$name" );
5140 $internalParamMap[$magicName] = array( $type, $name );
5145 # Add handler params
5146 $paramMap = $internalParamMap;
5148 $handlerParamMap = $handler->getParamMap();
5149 foreach ( $handlerParamMap as $magic => $paramName ) {
5150 $paramMap[$magic] = array( 'handler', $paramName );
5153 $this->mImageParams
[$handlerClass] = $paramMap;
5154 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5156 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5160 * Parse image options text and use it to make an image
5162 * @param $title Title
5163 * @param $options String
5164 * @param $holders LinkHolderArray|bool
5165 * @return string HTML
5167 function makeImage( $title, $options, $holders = false ) {
5168 # Check if the options text is of the form "options|alt text"
5170 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5171 # * left no resizing, just left align. label is used for alt= only
5172 # * right same, but right aligned
5173 # * none same, but not aligned
5174 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5175 # * center center the image
5176 # * frame Keep original image size, no magnify-button.
5177 # * framed Same as "frame"
5178 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5179 # * upright reduce width for upright images, rounded to full __0 px
5180 # * border draw a 1px border around the image
5181 # * alt Text for HTML alt attribute (defaults to empty)
5182 # * class Set a class for img node
5183 # * link Set the target of the image link. Can be external, interwiki, or local
5184 # vertical-align values (no % or length right now):
5194 $parts = StringUtils
::explode( "|", $options );
5196 # Give extensions a chance to select the file revision for us
5199 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5200 array( $this, $title, &$options, &$descQuery ) );
5201 # Fetch and register the file (file title may be different via hooks)
5202 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5205 $handler = $file ?
$file->getHandler() : false;
5207 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5210 $this->addTrackingCategory( 'broken-file-category' );
5213 # Process the input parameters
5215 $params = array( 'frame' => array(), 'handler' => array(),
5216 'horizAlign' => array(), 'vertAlign' => array() );
5217 foreach ( $parts as $part ) {
5218 $part = trim( $part );
5219 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5221 if ( isset( $paramMap[$magicName] ) ) {
5222 list( $type, $paramName ) = $paramMap[$magicName];
5224 # Special case; width and height come in one variable together
5225 if ( $type === 'handler' && $paramName === 'width' ) {
5226 $parsedWidthParam = $this->parseWidthParam( $value );
5227 if ( isset( $parsedWidthParam['width'] ) ) {
5228 $width = $parsedWidthParam['width'];
5229 if ( $handler->validateParam( 'width', $width ) ) {
5230 $params[$type]['width'] = $width;
5234 if ( isset( $parsedWidthParam['height'] ) ) {
5235 $height = $parsedWidthParam['height'];
5236 if ( $handler->validateParam( 'height', $height ) ) {
5237 $params[$type]['height'] = $height;
5241 # else no validation -- bug 13436
5243 if ( $type === 'handler' ) {
5244 # Validate handler parameter
5245 $validated = $handler->validateParam( $paramName, $value );
5247 # Validate internal parameters
5248 switch ( $paramName ) {
5252 # @todo FIXME: Possibly check validity here for
5253 # manualthumb? downstream behavior seems odd with
5254 # missing manual thumbs.
5256 $value = $this->stripAltText( $value, $holders );
5259 $chars = self
::EXT_LINK_URL_CLASS
;
5260 $prots = $this->mUrlProtocols
;
5261 if ( $value === '' ) {
5262 $paramName = 'no-link';
5265 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5266 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5267 $paramName = 'link-url';
5268 $this->mOutput
->addExternalLink( $value );
5269 if ( $this->mOptions
->getExternalLinkTarget() ) {
5270 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5275 $linkTitle = Title
::newFromText( $value );
5277 $paramName = 'link-title';
5278 $value = $linkTitle;
5279 $this->mOutput
->addLink( $linkTitle );
5285 # Most other things appear to be empty or numeric...
5286 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5291 $params[$type][$paramName] = $value;
5295 if ( !$validated ) {
5300 # Process alignment parameters
5301 if ( $params['horizAlign'] ) {
5302 $params['frame']['align'] = key( $params['horizAlign'] );
5304 if ( $params['vertAlign'] ) {
5305 $params['frame']['valign'] = key( $params['vertAlign'] );
5308 $params['frame']['caption'] = $caption;
5310 # Will the image be presented in a frame, with the caption below?
5311 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5312 isset( $params['frame']['framed'] ) ||
5313 isset( $params['frame']['thumbnail'] ) ||
5314 isset( $params['frame']['manualthumb'] );
5316 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5317 # came to also set the caption, ordinary text after the image -- which
5318 # makes no sense, because that just repeats the text multiple times in
5319 # screen readers. It *also* came to set the title attribute.
5321 # Now that we have an alt attribute, we should not set the alt text to
5322 # equal the caption: that's worse than useless, it just repeats the
5323 # text. This is the framed/thumbnail case. If there's no caption, we
5324 # use the unnamed parameter for alt text as well, just for the time be-
5325 # ing, if the unnamed param is set and the alt param is not.
5327 # For the future, we need to figure out if we want to tweak this more,
5328 # e.g., introducing a title= parameter for the title; ignoring the un-
5329 # named parameter entirely for images without a caption; adding an ex-
5330 # plicit caption= parameter and preserving the old magic unnamed para-
5332 if ( $imageIsFramed ) { # Framed image
5333 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5334 # No caption or alt text, add the filename as the alt text so
5335 # that screen readers at least get some description of the image
5336 $params['frame']['alt'] = $title->getText();
5338 # Do not set $params['frame']['title'] because tooltips don't make sense
5340 } else { # Inline image
5341 if ( !isset( $params['frame']['alt'] ) ) {
5342 # No alt text, use the "caption" for the alt text
5343 if ( $caption !== '' ) {
5344 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5346 # No caption, fall back to using the filename for the
5348 $params['frame']['alt'] = $title->getText();
5351 # Use the "caption" for the tooltip text
5352 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5355 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5357 # Linker does the rest
5358 $time = isset( $options['time'] ) ?
$options['time'] : false;
5359 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5360 $time, $descQuery, $this->mOptions
->getThumbSize() );
5362 # Give the handler a chance to modify the parser object
5364 $handler->parserTransformHook( $this, $file );
5372 * @param $holders LinkHolderArray
5373 * @return mixed|String
5375 protected function stripAltText( $caption, $holders ) {
5376 # Strip bad stuff out of the title (tooltip). We can't just use
5377 # replaceLinkHoldersText() here, because if this function is called
5378 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5380 $tooltip = $holders->replaceText( $caption );
5382 $tooltip = $this->replaceLinkHoldersText( $caption );
5385 # make sure there are no placeholders in thumbnail attributes
5386 # that are later expanded to html- so expand them now and
5388 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5389 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5395 * Set a flag in the output object indicating that the content is dynamic and
5396 * shouldn't be cached.
5398 function disableCache() {
5399 wfDebug( "Parser output marked as uncacheable.\n" );
5400 if ( !$this->mOutput
) {
5401 throw new MWException( __METHOD__
.
5402 " can only be called when actually parsing something" );
5404 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5405 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5409 * Callback from the Sanitizer for expanding items found in HTML attribute
5410 * values, so they can be safely tested and escaped.
5412 * @param $text String
5413 * @param $frame PPFrame
5416 function attributeStripCallback( &$text, $frame = false ) {
5417 $text = $this->replaceVariables( $text, $frame );
5418 $text = $this->mStripState
->unstripBoth( $text );
5427 function getTags() {
5428 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5432 * Replace transparent tags in $text with the values given by the callbacks.
5434 * Transparent tag hooks are like regular XML-style tag hooks, except they
5435 * operate late in the transformation sequence, on HTML instead of wikitext.
5437 * @param $text string
5441 function replaceTransparentTags( $text ) {
5443 $elements = array_keys( $this->mTransparentTagHooks
);
5444 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5445 $replacements = array();
5447 foreach ( $matches as $marker => $data ) {
5448 list( $element, $content, $params, $tag ) = $data;
5449 $tagName = strtolower( $element );
5450 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5451 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5455 $replacements[$marker] = $output;
5457 return strtr( $text, $replacements );
5461 * Break wikitext input into sections, and either pull or replace
5462 * some particular section's text.
5464 * External callers should use the getSection and replaceSection methods.
5466 * @param string $text Page wikitext
5467 * @param string $section a section identifier string of the form:
5468 * "<flag1> - <flag2> - ... - <section number>"
5470 * Currently the only recognised flag is "T", which means the target section number
5471 * was derived during a template inclusion parse, in other words this is a template
5472 * section edit link. If no flags are given, it was an ordinary section edit link.
5473 * This flag is required to avoid a section numbering mismatch when a section is
5474 * enclosed by "<includeonly>" (bug 6563).
5476 * The section number 0 pulls the text before the first heading; other numbers will
5477 * pull the given section along with its lower-level subsections. If the section is
5478 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5480 * Section 0 is always considered to exist, even if it only contains the empty
5481 * string. If $text is the empty string and section 0 is replaced, $newText is
5484 * @param string $mode one of "get" or "replace"
5485 * @param string $newText replacement text for section data.
5486 * @return String: for "get", the extracted section text.
5487 * for "replace", the whole page with the section replaced.
5489 private function extractSections( $text, $section, $mode, $newText = '' ) {
5490 global $wgTitle; # not generally used but removes an ugly failure mode
5491 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5493 $frame = $this->getPreprocessor()->newFrame();
5495 # Process section extraction flags
5497 $sectionParts = explode( '-', $section );
5498 $sectionIndex = array_pop( $sectionParts );
5499 foreach ( $sectionParts as $part ) {
5500 if ( $part === 'T' ) {
5501 $flags |
= self
::PTD_FOR_INCLUSION
;
5505 # Check for empty input
5506 if ( strval( $text ) === '' ) {
5507 # Only sections 0 and T-0 exist in an empty document
5508 if ( $sectionIndex == 0 ) {
5509 if ( $mode === 'get' ) {
5515 if ( $mode === 'get' ) {
5523 # Preprocess the text
5524 $root = $this->preprocessToDom( $text, $flags );
5526 # <h> nodes indicate section breaks
5527 # They can only occur at the top level, so we can find them by iterating the root's children
5528 $node = $root->getFirstChild();
5530 # Find the target section
5531 if ( $sectionIndex == 0 ) {
5532 # Section zero doesn't nest, level=big
5533 $targetLevel = 1000;
5536 if ( $node->getName() === 'h' ) {
5537 $bits = $node->splitHeading();
5538 if ( $bits['i'] == $sectionIndex ) {
5539 $targetLevel = $bits['level'];
5543 if ( $mode === 'replace' ) {
5544 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5546 $node = $node->getNextSibling();
5552 if ( $mode === 'get' ) {
5559 # Find the end of the section, including nested sections
5561 if ( $node->getName() === 'h' ) {
5562 $bits = $node->splitHeading();
5563 $curLevel = $bits['level'];
5564 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5568 if ( $mode === 'get' ) {
5569 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5571 $node = $node->getNextSibling();
5574 # Write out the remainder (in replace mode only)
5575 if ( $mode === 'replace' ) {
5576 # Output the replacement text
5577 # Add two newlines on -- trailing whitespace in $newText is conventionally
5578 # stripped by the editor, so we need both newlines to restore the paragraph gap
5579 # Only add trailing whitespace if there is newText
5580 if ( $newText != "" ) {
5581 $outText .= $newText . "\n\n";
5585 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5586 $node = $node->getNextSibling();
5590 if ( is_string( $outText ) ) {
5591 # Re-insert stripped tags
5592 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5599 * This function returns the text of a section, specified by a number ($section).
5600 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5601 * the first section before any such heading (section 0).
5603 * If a section contains subsections, these are also returned.
5605 * @param string $text text to look in
5606 * @param string $section section identifier
5607 * @param string $deftext default to return if section is not found
5608 * @return string text of the requested section
5610 public function getSection( $text, $section, $deftext = '' ) {
5611 return $this->extractSections( $text, $section, "get", $deftext );
5615 * This function returns $oldtext after the content of the section
5616 * specified by $section has been replaced with $text. If the target
5617 * section does not exist, $oldtext is returned unchanged.
5619 * @param string $oldtext former text of the article
5620 * @param int $section section identifier
5621 * @param string $text replacing text
5622 * @return String: modified text
5624 public function replaceSection( $oldtext, $section, $text ) {
5625 return $this->extractSections( $oldtext, $section, "replace", $text );
5629 * Get the ID of the revision we are parsing
5631 * @return Mixed: integer or null
5633 function getRevisionId() {
5634 return $this->mRevisionId
;
5638 * Get the revision object for $this->mRevisionId
5640 * @return Revision|null either a Revision object or null
5642 protected function getRevisionObject() {
5643 if ( !is_null( $this->mRevisionObject
) ) {
5644 return $this->mRevisionObject
;
5646 if ( is_null( $this->mRevisionId
) ) {
5650 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5651 return $this->mRevisionObject
;
5655 * Get the timestamp associated with the current revision, adjusted for
5656 * the default server-local timestamp
5658 function getRevisionTimestamp() {
5659 if ( is_null( $this->mRevisionTimestamp
) ) {
5660 wfProfileIn( __METHOD__
);
5664 $revObject = $this->getRevisionObject();
5665 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5667 # The cryptic '' timezone parameter tells to use the site-default
5668 # timezone offset instead of the user settings.
5670 # Since this value will be saved into the parser cache, served
5671 # to other users, and potentially even used inside links and such,
5672 # it needs to be consistent for all visitors.
5673 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5675 wfProfileOut( __METHOD__
);
5677 return $this->mRevisionTimestamp
;
5681 * Get the name of the user that edited the last revision
5683 * @return String: user name
5685 function getRevisionUser() {
5686 if ( is_null( $this->mRevisionUser
) ) {
5687 $revObject = $this->getRevisionObject();
5689 # if this template is subst: the revision id will be blank,
5690 # so just use the current user's name
5692 $this->mRevisionUser
= $revObject->getUserText();
5693 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5694 $this->mRevisionUser
= $this->getUser()->getName();
5697 return $this->mRevisionUser
;
5701 * Mutator for $mDefaultSort
5703 * @param string $sort New value
5705 public function setDefaultSort( $sort ) {
5706 $this->mDefaultSort
= $sort;
5707 $this->mOutput
->setProperty( 'defaultsort', $sort );
5711 * Accessor for $mDefaultSort
5712 * Will use the empty string if none is set.
5714 * This value is treated as a prefix, so the
5715 * empty string is equivalent to sorting by
5720 public function getDefaultSort() {
5721 if ( $this->mDefaultSort
!== false ) {
5722 return $this->mDefaultSort
;
5729 * Accessor for $mDefaultSort
5730 * Unlike getDefaultSort(), will return false if none is set
5732 * @return string or false
5734 public function getCustomDefaultSort() {
5735 return $this->mDefaultSort
;
5739 * Try to guess the section anchor name based on a wikitext fragment
5740 * presumably extracted from a heading, for example "Header" from
5743 * @param $text string
5747 public function guessSectionNameFromWikiText( $text ) {
5748 # Strip out wikitext links(they break the anchor)
5749 $text = $this->stripSectionName( $text );
5750 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5751 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5755 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5756 * instead. For use in redirects, since IE6 interprets Redirect: headers
5757 * as something other than UTF-8 (apparently?), resulting in breakage.
5759 * @param string $text The section name
5760 * @return string An anchor
5762 public function guessLegacySectionNameFromWikiText( $text ) {
5763 # Strip out wikitext links(they break the anchor)
5764 $text = $this->stripSectionName( $text );
5765 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5766 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5770 * Strips a text string of wikitext for use in a section anchor
5772 * Accepts a text string and then removes all wikitext from the
5773 * string and leaves only the resultant text (i.e. the result of
5774 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5775 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5776 * to create valid section anchors by mimicing the output of the
5777 * parser when headings are parsed.
5779 * @param string $text text string to be stripped of wikitext
5780 * for use in a Section anchor
5781 * @return string Filtered text string
5783 public function stripSectionName( $text ) {
5784 # Strip internal link markup
5785 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5786 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5788 # Strip external link markup
5789 # @todo FIXME: Not tolerant to blank link text
5790 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5791 # on how many empty links there are on the page - need to figure that out.
5792 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5794 # Parse wikitext quotes (italics & bold)
5795 $text = $this->doQuotes( $text );
5798 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5803 * strip/replaceVariables/unstrip for preprocessor regression testing
5805 * @param $text string
5806 * @param $title Title
5807 * @param $options ParserOptions
5808 * @param $outputType int
5812 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5813 $this->startParse( $title, $options, $outputType, true );
5815 $text = $this->replaceVariables( $text );
5816 $text = $this->mStripState
->unstripBoth( $text );
5817 $text = Sanitizer
::removeHTMLtags( $text );
5822 * @param $text string
5823 * @param $title Title
5824 * @param $options ParserOptions
5827 function testPst( $text, Title
$title, ParserOptions
$options ) {
5828 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5833 * @param $title Title
5834 * @param $options ParserOptions
5837 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5838 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5842 * Call a callback function on all regions of the given text that are not
5843 * inside strip markers, and replace those regions with the return value
5844 * of the callback. For example, with input:
5848 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5849 * two strings will be replaced with the value returned by the callback in
5857 function markerSkipCallback( $s, $callback ) {
5860 while ( $i < strlen( $s ) ) {
5861 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5862 if ( $markerStart === false ) {
5863 $out .= call_user_func( $callback, substr( $s, $i ) );
5866 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5867 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5868 if ( $markerEnd === false ) {
5869 $out .= substr( $s, $markerStart );
5872 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5873 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5882 * Remove any strip markers found in the given text.
5884 * @param $text Input string
5887 function killMarkers( $text ) {
5888 return $this->mStripState
->killMarkers( $text );
5892 * Save the parser state required to convert the given half-parsed text to
5893 * HTML. "Half-parsed" in this context means the output of
5894 * recursiveTagParse() or internalParse(). This output has strip markers
5895 * from replaceVariables (extensionSubstitution() etc.), and link
5896 * placeholders from replaceLinkHolders().
5898 * Returns an array which can be serialized and stored persistently. This
5899 * array can later be loaded into another parser instance with
5900 * unserializeHalfParsedText(). The text can then be safely incorporated into
5901 * the return value of a parser hook.
5903 * @param $text string
5907 function serializeHalfParsedText( $text ) {
5908 wfProfileIn( __METHOD__
);
5911 'version' => self
::HALF_PARSED_VERSION
,
5912 'stripState' => $this->mStripState
->getSubState( $text ),
5913 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5915 wfProfileOut( __METHOD__
);
5920 * Load the parser state given in the $data array, which is assumed to
5921 * have been generated by serializeHalfParsedText(). The text contents is
5922 * extracted from the array, and its markers are transformed into markers
5923 * appropriate for the current Parser instance. This transformed text is
5924 * returned, and can be safely included in the return value of a parser
5927 * If the $data array has been stored persistently, the caller should first
5928 * check whether it is still valid, by calling isValidHalfParsedText().
5930 * @param array $data Serialized data
5931 * @throws MWException
5934 function unserializeHalfParsedText( $data ) {
5935 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5936 throw new MWException( __METHOD__
. ': invalid version' );
5939 # First, extract the strip state.
5940 $texts = array( $data['text'] );
5941 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5943 # Now renumber links
5944 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5946 # Should be good to go.
5951 * Returns true if the given array, presumed to be generated by
5952 * serializeHalfParsedText(), is compatible with the current version of the
5955 * @param $data Array
5959 function isValidHalfParsedText( $data ) {
5960 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5964 * Parsed a width param of imagelink like 300px or 200x300px
5966 * @param $value String
5971 public function parseWidthParam( $value ) {
5972 $parsedWidthParam = array();
5973 if ( $value === '' ) {
5974 return $parsedWidthParam;
5977 # (bug 13500) In both cases (width/height and width only),
5978 # permit trailing "px" for backward compatibility.
5979 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5980 $width = intval( $m[1] );
5981 $height = intval( $m[2] );
5982 $parsedWidthParam['width'] = $width;
5983 $parsedWidthParam['height'] = $height;
5984 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5985 $width = intval( $value );
5986 $parsedWidthParam['width'] = $width;
5988 return $parsedWidthParam;