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
{
162 * In which language to get this message. True, which is the default,
163 * means the current user language, false content language.
167 protected $interface = true;
170 * In which language to get this message. Overrides the $interface setting.
172 * @var Language|bool Explicit language object, or false for user language
174 protected $language = false;
177 * @var string The message key. If $keysToTry has more than one element,
178 * this may change to one of the keys to try when fetching the message text.
183 * @var string[] List of keys to try when fetching the message.
185 protected $keysToTry;
188 * @var array List of parameters which will be substituted into the message.
190 protected $parameters = [];
193 * Format for the message.
194 * Supported formats are:
196 * * escaped (transform+htmlspecialchars)
203 protected $format = 'parse';
206 * @var bool Whether database can be used.
208 protected $useDatabase = true;
211 * @var Title Title object to use as context.
213 protected $title = null;
216 * @var Content Content object representing the message.
218 protected $content = null;
227 * @param string|string[]|MessageSpecifier $key Message key, or array of
228 * message keys to try and use the first non-empty message for, or a
229 * MessageSpecifier to copy from.
230 * @param array $params Message parameters.
231 * @param Language $language [optional] Language to use (defaults to current user language).
232 * @throws InvalidArgumentException
234 public function __construct( $key, $params = [], Language
$language = null ) {
235 if ( $key instanceof MessageSpecifier
) {
237 throw new InvalidArgumentException(
238 '$params must be empty if $key is a MessageSpecifier'
241 $params = $key->getParams();
242 $key = $key->getKey();
245 if ( !is_string( $key ) && !is_array( $key ) ) {
246 throw new InvalidArgumentException( '$key must be a string or an array' );
249 $this->keysToTry
= (array)$key;
251 if ( empty( $this->keysToTry
) ) {
252 throw new InvalidArgumentException( '$key must not be an empty list' );
255 $this->key
= reset( $this->keysToTry
);
257 $this->parameters
= array_values( $params );
258 // User language is only resolved in getLanguage(). This helps preserve the
259 // semantic intent of "user language" across serialize() and unserialize().
260 $this->language
= $language ?
: false;
264 * @see Serializable::serialize()
268 public function serialize() {
270 'interface' => $this->interface,
271 'language' => $this->language ?
$this->language
->getCode() : false,
273 'keysToTry' => $this->keysToTry
,
274 'parameters' => $this->parameters
,
275 'format' => $this->format
,
276 'useDatabase' => $this->useDatabase
,
277 'title' => $this->title
,
282 * @see Serializable::unserialize()
284 * @param string $serialized
286 public function unserialize( $serialized ) {
287 $data = unserialize( $serialized );
288 $this->interface = $data['interface'];
289 $this->key
= $data['key'];
290 $this->keysToTry
= $data['keysToTry'];
291 $this->parameters
= $data['parameters'];
292 $this->format
= $data['format'];
293 $this->useDatabase
= $data['useDatabase'];
294 $this->language
= $data['language'] ? Language
::factory( $data['language'] ) : false;
295 $this->title
= $data['title'];
301 * @return bool True if this is a multi-key message, that is, if the key provided to the
302 * constructor was a fallback list of keys to try.
304 public function isMultiKey() {
305 return count( $this->keysToTry
) > 1;
311 * @return string[] The list of keys to try when fetching the message text,
312 * in order of preference.
314 public function getKeysToTry() {
315 return $this->keysToTry
;
319 * Returns the message key.
321 * If a list of multiple possible keys was supplied to the constructor, this method may
322 * return any of these keys. After the message has been fetched, this method will return
323 * the key that was actually used to fetch the message.
329 public function getKey() {
334 * Returns the message parameters.
340 public function getParams() {
341 return $this->parameters
;
345 * Returns the message format.
351 public function getFormat() {
352 return $this->format
;
356 * Returns the Language of the Message.
362 public function getLanguage() {
363 // Defaults to false which means current user language
364 return $this->language ?
: RequestContext
::getMain()->getLanguage();
368 * Factory function that is just wrapper for the real constructor. It is
369 * intended to be used instead of the real constructor, because it allows
370 * chaining method calls, while new objects don't.
374 * @param string|string[]|MessageSpecifier $key
375 * @param mixed $param,... Parameters as strings.
379 public static function newFromKey( $key /*...*/ ) {
380 $params = func_get_args();
381 array_shift( $params );
382 return new self( $key, $params );
386 * Transform a MessageSpecifier or a primitive value used interchangeably with
387 * specifiers (a message key string, or a key + params array) into a proper Message.
389 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
390 * but is an easy error to make due to how StatusValue stores messages internally.
391 * Further array elements are ignored in that case.
393 * @param string|array|MessageSpecifier $value
395 * @throws InvalidArgumentException
398 public static function newFromSpecifier( $value ) {
400 if ( is_array( $value ) ) {
402 $value = array_shift( $params );
405 if ( $value instanceof Message
) { // Message, RawMessage, ApiMessage, etc
406 $message = clone( $value );
407 } elseif ( $value instanceof MessageSpecifier
) {
408 $message = new Message( $value );
409 } elseif ( is_string( $value ) ) {
410 $message = new Message( $value, $params );
412 throw new InvalidArgumentException( __METHOD__
. ': invalid argument type '
413 . gettype( $value ) );
420 * Factory function accepting multiple message keys and returning a message instance
421 * for the first message which is non-empty. If all messages are empty then an
422 * instance of the first message key is returned.
426 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
431 public static function newFallbackSequence( /*...*/ ) {
432 $keys = func_get_args();
433 if ( func_num_args() == 1 ) {
434 if ( is_array( $keys[0] ) ) {
435 // Allow an array to be passed as the first argument instead
436 $keys = array_values( $keys[0] );
438 // Optimize a single string to not need special fallback handling
442 return new self( $keys );
446 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
447 * The title will be for the current language, if the message key is in
448 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
449 * language), because Message::inContentLanguage will also return in user language.
451 * @see $wgForceUIMsgAsContentMsg
455 public function getTitle() {
456 global $wgContLang, $wgForceUIMsgAsContentMsg;
460 !$this->language
->equals( $wgContLang )
461 && in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg )
463 $code = $this->language
->getCode();
464 $title .= '/' . $code;
467 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
471 * Adds parameters to the parameter list of this message.
475 * @param mixed ... Parameters as strings, or a single argument that is
476 * an array of strings.
478 * @return Message $this
480 public function params( /*...*/ ) {
481 $args = func_get_args();
482 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
485 $args_values = array_values( $args );
486 $this->parameters
= array_merge( $this->parameters
, $args_values );
491 * Add parameters that are substituted after parsing or escaping.
492 * In other words the parsing process cannot access the contents
493 * of this type of parameter, and you need to make sure it is
494 * sanitized beforehand. The parser will see "$n", instead.
498 * @param mixed $params,... Raw parameters as strings, or a single argument that is
499 * an array of raw parameters.
501 * @return Message $this
503 public function rawParams( /*...*/ ) {
504 $params = func_get_args();
505 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
506 $params = $params[0];
508 foreach ( $params as $param ) {
509 $this->parameters
[] = self
::rawParam( $param );
515 * Add parameters that are numeric and will be passed through
516 * Language::formatNum before substitution
520 * @param mixed $param,... Numeric parameters, or a single argument that is
521 * an array of numeric parameters.
523 * @return Message $this
525 public function numParams( /*...*/ ) {
526 $params = func_get_args();
527 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
528 $params = $params[0];
530 foreach ( $params as $param ) {
531 $this->parameters
[] = self
::numParam( $param );
537 * Add parameters that are durations of time and will be passed through
538 * Language::formatDuration before substitution
542 * @param int|int[] $param,... Duration parameters, or a single argument that is
543 * an array of duration parameters.
545 * @return Message $this
547 public function durationParams( /*...*/ ) {
548 $params = func_get_args();
549 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
550 $params = $params[0];
552 foreach ( $params as $param ) {
553 $this->parameters
[] = self
::durationParam( $param );
559 * Add parameters that are expiration times and will be passed through
560 * Language::formatExpiry before substitution
564 * @param string|string[] $param,... Expiry parameters, or a single argument that is
565 * an array of expiry parameters.
567 * @return Message $this
569 public function expiryParams( /*...*/ ) {
570 $params = func_get_args();
571 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
572 $params = $params[0];
574 foreach ( $params as $param ) {
575 $this->parameters
[] = self
::expiryParam( $param );
581 * Add parameters that are time periods and will be passed through
582 * Language::formatTimePeriod before substitution
586 * @param int|int[] $param,... Time period parameters, or a single argument that is
587 * an array of time period parameters.
589 * @return Message $this
591 public function timeperiodParams( /*...*/ ) {
592 $params = func_get_args();
593 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
594 $params = $params[0];
596 foreach ( $params as $param ) {
597 $this->parameters
[] = self
::timeperiodParam( $param );
603 * Add parameters that are file sizes and will be passed through
604 * Language::formatSize before substitution
608 * @param int|int[] $param,... Size parameters, or a single argument that is
609 * an array of size parameters.
611 * @return Message $this
613 public function sizeParams( /*...*/ ) {
614 $params = func_get_args();
615 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
616 $params = $params[0];
618 foreach ( $params as $param ) {
619 $this->parameters
[] = self
::sizeParam( $param );
625 * Add parameters that are bitrates and will be passed through
626 * Language::formatBitrate before substitution
630 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
631 * an array of bit rate parameters.
633 * @return Message $this
635 public function bitrateParams( /*...*/ ) {
636 $params = func_get_args();
637 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
638 $params = $params[0];
640 foreach ( $params as $param ) {
641 $this->parameters
[] = self
::bitrateParam( $param );
647 * Add parameters that are plaintext and will be passed through without
648 * the content being evaluated. Plaintext parameters are not valid as
649 * arguments to parser functions. This differs from self::rawParams in
650 * that the Message class handles escaping to match the output format.
654 * @param string|string[] $param,... plaintext parameters, or a single argument that is
655 * an array of plaintext parameters.
657 * @return Message $this
659 public function plaintextParams( /*...*/ ) {
660 $params = func_get_args();
661 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
662 $params = $params[0];
664 foreach ( $params as $param ) {
665 $this->parameters
[] = self
::plaintextParam( $param );
671 * Set the language and the title from a context object
675 * @param IContextSource $context
677 * @return Message $this
679 public function setContext( IContextSource
$context ) {
680 $this->inLanguage( $context->getLanguage() );
681 $this->title( $context->getTitle() );
682 $this->interface = true;
688 * Request the message in any language that is supported.
690 * As a side effect interface message status is unconditionally
694 * @param Language|string $lang Language code or Language object.
695 * @return Message $this
696 * @throws MWException
698 public function inLanguage( $lang ) {
699 if ( $lang instanceof Language
) {
700 $this->language
= $lang;
701 } elseif ( is_string( $lang ) ) {
702 if ( !$this->language
instanceof Language ||
$this->language
->getCode() != $lang ) {
703 $this->language
= Language
::factory( $lang );
705 } elseif ( $lang instanceof StubUserLang
) {
706 $this->language
= false;
708 $type = gettype( $lang );
709 throw new MWException( __METHOD__
. " must be "
710 . "passed a String or Language object; $type given"
713 $this->message
= null;
714 $this->interface = false;
719 * Request the message in the wiki's content language,
720 * unless it is disabled for this message.
723 * @see $wgForceUIMsgAsContentMsg
725 * @return Message $this
727 public function inContentLanguage() {
728 global $wgForceUIMsgAsContentMsg;
729 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
734 $this->inLanguage( $wgContLang );
739 * Allows manipulating the interface message flag directly.
740 * Can be used to restore the flag after setting a language.
744 * @param bool $interface
746 * @return Message $this
748 public function setInterfaceMessageFlag( $interface ) {
749 $this->interface = (bool)$interface;
754 * Enable or disable database use.
758 * @param bool $useDatabase
760 * @return Message $this
762 public function useDatabase( $useDatabase ) {
763 $this->useDatabase
= (bool)$useDatabase;
768 * Set the Title object to use as context when transforming the message
772 * @param Title $title
774 * @return Message $this
776 public function title( $title ) {
777 $this->title
= $title;
782 * Returns the message as a Content object.
786 public function content() {
787 if ( !$this->content
) {
788 $this->content
= new MessageContent( $this );
791 return $this->content
;
795 * Returns the message parsed from wikitext to HTML.
799 * @return string HTML
801 public function toString() {
802 $string = $this->fetchMessage();
804 if ( $string === false ) {
805 // Err on the side of safety, ensure that the output
806 // is always html safe in the event the message key is
807 // missing, since in that case its highly likely the
808 // message key is user-controlled.
809 // '⧼' is used instead of '<' to side-step any
810 // double-escaping issues.
811 // (Keep synchronised with mw.Message#toString in JS.)
812 return '⧼' . htmlspecialchars( $this->key
) . '⧽';
815 # Replace $* with a list of parameters for &uselang=qqx.
816 if ( strpos( $string, '$*' ) !== false ) {
818 if ( $this->parameters
!== [] ) {
819 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
821 $string = str_replace( '$*', $paramlist, $string );
824 # Replace parameters before text parsing
825 $string = $this->replaceParameters( $string, 'before' );
827 # Maybe transform using the full parser
828 if ( $this->format
=== 'parse' ) {
829 $string = $this->parseText( $string );
830 $string = Parser
::stripOuterParagraph( $string );
831 } elseif ( $this->format
=== 'block-parse' ) {
832 $string = $this->parseText( $string );
833 } elseif ( $this->format
=== 'text' ) {
834 $string = $this->transformText( $string );
835 } elseif ( $this->format
=== 'escaped' ) {
836 $string = $this->transformText( $string );
837 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
840 # Raw parameter replacement
841 $string = $this->replaceParameters( $string, 'after' );
847 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
848 * $foo = new Message( $key );
849 * $string = "<abbr>$foo</abbr>";
855 public function __toString() {
856 if ( $this->format
!== 'parse' ) {
857 $ex = new LogicException( __METHOD__
. ' using implicit format: ' . $this->format
);
858 \MediaWiki\Logger\LoggerFactory
::getInstance( 'message-format' )->warning(
859 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format
, 'key' => $this->key
] );
862 // PHP doesn't allow __toString to throw exceptions and will
863 // trigger a fatal error if it does. So, catch any exceptions.
866 return $this->toString();
867 } catch ( Exception
$ex ) {
869 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
870 . $ex, E_USER_WARNING
);
871 } catch ( Exception
$ex ) {
872 // Doh! Cause a fatal error after all?
875 if ( $this->format
=== 'plain' ||
$this->format
=== 'text' ) {
876 return '<' . $this->key
. '>';
878 return '<' . htmlspecialchars( $this->key
) . '>';
883 * Fully parse the text from wikitext to HTML.
887 * @return string Parsed HTML.
889 public function parse() {
890 $this->format
= 'parse';
891 return $this->toString();
895 * Returns the message text. {{-transformation is done.
899 * @return string Unescaped message text.
901 public function text() {
902 $this->format
= 'text';
903 return $this->toString();
907 * Returns the message text as-is, only parameters are substituted.
911 * @return string Unescaped untransformed message text.
913 public function plain() {
914 $this->format
= 'plain';
915 return $this->toString();
919 * Returns the parsed message text which is always surrounded by a block element.
923 * @return string HTML
925 public function parseAsBlock() {
926 $this->format
= 'block-parse';
927 return $this->toString();
931 * Returns the message text. {{-transformation is done and the result
932 * is escaped excluding any raw parameters.
936 * @return string Escaped message text.
938 public function escaped() {
939 $this->format
= 'escaped';
940 return $this->toString();
944 * Check whether a message key has been defined currently.
950 public function exists() {
951 return $this->fetchMessage() !== false;
955 * Check whether a message does not exist, or is an empty string
958 * @todo FIXME: Merge with isDisabled()?
962 public function isBlank() {
963 $message = $this->fetchMessage();
964 return $message === false ||
$message === '';
968 * Check whether a message does not exist, is an empty string, or is "-".
974 public function isDisabled() {
975 $message = $this->fetchMessage();
976 return $message === false ||
$message === '' ||
$message === '-';
984 * @return array Array with a single "raw" key.
986 public static function rawParam( $raw ) {
987 return [ 'raw' => $raw ];
995 * @return array Array with a single "num" key.
997 public static function numParam( $num ) {
998 return [ 'num' => $num ];
1004 * @param int $duration
1006 * @return int[] Array with a single "duration" key.
1008 public static function durationParam( $duration ) {
1009 return [ 'duration' => $duration ];
1015 * @param string $expiry
1017 * @return string[] Array with a single "expiry" key.
1019 public static function expiryParam( $expiry ) {
1020 return [ 'expiry' => $expiry ];
1026 * @param number $period
1028 * @return number[] Array with a single "period" key.
1030 public static function timeperiodParam( $period ) {
1031 return [ 'period' => $period ];
1039 * @return int[] Array with a single "size" key.
1041 public static function sizeParam( $size ) {
1042 return [ 'size' => $size ];
1048 * @param int $bitrate
1050 * @return int[] Array with a single "bitrate" key.
1052 public static function bitrateParam( $bitrate ) {
1053 return [ 'bitrate' => $bitrate ];
1059 * @param string $plaintext
1061 * @return string[] Array with a single "plaintext" key.
1063 public static function plaintextParam( $plaintext ) {
1064 return [ 'plaintext' => $plaintext ];
1068 * Substitutes any parameters into the message text.
1072 * @param string $message The message text.
1073 * @param string $type Either "before" or "after".
1077 protected function replaceParameters( $message, $type = 'before' ) {
1078 $replacementKeys = [];
1079 foreach ( $this->parameters
as $n => $param ) {
1080 list( $paramType, $value ) = $this->extractParam( $param );
1081 if ( $type === $paramType ) {
1082 $replacementKeys['$' . ( $n +
1 )] = $value;
1085 $message = strtr( $message, $replacementKeys );
1090 * Extracts the parameter type and preprocessed the value if needed.
1094 * @param mixed $param Parameter as defined in this class.
1096 * @return array Array with the parameter type (either "before" or "after") and the value.
1098 protected function extractParam( $param ) {
1099 if ( is_array( $param ) ) {
1100 if ( isset( $param['raw'] ) ) {
1101 return [ 'after', $param['raw'] ];
1102 } elseif ( isset( $param['num'] ) ) {
1103 // Replace number params always in before step for now.
1104 // No support for combined raw and num params
1105 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1106 } elseif ( isset( $param['duration'] ) ) {
1107 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1108 } elseif ( isset( $param['expiry'] ) ) {
1109 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1110 } elseif ( isset( $param['period'] ) ) {
1111 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1112 } elseif ( isset( $param['size'] ) ) {
1113 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1114 } elseif ( isset( $param['bitrate'] ) ) {
1115 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1116 } elseif ( isset( $param['plaintext'] ) ) {
1117 return [ 'after', $this->formatPlaintext( $param['plaintext'] ) ];
1119 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
1120 htmlspecialchars( serialize( $param ) );
1121 trigger_error( $warning, E_USER_WARNING
);
1123 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1125 return [ 'before', '[INVALID]' ];
1127 } elseif ( $param instanceof Message
) {
1128 // Message objects should not be before parameters because
1129 // then they'll get double escaped. If the message needs to be
1130 // escaped, it'll happen right here when we call toString().
1131 return [ 'after', $param->toString() ];
1133 return [ 'before', $param ];
1138 * Wrapper for what ever method we use to parse wikitext.
1142 * @param string $string Wikitext message contents.
1144 * @return string Wikitext parsed into HTML.
1146 protected function parseText( $string ) {
1147 $out = MessageCache
::singleton()->parse(
1152 $this->getLanguage()
1155 return $out instanceof ParserOutput ?
$out->getText() : $out;
1159 * Wrapper for what ever method we use to {{-transform wikitext.
1163 * @param string $string Wikitext message contents.
1165 * @return string Wikitext with {{-constructs replaced with their values.
1167 protected function transformText( $string ) {
1168 return MessageCache
::singleton()->transform(
1171 $this->getLanguage(),
1177 * Wrapper for what ever method we use to get message contents.
1182 * @throws MWException If message key array is empty.
1184 protected function fetchMessage() {
1185 if ( $this->message
=== null ) {
1186 $cache = MessageCache
::singleton();
1188 foreach ( $this->keysToTry
as $key ) {
1189 $message = $cache->get( $key, $this->useDatabase
, $this->getLanguage() );
1190 if ( $message !== false && $message !== '' ) {
1195 // NOTE: The constructor makes sure keysToTry isn't empty,
1196 // so we know that $key and $message are initialized.
1198 $this->message
= $message;
1200 return $this->message
;
1204 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1205 * the entire string is displayed unchanged when displayed in the output
1210 * @param string $plaintext String to ensure plaintext output of
1212 * @return string Input plaintext encoded for output to $this->format
1214 protected function formatPlaintext( $plaintext ) {
1215 switch ( $this->format
) {
1224 return htmlspecialchars( $plaintext, ENT_QUOTES
);
1231 * Variant of the Message class.
1233 * Rather than treating the message key as a lookup
1234 * value (which is passed to the MessageCache and
1235 * translated as necessary), a RawMessage key is
1236 * treated as the actual message.
1238 * All other functionality (parsing, escaping, etc.)
1243 class RawMessage
extends Message
{
1246 * Call the parent constructor, then store the key as
1249 * @see Message::__construct
1251 * @param string $text Message to use.
1252 * @param array $params Parameters for the message.
1254 * @throws InvalidArgumentException
1256 public function __construct( $text, $params = [] ) {
1257 if ( !is_string( $text ) ) {
1258 throw new InvalidArgumentException( '$text must be a string' );
1261 parent
::__construct( $text, $params );
1263 // The key is the message.
1264 $this->message
= $text;
1268 * Fetch the message (in this case, the key).
1272 public function fetchMessage() {
1273 // Just in case the message is unset somewhere.
1274 if ( $this->message
=== null ) {
1275 $this->message
= $this->key
;
1278 return $this->message
;