3 * Fetching and processing of interface messages.
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
21 * @author Niklas Laxström
23 use MediaWiki\MediaWikiServices
;
26 * The Message class provides methods which fulfil two basic services:
27 * - fetching interface messages
28 * - processing messages into a variety of formats
30 * First implemented with MediaWiki 1.17, the Message class is intended to
31 * replace the old wfMsg* functions that over time grew unusable.
32 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
33 * between old and new functions.
35 * You should use the wfMessage() global function which acts as a wrapper for
36 * the Message class. The wrapper let you pass parameters as arguments.
38 * The most basic usage cases would be:
41 * // Initialize a Message object using the 'some_key' message key
42 * $message = wfMessage( 'some_key' );
44 * // Using two parameters those values are strings 'value1' and 'value2':
45 * $message = wfMessage( 'some_key',
50 * @section message_global_fn Global function wrapper:
52 * Since wfMessage() returns a Message instance, you can chain its call with
53 * a method. Some of them return a Message instance too so you can chain them.
54 * You will find below several examples of wfMessage() usage.
56 * Fetching a message text for interface message:
59 * $button = Xml::button(
60 * wfMessage( 'submit' )->text()
64 * A Message instance can be passed parameters after it has been constructed,
65 * use the params() method to do so:
68 * wfMessage( 'welcome-to' )
69 * ->params( $wgSitename )
73 * {{GRAMMAR}} and friends work correctly:
76 * wfMessage( 'are-friends',
79 * wfMessage( 'bad-message' )
80 * ->rawParams( '<script>...</script>' )
84 * @section message_language Changing language:
86 * Messages can be requested in a different language or in whatever current
87 * content language is being used. The methods are:
88 * - Message->inContentLanguage()
89 * - Message->inLanguage()
91 * Sometimes the message text ends up in the database, so content language is
95 * wfMessage( 'file-log',
97 * )->inContentLanguage()->text();
100 * Checking whether a message exists:
103 * wfMessage( 'mysterious-message' )->exists()
104 * // returns a boolean whether the 'mysterious-message' key exist.
107 * If you want to use a different language:
110 * $userLanguage = $user->getOption( 'language' );
111 * wfMessage( 'email-header' )
112 * ->inLanguage( $userLanguage )
116 * @note You can parse the text only in the content or interface languages
118 * @section message_compare_old Comparison with old wfMsg* functions:
124 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
126 * wfMessage( 'key', 'apple' )->parse();
129 * Parseinline is used because it is more useful when pre-building HTML.
130 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
132 * Places where HTML cannot be used. {{-transformation is done.
135 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
137 * wfMessage( 'key', 'apple', 'pear' )->text();
140 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
141 * parameters are not replaced after escaping by default.
143 * $escaped = wfMessage( 'key' )
144 * ->rawParams( 'apple' )
148 * @section message_appendix Appendix:
151 * - test, can we have tests?
152 * - this documentation needs to be extended
154 * @see https://www.mediawiki.org/wiki/WfMessage()
155 * @see https://www.mediawiki.org/wiki/New_messages_API
156 * @see https://www.mediawiki.org/wiki/Localisation
160 class Message
implements MessageSpecifier
, Serializable
{
161 /** Use message text as-is */
162 const FORMAT_PLAIN
= 'plain';
163 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
164 const FORMAT_BLOCK_PARSE
= 'block-parse';
165 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
166 const FORMAT_PARSE
= 'parse';
167 /** Transform {{..}} constructs but don't transform to HTML */
168 const FORMAT_TEXT
= 'text';
169 /** Transform {{..}} constructs, HTML-escape the result */
170 const FORMAT_ESCAPED
= 'escaped';
173 * Mapping from Message::listParam() types to Language methods.
176 protected static $listTypeMap = [
177 'comma' => 'commaList',
178 'semicolon' => 'semicolonList',
179 'pipe' => 'pipeList',
180 'text' => 'listToText',
184 * In which language to get this message. True, which is the default,
185 * means the current user language, false content language.
189 protected $interface = true;
192 * In which language to get this message. Overrides the $interface setting.
194 * @var Language|bool Explicit language object, or false for user language
196 protected $language = false;
199 * @var string The message key. If $keysToTry has more than one element,
200 * this may change to one of the keys to try when fetching the message text.
205 * @var string[] List of keys to try when fetching the message.
207 protected $keysToTry;
210 * @var array List of parameters which will be substituted into the message.
212 protected $parameters = [];
218 protected $format = 'parse';
221 * @var bool Whether database can be used.
223 protected $useDatabase = true;
226 * @var Title Title object to use as context.
228 protected $title = null;
231 * @var Content Content object representing the message.
233 protected $content = null;
242 * @param string|string[]|MessageSpecifier $key Message key, or array of
243 * message keys to try and use the first non-empty message for, or a
244 * MessageSpecifier to copy from.
245 * @param array $params Message parameters.
246 * @param Language|null $language [optional] Language to use (defaults to current user language).
247 * @throws InvalidArgumentException
249 public function __construct( $key, $params = [], Language
$language = null ) {
250 if ( $key instanceof MessageSpecifier
) {
252 throw new InvalidArgumentException(
253 '$params must be empty if $key is a MessageSpecifier'
256 $params = $key->getParams();
257 $key = $key->getKey();
260 if ( !is_string( $key ) && !is_array( $key ) ) {
261 throw new InvalidArgumentException( '$key must be a string or an array' );
264 $this->keysToTry
= (array)$key;
266 if ( empty( $this->keysToTry
) ) {
267 throw new InvalidArgumentException( '$key must not be an empty list' );
270 $this->key
= reset( $this->keysToTry
);
272 $this->parameters
= array_values( $params );
273 // User language is only resolved in getLanguage(). This helps preserve the
274 // semantic intent of "user language" across serialize() and unserialize().
275 $this->language
= $language ?
: false;
279 * @see Serializable::serialize()
283 public function serialize() {
285 'interface' => $this->interface,
286 'language' => $this->language ?
$this->language
->getCode() : false,
288 'keysToTry' => $this->keysToTry
,
289 'parameters' => $this->parameters
,
290 'format' => $this->format
,
291 'useDatabase' => $this->useDatabase
,
292 'title' => $this->title
,
293 'titlestr' => $this->title ?
$this->title
->getFullText() : null,
298 * @see Serializable::unserialize()
300 * @param string $serialized
302 public function unserialize( $serialized ) {
303 $data = unserialize( $serialized );
304 $this->interface = $data['interface'];
305 $this->key
= $data['key'];
306 $this->keysToTry
= $data['keysToTry'];
307 $this->parameters
= $data['parameters'];
308 $this->format
= $data['format'];
309 $this->useDatabase
= $data['useDatabase'];
310 $this->language
= $data['language'] ? Language
::factory( $data['language'] ) : false;
312 if ( isset( $data['titlestr'] ) ) {
313 $this->title
= Title
::newFromText( $data['titlestr'] );
314 } elseif ( isset( $data['title'] ) && $data['title'] instanceof Title
) {
315 // Old serializations from before December 2018
316 $this->title
= $data['title'];
318 $this->title
= null; // Explicit for sanity
325 * @return bool True if this is a multi-key message, that is, if the key provided to the
326 * constructor was a fallback list of keys to try.
328 public function isMultiKey() {
329 return count( $this->keysToTry
) > 1;
335 * @return string[] The list of keys to try when fetching the message text,
336 * in order of preference.
338 public function getKeysToTry() {
339 return $this->keysToTry
;
343 * Returns the message key.
345 * If a list of multiple possible keys was supplied to the constructor, this method may
346 * return any of these keys. After the message has been fetched, this method will return
347 * the key that was actually used to fetch the message.
353 public function getKey() {
358 * Returns the message parameters.
364 public function getParams() {
365 return $this->parameters
;
369 * Returns the message format.
374 * @deprecated since 1.29 formatting is not stateful
376 public function getFormat() {
377 wfDeprecated( __METHOD__
, '1.29' );
378 return $this->format
;
382 * Returns the Language of the Message.
388 public function getLanguage() {
389 // Defaults to false which means current user language
390 return $this->language ?
: RequestContext
::getMain()->getLanguage();
394 * Factory function that is just wrapper for the real constructor. It is
395 * intended to be used instead of the real constructor, because it allows
396 * chaining method calls, while new objects don't.
400 * @param string|string[]|MessageSpecifier $key
401 * @param mixed $param,... Parameters as strings.
405 public static function newFromKey( $key /*...*/ ) {
406 $params = func_get_args();
407 array_shift( $params );
408 return new self( $key, $params );
412 * Transform a MessageSpecifier or a primitive value used interchangeably with
413 * specifiers (a message key string, or a key + params array) into a proper Message.
415 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
416 * but is an easy error to make due to how StatusValue stores messages internally.
417 * Further array elements are ignored in that case.
419 * @param string|array|MessageSpecifier $value
421 * @throws InvalidArgumentException
424 public static function newFromSpecifier( $value ) {
426 if ( is_array( $value ) ) {
428 $value = array_shift( $params );
431 if ( $value instanceof Message
) { // Message, RawMessage, ApiMessage, etc
432 $message = clone $value;
433 } elseif ( $value instanceof MessageSpecifier
) {
434 $message = new Message( $value );
435 } elseif ( is_string( $value ) ) {
436 $message = new Message( $value, $params );
438 throw new InvalidArgumentException( __METHOD__
. ': invalid argument type '
439 . gettype( $value ) );
446 * Factory function accepting multiple message keys and returning a message instance
447 * for the first message which is non-empty. If all messages are empty then an
448 * instance of the first message key is returned.
452 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
457 public static function newFallbackSequence( /*...*/ ) {
458 $keys = func_get_args();
459 if ( func_num_args() == 1 ) {
460 if ( is_array( $keys[0] ) ) {
461 // Allow an array to be passed as the first argument instead
462 $keys = array_values( $keys[0] );
464 // Optimize a single string to not need special fallback handling
468 return new self( $keys );
472 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
473 * The title will be for the current language, if the message key is in
474 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
475 * language), because Message::inContentLanguage will also return in user language.
477 * @see $wgForceUIMsgAsContentMsg
481 public function getTitle() {
482 global $wgForceUIMsgAsContentMsg;
484 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
485 $lang = $this->getLanguage();
488 !$lang->equals( $contLang )
489 && in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg )
491 $title .= '/' . $lang->getCode();
494 return Title
::makeTitle(
495 NS_MEDIAWIKI
, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) );
499 * Adds parameters to the parameter list of this message.
503 * @param mixed $args,... Parameters as strings or arrays from
504 * Message::numParam() and the like, or a single array of parameters.
506 * @return Message $this
508 public function params( /*...*/ ) {
509 $args = func_get_args();
511 // If $args has only one entry and it's an array, then it's either a
512 // non-varargs call or it happens to be a call with just a single
513 // "special" parameter. Since the "special" parameters don't have any
514 // numeric keys, we'll test that to differentiate the cases.
515 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
516 if ( $args[0] === [] ) {
519 foreach ( $args[0] as $key => $value ) {
520 if ( is_int( $key ) ) {
528 $this->parameters
= array_merge( $this->parameters
, array_values( $args ) );
533 * Add parameters that are substituted after parsing or escaping.
534 * In other words the parsing process cannot access the contents
535 * of this type of parameter, and you need to make sure it is
536 * sanitized beforehand. The parser will see "$n", instead.
540 * @param mixed $params,... Raw parameters as strings, or a single argument that is
541 * an array of raw parameters.
543 * @return Message $this
545 public function rawParams( /*...*/ ) {
546 $params = func_get_args();
547 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
548 $params = $params[0];
550 foreach ( $params as $param ) {
551 $this->parameters
[] = self
::rawParam( $param );
557 * Add parameters that are numeric and will be passed through
558 * Language::formatNum before substitution
562 * @param mixed $param,... Numeric parameters, or a single argument that is
563 * an array of numeric parameters.
565 * @return Message $this
567 public function numParams( /*...*/ ) {
568 $params = func_get_args();
569 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
570 $params = $params[0];
572 foreach ( $params as $param ) {
573 $this->parameters
[] = self
::numParam( $param );
579 * Add parameters that are durations of time and will be passed through
580 * Language::formatDuration before substitution
584 * @param int|int[] $param,... Duration parameters, or a single argument that is
585 * an array of duration parameters.
587 * @return Message $this
589 public function durationParams( /*...*/ ) {
590 $params = func_get_args();
591 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
592 $params = $params[0];
594 foreach ( $params as $param ) {
595 $this->parameters
[] = self
::durationParam( $param );
601 * Add parameters that are expiration times and will be passed through
602 * Language::formatExpiry before substitution
606 * @param string|string[] $param,... Expiry parameters, or a single argument that is
607 * an array of expiry parameters.
609 * @return Message $this
611 public function expiryParams( /*...*/ ) {
612 $params = func_get_args();
613 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
614 $params = $params[0];
616 foreach ( $params as $param ) {
617 $this->parameters
[] = self
::expiryParam( $param );
623 * Add parameters that are time periods and will be passed through
624 * Language::formatTimePeriod before substitution
628 * @param int|int[] $param,... Time period parameters, or a single argument that is
629 * an array of time period parameters.
631 * @return Message $this
633 public function timeperiodParams( /*...*/ ) {
634 $params = func_get_args();
635 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
636 $params = $params[0];
638 foreach ( $params as $param ) {
639 $this->parameters
[] = self
::timeperiodParam( $param );
645 * Add parameters that are file sizes and will be passed through
646 * Language::formatSize before substitution
650 * @param int|int[] $param,... Size parameters, or a single argument that is
651 * an array of size parameters.
653 * @return Message $this
655 public function sizeParams( /*...*/ ) {
656 $params = func_get_args();
657 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
658 $params = $params[0];
660 foreach ( $params as $param ) {
661 $this->parameters
[] = self
::sizeParam( $param );
667 * Add parameters that are bitrates and will be passed through
668 * Language::formatBitrate before substitution
672 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
673 * an array of bit rate parameters.
675 * @return Message $this
677 public function bitrateParams( /*...*/ ) {
678 $params = func_get_args();
679 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
680 $params = $params[0];
682 foreach ( $params as $param ) {
683 $this->parameters
[] = self
::bitrateParam( $param );
689 * Add parameters that are plaintext and will be passed through without
690 * the content being evaluated. Plaintext parameters are not valid as
691 * arguments to parser functions. This differs from self::rawParams in
692 * that the Message class handles escaping to match the output format.
696 * @param string|string[] $param,... plaintext parameters, or a single argument that is
697 * an array of plaintext parameters.
699 * @return Message $this
701 public function plaintextParams( /*...*/ ) {
702 $params = func_get_args();
703 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
704 $params = $params[0];
706 foreach ( $params as $param ) {
707 $this->parameters
[] = self
::plaintextParam( $param );
713 * Set the language and the title from a context object
717 * @param IContextSource $context
719 * @return Message $this
721 public function setContext( IContextSource
$context ) {
722 $this->inLanguage( $context->getLanguage() );
723 $this->title( $context->getTitle() );
724 $this->interface = true;
730 * Request the message in any language that is supported.
732 * As a side effect interface message status is unconditionally
736 * @param Language|string $lang Language code or Language object.
737 * @return Message $this
738 * @throws MWException
740 public function inLanguage( $lang ) {
741 $previousLanguage = $this->language
;
743 if ( $lang instanceof Language
) {
744 $this->language
= $lang;
745 } elseif ( is_string( $lang ) ) {
746 if ( !$this->language
instanceof Language ||
$this->language
->getCode() != $lang ) {
747 $this->language
= Language
::factory( $lang );
749 } elseif ( $lang instanceof StubUserLang
) {
750 $this->language
= false;
752 $type = gettype( $lang );
753 throw new MWException( __METHOD__
. " must be "
754 . "passed a String or Language object; $type given"
758 if ( $this->language
!== $previousLanguage ) {
759 // The language has changed. Clear the message cache.
760 $this->message
= null;
762 $this->interface = false;
767 * Request the message in the wiki's content language,
768 * unless it is disabled for this message.
771 * @see $wgForceUIMsgAsContentMsg
773 * @return Message $this
775 public function inContentLanguage() {
776 global $wgForceUIMsgAsContentMsg;
777 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
781 $this->inLanguage( MediaWikiServices
::getInstance()->getContentLanguage() );
786 * Allows manipulating the interface message flag directly.
787 * Can be used to restore the flag after setting a language.
791 * @param bool $interface
793 * @return Message $this
795 public function setInterfaceMessageFlag( $interface ) {
796 $this->interface = (bool)$interface;
801 * Enable or disable database use.
805 * @param bool $useDatabase
807 * @return Message $this
809 public function useDatabase( $useDatabase ) {
810 $this->useDatabase
= (bool)$useDatabase;
811 $this->message
= null;
816 * Set the Title object to use as context when transforming the message
820 * @param Title $title
822 * @return Message $this
824 public function title( $title ) {
825 $this->title
= $title;
830 * Returns the message as a Content object.
834 public function content() {
835 if ( !$this->content
) {
836 $this->content
= new MessageContent( $this );
839 return $this->content
;
843 * Returns the message parsed from wikitext to HTML.
847 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
848 * the last time (this is for B/C and should be avoided).
850 * @return string HTML
851 * @suppress SecurityCheck-DoubleEscaped phan false positive
853 public function toString( $format = null ) {
854 if ( $format === null ) {
855 $ex = new LogicException( __METHOD__
. ' using implicit format: ' . $this->format
);
856 \MediaWiki\Logger\LoggerFactory
::getInstance( 'message-format' )->warning(
857 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format
, 'key' => $this->key
] );
858 $format = $this->format
;
860 $string = $this->fetchMessage();
862 if ( $string === false ) {
863 // Err on the side of safety, ensure that the output
864 // is always html safe in the event the message key is
865 // missing, since in that case its highly likely the
866 // message key is user-controlled.
867 // '⧼' is used instead of '<' to side-step any
868 // double-escaping issues.
869 // (Keep synchronised with mw.Message#toString in JS.)
870 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
873 # Replace $* with a list of parameters for &uselang=qqx.
874 if ( strpos( $string, '$*' ) !== false ) {
876 if ( $this->parameters
!== [] ) {
877 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
879 $string = str_replace( '$*', $paramlist, $string );
882 # Replace parameters before text parsing
883 $string = $this->replaceParameters( $string, 'before', $format );
885 # Maybe transform using the full parser
886 if ( $format === self
::FORMAT_PARSE
) {
887 $string = $this->parseText( $string );
888 $string = Parser
::stripOuterParagraph( $string );
889 } elseif ( $format === self
::FORMAT_BLOCK_PARSE
) {
890 $string = $this->parseText( $string );
891 } elseif ( $format === self
::FORMAT_TEXT
) {
892 $string = $this->transformText( $string );
893 } elseif ( $format === self
::FORMAT_ESCAPED
) {
894 $string = $this->transformText( $string );
895 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
898 # Raw parameter replacement
899 $string = $this->replaceParameters( $string, 'after', $format );
905 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
906 * $foo = new Message( $key );
907 * $string = "<abbr>$foo</abbr>";
913 public function __toString() {
914 // PHP doesn't allow __toString to throw exceptions and will
915 // trigger a fatal error if it does. So, catch any exceptions.
918 return $this->toString( self
::FORMAT_PARSE
);
919 } catch ( Exception
$ex ) {
921 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
922 . $ex, E_USER_WARNING
);
923 } catch ( Exception
$ex ) {
924 // Doh! Cause a fatal error after all?
927 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
932 * Fully parse the text from wikitext to HTML.
936 * @return string Parsed HTML.
938 public function parse() {
939 $this->format
= self
::FORMAT_PARSE
;
940 return $this->toString( self
::FORMAT_PARSE
);
944 * Returns the message text. {{-transformation is done.
948 * @return string Unescaped message text.
950 public function text() {
951 $this->format
= self
::FORMAT_TEXT
;
952 return $this->toString( self
::FORMAT_TEXT
);
956 * Returns the message text as-is, only parameters are substituted.
960 * @return string Unescaped untransformed message text.
962 public function plain() {
963 $this->format
= self
::FORMAT_PLAIN
;
964 return $this->toString( self
::FORMAT_PLAIN
);
968 * Returns the parsed message text which is always surrounded by a block element.
972 * @return string HTML
974 public function parseAsBlock() {
975 $this->format
= self
::FORMAT_BLOCK_PARSE
;
976 return $this->toString( self
::FORMAT_BLOCK_PARSE
);
980 * Returns the message text. {{-transformation is done and the result
981 * is escaped excluding any raw parameters.
985 * @return string Escaped message text.
987 public function escaped() {
988 $this->format
= self
::FORMAT_ESCAPED
;
989 return $this->toString( self
::FORMAT_ESCAPED
);
993 * Check whether a message key has been defined currently.
999 public function exists() {
1000 return $this->fetchMessage() !== false;
1004 * Check whether a message does not exist, or is an empty string
1007 * @todo FIXME: Merge with isDisabled()?
1011 public function isBlank() {
1012 $message = $this->fetchMessage();
1013 return $message === false ||
$message === '';
1017 * Check whether a message does not exist, is an empty string, or is "-".
1023 public function isDisabled() {
1024 $message = $this->fetchMessage();
1025 return $message === false ||
$message === '' ||
$message === '-';
1033 * @return array Array with a single "raw" key.
1035 public static function rawParam( $raw ) {
1036 return [ 'raw' => $raw ];
1044 * @return array Array with a single "num" key.
1046 public static function numParam( $num ) {
1047 return [ 'num' => $num ];
1053 * @param int $duration
1055 * @return int[] Array with a single "duration" key.
1057 public static function durationParam( $duration ) {
1058 return [ 'duration' => $duration ];
1064 * @param string $expiry
1066 * @return string[] Array with a single "expiry" key.
1068 public static function expiryParam( $expiry ) {
1069 return [ 'expiry' => $expiry ];
1075 * @param int $period
1077 * @return int[] Array with a single "period" key.
1079 public static function timeperiodParam( $period ) {
1080 return [ 'period' => $period ];
1088 * @return int[] Array with a single "size" key.
1090 public static function sizeParam( $size ) {
1091 return [ 'size' => $size ];
1097 * @param int $bitrate
1099 * @return int[] Array with a single "bitrate" key.
1101 public static function bitrateParam( $bitrate ) {
1102 return [ 'bitrate' => $bitrate ];
1108 * @param string $plaintext
1110 * @return string[] Array with a single "plaintext" key.
1112 public static function plaintextParam( $plaintext ) {
1113 return [ 'plaintext' => $plaintext ];
1119 * @param array $list
1120 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1121 * @return array Array with "list" and "type" keys.
1123 public static function listParam( array $list, $type = 'text' ) {
1124 if ( !isset( self
::$listTypeMap[$type] ) ) {
1125 throw new InvalidArgumentException(
1126 "Invalid type '$type'. Known types are: " . implode( ', ', array_keys( self
::$listTypeMap ) )
1129 return [ 'list' => $list, 'type' => $type ];
1133 * Substitutes any parameters into the message text.
1137 * @param string $message The message text.
1138 * @param string $type Either "before" or "after".
1139 * @param string $format One of the FORMAT_* constants.
1143 protected function replaceParameters( $message, $type, $format ) {
1144 // A temporary marker for $1 parameters that is only valid
1145 // in non-attribute contexts. However if the entire message is escaped
1146 // then we don't want to use it because it will be mangled in all contexts
1147 // and its unnessary as ->escaped() messages aren't html.
1148 $marker = $format === self
::FORMAT_ESCAPED ?
'$' : '$\'"';
1149 $replacementKeys = [];
1150 foreach ( $this->parameters
as $n => $param ) {
1151 list( $paramType, $value ) = $this->extractParam( $param, $format );
1152 if ( $type === 'before' ) {
1153 if ( $paramType === 'before' ) {
1154 $replacementKeys['$' . ( $n +
1 )] = $value;
1155 } else /* $paramType === 'after' */ {
1156 // To protect against XSS from replacing parameters
1157 // inside html attributes, we convert $1 to $'"1.
1158 // In the event that one of the parameters ends up
1159 // in an attribute, either the ' or the " will be
1160 // escaped, breaking the replacement and avoiding XSS.
1161 $replacementKeys['$' . ( $n +
1 )] = $marker . ( $n +
1 );
1164 if ( $paramType === 'after' ) {
1165 $replacementKeys[$marker . ( $n +
1 )] = $value;
1169 $message = strtr( $message, $replacementKeys );
1174 * Extracts the parameter type and preprocessed the value if needed.
1178 * @param mixed $param Parameter as defined in this class.
1179 * @param string $format One of the FORMAT_* constants.
1181 * @return array Array with the parameter type (either "before" or "after") and the value.
1183 protected function extractParam( $param, $format ) {
1184 if ( is_array( $param ) ) {
1185 if ( isset( $param['raw'] ) ) {
1186 return [ 'after', $param['raw'] ];
1187 } elseif ( isset( $param['num'] ) ) {
1188 // Replace number params always in before step for now.
1189 // No support for combined raw and num params
1190 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1191 } elseif ( isset( $param['duration'] ) ) {
1192 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1193 } elseif ( isset( $param['expiry'] ) ) {
1194 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1195 } elseif ( isset( $param['period'] ) ) {
1196 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1197 } elseif ( isset( $param['size'] ) ) {
1198 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1199 } elseif ( isset( $param['bitrate'] ) ) {
1200 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1201 } elseif ( isset( $param['plaintext'] ) ) {
1202 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1203 } elseif ( isset( $param['list'] ) ) {
1204 return $this->formatListParam( $param['list'], $param['type'], $format );
1206 if ( !is_scalar( $param ) ) {
1207 $param = serialize( $param );
1209 \MediaWiki\Logger\LoggerFactory
::getInstance( 'Bug58676' )->warning(
1210 'Invalid parameter for message "{msgkey}": {param}',
1212 'exception' => new Exception
,
1213 'msgkey' => $this->getKey(),
1214 'param' => htmlspecialchars( $param ),
1218 return [ 'before', '[INVALID]' ];
1220 } elseif ( $param instanceof Message
) {
1221 // Match language, flags, etc. to the current message.
1222 $msg = clone $param;
1223 if ( $msg->language
!== $this->language ||
$msg->useDatabase
!== $this->useDatabase
) {
1224 // Cache depends on these parameters
1225 $msg->message
= null;
1227 $msg->interface = $this->interface;
1228 $msg->language
= $this->language
;
1229 $msg->useDatabase
= $this->useDatabase
;
1230 $msg->title
= $this->title
;
1233 if ( $format === 'block-parse' ) {
1236 $msg->format
= $format;
1238 // Message objects should not be before parameters because
1239 // then they'll get double escaped. If the message needs to be
1240 // escaped, it'll happen right here when we call toString().
1241 return [ 'after', $msg->toString( $format ) ];
1243 return [ 'before', $param ];
1248 * Wrapper for what ever method we use to parse wikitext.
1252 * @param string $string Wikitext message contents.
1254 * @return string Wikitext parsed into HTML.
1256 protected function parseText( $string ) {
1257 $out = MessageCache
::singleton()->parse(
1262 $this->getLanguage()
1265 return $out instanceof ParserOutput
1267 'enableSectionEditLinks' => false,
1268 // Wrapping messages in an extra <div> is probably not expected. If
1269 // they're outside the content area they probably shouldn't be
1270 // targeted by CSS that's targeting the parser output, and if
1271 // they're inside they already are from the outer div.
1278 * Wrapper for what ever method we use to {{-transform wikitext.
1282 * @param string $string Wikitext message contents.
1284 * @return string Wikitext with {{-constructs replaced with their values.
1286 protected function transformText( $string ) {
1287 return MessageCache
::singleton()->transform(
1290 $this->getLanguage(),
1296 * Wrapper for what ever method we use to get message contents.
1301 * @throws MWException If message key array is empty.
1303 protected function fetchMessage() {
1304 if ( $this->message
=== null ) {
1305 $cache = MessageCache
::singleton();
1307 foreach ( $this->keysToTry
as $key ) {
1308 $message = $cache->get( $key, $this->useDatabase
, $this->getLanguage() );
1309 if ( $message !== false && $message !== '' ) {
1314 // NOTE: The constructor makes sure keysToTry isn't empty,
1315 // so we know that $key and $message are initialized.
1317 $this->message
= $message;
1319 return $this->message
;
1323 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1324 * the entire string is displayed unchanged when displayed in the output
1329 * @param string $plaintext String to ensure plaintext output of
1330 * @param string $format One of the FORMAT_* constants.
1332 * @return string Input plaintext encoded for output to $format
1334 protected function formatPlaintext( $plaintext, $format ) {
1335 switch ( $format ) {
1336 case self
::FORMAT_TEXT
:
1337 case self
::FORMAT_PLAIN
:
1340 case self
::FORMAT_PARSE
:
1341 case self
::FORMAT_BLOCK_PARSE
:
1342 case self
::FORMAT_ESCAPED
:
1344 return htmlspecialchars( $plaintext, ENT_QUOTES
);
1349 * Formats a list of parameters as a concatenated string.
1351 * @param array $params
1352 * @param string $listType
1353 * @param string $format One of the FORMAT_* constants.
1354 * @return array Array with the parameter type (either "before" or "after") and the value.
1356 protected function formatListParam( array $params, $listType, $format ) {
1357 if ( !isset( self
::$listTypeMap[$listType] ) ) {
1358 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1359 . htmlspecialchars( $listType )
1360 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1361 trigger_error( $warning, E_USER_WARNING
);
1363 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1364 return [ 'before', '[INVALID]' ];
1366 $func = self
::$listTypeMap[$listType];
1368 // Handle an empty list sensibly
1370 return [ 'before', $this->getLanguage()->$func( [] ) ];
1373 // First, determine what kinds of list items we have
1377 foreach ( $params as $n => $p ) {
1378 list( $type, $value ) = $this->extractParam( $p, $format );
1379 $types[$type] = true;
1381 $vars[] = '$' . ( $n +
1 );
1384 // Easy case: all are 'before' or 'after', so just join the
1385 // values and use the same type.
1386 if ( count( $types ) === 1 ) {
1387 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1390 // Hard case: We need to process each value per its type, then
1391 // return the concatenated values as 'after'. We handle this by turning
1392 // the list into a RawMessage and processing that as a parameter.
1393 $vars = $this->getLanguage()->$func( $vars );
1394 return $this->extractParam( new RawMessage( $vars, $params ), $format );