Debian Codegraph @

includes/Message/Message.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Niklas Laxström
20 */
21
22 namespace MediaWiki\Message;
23
24 use InvalidArgumentException;
25 use MediaWiki\Content\Content;
26 use MediaWiki\Context\IContextSource;
27 use MediaWiki\Context\RequestContext;
28 use MediaWiki\Language\Language;
29 use MediaWiki\Language\RawMessage;
30 use MediaWiki\Logger\LoggerFactory;
31 use MediaWiki\MainConfigNames;
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Page\PageReference;
34 use MediaWiki\Page\PageReferenceValue;
35 use MediaWiki\Parser\Parser;
36 use MediaWiki\Parser\ParserOutput;
37 use MediaWiki\Parser\Sanitizer;
38 use MediaWiki\StubObject\StubUserLang;
39 use MediaWiki\Title\Title;
40 use RuntimeException;
41 use Serializable;
42 use Stringable;
43 use Wikimedia\Assert\Assert;
44 use Wikimedia\Bcp47Code\Bcp47Code;
45 use Wikimedia\Message\ListParam;
46 use Wikimedia\Message\ListType;
47 use Wikimedia\Message\MessageParam;
48 use Wikimedia\Message\MessageSpecifier;
49 use Wikimedia\Message\ParamType;
50 use Wikimedia\Message\ScalarParam;
51
52 /**
53 * The Message class deals with fetching and processing of interface message
54 * into a variety of formats.
55 *
56 * First implemented with MediaWiki 1.17, the Message class is intended to
57 * replace the old wfMsg* functions that over time grew unusable.
58 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
59 * between old and new functions.
60 *
61 * The preferred way to create Message objects is via the msg() method of
62 * of an available RequestContext and ResourceLoader Context object; this will
63 * ensure that the message uses the correct language. When that is not
64 * possible, the wfMessage() global function can be used, which will cause
65 * Message to get the language from the global RequestContext object. In
66 * rare circumstances when sessions are not available or not initialized,
67 * that can lead to errors.
68 *
69 * The most basic usage cases would be:
70 *
71 * @code
72 * // Initialize a Message object using the 'some_key' message key
73 * $message = $context->msg( 'some_key' );
74 *
75 * // Using two parameters those values are strings 'value1' and 'value2':
76 * $message = $context->msg( 'some_key',
77 * 'value1', 'value2'
78 * );
79 * @endcode
80 *
81 * @section message_global_fn Global function wrapper:
82 *
83 * Since msg() returns a Message instance, you can chain its call with a method.
84 * Some of them return a Message instance too so you can chain them.
85 * You will find below several examples of msg() usage.
86 *
87 * Fetching a message text for interface message:
88 *
89 * @code
90 * $button = Xml::button(
91 * $context->msg( 'submit' )->text()
92 * );
93 * @endcode
94 *
95 * A Message instance can be passed parameters after it has been constructed,
96 * use the params() method to do so:
97 *
98 * @code
99 * $context->msg( 'welcome-to' )
100 * ->params( $wgSitename )
101 * ->text();
102 * @endcode
103 *
104 * {{GRAMMAR}} and friends work correctly:
105 *
106 * @code
107 * $context->msg( 'are-friends',
108 * $user, $friend
109 * );
110 * $context->msg( 'bad-message' )
111 * ->rawParams( '<script>...</script>' )
112 * ->escaped();
113 * @endcode
114 *
115 * @section message_language Changing language:
116 *
117 * Messages can be requested in a different language or in whatever current
118 * content language is being used. The methods are:
119 * - Message->inContentLanguage()
120 * - Message->inLanguage()
121 *
122 * Sometimes the message text ends up in the database, so content language is
123 * needed:
124 *
125 * @code
126 * wfMessage( 'file-log',
127 * $user, $filename
128 * )->inContentLanguage()->text();
129 * @endcode
130 *
131 * Checking whether a message exists:
132 *
133 * @code
134 * $context->msg( 'mysterious-message' )->exists()
135 * // returns a boolean whether the 'mysterious-message' key exist.
136 * @endcode
137 *
138 * If you want to use a different language:
139 *
140 * @code
141 * $userLanguage = $user->getOption( 'language' );
142 * wfMessage( 'email-header' )
143 * ->inLanguage( $userLanguage )
144 * ->plain();
145 * @endcode
146 *
147 * @note You can parse the text only in the content or interface languages
148 *
149 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
150 * @see https://www.mediawiki.org/wiki/Localisation
151 *
152 * @since 1.17
153 * @newable
154 * @ingroup Language
155 */
156 class Message implements Stringable, MessageSpecifier, Serializable {
157 /** Use message text as-is */
158 public const FORMAT_PLAIN = 'plain';
159 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
160 public const FORMAT_BLOCK_PARSE = 'block-parse';
161 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
162 public const FORMAT_PARSE = 'parse';
163 /** Transform {{..}} constructs but don't transform to HTML */
164 public const FORMAT_TEXT = 'text';
165 /** Transform {{..}} constructs, HTML-escape the result */
166 public const FORMAT_ESCAPED = 'escaped';
167
168 /**
169 * Mapping from Message::listParam() types to Language methods.
170 * @var array
171 */
172 protected static $listTypeMap = [
173 ListType::COMMA => 'commaList',
174 ListType::SEMICOLON => 'semicolonList',
175 ListType::PIPE => 'pipeList',
176 ListType::AND => 'listToText',
177 ];
178
179 /**
180 * In which language to get this message. True, which is the default,
181 * means the current user language, false content language.
182 *
183 * @var bool
184 */
185 protected $isInterface = true;
186
187 /**
188 * In which language to get this message. Overrides the $interface setting.
189 *
190 * @var Language|null Explicit language object, or null for user language
191 */
192 protected ?Language $language = null;
193
194 /**
195 * @var callable|null A callable which returns the current user language,
196 * or null to get it from global state.
197 */
198 protected $userLangCallback;
199
200 /**
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.
203 */
204 protected $key;
205
206 /**
207 * @var string[] List of keys to try when fetching the message.
208 * @phan-var non-empty-list<string>
209 */
210 protected $keysToTry;
211
212 /**
213 * @var ?string The message key that the message was fetched from, if different from
214 * all of the requested $keysToTry (the requested key may be overridden by hooks).
215 */
216 protected $overriddenKey = null;
217
218 /**
219 * @var (MessageParam|Message|string|int|float)[] List of parameters which will be substituted
220 * into the message.
221 */
222 protected $parameters = [];
223
224 /**
225 * @var bool If messages in the local MediaWiki namespace should be loaded; false to use only
226 * the compiled LocalisationCache
227 */
228 protected $useDatabase = true;
229
230 /**
231 * @var ?PageReference page object to use as context.
232 */
233 protected $contextPage = null;
234
235 /**
236 * @var Content|null Content object representing the message.
237 */
238 protected $content = null;
239
240 /**
241 * @var string|null|false
242 */
243 protected $message;
244
245 /**
246 * @stable to call
247 * @since 1.17
248 * @param string|MessageSpecifier|string[] $key Message key, MessageSpecifier object to copy,
249 * or array of fallback message keys where we use the first message that exists and is non-empty.
250 * @param array $params Message parameters
251 * @param Language|null $language [optional] Language to use (defaults to current user language).
252 */
253 public function __construct( $key, $params = [], ?Language $language = null ) {
254 if ( $key instanceof MessageSpecifier ) {
255 if ( $params ) {
256 throw new InvalidArgumentException(
257 'Cannot set $params when $key is a MessageSpecifier'
258 );
259 }
260 $params = $key->getParams();
261 $key = $key->getKey();
262 }
263
264 if ( is_string( $key ) ) {
265 $this->keysToTry = [ $key ];
266 $this->key = $key;
267 } elseif ( is_array( $key ) && $key ) {
268 $this->keysToTry = $key;
269 foreach ( $this->keysToTry as $key ) {
270 if ( !is_string( $key ) ) {
271 throw new InvalidArgumentException( 'Message keys must be strings. ' .
272 'Did you accidentally pass message key and parameters in one array?' );
273 }
274 }
275 $this->key = reset( $this->keysToTry );
276 } else {
277 throw new InvalidArgumentException( '$key must be a string or non-empty array' );
278 }
279
280 $this->params( ...$params );
281 // User language is only resolved in getLanguage(). This helps preserve the
282 // semantic intent of "user language" across serialize() and unserialize().
283 $this->language = $language;
284 }
285
286 /**
287 * @see Serializable::serialize()
288 * @since 1.26
289 * @return string
290 */
291 public function serialize(): string {
292 return serialize( $this->__serialize() );
293 }
294
295 /**
296 * @see Serializable::serialize()
297 * @since 1.38
298 * @return array
299 */
300 public function __serialize() {
301 return [
302 'interface' => $this->isInterface,
303 'language' => $this->language ? $this->language->getCode() : null,
304 'key' => $this->key,
305 'keysToTry' => $this->keysToTry,
306 'parameters' => $this->parameters,
307 'useDatabase' => $this->useDatabase,
308 // Optimisation: Avoid cost of TitleFormatter on serialize,
309 // and especially cost of TitleParser (via Title::newFromText)
310 // on retrieval.
311 'titlevalue' => ( $this->contextPage
312 ? [ 0 => $this->contextPage->getNamespace(), 1 => $this->contextPage->getDBkey() ]
313 : null
314 ),
315 ];
316 }
317
318 /**
319 * @see Serializable::unserialize()
320 * @since 1.38
321 * @param string $serialized
322 */
323 public function unserialize( $serialized ): void {
324 $this->__unserialize( unserialize( $serialized ) );
325 }
326
327 /**
328 * @see Serializable::unserialize()
329 * @since 1.26
330 * @param array $data
331 */
332 public function __unserialize( $data ) {
333 if ( !is_array( $data ) ) {
334 throw new InvalidArgumentException( __METHOD__ . ': Invalid serialized data' );
335 }
336 $this->isInterface = $data['interface'];
337 $this->key = $data['key'];
338 $this->keysToTry = $data['keysToTry'];
339 // Accept old serialization format for compatibility with pre-MessageParam stored values
340 $this->parameters = array_map( static function ( $param ) {
341 if ( is_array( $param ) ) {
342 if ( isset( $param['type'] ) ) {
343 return ListParam::newFromJsonArray( $param );
344 } else {
345 return ScalarParam::newFromJsonArray( $param );
346 }
347 } else {
348 return $param;
349 }
350 }, $data['parameters'] );
351 $this->useDatabase = $data['useDatabase'];
352 $this->language = $data['language']
353 ? MediaWikiServices::getInstance()->getLanguageFactory()
354 ->getLanguage( $data['language'] )
355 : null;
356
357 // Since 1.35, the key 'titlevalue' is set, instead of 'titlestr'.
358 if ( isset( $data['titlevalue'] ) ) {
359 $this->contextPage = new PageReferenceValue(
360 $data['titlevalue'][0],
361 $data['titlevalue'][1],
362 PageReference::LOCAL
363 );
364 } elseif ( isset( $data['titlestr'] ) ) {
365 // TODO: figure out what's needed to remove this codepath
366 $this->contextPage = Title::newFromText( $data['titlestr'] );
367 } else {
368 $this->contextPage = null;
369 }
370 }
371
372 /**
373 * @since 1.24
374 *
375 * @return bool True if this is a multi-key message, that is, if the key provided to the
376 * constructor was a fallback list of keys to try.
377 */
378 public function isMultiKey() {
379 return count( $this->keysToTry ) > 1;
380 }
381
382 /**
383 * @since 1.24
384 *
385 * @return string[] The list of keys to try when fetching the message text,
386 * in order of preference.
387 */
388 public function getKeysToTry() {
389 return $this->keysToTry;
390 }
391
392 /**
393 * Returns the message key.
394 *
395 * If a list of multiple possible keys was supplied to the constructor, this method may
396 * return any of these keys. After the message has been fetched, this method will return
397 * the key that was actually used to fetch the message.
398 *
399 * @since 1.21
400 *
401 * @return string
402 */
403 public function getKey() {
404 return $this->key;
405 }
406
407 /**
408 * Returns the message parameters.
409 *
410 * @since 1.21
411 *
412 * @return (MessageParam|Message|string|int|float)[]
413 */
414 public function getParams() {
415 return $this->parameters;
416 }
417
418 /**
419 * Returns the Language of the Message.
420 *
421 * @since 1.23
422 *
423 * @return Language
424 */
425 public function getLanguage(): Language {
426 // Defaults to null which means current user language
427 if ( $this->language !== null ) {
428 return $this->language;
429 } elseif ( $this->userLangCallback ) {
430 return ( $this->userLangCallback )();
431 } else {
432 return RequestContext::getMain()->getLanguage();
433 }
434 }
435
436 /**
437 * Factory function that is just wrapper for the real constructor. It is
438 * intended to be used instead of the real constructor, because it allows
439 * chaining method calls, while new objects don't.
440 *
441 * @since 1.17
442 *
443 * @param string|string[]|MessageSpecifier $key
444 * @param mixed ...$params Parameters as strings.
445 *
446 * @return self
447 */
448 public static function newFromKey( $key, ...$params ) {
449 return new self( $key, $params );
450 }
451
452 /**
453 * Transform a MessageSpecifier or a primitive value used interchangeably with
454 * specifiers (a message key string, or a key + params array) into a proper Message.
455 *
456 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
457 * but is an easy error to make due to how StatusValue stores messages internally.
458 * Providing further array elements in that case causes an exception to be thrown.
459 *
460 * When the MessageSpecifier object is an instance of Message, a clone of the object is returned.
461 * This is unlike the `new Message( … )` constructor, which returns a new object constructed from
462 * scratch with the same key. This difference is mostly relevant when the passed object is an
463 * instance of a subclass like RawMessage or ApiMessage.
464 *
465 * @param string|array|MessageSpecifier $value
466 * @param-taint $value tainted
467 * @return self
468 * @since 1.27
469 */
470 public static function newFromSpecifier( $value ) {
471 $params = [];
472 if ( is_array( $value ) ) {
473 $params = $value;
474 $value = array_shift( $params );
475 }
476
477 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
478 if ( $params ) {
479 throw new InvalidArgumentException(
480 'Cannot have parameters when the key is already a Message instance'
481 );
482 }
483 $message = clone $value;
484 } elseif ( $value instanceof MessageSpecifier ) {
485 if ( $params ) {
486 throw new InvalidArgumentException(
487 'Cannot have parameters when the key is already a MessageSpecifier instance'
488 );
489 }
490 $message = new Message( $value );
491 } elseif ( is_string( $value ) ) {
492 $message = new Message( $value, $params );
493 } else {
494 throw new InvalidArgumentException( 'Invalid argument type ' . get_debug_type( $value ) );
495 }
496
497 return $message;
498 }
499
500 /**
501 * Factory function accepting multiple message keys and returning a message instance
502 * for the first message which is non-empty. If all messages are empty then an
503 * instance of the last message key is returned.
504 *
505 * @since 1.18
506 *
507 * @param string|string[] ...$keys Message keys, or first argument as an array of all the
508 * message keys.
509 * @param-taint ...$keys tainted
510 *
511 * @return self
512 */
513 public static function newFallbackSequence( ...$keys ) {
514 if ( func_num_args() == 1 ) {
515 if ( is_array( $keys[0] ) ) {
516 // Allow an array to be passed as the first argument instead
517 $keys = array_values( $keys[0] );
518 } else {
519 // Optimize a single string to not need special fallback handling
520 $keys = $keys[0];
521 }
522 }
523 return new self( $keys );
524 }
525
526 /**
527 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
528 * The title will be for the current language, if the message key is in
529 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
530 * language), because Message::inContentLanguage will also return in user language.
531 *
532 * @see $wgForceUIMsgAsContentMsg
533 * @return Title
534 * @since 1.26
535 */
536 public function getTitle() {
537 $forceUIMsgAsContentMsg = MediaWikiServices::getInstance()->getMainConfig()->get(
538 MainConfigNames::ForceUIMsgAsContentMsg );
539
540 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
541 $lang = $this->getLanguage();
542 $title = $this->key;
543 if (
544 !$lang->equals( $contLang )
545 && in_array( $this->key, (array)$forceUIMsgAsContentMsg )
546 ) {
547 $title .= '/' . $lang->getCode();
548 }
549
550 // Don't use $contLang->ucfirst() here. See T362654
551 return Title::makeTitle(
552 NS_MEDIAWIKI, ucfirst( strtr( $title, ' ', '_' ) ) );
553 }
554
555 /**
556 * Adds parameters to the parameter list of this message.
557 *
558 * @since 1.17
559 *
560 * @param MessageParam|MessageSpecifier|string|int|float|array ...$params Parameters as strings or
561 * MessageParam values (from Message::numParam() and the like), or a single array of parameters.
562 *
563 * @return self $this
564 */
565 public function params( ...$params ) {
566 if ( count( $params ) === 1 && isset( $params[0] ) && is_array( $params[0] ) ) {
567 $params = $params[0];
568 }
569 foreach ( $params as $param ) {
570 if ( $param instanceof ScalarParam && $param->getType() === ParamType::TEXT ) {
571 // Unwrap for compatibility with legacy code that inspects the parameters
572 $param = $param->getValue();
573 }
574 if ( $param instanceof MessageSpecifier ) {
575 $param = static::newFromSpecifier( $param );
576 }
577 $this->parameters[] = $param;
578 }
579 return $this;
580 }
581
582 /**
583 * Add parameters that are substituted after parsing or escaping.
584 * In other words the parsing process cannot access the contents
585 * of this type of parameter, and you need to make sure it is
586 * sanitized beforehand. The parser will see "$n", instead.
587 *
588 * @since 1.17
589 *
590 * @param mixed ...$params Raw parameters as strings, or a single argument that is
591 * an array of raw parameters.
592 * @param-taint ...$params html,exec_html
593 *
594 * @return self $this
595 */
596 public function rawParams( ...$params ) {
597 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
598 $params = $params[0];
599 }
600 foreach ( $params as $param ) {
601 $this->parameters[] = self::rawParam( $param );
602 }
603 return $this;
604 }
605
606 /**
607 * Add parameters that are numeric and will be passed through
608 * Language::formatNum before substitution
609 *
610 * @since 1.18
611 *
612 * @param mixed ...$params Numeric parameters, or a single argument that is
613 * an array of numeric parameters.
614 *
615 * @return self $this
616 */
617 public function numParams( ...$params ) {
618 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
619 $params = $params[0];
620 }
621 foreach ( $params as $param ) {
622 $this->parameters[] = self::numParam( $param );
623 }
624 return $this;
625 }
626
627 /**
628 * Add parameters that are durations of time and will be passed through
629 * Language::formatDuration before substitution
630 *
631 * @since 1.22
632 *
633 * @param int|int[] ...$params Duration parameters, or a single argument that is
634 * an array of duration parameters.
635 *
636 * @return self $this
637 */
638 public function durationParams( ...$params ) {
639 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
640 $params = $params[0];
641 }
642 foreach ( $params as $param ) {
643 $this->parameters[] = self::durationParam( $param );
644 }
645 return $this;
646 }
647
648 /**
649 * Add parameters that are expiration times and will be passed through
650 * Language::formatExpiry before substitution
651 *
652 * @since 1.22
653 *
654 * @param string|string[] ...$params Expiry parameters, or a single argument that is
655 * an array of expiry parameters.
656 *
657 * @return self $this
658 */
659 public function expiryParams( ...$params ) {
660 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
661 $params = $params[0];
662 }
663 foreach ( $params as $param ) {
664 $this->parameters[] = self::expiryParam( $param );
665 }
666 return $this;
667 }
668
669 /**
670 * Add parameters that are date-times and will be passed through
671 * Language::timeanddate before substitution
672 *
673 * @since 1.36
674 *
675 * @param string|string[] ...$params Date-time parameters, or a single argument that is
676 * an array of date-time parameters.
677 *
678 * @return self $this
679 */
680 public function dateTimeParams( ...$params ) {
681 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
682 $params = $params[0];
683 }
684 foreach ( $params as $param ) {
685 $this->parameters[] = self::dateTimeParam( $param );
686 }
687 return $this;
688 }
689
690 /**
691 * Add parameters that are dates and will be passed through
692 * Language::date before substitution
693 *
694 * @since 1.36
695 *
696 * @param string|string[] ...$params Date parameters, or a single argument that is
697 * an array of date parameters.
698 *
699 * @return self $this
700 */
701 public function dateParams( ...$params ) {
702 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
703 $params = $params[0];
704 }
705 foreach ( $params as $param ) {
706 $this->parameters[] = self::dateParam( $param );
707 }
708 return $this;
709 }
710
711 /**
712 * Add parameters that represent user groups
713 *
714 * @since 1.38
715 *
716 * @param string|string[] ...$params User Group parameters, or a single argument that is
717 * an array of user group parameters.
718 *
719 * @return self $this
720 */
721 public function userGroupParams( ...$params ) {
722 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
723 $params = $params[0];
724 }
725 foreach ( $params as $param ) {
726 $this->parameters[] = self::userGroupParam( $param );
727 }
728 return $this;
729 }
730
731 /**
732 * Add parameters that represent stringable objects
733 *
734 * @since 1.38
735 * @deprecated since 1.43
736 *
737 * @param Stringable|Stringable[] ...$params stringable parameters,
738 * or a single argument that is an array of stringable parameters.
739 *
740 * @return self $this
741 */
742 public function objectParams( ...$params ) {
743 wfDeprecated( __METHOD__, '1.43' );
744 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
745 $params = $params[0];
746 }
747 foreach ( $params as $param ) {
748 // Suppress redundant deprecation warning
749 // phpcs:ignore Generic.PHP.NoSilencedErrors
750 $this->parameters[] = @self::objectParam( $param );
751 }
752 return $this;
753 }
754
755 /**
756 * Add parameters that are times and will be passed through
757 * Language::time before substitution
758 *
759 * @since 1.36
760 *
761 * @param string|string[] ...$params Time parameters, or a single argument that is
762 * an array of time parameters.
763 *
764 * @return self $this
765 */
766 public function timeParams( ...$params ) {
767 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
768 $params = $params[0];
769 }
770 foreach ( $params as $param ) {
771 $this->parameters[] = self::timeParam( $param );
772 }
773 return $this;
774 }
775
776 /**
777 * Add parameters that are time periods and will be passed through
778 * Language::formatTimePeriod before substitution
779 *
780 * @since 1.22
781 *
782 * @param int|float|(int|float)[] ...$params Time period parameters, or a single argument that is
783 * an array of time period parameters.
784 *
785 * @return self $this
786 */
787 public function timeperiodParams( ...$params ) {
788 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
789 $params = $params[0];
790 }
791 foreach ( $params as $param ) {
792 $this->parameters[] = self::timeperiodParam( $param );
793 }
794 return $this;
795 }
796
797 /**
798 * Add parameters that are file sizes and will be passed through
799 * Language::formatSize before substitution
800 *
801 * @since 1.22
802 *
803 * @param int|int[] ...$params Size parameters, or a single argument that is
804 * an array of size parameters.
805 *
806 * @return self $this
807 */
808 public function sizeParams( ...$params ) {
809 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
810 $params = $params[0];
811 }
812 foreach ( $params as $param ) {
813 $this->parameters[] = self::sizeParam( $param );
814 }
815 return $this;
816 }
817
818 /**
819 * Add parameters that are bitrates and will be passed through
820 * Language::formatBitrate before substitution
821 *
822 * @since 1.22
823 *
824 * @param int|int[] ...$params Bit rate parameters, or a single argument that is
825 * an array of bit rate parameters.
826 *
827 * @return self $this
828 */
829 public function bitrateParams( ...$params ) {
830 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
831 $params = $params[0];
832 }
833 foreach ( $params as $param ) {
834 $this->parameters[] = self::bitrateParam( $param );
835 }
836 return $this;
837 }
838
839 /**
840 * Add parameters that are plaintext and will be passed through without
841 * the content being evaluated. Plaintext parameters are not valid as
842 * arguments to parser functions. This differs from self::rawParams in
843 * that the Message class handles escaping to match the output format.
844 *
845 * @since 1.25
846 *
847 * @param string|string[] ...$params plaintext parameters, or a single argument that is
848 * an array of plaintext parameters.
849 *
850 * @return self $this
851 */
852 public function plaintextParams( ...$params ) {
853 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
854 $params = $params[0];
855 }
856 foreach ( $params as $param ) {
857 $this->parameters[] = self::plaintextParam( $param );
858 }
859 return $this;
860 }
861
862 /**
863 * Set the language and the title from a context object
864 *
865 * @since 1.19
866 *
867 * @param IContextSource $context
868 *
869 * @return self $this
870 */
871 public function setContext( IContextSource $context ) {
872 $this->userLangCallback = static function () use ( $context ) {
873 return $context->getLanguage();
874 };
875 $this->inUserLanguage();
876 $this->page( $context->getTitle() );
877
878 return $this;
879 }
880
881 /**
882 * Request the message in any language that is supported.
883 *
884 * As a side effect interface message status is unconditionally
885 * turned off.
886 *
887 * @since 1.17
888 * @param Bcp47Code|StubUserLang|string $lang Language code or language object.
889 * @return self $this
890 */
891 public function inLanguage( $lang ) {
892 $previousLanguage = $this->language;
893
894 if ( $lang instanceof Language ) {
895 $this->language = $lang;
896 } elseif ( $lang instanceof StubUserLang ) {
897 $this->language = null;
898 } elseif ( $lang instanceof Bcp47Code ) {
899 if ( $this->language === null || !$this->language->isSameCodeAs( $lang ) ) {
900 $this->language = MediaWikiServices::getInstance()->getLanguageFactory()
901 ->getLanguage( $lang );
902 }
903 } elseif ( is_string( $lang ) ) {
904 if ( $this->language === null || $this->language->getCode() != $lang ) {
905 $this->language = MediaWikiServices::getInstance()->getLanguageFactory()
906 ->getLanguage( $lang );
907 }
908 } else {
909 // Always throws. Moved here as an optimization.
910 Assert::parameterType( [ Bcp47Code::class, StubUserLang::class, 'string' ], $lang, '$lang' );
911 }
912
913 if ( $this->language !== $previousLanguage ) {
914 // The language has changed. Clear the message cache.
915 $this->message = null;
916 }
917 $this->isInterface = false;
918 return $this;
919 }
920
921 /**
922 * Request the message in the user's current language, overriding any
923 * explicit language that was previously set. Set the interface flag to
924 * true.
925 *
926 * @since 1.42
927 * @return $this
928 */
929 public function inUserLanguage(): self {
930 if ( $this->language ) {
931 // The language has changed. Clear the message cache.
932 $this->message = null;
933 }
934 $this->language = null;
935 $this->isInterface = true;
936 return $this;
937 }
938
939 /**
940 * Request the message in the wiki's content language,
941 * unless it is disabled for this message.
942 *
943 * @since 1.17
944 * @see $wgForceUIMsgAsContentMsg
945 *
946 * @return self $this
947 */
948 public function inContentLanguage(): self {
949 $forceUIMsgAsContentMsg = MediaWikiServices::getInstance()->getMainConfig()->get(
950 MainConfigNames::ForceUIMsgAsContentMsg );
951 if ( in_array( $this->key, (array)$forceUIMsgAsContentMsg ) ) {
952 return $this;
953 }
954
955 $this->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() );
956 return $this;
957 }
958
959 /**
960 * Allows manipulating the interface message flag directly.
961 * Can be used to restore the flag after setting a language.
962 *
963 * @since 1.20
964 *
965 * @param bool $interface
966 *
967 * @return self $this
968 */
969 public function setInterfaceMessageFlag( $interface ) {
970 $this->isInterface = (bool)$interface;
971 return $this;
972 }
973
974 /**
975 * @since 1.17
976 *
977 * @param bool $useDatabase If messages in the local MediaWiki namespace should be loaded; false
978 * to use only the compiled LocalisationCache
979 *
980 * @return self $this
981 */
982 public function useDatabase( $useDatabase ) {
983 $this->useDatabase = (bool)$useDatabase;
984 $this->message = null;
985 return $this;
986 }
987
988 /**
989 * Set the Title object to use as context when transforming the message
990 *
991 * @since 1.18
992 * @deprecated since 1.37. Use ::page instead
993 *
994 * @param Title $title
995 *
996 * @return self $this
997 */
998 public function title( $title ) {
999 return $this->page( $title );
1000 }
1001
1002 /**
1003 * Set the page object to use as context when transforming the message
1004 *
1005 * @since 1.37
1006 *
1007 * @param ?PageReference $page
1008 *
1009 * @return self $this
1010 */
1011 public function page( ?PageReference $page ) {
1012 $this->contextPage = $page;
1013 return $this;
1014 }
1015
1016 /**
1017 * Returns the message formatted a certain way.
1018 *
1019 * @since 1.17
1020 * @param string $format One of the FORMAT_* constants.
1021 * @return string Text or HTML
1022 */
1023 public function toString( string $format ): string {
1024 return $this->format( $format );
1025 }
1026
1027 /**
1028 * Returns the message formatted a certain way.
1029 *
1030 * @param string $format One of the FORMAT_* constants.
1031 * @return string Text or HTML
1032 * @suppress SecurityCheck-DoubleEscaped phan false positive
1033 */
1034 private function format( string $format ): string {
1035 $string = $this->fetchMessage();
1036
1037 if ( $string === false ) {
1038 // Err on the side of safety, ensure that the output
1039 // is always html safe in the event the message key is
1040 // missing, since in that case its highly likely the
1041 // message key is user-controlled.
1042 // 'â§¼' is used instead of '<' to side-step any
1043 // double-escaping issues.
1044 // (Keep synchronised with mw.Message#toString in JS.)
1045 return 'â§¼' . Sanitizer::escapeCombiningChar( htmlspecialchars( $this->key ) ) . 'â§½';
1046 }
1047
1048 if ( in_array( $this->getLanguage()->getCode(), [ 'qqx', 'x-xss' ] ) ) {
1049 # Insert a list of alternative message keys for &uselang=qqx.
1050 if ( $string === '($*)' ) {
1051 $keylist = implode( ' / ', $this->keysToTry );
1052 if ( $this->overriddenKey !== null ) {
1053 $keylist .= ' = ' . $this->overriddenKey;
1054 }
1055 $string = "($keylist$*)";
1056 }
1057 # Replace $* with a list of parameters for &uselang=qqx.
1058 if ( strpos( $string, '$*' ) !== false ) {
1059 $paramlist = '';
1060 if ( $this->parameters !== [] ) {
1061 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
1062 }
1063 $string = str_replace( '$*', $paramlist, $string );
1064 }
1065 }
1066
1067 # Replace parameters before text parsing
1068 $string = $this->replaceParameters( $string, 'before', $format );
1069
1070 # Maybe transform using the full parser
1071 if ( $format === self::FORMAT_PARSE ) {
1072 $string = $this->parseText( $string );
1073 $string = Parser::stripOuterParagraph( $string );
1074 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
1075 $string = $this->parseText( $string );
1076 } elseif ( $format === self::FORMAT_TEXT ) {
1077 $string = $this->transformText( $string );
1078 } elseif ( $format === self::FORMAT_ESCAPED ) {
1079 $string = $this->transformText( $string );
1080 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
1081 $string = Sanitizer::escapeCombiningChar( $string );
1082 }
1083
1084 # Raw parameter replacement
1085 $string = $this->replaceParameters( $string, 'after', $format );
1086
1087 return $string;
1088 }
1089
1090 /**
1091 * Magic method implementation of the above, so we can do, eg:
1092 * $foo = new Message( $key );
1093 * $string = "<abbr>$foo</abbr>";
1094 *
1095 * @since 1.18
1096 *
1097 * @return string
1098 * @return-taint escaped
1099 */
1100 public function __toString() {
1101 return $this->format( self::FORMAT_PARSE );
1102 }
1103
1104 /**
1105 * Fully parse the text from wikitext to HTML.
1106 *
1107 * @since 1.17
1108 *
1109 * @return string Parsed HTML.
1110 * @return-taint escaped
1111 */
1112 public function parse() {
1113 return $this->format( self::FORMAT_PARSE );
1114 }
1115
1116 /**
1117 * Returns the message text. {{-transformation occurs (substituting the template
1118 * with its parsed result).
1119 *
1120 * @since 1.17
1121 *
1122 * @return string Unescaped message text.
1123 * @return-taint tainted
1124 */
1125 public function text() {
1126 return $this->format( self::FORMAT_TEXT );
1127 }
1128
1129 /**
1130 * Returns the message text as-is, only parameters are substituted.
1131 *
1132 * @since 1.17
1133 *
1134 * @return string Unescaped untransformed message text.
1135 * @return-taint tainted
1136 */
1137 public function plain() {
1138 return $this->format( self::FORMAT_PLAIN );
1139 }
1140
1141 /**
1142 * Returns the parsed message text which is always surrounded by a block element.
1143 *
1144 * @since 1.17
1145 *
1146 * @return string HTML
1147 * @return-taint escaped
1148 */
1149 public function parseAsBlock() {
1150 return $this->format( self::FORMAT_BLOCK_PARSE );
1151 }
1152
1153 /**
1154 * Returns the message text. {{-transformation (substituting the template with its
1155 * parsed result) is done and the result is HTML escaped excluding any raw parameters.
1156 *
1157 * @since 1.17
1158 *
1159 * @return string HTML escaped message text.
1160 * @return-taint escaped
1161 */
1162 public function escaped() {
1163 return $this->format( self::FORMAT_ESCAPED );
1164 }
1165
1166 /**
1167 * Check whether a message key has been defined currently.
1168 *
1169 * @since 1.17
1170 *
1171 * @return bool
1172 */
1173 public function exists() {
1174 return $this->fetchMessage() !== false;
1175 }
1176
1177 /**
1178 * Check whether a message does not exist, or is an empty string
1179 *
1180 * @since 1.18
1181 * @todo FIXME: Merge with isDisabled()?
1182 *
1183 * @return bool
1184 */
1185 public function isBlank() {
1186 $message = $this->fetchMessage();
1187 return $message === false || $message === '';
1188 }
1189
1190 /**
1191 * Check whether a message does not exist, is an empty string, or is "-".
1192 *
1193 * @since 1.18
1194 *
1195 * @return bool
1196 */
1197 public function isDisabled() {
1198 $message = $this->fetchMessage();
1199 return $message === false || $message === '' || $message === '-';
1200 }
1201
1202 /**
1203 * @since 1.17
1204 *
1205 * @param mixed $raw
1206 * @param-taint $raw html,exec_html
1207 *
1208 * @return ScalarParam
1209 */
1210 public static function rawParam( $raw ): ScalarParam {
1211 return new ScalarParam( ParamType::RAW, $raw );
1212 }
1213
1214 /**
1215 * @since 1.18
1216 *
1217 * @param mixed $num
1218 *
1219 * @return ScalarParam
1220 */
1221 public static function numParam( $num ): ScalarParam {
1222 return new ScalarParam( ParamType::NUM, $num );
1223 }
1224
1225 /**
1226 * @since 1.22
1227 *
1228 * @param int $duration
1229 *
1230 * @return ScalarParam
1231 */
1232 public static function durationParam( $duration ): ScalarParam {
1233 return new ScalarParam( ParamType::DURATION_LONG, $duration );
1234 }
1235
1236 /**
1237 * @since 1.22
1238 *
1239 * @param string $expiry
1240 *
1241 * @return ScalarParam
1242 */
1243 public static function expiryParam( $expiry ): ScalarParam {
1244 return new ScalarParam( ParamType::EXPIRY, $expiry );
1245 }
1246
1247 /**
1248 * @since 1.36
1249 *
1250 * @param string $dateTime
1251 *
1252 * @return ScalarParam
1253 */
1254 public static function dateTimeParam( string $dateTime ): ScalarParam {
1255 return new ScalarParam( ParamType::DATETIME, $dateTime );
1256 }
1257
1258 /**
1259 * @since 1.36
1260 *
1261 * @param string $date
1262 *
1263 * @return ScalarParam
1264 */
1265 public static function dateParam( string $date ): ScalarParam {
1266 return new ScalarParam( ParamType::DATE, $date );
1267 }
1268
1269 /**
1270 * @since 1.36
1271 *
1272 * @param string $time
1273 *
1274 * @return ScalarParam
1275 */
1276 public static function timeParam( string $time ): ScalarParam {
1277 return new ScalarParam( ParamType::TIME, $time );
1278 }
1279
1280 /**
1281 * @since 1.38
1282 *
1283 * @param string $userGroup
1284 *
1285 * @return ScalarParam
1286 */
1287 public static function userGroupParam( string $userGroup ): ScalarParam {
1288 return new ScalarParam( ParamType::GROUP, $userGroup );
1289 }
1290
1291 /**
1292 * @since 1.38
1293 * @deprecated since 1.43
1294 *
1295 * @param Stringable $object
1296 *
1297 * @return ScalarParam
1298 */
1299 public static function objectParam( Stringable $object ): ScalarParam {
1300 wfDeprecated( __METHOD__, '1.43' );
1301 return new ScalarParam( ParamType::OBJECT, $object );
1302 }
1303
1304 /**
1305 * @since 1.22
1306 *
1307 * @param int|float $period
1308 *
1309 * @return ScalarParam
1310 */
1311 public static function timeperiodParam( $period ): ScalarParam {
1312 return new ScalarParam( ParamType::DURATION_SHORT, $period );
1313 }
1314
1315 /**
1316 * @since 1.22
1317 *
1318 * @param int $size
1319 *
1320 * @return ScalarParam
1321 */
1322 public static function sizeParam( $size ): ScalarParam {
1323 return new ScalarParam( ParamType::SIZE, $size );
1324 }
1325
1326 /**
1327 * @since 1.22
1328 *
1329 * @param int $bitrate
1330 *
1331 * @return ScalarParam
1332 */
1333 public static function bitrateParam( $bitrate ): ScalarParam {
1334 return new ScalarParam( ParamType::BITRATE, $bitrate );
1335 }
1336
1337 /**
1338 * @since 1.25
1339 *
1340 * @param string $plaintext
1341 *
1342 * @return ScalarParam
1343 */
1344 public static function plaintextParam( $plaintext ): ScalarParam {
1345 return new ScalarParam( ParamType::PLAINTEXT, $plaintext );
1346 }
1347
1348 /**
1349 * @since 1.29
1350 *
1351 * @param array $list
1352 * @param string $type One of the ListType constants
1353 * @return ListParam
1354 */
1355 public static function listParam( array $list, $type = ListType::AND ): ListParam {
1356 return new ListParam( $type, $list );
1357 }
1358
1359 /**
1360 * Substitutes any parameters into the message text.
1361 *
1362 * @since 1.17
1363 *
1364 * @param string $message The message text.
1365 * @param string $type Either "before" or "after".
1366 * @param string $format One of the FORMAT_* constants.
1367 *
1368 * @return string
1369 */
1370 protected function replaceParameters( $message, $type, $format ) {
1371 // A temporary marker for $1 parameters that is only valid
1372 // in non-attribute contexts. However if the entire message is escaped
1373 // then we don't want to use it because it will be mangled in all contexts
1374 // and its unnecessary as ->escaped() messages aren't html.
1375 $marker = $format === self::FORMAT_ESCAPED ? '$' : '$\'"';
1376 $replacementKeys = [];
1377 foreach ( $this->parameters as $n => $param ) {
1378 [ $paramType, $value ] = $this->extractParam( $param, $format );
1379 if ( $type === 'before' ) {
1380 if ( $paramType === 'before' ) {
1381 $replacementKeys['$' . ( $n + 1 )] = $value;
1382 } else /* $paramType === 'after' */ {
1383 // To protect against XSS from replacing parameters
1384 // inside html attributes, we convert $1 to $'"1.
1385 // In the event that one of the parameters ends up
1386 // in an attribute, either the ' or the " will be
1387 // escaped, breaking the replacement and avoiding XSS.
1388 $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 );
1389 }
1390 } elseif ( $paramType === 'after' ) {
1391 $replacementKeys[$marker . ( $n + 1 )] = $value;
1392 }
1393 }
1394 return strtr( $message, $replacementKeys );
1395 }
1396
1397 /**
1398 * Extracts the parameter type and preprocessed the value if needed.
1399 *
1400 * @since 1.18
1401 *
1402 * @param ScalarParam|ListParam|MessageSpecifier|string $param Parameter as defined in this class.
1403 * @param string $format One of the FORMAT_* constants.
1404 *
1405 * @return array Array with the parameter type (either "before" or "after") and the value.
1406 */
1407 protected function extractParam( $param, $format ) {
1408 if ( $param instanceof ScalarParam ) {
1409 switch ( $param->getType() ) {
1410 case ParamType::RAW:
1411 return [ 'after', $this->extractParam( $param->getValue(), self::FORMAT_PARSE )[1] ];
1412 case ParamType::NUM:
1413 // Replace number params always in before step for now.
1414 // No support for combined raw and num params
1415 return [ 'before', $this->getLanguage()->formatNum( $param->getValue() ) ];
1416 case ParamType::DURATION_LONG:
1417 return [ 'before', $this->getLanguage()->formatDuration( $param->getValue() ) ];
1418 case ParamType::EXPIRY:
1419 return [ 'before', $this->getLanguage()->formatExpiry( $param->getValue() ) ];
1420 case ParamType::DATETIME:
1421 return [ 'before', $this->getLanguage()->timeanddate( $param->getValue() ) ];
1422 case ParamType::DATE:
1423 return [ 'before', $this->getLanguage()->date( $param->getValue() ) ];
1424 case ParamType::TIME:
1425 return [ 'before', $this->getLanguage()->time( $param->getValue() ) ];
1426 case ParamType::GROUP:
1427 return [ 'before', $this->getLanguage()->getGroupName( $param->getValue() ) ];
1428 case ParamType::DURATION_SHORT:
1429 return [ 'before', $this->getLanguage()->formatTimePeriod( $param->getValue() ) ];
1430 case ParamType::SIZE:
1431 return [ 'before', $this->getLanguage()->formatSize( $param->getValue() ) ];
1432 case ParamType::BITRATE:
1433 return [ 'before', $this->getLanguage()->formatBitrate( $param->getValue() ) ];
1434 case ParamType::PLAINTEXT:
1435 return [ 'after', $this->formatPlaintext( $param->getValue(), $format ) ];
1436 case ParamType::OBJECT:
1437 $obj = $param->getValue();
1438 if ( $obj instanceof UserGroupMembershipParam ) {
1439 return [
1440 'before',
1441 $this->getLanguage()->getGroupMemberName( $obj->getGroup(), $obj->getMember() )
1442 ];
1443 } else {
1444 return [ 'before', $obj->__toString() ];
1445 }
1446 case ParamType::TEXT: // impossible because we unwrapped it in params()
1447 default:
1448 throw new \LogicException( "Invalid ScalarParam type: {$param->getType()}" );
1449 }
1450 } elseif ( $param instanceof ListParam ) {
1451 return $this->formatListParam( $param->getValue(), $param->getListType(), $format );
1452 } elseif ( is_array( $param ) ) {
1453 LoggerFactory::getInstance( 'Bug58676' )->warning(
1454 'Invalid parameter for message "{msgkey}": {param}',
1455 [
1456 'exception' => new RuntimeException,
1457 'msgkey' => $this->key,
1458 'param' => htmlspecialchars( serialize( $param ) ),
1459 ]
1460 );
1461 return [ 'before', '[INVALID]' ];
1462 } elseif ( $param instanceof MessageSpecifier ) {
1463 // Match language, flags, etc. to the current message.
1464 $msg = static::newFromSpecifier( $param );
1465 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1466 // Cache depends on these parameters
1467 $msg->message = null;
1468 }
1469 $msg->isInterface = $this->isInterface;
1470 $msg->language = $this->language;
1471 $msg->userLangCallback = $this->userLangCallback;
1472 $msg->useDatabase = $this->useDatabase;
1473 $msg->contextPage = $this->contextPage;
1474
1475 // DWIM
1476 if ( $format === 'block-parse' ) {
1477 $format = 'parse';
1478 }
1479
1480 // Message objects should not be before parameters because
1481 // then they'll get double escaped. If the message needs to be
1482 // escaped, it'll happen right here when we call toString().
1483 // (Using the public toString() to allow mocking / subclassing.)
1484 return [ 'after', $msg->toString( $format ) ];
1485 } else {
1486 return [ 'before', $param ];
1487 }
1488 }
1489
1490 /**
1491 * Wrapper for what ever method we use to parse wikitext.
1492 *
1493 * @since 1.17
1494 *
1495 * @param string $string Wikitext message contents.
1496 *
1497 * @return string Wikitext parsed into HTML.
1498 */
1499 protected function parseText( $string ) {
1500 $out = MediaWikiServices::getInstance()->getMessageCache()->parse(
1501 $string,
1502 $this->contextPage,
1503 /*linestart*/true,
1504 $this->isInterface,
1505 $this->getLanguage()
1506 );
1507
1508 return $out instanceof ParserOutput
1509 ? $out->getText( [
1510 'allowTOC' => false,
1511 'enableSectionEditLinks' => false,
1512 // Wrapping messages in an extra <div> is probably not expected. If
1513 // they're outside the content area they probably shouldn't be
1514 // targeted by CSS that's targeting the parser output, and if
1515 // they're inside they already are from the outer div.
1516 'unwrap' => true,
1517 'userLang' => $this->getLanguage(),
1518 ] )
1519 : $out;
1520 }
1521
1522 /**
1523 * Wrapper for what ever method we use to {{-transform wikitext (substituting the
1524 * template with its parsed result).
1525 *
1526 * @since 1.17
1527 *
1528 * @param string $string Wikitext message contents.
1529 *
1530 * @return string Wikitext with {{-constructs substituted with its parsed result.
1531 */
1532 protected function transformText( $string ) {
1533 return MediaWikiServices::getInstance()->getMessageCache()->transform(
1534 $string,
1535 $this->isInterface,
1536 $this->getLanguage(),
1537 $this->contextPage
1538 );
1539 }
1540
1541 /**
1542 * Wrapper for whatever method we use to get message contents.
1543 *
1544 * @since 1.17
1545 *
1546 * @return string|false
1547 */
1548 protected function fetchMessage() {
1549 if ( $this->message === null ) {
1550 $cache = MediaWikiServices::getInstance()->getMessageCache();
1551
1552 $usedKey = null;
1553 foreach ( $this->keysToTry as $key ) {
1554 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage(), $usedKey );
1555 if ( $message !== false && $message !== '' ) {
1556 if ( $usedKey !== $key ) {
1557 $this->overriddenKey = $usedKey;
1558 }
1559 break;
1560 }
1561 }
1562
1563 // NOTE: The constructor makes sure keysToTry isn't empty,
1564 // so we know that $key and $message are initialized.
1565 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable False positive
1566 // @phan-suppress-next-line PhanPossiblyNullTypeMismatchProperty False positive
1567 $this->key = $key;
1568 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable False positive
1569 $this->message = $message;
1570 }
1571 return $this->message;
1572 }
1573
1574 /**
1575 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1576 * the entire string is displayed unchanged when displayed in the output
1577 * format.
1578 *
1579 * @since 1.25
1580 *
1581 * @param string $plaintext String to ensure plaintext output of
1582 * @param string $format One of the FORMAT_* constants.
1583 *
1584 * @return string Input plaintext encoded for output to $format
1585 */
1586 protected function formatPlaintext( $plaintext, $format ) {
1587 switch ( $format ) {
1588 case self::FORMAT_TEXT:
1589 case self::FORMAT_PLAIN:
1590 return $plaintext;
1591
1592 case self::FORMAT_PARSE:
1593 case self::FORMAT_BLOCK_PARSE:
1594 case self::FORMAT_ESCAPED:
1595 default:
1596 return Sanitizer::escapeCombiningChar( htmlspecialchars( $plaintext, ENT_QUOTES ) );
1597 }
1598 }
1599
1600 /**
1601 * Formats a list of parameters as a concatenated string.
1602 * @since 1.29
1603 * @param array $params
1604 * @param string $listType
1605 * @param string $format One of the FORMAT_* constants.
1606 * @return array Array with the parameter type (either "before" or "after") and the value.
1607 */
1608 protected function formatListParam( array $params, $listType, $format ) {
1609 if ( !isset( self::$listTypeMap[$listType] ) ) {
1610 $warning = 'Invalid list type for message "' . $this->key . '": '
1611 . htmlspecialchars( $listType )
1612 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1613 trigger_error( $warning, E_USER_WARNING );
1614 $e = new InvalidArgumentException;
1615 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1616 return [ 'before', '[INVALID]' ];
1617 }
1618 $func = self::$listTypeMap[$listType];
1619
1620 // Handle an empty list sensibly
1621 if ( !$params ) {
1622 return [ 'before', $this->getLanguage()->$func( [] ) ];
1623 }
1624
1625 // First, determine what kinds of list items we have
1626 $types = [];
1627 $vars = [];
1628 $list = [];
1629 foreach ( $params as $n => $p ) {
1630 if ( $p instanceof ScalarParam && $p->getType() === ParamType::TEXT ) {
1631 // Unwrap like in params()
1632 $p = $p->getValue();
1633 }
1634 [ $type, $value ] = $this->extractParam( $p, $format );
1635 $types[$type] = true;
1636 $list[] = $value;
1637 $vars[] = '$' . ( $n + 1 );
1638 }
1639
1640 // Easy case: all are 'before' or 'after', so just join the
1641 // values and use the same type.
1642 if ( count( $types ) === 1 ) {
1643 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1644 }
1645
1646 // Hard case: We need to process each value per its type, then
1647 // return the concatenated values as 'after'. We handle this by turning
1648 // the list into a RawMessage and processing that as a parameter.
1649 $vars = $this->getLanguage()->$func( $vars );
1650 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1651 }
1652 }
1653
1654 /** @deprecated class alias since 1.42 */
1655 class_alias( Message::class, 'Message' );