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
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
28 * The Message class provides methods which fulfil two basic services:
29 * - fetching interface messages
30 * - processing messages into a variety of formats
32 * First implemented with MediaWiki 1.17, the Message class is intended to
33 * replace the old wfMsg* functions that over time grew unusable.
34 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
35 * between old and new functions.
37 * You should use the wfMessage() global function which acts as a wrapper for
38 * the Message class. The wrapper let you pass parameters as arguments.
40 * The most basic usage cases would be:
43 * // Initialize a Message object using the 'some_key' message key
44 * $message = wfMessage( 'some_key' );
46 * // Using two parameters those values are strings 'value1' and 'value2':
47 * $message = wfMessage( 'some_key',
52 * @section message_global_fn Global function wrapper:
54 * Since wfMessage() returns a Message instance, you can chain its call with
55 * a method. Some of them return a Message instance too so you can chain them.
56 * You will find below several examples of wfMessage() usage.
58 * Fetching a message text for interface message:
61 * $button = Xml::button(
62 * wfMessage( 'submit' )->text()
66 * A Message instance can be passed parameters after it has been constructed,
67 * use the params() method to do so:
70 * wfMessage( 'welcome-to' )
71 * ->params( $wgSitename )
75 * {{GRAMMAR}} and friends work correctly:
78 * wfMessage( 'are-friends',
81 * wfMessage( 'bad-message' )
82 * ->rawParams( '<script>...</script>' )
86 * @section message_language Changing language:
88 * Messages can be requested in a different language or in whatever current
89 * content language is being used. The methods are:
90 * - Message->inContentLanguage()
91 * - Message->inLanguage()
93 * Sometimes the message text ends up in the database, so content language is
97 * wfMessage( 'file-log',
99 * )->inContentLanguage()->text();
102 * Checking whether a message exists:
105 * wfMessage( 'mysterious-message' )->exists()
106 * // returns a boolean whether the 'mysterious-message' key exist.
109 * If you want to use a different language:
112 * $userLanguage = $user->getOption( 'language' );
113 * wfMessage( 'email-header' )
114 * ->inLanguage( $userLanguage )
118 * @note You can parse the text only in the content or interface languages
120 * @section message_compare_old Comparison with old wfMsg* functions:
126 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
128 * wfMessage( 'key', 'apple' )->parse();
131 * Parseinline is used because it is more useful when pre-building HTML.
132 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
134 * Places where HTML cannot be used. {{-transformation is done.
137 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
139 * wfMessage( 'key', 'apple', 'pear' )->text();
142 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
143 * parameters are not replaced after escaping by default.
145 * $escaped = wfMessage( 'key' )
146 * ->rawParams( 'apple' )
150 * @section message_appendix Appendix:
153 * - test, can we have tests?
154 * - this documentation needs to be extended
156 * @see https://www.mediawiki.org/wiki/WfMessage()
157 * @see https://www.mediawiki.org/wiki/New_messages_API
158 * @see https://www.mediawiki.org/wiki/Localisation
162 class Message
implements MessageSpecifier
, Serializable
{
163 /** Use message text as-is */
164 const FORMAT_PLAIN
= 'plain';
165 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
166 const FORMAT_BLOCK_PARSE
= 'block-parse';
167 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
168 const FORMAT_PARSE
= 'parse';
169 /** Transform {{..}} constructs but don't transform to HTML */
170 const FORMAT_TEXT
= 'text';
171 /** Transform {{..}} constructs, HTML-escape the result */
172 const FORMAT_ESCAPED
= 'escaped';
175 * Mapping from Message::listParam() types to Language methods.
178 protected static $listTypeMap = [
179 'comma' => 'commaList',
180 'semicolon' => 'semicolonList',
181 'pipe' => 'pipeList',
182 'text' => 'listToText',
186 * In which language to get this message. True, which is the default,
187 * means the current user language, false content language.
191 protected $interface = true;
194 * In which language to get this message. Overrides the $interface setting.
196 * @var Language|bool Explicit language object, or false for user language
198 protected $language = false;
201 * @var string The message key. If $keysToTry has more than one element,
202 * this may change to one of the keys to try when fetching the message text.
207 * @var string[] List of keys to try when fetching the message.
209 protected $keysToTry;
212 * @var array List of parameters which will be substituted into the message.
214 protected $parameters = [];
220 protected $format = 'parse';
223 * @var bool Whether database can be used.
225 protected $useDatabase = true;
228 * @var Title Title object to use as context.
230 protected $title = null;
233 * @var Content Content object representing the message.
235 protected $content = null;
244 * @param string|string[]|MessageSpecifier $key Message key, or array of
245 * message keys to try and use the first non-empty message for, or a
246 * MessageSpecifier to copy from.
247 * @param array $params Message parameters.
248 * @param Language|null $language [optional] Language to use (defaults to current user language).
249 * @throws InvalidArgumentException
251 public function __construct( $key, $params = [], Language
$language = null ) {
252 if ( $key instanceof MessageSpecifier
) {
254 throw new InvalidArgumentException(
255 '$params must be empty if $key is a MessageSpecifier'
258 $params = $key->getParams();
259 $key = $key->getKey();
262 if ( !is_string( $key ) && !is_array( $key ) ) {
263 throw new InvalidArgumentException( '$key must be a string or an array' );
266 $this->keysToTry
= (array)$key;
268 if ( empty( $this->keysToTry
) ) {
269 throw new InvalidArgumentException( '$key must not be an empty list' );
272 $this->key
= reset( $this->keysToTry
);
274 $this->parameters
= array_values( $params );
275 // User language is only resolved in getLanguage(). This helps preserve the
276 // semantic intent of "user language" across serialize() and unserialize().
277 $this->language
= $language ?
: false;
281 * @see Serializable::serialize()
285 public function serialize() {
287 'interface' => $this->interface,
288 'language' => $this->language ?
$this->language
->getCode() : false,
290 'keysToTry' => $this->keysToTry
,
291 'parameters' => $this->parameters
,
292 'format' => $this->format
,
293 'useDatabase' => $this->useDatabase
,
294 'titlestr' => $this->title ?
$this->title
->getFullText() : null,
299 * @see Serializable::unserialize()
301 * @param string $serialized
303 public function unserialize( $serialized ) {
304 $data = unserialize( $serialized );
305 if ( !is_array( $data ) ) {
306 throw new InvalidArgumentException( __METHOD__
. ': Invalid serialized data' );
309 $this->interface = $data['interface'];
310 $this->key
= $data['key'];
311 $this->keysToTry
= $data['keysToTry'];
312 $this->parameters
= $data['parameters'];
313 $this->format
= $data['format'];
314 $this->useDatabase
= $data['useDatabase'];
315 $this->language
= $data['language'] ? Language
::factory( $data['language'] ) : false;
317 if ( isset( $data['titlestr'] ) ) {
318 $this->title
= Title
::newFromText( $data['titlestr'] );
319 } elseif ( isset( $data['title'] ) && $data['title'] instanceof Title
) {
320 // Old serializations from before December 2018
321 $this->title
= $data['title'];
323 $this->title
= null; // Explicit for sanity
330 * @return bool True if this is a multi-key message, that is, if the key provided to the
331 * constructor was a fallback list of keys to try.
333 public function isMultiKey() {
334 return count( $this->keysToTry
) > 1;
340 * @return string[] The list of keys to try when fetching the message text,
341 * in order of preference.
343 public function getKeysToTry() {
344 return $this->keysToTry
;
348 * Returns the message key.
350 * If a list of multiple possible keys was supplied to the constructor, this method may
351 * return any of these keys. After the message has been fetched, this method will return
352 * the key that was actually used to fetch the message.
358 public function getKey() {
363 * Returns the message parameters.
369 public function getParams() {
370 return $this->parameters
;
374 * Returns the message format.
379 * @deprecated since 1.29 formatting is not stateful
381 public function getFormat() {
382 wfDeprecated( __METHOD__
, '1.29' );
383 return $this->format
;
387 * Returns the Language of the Message.
393 public function getLanguage() {
394 // Defaults to false which means current user language
395 return $this->language ?
: RequestContext
::getMain()->getLanguage();
399 * Factory function that is just wrapper for the real constructor. It is
400 * intended to be used instead of the real constructor, because it allows
401 * chaining method calls, while new objects don't.
405 * @param string|string[]|MessageSpecifier $key
406 * @param mixed $param,... Parameters as strings.
410 public static function newFromKey( $key /*...*/ ) {
411 $params = func_get_args();
412 array_shift( $params );
413 return new self( $key, $params );
417 * Transform a MessageSpecifier or a primitive value used interchangeably with
418 * specifiers (a message key string, or a key + params array) into a proper Message.
420 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
421 * but is an easy error to make due to how StatusValue stores messages internally.
422 * Further array elements are ignored in that case.
424 * @param string|array|MessageSpecifier $value
426 * @throws InvalidArgumentException
429 public static function newFromSpecifier( $value ) {
431 if ( is_array( $value ) ) {
433 $value = array_shift( $params );
436 if ( $value instanceof Message
) { // Message, RawMessage, ApiMessage, etc
437 $message = clone $value;
438 } elseif ( $value instanceof MessageSpecifier
) {
439 $message = new Message( $value );
440 } elseif ( is_string( $value ) ) {
441 $message = new Message( $value, $params );
443 throw new InvalidArgumentException( __METHOD__
. ': invalid argument type '
444 . gettype( $value ) );
451 * Factory function accepting multiple message keys and returning a message instance
452 * for the first message which is non-empty. If all messages are empty then an
453 * instance of the first message key is returned.
457 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
462 public static function newFallbackSequence( /*...*/ ) {
463 $keys = func_get_args();
464 if ( func_num_args() == 1 ) {
465 if ( is_array( $keys[0] ) ) {
466 // Allow an array to be passed as the first argument instead
467 $keys = array_values( $keys[0] );
469 // Optimize a single string to not need special fallback handling
473 return new self( $keys );
477 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
478 * The title will be for the current language, if the message key is in
479 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
480 * language), because Message::inContentLanguage will also return in user language.
482 * @see $wgForceUIMsgAsContentMsg
486 public function getTitle() {
487 global $wgForceUIMsgAsContentMsg;
489 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
490 $lang = $this->getLanguage();
493 !$lang->equals( $contLang )
494 && in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg )
496 $title .= '/' . $lang->getCode();
499 return Title
::makeTitle(
500 NS_MEDIAWIKI
, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) );
504 * Adds parameters to the parameter list of this message.
508 * @param mixed $args,... Parameters as strings or arrays from
509 * Message::numParam() and the like, or a single array of parameters.
511 * @return Message $this
513 public function params( /*...*/ ) {
514 $args = func_get_args();
516 // If $args has only one entry and it's an array, then it's either a
517 // non-varargs call or it happens to be a call with just a single
518 // "special" parameter. Since the "special" parameters don't have any
519 // numeric keys, we'll test that to differentiate the cases.
520 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
521 if ( $args[0] === [] ) {
524 foreach ( $args[0] as $key => $value ) {
525 if ( is_int( $key ) ) {
533 $this->parameters
= array_merge( $this->parameters
, array_values( $args ) );
538 * Add parameters that are substituted after parsing or escaping.
539 * In other words the parsing process cannot access the contents
540 * of this type of parameter, and you need to make sure it is
541 * sanitized beforehand. The parser will see "$n", instead.
545 * @param mixed $params,... Raw parameters as strings, or a single argument that is
546 * an array of raw parameters.
548 * @return Message $this
550 public function rawParams( /*...*/ ) {
551 $params = func_get_args();
552 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
553 $params = $params[0];
555 foreach ( $params as $param ) {
556 $this->parameters
[] = self
::rawParam( $param );
562 * Add parameters that are numeric and will be passed through
563 * Language::formatNum before substitution
567 * @param mixed $param,... Numeric parameters, or a single argument that is
568 * an array of numeric parameters.
570 * @return Message $this
572 public function numParams( /*...*/ ) {
573 $params = func_get_args();
574 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
575 $params = $params[0];
577 foreach ( $params as $param ) {
578 $this->parameters
[] = self
::numParam( $param );
584 * Add parameters that are durations of time and will be passed through
585 * Language::formatDuration before substitution
589 * @param int|int[] $param,... Duration parameters, or a single argument that is
590 * an array of duration parameters.
592 * @return Message $this
594 public function durationParams( /*...*/ ) {
595 $params = func_get_args();
596 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
597 $params = $params[0];
599 foreach ( $params as $param ) {
600 $this->parameters
[] = self
::durationParam( $param );
606 * Add parameters that are expiration times and will be passed through
607 * Language::formatExpiry before substitution
611 * @param string|string[] $param,... Expiry parameters, or a single argument that is
612 * an array of expiry parameters.
614 * @return Message $this
616 public function expiryParams( /*...*/ ) {
617 $params = func_get_args();
618 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
619 $params = $params[0];
621 foreach ( $params as $param ) {
622 $this->parameters
[] = self
::expiryParam( $param );
628 * Add parameters that are time periods and will be passed through
629 * Language::formatTimePeriod before substitution
633 * @param int|int[] $param,... Time period parameters, or a single argument that is
634 * an array of time period parameters.
636 * @return Message $this
638 public function timeperiodParams( /*...*/ ) {
639 $params = func_get_args();
640 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
641 $params = $params[0];
643 foreach ( $params as $param ) {
644 $this->parameters
[] = self
::timeperiodParam( $param );
650 * Add parameters that are file sizes and will be passed through
651 * Language::formatSize before substitution
655 * @param int|int[] $param,... Size parameters, or a single argument that is
656 * an array of size parameters.
658 * @return Message $this
660 public function sizeParams( /*...*/ ) {
661 $params = func_get_args();
662 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
663 $params = $params[0];
665 foreach ( $params as $param ) {
666 $this->parameters
[] = self
::sizeParam( $param );
672 * Add parameters that are bitrates and will be passed through
673 * Language::formatBitrate before substitution
677 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
678 * an array of bit rate parameters.
680 * @return Message $this
682 public function bitrateParams( /*...*/ ) {
683 $params = func_get_args();
684 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
685 $params = $params[0];
687 foreach ( $params as $param ) {
688 $this->parameters
[] = self
::bitrateParam( $param );
694 * Add parameters that are plaintext and will be passed through without
695 * the content being evaluated. Plaintext parameters are not valid as
696 * arguments to parser functions. This differs from self::rawParams in
697 * that the Message class handles escaping to match the output format.
701 * @param string|string[] $param,... plaintext parameters, or a single argument that is
702 * an array of plaintext parameters.
704 * @return Message $this
706 public function plaintextParams( /*...*/ ) {
707 $params = func_get_args();
708 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
709 $params = $params[0];
711 foreach ( $params as $param ) {
712 $this->parameters
[] = self
::plaintextParam( $param );
718 * Set the language and the title from a context object
722 * @param IContextSource $context
724 * @return Message $this
726 public function setContext( IContextSource
$context ) {
727 $this->inLanguage( $context->getLanguage() );
728 $this->title( $context->getTitle() );
729 $this->interface = true;
735 * Request the message in any language that is supported.
737 * As a side effect interface message status is unconditionally
741 * @param Language|string $lang Language code or Language object.
742 * @return Message $this
743 * @throws MWException
745 public function inLanguage( $lang ) {
746 $previousLanguage = $this->language
;
748 if ( $lang instanceof Language
) {
749 $this->language
= $lang;
750 } elseif ( is_string( $lang ) ) {
751 if ( !$this->language
instanceof Language ||
$this->language
->getCode() != $lang ) {
752 $this->language
= Language
::factory( $lang );
754 } elseif ( $lang instanceof StubUserLang
) {
755 $this->language
= false;
757 $type = gettype( $lang );
758 throw new MWException( __METHOD__
. " must be "
759 . "passed a String or Language object; $type given"
763 if ( $this->language
!== $previousLanguage ) {
764 // The language has changed. Clear the message cache.
765 $this->message
= null;
767 $this->interface = false;
772 * Request the message in the wiki's content language,
773 * unless it is disabled for this message.
776 * @see $wgForceUIMsgAsContentMsg
778 * @return Message $this
780 public function inContentLanguage() {
781 global $wgForceUIMsgAsContentMsg;
782 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
786 $this->inLanguage( MediaWikiServices
::getInstance()->getContentLanguage() );
791 * Allows manipulating the interface message flag directly.
792 * Can be used to restore the flag after setting a language.
796 * @param bool $interface
798 * @return Message $this
800 public function setInterfaceMessageFlag( $interface ) {
801 $this->interface = (bool)$interface;
806 * Enable or disable database use.
810 * @param bool $useDatabase
812 * @return Message $this
814 public function useDatabase( $useDatabase ) {
815 $this->useDatabase
= (bool)$useDatabase;
816 $this->message
= null;
821 * Set the Title object to use as context when transforming the message
825 * @param Title $title
827 * @return Message $this
829 public function title( $title ) {
830 $this->title
= $title;
835 * Returns the message as a Content object.
839 public function content() {
840 if ( !$this->content
) {
841 $this->content
= new MessageContent( $this );
844 return $this->content
;
848 * Returns the message parsed from wikitext to HTML.
852 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
853 * the last time (this is for B/C and should be avoided).
855 * @return string HTML
856 * @suppress SecurityCheck-DoubleEscaped phan false positive
858 public function toString( $format = null ) {
859 if ( $format === null ) {
860 $ex = new LogicException( __METHOD__
. ' using implicit format: ' . $this->format
);
861 LoggerFactory
::getInstance( 'message-format' )->warning(
862 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format
, 'key' => $this->key
] );
863 $format = $this->format
;
865 $string = $this->fetchMessage();
867 if ( $string === false ) {
868 // Err on the side of safety, ensure that the output
869 // is always html safe in the event the message key is
870 // missing, since in that case its highly likely the
871 // message key is user-controlled.
872 // '⧼' is used instead of '<' to side-step any
873 // double-escaping issues.
874 // (Keep synchronised with mw.Message#toString in JS.)
875 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
878 # Replace $* with a list of parameters for &uselang=qqx.
879 if ( strpos( $string, '$*' ) !== false ) {
881 if ( $this->parameters
!== [] ) {
882 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
884 $string = str_replace( '$*', $paramlist, $string );
887 # Replace parameters before text parsing
888 $string = $this->replaceParameters( $string, 'before', $format );
890 # Maybe transform using the full parser
891 if ( $format === self
::FORMAT_PARSE
) {
892 $string = $this->parseText( $string );
893 $string = Parser
::stripOuterParagraph( $string );
894 } elseif ( $format === self
::FORMAT_BLOCK_PARSE
) {
895 $string = $this->parseText( $string );
896 } elseif ( $format === self
::FORMAT_TEXT
) {
897 $string = $this->transformText( $string );
898 } elseif ( $format === self
::FORMAT_ESCAPED
) {
899 $string = $this->transformText( $string );
900 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
903 # Raw parameter replacement
904 $string = $this->replaceParameters( $string, 'after', $format );
910 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
911 * $foo = new Message( $key );
912 * $string = "<abbr>$foo</abbr>";
918 public function __toString() {
919 // PHP doesn't allow __toString to throw exceptions and will
920 // trigger a fatal error if it does. So, catch any exceptions.
923 return $this->toString( self
::FORMAT_PARSE
);
924 } catch ( Exception
$ex ) {
926 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
927 . $ex, E_USER_WARNING
);
928 } catch ( Exception
$ex ) {
929 // Doh! Cause a fatal error after all?
932 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
937 * Fully parse the text from wikitext to HTML.
941 * @return string Parsed HTML.
943 public function parse() {
944 $this->format
= self
::FORMAT_PARSE
;
945 return $this->toString( self
::FORMAT_PARSE
);
949 * Returns the message text. {{-transformation is done.
953 * @return string Unescaped message text.
955 public function text() {
956 $this->format
= self
::FORMAT_TEXT
;
957 return $this->toString( self
::FORMAT_TEXT
);
961 * Returns the message text as-is, only parameters are substituted.
965 * @return string Unescaped untransformed message text.
967 public function plain() {
968 $this->format
= self
::FORMAT_PLAIN
;
969 return $this->toString( self
::FORMAT_PLAIN
);
973 * Returns the parsed message text which is always surrounded by a block element.
977 * @return string HTML
979 public function parseAsBlock() {
980 $this->format
= self
::FORMAT_BLOCK_PARSE
;
981 return $this->toString( self
::FORMAT_BLOCK_PARSE
);
985 * Returns the message text. {{-transformation is done and the result
986 * is escaped excluding any raw parameters.
990 * @return string Escaped message text.
992 public function escaped() {
993 $this->format
= self
::FORMAT_ESCAPED
;
994 return $this->toString( self
::FORMAT_ESCAPED
);
998 * Check whether a message key has been defined currently.
1004 public function exists() {
1005 return $this->fetchMessage() !== false;
1009 * Check whether a message does not exist, or is an empty string
1012 * @todo FIXME: Merge with isDisabled()?
1016 public function isBlank() {
1017 $message = $this->fetchMessage();
1018 return $message === false ||
$message === '';
1022 * Check whether a message does not exist, is an empty string, or is "-".
1028 public function isDisabled() {
1029 $message = $this->fetchMessage();
1030 return $message === false ||
$message === '' ||
$message === '-';
1038 * @return array Array with a single "raw" key.
1040 public static function rawParam( $raw ) {
1041 return [ 'raw' => $raw ];
1049 * @return array Array with a single "num" key.
1051 public static function numParam( $num ) {
1052 return [ 'num' => $num ];
1058 * @param int $duration
1060 * @return int[] Array with a single "duration" key.
1062 public static function durationParam( $duration ) {
1063 return [ 'duration' => $duration ];
1069 * @param string $expiry
1071 * @return string[] Array with a single "expiry" key.
1073 public static function expiryParam( $expiry ) {
1074 return [ 'expiry' => $expiry ];
1080 * @param int $period
1082 * @return int[] Array with a single "period" key.
1084 public static function timeperiodParam( $period ) {
1085 return [ 'period' => $period ];
1093 * @return int[] Array with a single "size" key.
1095 public static function sizeParam( $size ) {
1096 return [ 'size' => $size ];
1102 * @param int $bitrate
1104 * @return int[] Array with a single "bitrate" key.
1106 public static function bitrateParam( $bitrate ) {
1107 return [ 'bitrate' => $bitrate ];
1113 * @param string $plaintext
1115 * @return string[] Array with a single "plaintext" key.
1117 public static function plaintextParam( $plaintext ) {
1118 return [ 'plaintext' => $plaintext ];
1124 * @param array $list
1125 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1126 * @return array Array with "list" and "type" keys.
1128 public static function listParam( array $list, $type = 'text' ) {
1129 if ( !isset( self
::$listTypeMap[$type] ) ) {
1130 throw new InvalidArgumentException(
1131 "Invalid type '$type'. Known types are: " . implode( ', ', array_keys( self
::$listTypeMap ) )
1134 return [ 'list' => $list, 'type' => $type ];
1138 * Substitutes any parameters into the message text.
1142 * @param string $message The message text.
1143 * @param string $type Either "before" or "after".
1144 * @param string $format One of the FORMAT_* constants.
1148 protected function replaceParameters( $message, $type, $format ) {
1149 // A temporary marker for $1 parameters that is only valid
1150 // in non-attribute contexts. However if the entire message is escaped
1151 // then we don't want to use it because it will be mangled in all contexts
1152 // and its unnessary as ->escaped() messages aren't html.
1153 $marker = $format === self
::FORMAT_ESCAPED ?
'$' : '$\'"';
1154 $replacementKeys = [];
1155 foreach ( $this->parameters
as $n => $param ) {
1156 list( $paramType, $value ) = $this->extractParam( $param, $format );
1157 if ( $type === 'before' ) {
1158 if ( $paramType === 'before' ) {
1159 $replacementKeys['$' . ( $n +
1 )] = $value;
1160 } else /* $paramType === 'after' */ {
1161 // To protect against XSS from replacing parameters
1162 // inside html attributes, we convert $1 to $'"1.
1163 // In the event that one of the parameters ends up
1164 // in an attribute, either the ' or the " will be
1165 // escaped, breaking the replacement and avoiding XSS.
1166 $replacementKeys['$' . ( $n +
1 )] = $marker . ( $n +
1 );
1168 } elseif ( $paramType === 'after' ) {
1169 $replacementKeys[$marker . ( $n +
1 )] = $value;
1172 return strtr( $message, $replacementKeys );
1176 * Extracts the parameter type and preprocessed the value if needed.
1180 * @param mixed $param Parameter as defined in this class.
1181 * @param string $format One of the FORMAT_* constants.
1183 * @return array Array with the parameter type (either "before" or "after") and the value.
1185 protected function extractParam( $param, $format ) {
1186 if ( is_array( $param ) ) {
1187 if ( isset( $param['raw'] ) ) {
1188 return [ 'after', $param['raw'] ];
1189 } elseif ( isset( $param['num'] ) ) {
1190 // Replace number params always in before step for now.
1191 // No support for combined raw and num params
1192 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1193 } elseif ( isset( $param['duration'] ) ) {
1194 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1195 } elseif ( isset( $param['expiry'] ) ) {
1196 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1197 } elseif ( isset( $param['period'] ) ) {
1198 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1199 } elseif ( isset( $param['size'] ) ) {
1200 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1201 } elseif ( isset( $param['bitrate'] ) ) {
1202 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1203 } elseif ( isset( $param['plaintext'] ) ) {
1204 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1205 } elseif ( isset( $param['list'] ) ) {
1206 return $this->formatListParam( $param['list'], $param['type'], $format );
1208 if ( !is_scalar( $param ) ) {
1209 $param = serialize( $param );
1211 LoggerFactory
::getInstance( 'Bug58676' )->warning(
1212 'Invalid parameter for message "{msgkey}": {param}',
1214 'exception' => new Exception
,
1215 'msgkey' => $this->getKey(),
1216 'param' => htmlspecialchars( $param ),
1220 return [ 'before', '[INVALID]' ];
1222 } elseif ( $param instanceof Message
) {
1223 // Match language, flags, etc. to the current message.
1224 $msg = clone $param;
1225 if ( $msg->language
!== $this->language ||
$msg->useDatabase
!== $this->useDatabase
) {
1226 // Cache depends on these parameters
1227 $msg->message
= null;
1229 $msg->interface = $this->interface;
1230 $msg->language
= $this->language
;
1231 $msg->useDatabase
= $this->useDatabase
;
1232 $msg->title
= $this->title
;
1235 if ( $format === 'block-parse' ) {
1238 $msg->format
= $format;
1240 // Message objects should not be before parameters because
1241 // then they'll get double escaped. If the message needs to be
1242 // escaped, it'll happen right here when we call toString().
1243 return [ 'after', $msg->toString( $format ) ];
1245 return [ 'before', $param ];
1250 * Wrapper for what ever method we use to parse wikitext.
1254 * @param string $string Wikitext message contents.
1256 * @return string Wikitext parsed into HTML.
1258 protected function parseText( $string ) {
1259 $out = MessageCache
::singleton()->parse(
1264 $this->getLanguage()
1267 return $out instanceof ParserOutput
1269 'enableSectionEditLinks' => false,
1270 // Wrapping messages in an extra <div> is probably not expected. If
1271 // they're outside the content area they probably shouldn't be
1272 // targeted by CSS that's targeting the parser output, and if
1273 // they're inside they already are from the outer div.
1280 * Wrapper for what ever method we use to {{-transform wikitext.
1284 * @param string $string Wikitext message contents.
1286 * @return string Wikitext with {{-constructs replaced with their values.
1288 protected function transformText( $string ) {
1289 return MessageCache
::singleton()->transform(
1292 $this->getLanguage(),
1298 * Wrapper for what ever method we use to get message contents.
1303 * @throws MWException If message key array is empty.
1305 protected function fetchMessage() {
1306 if ( $this->message
=== null ) {
1307 $cache = MessageCache
::singleton();
1309 foreach ( $this->keysToTry
as $key ) {
1310 $message = $cache->get( $key, $this->useDatabase
, $this->getLanguage() );
1311 if ( $message !== false && $message !== '' ) {
1316 // NOTE: The constructor makes sure keysToTry isn't empty,
1317 // so we know that $key and $message are initialized.
1319 $this->message
= $message;
1321 return $this->message
;
1325 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1326 * the entire string is displayed unchanged when displayed in the output
1331 * @param string $plaintext String to ensure plaintext output of
1332 * @param string $format One of the FORMAT_* constants.
1334 * @return string Input plaintext encoded for output to $format
1336 protected function formatPlaintext( $plaintext, $format ) {
1337 switch ( $format ) {
1338 case self
::FORMAT_TEXT
:
1339 case self
::FORMAT_PLAIN
:
1342 case self
::FORMAT_PARSE
:
1343 case self
::FORMAT_BLOCK_PARSE
:
1344 case self
::FORMAT_ESCAPED
:
1346 return htmlspecialchars( $plaintext, ENT_QUOTES
);
1351 * Formats a list of parameters as a concatenated string.
1353 * @param array $params
1354 * @param string $listType
1355 * @param string $format One of the FORMAT_* constants.
1356 * @return array Array with the parameter type (either "before" or "after") and the value.
1358 protected function formatListParam( array $params, $listType, $format ) {
1359 if ( !isset( self
::$listTypeMap[$listType] ) ) {
1360 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1361 . htmlspecialchars( $listType )
1362 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1363 trigger_error( $warning, E_USER_WARNING
);
1365 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1366 return [ 'before', '[INVALID]' ];
1368 $func = self
::$listTypeMap[$listType];
1370 // Handle an empty list sensibly
1372 return [ 'before', $this->getLanguage()->$func( [] ) ];
1375 // First, determine what kinds of list items we have
1379 foreach ( $params as $n => $p ) {
1380 list( $type, $value ) = $this->extractParam( $p, $format );
1381 $types[$type] = true;
1383 $vars[] = '$' . ( $n +
1 );
1386 // Easy case: all are 'before' or 'after', so just join the
1387 // values and use the same type.
1388 if ( count( $types ) === 1 ) {
1389 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1392 // Hard case: We need to process each value per its type, then
1393 // return the concatenated values as 'after'. We handle this by turning
1394 // the list into a RawMessage and processing that as a parameter.
1395 $vars = $this->getLanguage()->$func( $vars );
1396 return $this->extractParam( new RawMessage( $vars, $params ), $format );