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
25 * The Message class provides methods which fulfil two basic services:
26 * - fetching interface messages
27 * - processing messages into a variety of formats
29 * First implemented with MediaWiki 1.17, the Message class is intended to
30 * replace the old wfMsg* functions that over time grew unusable.
31 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
32 * between old and new functions.
34 * You should use the wfMessage() global function which acts as a wrapper for
35 * the Message class. The wrapper let you pass parameters as arguments.
37 * The most basic usage cases would be:
40 * // Initialize a Message object using the 'some_key' message key
41 * $message = wfMessage( 'some_key' );
43 * // Using two parameters those values are strings 'value1' and 'value2':
44 * $message = wfMessage( 'some_key',
49 * @section message_global_fn Global function wrapper:
51 * Since wfMessage() returns a Message instance, you can chain its call with
52 * a method. Some of them return a Message instance too so you can chain them.
53 * You will find below several examples of wfMessage() usage.
55 * Fetching a message text for interface message:
58 * $button = Xml::button(
59 * wfMessage( 'submit' )->text()
63 * A Message instance can be passed parameters after it has been constructed,
64 * use the params() method to do so:
67 * wfMessage( 'welcome-to' )
68 * ->params( $wgSitename )
72 * {{GRAMMAR}} and friends work correctly:
75 * wfMessage( 'are-friends',
78 * wfMessage( 'bad-message' )
79 * ->rawParams( '<script>...</script>' )
83 * @section message_language Changing language:
85 * Messages can be requested in a different language or in whatever current
86 * content language is being used. The methods are:
87 * - Message->inContentLanguage()
88 * - Message->inLanguage()
90 * Sometimes the message text ends up in the database, so content language is
94 * wfMessage( 'file-log',
96 * )->inContentLanguage()->text();
99 * Checking whether a message exists:
102 * wfMessage( 'mysterious-message' )->exists()
103 * // returns a boolean whether the 'mysterious-message' key exist.
106 * If you want to use a different language:
109 * $userLanguage = $user->getOption( 'language' );
110 * wfMessage( 'email-header' )
111 * ->inLanguage( $userLanguage )
115 * @note You can parse the text only in the content or interface languages
117 * @section message_compare_old Comparison with old wfMsg* functions:
123 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
125 * wfMessage( 'key', 'apple' )->parse();
128 * Parseinline is used because it is more useful when pre-building HTML.
129 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
131 * Places where HTML cannot be used. {{-transformation is done.
134 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
136 * wfMessage( 'key', 'apple', 'pear' )->text();
139 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
140 * parameters are not replaced after escaping by default.
142 * $escaped = wfMessage( 'key' )
143 * ->rawParams( 'apple' )
147 * @section message_appendix Appendix:
150 * - test, can we have tests?
151 * - this documentation needs to be extended
153 * @see https://www.mediawiki.org/wiki/WfMessage()
154 * @see https://www.mediawiki.org/wiki/New_messages_API
155 * @see https://www.mediawiki.org/wiki/Localisation
159 class Message
implements MessageSpecifier
, Serializable
{
160 /** Use message text as-is */
161 const FORMAT_PLAIN
= 'plain';
162 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
163 const FORMAT_BLOCK_PARSE
= 'block-parse';
164 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
165 const FORMAT_PARSE
= 'parse';
166 /** Transform {{..}} constructs but don't transform to HTML */
167 const FORMAT_TEXT
= 'text';
168 /** Transform {{..}} constructs, HTML-escape the result */
169 const FORMAT_ESCAPED
= 'escaped';
172 * In which language to get this message. True, which is the default,
173 * means the current user language, false content language.
177 protected $interface = true;
180 * In which language to get this message. Overrides the $interface setting.
182 * @var Language|bool Explicit language object, or false for user language
184 protected $language = false;
187 * @var string The message key. If $keysToTry has more than one element,
188 * this may change to one of the keys to try when fetching the message text.
193 * @var string[] List of keys to try when fetching the message.
195 protected $keysToTry;
198 * @var array List of parameters which will be substituted into the message.
200 protected $parameters = [];
206 protected $format = 'parse';
209 * @var bool Whether database can be used.
211 protected $useDatabase = true;
214 * @var Title Title object to use as context.
216 protected $title = null;
219 * @var Content Content object representing the message.
221 protected $content = null;
230 * @param string|string[]|MessageSpecifier $key Message key, or array of
231 * message keys to try and use the first non-empty message for, or a
232 * MessageSpecifier to copy from.
233 * @param array $params Message parameters.
234 * @param Language $language [optional] Language to use (defaults to current user language).
235 * @throws InvalidArgumentException
237 public function __construct( $key, $params = [], Language
$language = null ) {
238 if ( $key instanceof MessageSpecifier
) {
240 throw new InvalidArgumentException(
241 '$params must be empty if $key is a MessageSpecifier'
244 $params = $key->getParams();
245 $key = $key->getKey();
248 if ( !is_string( $key ) && !is_array( $key ) ) {
249 throw new InvalidArgumentException( '$key must be a string or an array' );
252 $this->keysToTry
= (array)$key;
254 if ( empty( $this->keysToTry
) ) {
255 throw new InvalidArgumentException( '$key must not be an empty list' );
258 $this->key
= reset( $this->keysToTry
);
260 $this->parameters
= array_values( $params );
261 // User language is only resolved in getLanguage(). This helps preserve the
262 // semantic intent of "user language" across serialize() and unserialize().
263 $this->language
= $language ?
: false;
267 * @see Serializable::serialize()
271 public function serialize() {
273 'interface' => $this->interface,
274 'language' => $this->language ?
$this->language
->getCode() : false,
276 'keysToTry' => $this->keysToTry
,
277 'parameters' => $this->parameters
,
278 'format' => $this->format
,
279 'useDatabase' => $this->useDatabase
,
280 'title' => $this->title
,
285 * @see Serializable::unserialize()
287 * @param string $serialized
289 public function unserialize( $serialized ) {
290 $data = unserialize( $serialized );
291 $this->interface = $data['interface'];
292 $this->key
= $data['key'];
293 $this->keysToTry
= $data['keysToTry'];
294 $this->parameters
= $data['parameters'];
295 $this->format
= $data['format'];
296 $this->useDatabase
= $data['useDatabase'];
297 $this->language
= $data['language'] ? Language
::factory( $data['language'] ) : false;
298 $this->title
= $data['title'];
304 * @return bool True if this is a multi-key message, that is, if the key provided to the
305 * constructor was a fallback list of keys to try.
307 public function isMultiKey() {
308 return count( $this->keysToTry
) > 1;
314 * @return string[] The list of keys to try when fetching the message text,
315 * in order of preference.
317 public function getKeysToTry() {
318 return $this->keysToTry
;
322 * Returns the message key.
324 * If a list of multiple possible keys was supplied to the constructor, this method may
325 * return any of these keys. After the message has been fetched, this method will return
326 * the key that was actually used to fetch the message.
332 public function getKey() {
337 * Returns the message parameters.
343 public function getParams() {
344 return $this->parameters
;
348 * Returns the message format.
353 * @deprecated since 1.29 formatting is not stateful
355 public function getFormat() {
356 wfDeprecated( __METHOD__
, '1.29' );
357 return $this->format
;
361 * Returns the Language of the Message.
367 public function getLanguage() {
368 // Defaults to false which means current user language
369 return $this->language ?
: RequestContext
::getMain()->getLanguage();
373 * Factory function that is just wrapper for the real constructor. It is
374 * intended to be used instead of the real constructor, because it allows
375 * chaining method calls, while new objects don't.
379 * @param string|string[]|MessageSpecifier $key
380 * @param mixed $param,... Parameters as strings.
384 public static function newFromKey( $key /*...*/ ) {
385 $params = func_get_args();
386 array_shift( $params );
387 return new self( $key, $params );
391 * Transform a MessageSpecifier or a primitive value used interchangeably with
392 * specifiers (a message key string, or a key + params array) into a proper Message.
394 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
395 * but is an easy error to make due to how StatusValue stores messages internally.
396 * Further array elements are ignored in that case.
398 * @param string|array|MessageSpecifier $value
400 * @throws InvalidArgumentException
403 public static function newFromSpecifier( $value ) {
405 if ( is_array( $value ) ) {
407 $value = array_shift( $params );
410 if ( $value instanceof Message
) { // Message, RawMessage, ApiMessage, etc
411 $message = clone( $value );
412 } elseif ( $value instanceof MessageSpecifier
) {
413 $message = new Message( $value );
414 } elseif ( is_string( $value ) ) {
415 $message = new Message( $value, $params );
417 throw new InvalidArgumentException( __METHOD__
. ': invalid argument type '
418 . gettype( $value ) );
425 * Factory function accepting multiple message keys and returning a message instance
426 * for the first message which is non-empty. If all messages are empty then an
427 * instance of the first message key is returned.
431 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
436 public static function newFallbackSequence( /*...*/ ) {
437 $keys = func_get_args();
438 if ( func_num_args() == 1 ) {
439 if ( is_array( $keys[0] ) ) {
440 // Allow an array to be passed as the first argument instead
441 $keys = array_values( $keys[0] );
443 // Optimize a single string to not need special fallback handling
447 return new self( $keys );
451 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
452 * The title will be for the current language, if the message key is in
453 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
454 * language), because Message::inContentLanguage will also return in user language.
456 * @see $wgForceUIMsgAsContentMsg
460 public function getTitle() {
461 global $wgContLang, $wgForceUIMsgAsContentMsg;
465 !$this->language
->equals( $wgContLang )
466 && in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg )
468 $code = $this->language
->getCode();
469 $title .= '/' . $code;
472 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
476 * Adds parameters to the parameter list of this message.
480 * @param mixed ... Parameters as strings, or a single argument that is
481 * an array of strings.
483 * @return Message $this
485 public function params( /*...*/ ) {
486 $args = func_get_args();
487 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
490 $args_values = array_values( $args );
491 $this->parameters
= array_merge( $this->parameters
, $args_values );
496 * Add parameters that are substituted after parsing or escaping.
497 * In other words the parsing process cannot access the contents
498 * of this type of parameter, and you need to make sure it is
499 * sanitized beforehand. The parser will see "$n", instead.
503 * @param mixed $params,... Raw parameters as strings, or a single argument that is
504 * an array of raw parameters.
506 * @return Message $this
508 public function rawParams( /*...*/ ) {
509 $params = func_get_args();
510 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
511 $params = $params[0];
513 foreach ( $params as $param ) {
514 $this->parameters
[] = self
::rawParam( $param );
520 * Add parameters that are numeric and will be passed through
521 * Language::formatNum before substitution
525 * @param mixed $param,... Numeric parameters, or a single argument that is
526 * an array of numeric parameters.
528 * @return Message $this
530 public function numParams( /*...*/ ) {
531 $params = func_get_args();
532 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
533 $params = $params[0];
535 foreach ( $params as $param ) {
536 $this->parameters
[] = self
::numParam( $param );
542 * Add parameters that are durations of time and will be passed through
543 * Language::formatDuration before substitution
547 * @param int|int[] $param,... Duration parameters, or a single argument that is
548 * an array of duration parameters.
550 * @return Message $this
552 public function durationParams( /*...*/ ) {
553 $params = func_get_args();
554 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
555 $params = $params[0];
557 foreach ( $params as $param ) {
558 $this->parameters
[] = self
::durationParam( $param );
564 * Add parameters that are expiration times and will be passed through
565 * Language::formatExpiry before substitution
569 * @param string|string[] $param,... Expiry parameters, or a single argument that is
570 * an array of expiry parameters.
572 * @return Message $this
574 public function expiryParams( /*...*/ ) {
575 $params = func_get_args();
576 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
577 $params = $params[0];
579 foreach ( $params as $param ) {
580 $this->parameters
[] = self
::expiryParam( $param );
586 * Add parameters that are time periods and will be passed through
587 * Language::formatTimePeriod before substitution
591 * @param int|int[] $param,... Time period parameters, or a single argument that is
592 * an array of time period parameters.
594 * @return Message $this
596 public function timeperiodParams( /*...*/ ) {
597 $params = func_get_args();
598 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
599 $params = $params[0];
601 foreach ( $params as $param ) {
602 $this->parameters
[] = self
::timeperiodParam( $param );
608 * Add parameters that are file sizes and will be passed through
609 * Language::formatSize before substitution
613 * @param int|int[] $param,... Size parameters, or a single argument that is
614 * an array of size parameters.
616 * @return Message $this
618 public function sizeParams( /*...*/ ) {
619 $params = func_get_args();
620 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
621 $params = $params[0];
623 foreach ( $params as $param ) {
624 $this->parameters
[] = self
::sizeParam( $param );
630 * Add parameters that are bitrates and will be passed through
631 * Language::formatBitrate before substitution
635 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
636 * an array of bit rate parameters.
638 * @return Message $this
640 public function bitrateParams( /*...*/ ) {
641 $params = func_get_args();
642 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
643 $params = $params[0];
645 foreach ( $params as $param ) {
646 $this->parameters
[] = self
::bitrateParam( $param );
652 * Add parameters that are plaintext and will be passed through without
653 * the content being evaluated. Plaintext parameters are not valid as
654 * arguments to parser functions. This differs from self::rawParams in
655 * that the Message class handles escaping to match the output format.
659 * @param string|string[] $param,... plaintext parameters, or a single argument that is
660 * an array of plaintext parameters.
662 * @return Message $this
664 public function plaintextParams( /*...*/ ) {
665 $params = func_get_args();
666 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
667 $params = $params[0];
669 foreach ( $params as $param ) {
670 $this->parameters
[] = self
::plaintextParam( $param );
676 * Set the language and the title from a context object
680 * @param IContextSource $context
682 * @return Message $this
684 public function setContext( IContextSource
$context ) {
685 $this->inLanguage( $context->getLanguage() );
686 $this->title( $context->getTitle() );
687 $this->interface = true;
693 * Request the message in any language that is supported.
695 * As a side effect interface message status is unconditionally
699 * @param Language|string $lang Language code or Language object.
700 * @return Message $this
701 * @throws MWException
703 public function inLanguage( $lang ) {
704 if ( $lang instanceof Language
) {
705 $this->language
= $lang;
706 } elseif ( is_string( $lang ) ) {
707 if ( !$this->language
instanceof Language ||
$this->language
->getCode() != $lang ) {
708 $this->language
= Language
::factory( $lang );
710 } elseif ( $lang instanceof StubUserLang
) {
711 $this->language
= false;
713 $type = gettype( $lang );
714 throw new MWException( __METHOD__
. " must be "
715 . "passed a String or Language object; $type given"
718 $this->message
= null;
719 $this->interface = false;
724 * Request the message in the wiki's content language,
725 * unless it is disabled for this message.
728 * @see $wgForceUIMsgAsContentMsg
730 * @return Message $this
732 public function inContentLanguage() {
733 global $wgForceUIMsgAsContentMsg;
734 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
739 $this->inLanguage( $wgContLang );
744 * Allows manipulating the interface message flag directly.
745 * Can be used to restore the flag after setting a language.
749 * @param bool $interface
751 * @return Message $this
753 public function setInterfaceMessageFlag( $interface ) {
754 $this->interface = (bool)$interface;
759 * Enable or disable database use.
763 * @param bool $useDatabase
765 * @return Message $this
767 public function useDatabase( $useDatabase ) {
768 $this->useDatabase
= (bool)$useDatabase;
769 $this->message
= null;
774 * Set the Title object to use as context when transforming the message
778 * @param Title $title
780 * @return Message $this
782 public function title( $title ) {
783 $this->title
= $title;
788 * Returns the message as a Content object.
792 public function content() {
793 if ( !$this->content
) {
794 $this->content
= new MessageContent( $this );
797 return $this->content
;
801 * Returns the message parsed from wikitext to HTML.
805 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
806 * the last time (this is for B/C and should be avoided).
808 * @return string HTML
810 public function toString( $format = null ) {
811 if ( $format === null ) {
812 $ex = new LogicException( __METHOD__
. ' using implicit format: ' . $this->format
);
813 \MediaWiki\Logger\LoggerFactory
::getInstance( 'message-format' )->warning(
814 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format
, 'key' => $this->key
] );
815 $format = $this->format
;
817 $string = $this->fetchMessage();
819 if ( $string === false ) {
820 // Err on the side of safety, ensure that the output
821 // is always html safe in the event the message key is
822 // missing, since in that case its highly likely the
823 // message key is user-controlled.
824 // '⧼' is used instead of '<' to side-step any
825 // double-escaping issues.
826 // (Keep synchronised with mw.Message#toString in JS.)
827 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
830 # Replace $* with a list of parameters for &uselang=qqx.
831 if ( strpos( $string, '$*' ) !== false ) {
833 if ( $this->parameters
!== [] ) {
834 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
836 $string = str_replace( '$*', $paramlist, $string );
839 # Replace parameters before text parsing
840 $string = $this->replaceParameters( $string, 'before', $format );
842 # Maybe transform using the full parser
843 if ( $format === self
::FORMAT_PARSE
) {
844 $string = $this->parseText( $string );
845 $string = Parser
::stripOuterParagraph( $string );
846 } elseif ( $format === self
::FORMAT_BLOCK_PARSE
) {
847 $string = $this->parseText( $string );
848 } elseif ( $format === self
::FORMAT_TEXT
) {
849 $string = $this->transformText( $string );
850 } elseif ( $format === self
::FORMAT_ESCAPED
) {
851 $string = $this->transformText( $string );
852 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
855 # Raw parameter replacement
856 $string = $this->replaceParameters( $string, 'after', $format );
862 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
863 * $foo = new Message( $key );
864 * $string = "<abbr>$foo</abbr>";
870 public function __toString() {
871 // PHP doesn't allow __toString to throw exceptions and will
872 // trigger a fatal error if it does. So, catch any exceptions.
875 return $this->toString( self
::FORMAT_PARSE
);
876 } catch ( Exception
$ex ) {
878 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
879 . $ex, E_USER_WARNING
);
880 } catch ( Exception
$ex ) {
881 // Doh! Cause a fatal error after all?
884 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
889 * Fully parse the text from wikitext to HTML.
893 * @return string Parsed HTML.
895 public function parse() {
896 $this->format
= self
::FORMAT_PARSE
;
897 return $this->toString( self
::FORMAT_PARSE
);
901 * Returns the message text. {{-transformation is done.
905 * @return string Unescaped message text.
907 public function text() {
908 $this->format
= self
::FORMAT_TEXT
;
909 return $this->toString( self
::FORMAT_TEXT
);
913 * Returns the message text as-is, only parameters are substituted.
917 * @return string Unescaped untransformed message text.
919 public function plain() {
920 $this->format
= self
::FORMAT_PLAIN
;
921 return $this->toString( self
::FORMAT_PLAIN
);
925 * Returns the parsed message text which is always surrounded by a block element.
929 * @return string HTML
931 public function parseAsBlock() {
932 $this->format
= self
::FORMAT_BLOCK_PARSE
;
933 return $this->toString( self
::FORMAT_BLOCK_PARSE
);
937 * Returns the message text. {{-transformation is done and the result
938 * is escaped excluding any raw parameters.
942 * @return string Escaped message text.
944 public function escaped() {
945 $this->format
= self
::FORMAT_ESCAPED
;
946 return $this->toString( self
::FORMAT_ESCAPED
);
950 * Check whether a message key has been defined currently.
956 public function exists() {
957 return $this->fetchMessage() !== false;
961 * Check whether a message does not exist, or is an empty string
964 * @todo FIXME: Merge with isDisabled()?
968 public function isBlank() {
969 $message = $this->fetchMessage();
970 return $message === false ||
$message === '';
974 * Check whether a message does not exist, is an empty string, or is "-".
980 public function isDisabled() {
981 $message = $this->fetchMessage();
982 return $message === false ||
$message === '' ||
$message === '-';
990 * @return array Array with a single "raw" key.
992 public static function rawParam( $raw ) {
993 return [ 'raw' => $raw ];
1001 * @return array Array with a single "num" key.
1003 public static function numParam( $num ) {
1004 return [ 'num' => $num ];
1010 * @param int $duration
1012 * @return int[] Array with a single "duration" key.
1014 public static function durationParam( $duration ) {
1015 return [ 'duration' => $duration ];
1021 * @param string $expiry
1023 * @return string[] Array with a single "expiry" key.
1025 public static function expiryParam( $expiry ) {
1026 return [ 'expiry' => $expiry ];
1032 * @param number $period
1034 * @return number[] Array with a single "period" key.
1036 public static function timeperiodParam( $period ) {
1037 return [ 'period' => $period ];
1045 * @return int[] Array with a single "size" key.
1047 public static function sizeParam( $size ) {
1048 return [ 'size' => $size ];
1054 * @param int $bitrate
1056 * @return int[] Array with a single "bitrate" key.
1058 public static function bitrateParam( $bitrate ) {
1059 return [ 'bitrate' => $bitrate ];
1065 * @param string $plaintext
1067 * @return string[] Array with a single "plaintext" key.
1069 public static function plaintextParam( $plaintext ) {
1070 return [ 'plaintext' => $plaintext ];
1074 * Substitutes any parameters into the message text.
1078 * @param string $message The message text.
1079 * @param string $type Either "before" or "after".
1080 * @param string $format One of the FORMAT_* constants.
1084 protected function replaceParameters( $message, $type = 'before', $format ) {
1085 $replacementKeys = [];
1086 foreach ( $this->parameters
as $n => $param ) {
1087 list( $paramType, $value ) = $this->extractParam( $param, $format );
1088 if ( $type === $paramType ) {
1089 $replacementKeys['$' . ( $n +
1 )] = $value;
1092 $message = strtr( $message, $replacementKeys );
1097 * Extracts the parameter type and preprocessed the value if needed.
1101 * @param mixed $param Parameter as defined in this class.
1102 * @param string $format One of the FORMAT_* constants.
1104 * @return array Array with the parameter type (either "before" or "after") and the value.
1106 protected function extractParam( $param, $format ) {
1107 if ( is_array( $param ) ) {
1108 if ( isset( $param['raw'] ) ) {
1109 return [ 'after', $param['raw'] ];
1110 } elseif ( isset( $param['num'] ) ) {
1111 // Replace number params always in before step for now.
1112 // No support for combined raw and num params
1113 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1114 } elseif ( isset( $param['duration'] ) ) {
1115 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1116 } elseif ( isset( $param['expiry'] ) ) {
1117 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1118 } elseif ( isset( $param['period'] ) ) {
1119 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1120 } elseif ( isset( $param['size'] ) ) {
1121 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1122 } elseif ( isset( $param['bitrate'] ) ) {
1123 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1124 } elseif ( isset( $param['plaintext'] ) ) {
1125 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1127 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
1128 htmlspecialchars( serialize( $param ) );
1129 trigger_error( $warning, E_USER_WARNING
);
1131 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1133 return [ 'before', '[INVALID]' ];
1135 } elseif ( $param instanceof Message
) {
1136 // Match language, flags, etc. to the current message.
1137 $msg = clone $param;
1138 if ( $msg->language
!== $this->language ||
$msg->useDatabase
!== $this->useDatabase
) {
1139 // Cache depends on these parameters
1140 $msg->message
= null;
1142 $msg->interface = $this->interface;
1143 $msg->language
= $this->language
;
1144 $msg->useDatabase
= $this->useDatabase
;
1145 $msg->title
= $this->title
;
1148 if ( $format === 'block-parse' ) {
1151 $msg->format
= $format;
1153 // Message objects should not be before parameters because
1154 // then they'll get double escaped. If the message needs to be
1155 // escaped, it'll happen right here when we call toString().
1156 return [ 'after', $msg->toString( $format ) ];
1158 return [ 'before', $param ];
1163 * Wrapper for what ever method we use to parse wikitext.
1167 * @param string $string Wikitext message contents.
1169 * @return string Wikitext parsed into HTML.
1171 protected function parseText( $string ) {
1172 $out = MessageCache
::singleton()->parse(
1177 $this->getLanguage()
1180 return $out instanceof ParserOutput ?
$out->getText() : $out;
1184 * Wrapper for what ever method we use to {{-transform wikitext.
1188 * @param string $string Wikitext message contents.
1190 * @return string Wikitext with {{-constructs replaced with their values.
1192 protected function transformText( $string ) {
1193 return MessageCache
::singleton()->transform(
1196 $this->getLanguage(),
1202 * Wrapper for what ever method we use to get message contents.
1207 * @throws MWException If message key array is empty.
1209 protected function fetchMessage() {
1210 if ( $this->message
=== null ) {
1211 $cache = MessageCache
::singleton();
1213 foreach ( $this->keysToTry
as $key ) {
1214 $message = $cache->get( $key, $this->useDatabase
, $this->getLanguage() );
1215 if ( $message !== false && $message !== '' ) {
1220 // NOTE: The constructor makes sure keysToTry isn't empty,
1221 // so we know that $key and $message are initialized.
1223 $this->message
= $message;
1225 return $this->message
;
1229 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1230 * the entire string is displayed unchanged when displayed in the output
1235 * @param string $plaintext String to ensure plaintext output of
1236 * @param string $format One of the FORMAT_* constants.
1238 * @return string Input plaintext encoded for output to $format
1240 protected function formatPlaintext( $plaintext, $format ) {
1241 switch ( $format ) {
1242 case self
::FORMAT_TEXT
:
1243 case self
::FORMAT_PLAIN
:
1246 case self
::FORMAT_PARSE
:
1247 case self
::FORMAT_BLOCK_PARSE
:
1248 case self
::FORMAT_ESCAPED
:
1250 return htmlspecialchars( $plaintext, ENT_QUOTES
);
1257 * Variant of the Message class.
1259 * Rather than treating the message key as a lookup
1260 * value (which is passed to the MessageCache and
1261 * translated as necessary), a RawMessage key is
1262 * treated as the actual message.
1264 * All other functionality (parsing, escaping, etc.)
1269 class RawMessage
extends Message
{
1272 * Call the parent constructor, then store the key as
1275 * @see Message::__construct
1277 * @param string $text Message to use.
1278 * @param array $params Parameters for the message.
1280 * @throws InvalidArgumentException
1282 public function __construct( $text, $params = [] ) {
1283 if ( !is_string( $text ) ) {
1284 throw new InvalidArgumentException( '$text must be a string' );
1287 parent
::__construct( $text, $params );
1289 // The key is the message.
1290 $this->message
= $text;
1294 * Fetch the message (in this case, the key).
1298 public function fetchMessage() {
1299 // Just in case the message is unset somewhere.
1300 if ( $this->message
=== null ) {
1301 $this->message
= $this->key
;
1304 return $this->message
;