Use real variargs for variadic methods
[lhc/web/wiklou.git] / includes / language / Message.php
1 <?php
2 /**
3 * Fetching and processing of interface messages.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Niklas Laxström
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * The Message class provides methods which fulfil two basic services:
29 * - fetching interface messages
30 * - processing messages into a variety of formats
31 *
32 * First implemented with MediaWiki 1.17, the Message class is intended to
33 * replace the old wfMsg* functions that over time grew unusable.
34 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
35 * between old and new functions.
36 *
37 * You should use the wfMessage() global function which acts as a wrapper for
38 * the Message class. The wrapper let you pass parameters as arguments.
39 *
40 * The most basic usage cases would be:
41 *
42 * @code
43 * // Initialize a Message object using the 'some_key' message key
44 * $message = wfMessage( 'some_key' );
45 *
46 * // Using two parameters those values are strings 'value1' and 'value2':
47 * $message = wfMessage( 'some_key',
48 * 'value1', 'value2'
49 * );
50 * @endcode
51 *
52 * @section message_global_fn Global function wrapper:
53 *
54 * Since wfMessage() returns a Message instance, you can chain its call with
55 * a method. Some of them return a Message instance too so you can chain them.
56 * You will find below several examples of wfMessage() usage.
57 *
58 * Fetching a message text for interface message:
59 *
60 * @code
61 * $button = Xml::button(
62 * wfMessage( 'submit' )->text()
63 * );
64 * @endcode
65 *
66 * A Message instance can be passed parameters after it has been constructed,
67 * use the params() method to do so:
68 *
69 * @code
70 * wfMessage( 'welcome-to' )
71 * ->params( $wgSitename )
72 * ->text();
73 * @endcode
74 *
75 * {{GRAMMAR}} and friends work correctly:
76 *
77 * @code
78 * wfMessage( 'are-friends',
79 * $user, $friend
80 * );
81 * wfMessage( 'bad-message' )
82 * ->rawParams( '<script>...</script>' )
83 * ->escaped();
84 * @endcode
85 *
86 * @section message_language Changing language:
87 *
88 * Messages can be requested in a different language or in whatever current
89 * content language is being used. The methods are:
90 * - Message->inContentLanguage()
91 * - Message->inLanguage()
92 *
93 * Sometimes the message text ends up in the database, so content language is
94 * needed:
95 *
96 * @code
97 * wfMessage( 'file-log',
98 * $user, $filename
99 * )->inContentLanguage()->text();
100 * @endcode
101 *
102 * Checking whether a message exists:
103 *
104 * @code
105 * wfMessage( 'mysterious-message' )->exists()
106 * // returns a boolean whether the 'mysterious-message' key exist.
107 * @endcode
108 *
109 * If you want to use a different language:
110 *
111 * @code
112 * $userLanguage = $user->getOption( 'language' );
113 * wfMessage( 'email-header' )
114 * ->inLanguage( $userLanguage )
115 * ->plain();
116 * @endcode
117 *
118 * @note You can parse the text only in the content or interface languages
119 *
120 * @section message_compare_old Comparison with old wfMsg* functions:
121 *
122 * Use full parsing:
123 *
124 * @code
125 * // old style:
126 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
127 * // new style:
128 * wfMessage( 'key', 'apple' )->parse();
129 * @endcode
130 *
131 * Parseinline is used because it is more useful when pre-building HTML.
132 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
133 *
134 * Places where HTML cannot be used. {{-transformation is done.
135 * @code
136 * // old style:
137 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
138 * // new style:
139 * wfMessage( 'key', 'apple', 'pear' )->text();
140 * @endcode
141 *
142 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
143 * parameters are not replaced after escaping by default.
144 * @code
145 * $escaped = wfMessage( 'key' )
146 * ->rawParams( 'apple' )
147 * ->escaped();
148 * @endcode
149 *
150 * @section message_appendix Appendix:
151 *
152 * @todo
153 * - test, can we have tests?
154 * - this documentation needs to be extended
155 *
156 * @see https://www.mediawiki.org/wiki/WfMessage()
157 * @see https://www.mediawiki.org/wiki/New_messages_API
158 * @see https://www.mediawiki.org/wiki/Localisation
159 *
160 * @since 1.17
161 */
162 class Message implements MessageSpecifier, Serializable {
163 /** Use message text as-is */
164 const FORMAT_PLAIN = 'plain';
165 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
166 const FORMAT_BLOCK_PARSE = 'block-parse';
167 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
168 const FORMAT_PARSE = 'parse';
169 /** Transform {{..}} constructs but don't transform to HTML */
170 const FORMAT_TEXT = 'text';
171 /** Transform {{..}} constructs, HTML-escape the result */
172 const FORMAT_ESCAPED = 'escaped';
173
174 /**
175 * Mapping from Message::listParam() types to Language methods.
176 * @var array
177 */
178 protected static $listTypeMap = [
179 'comma' => 'commaList',
180 'semicolon' => 'semicolonList',
181 'pipe' => 'pipeList',
182 'text' => 'listToText',
183 ];
184
185 /**
186 * In which language to get this message. True, which is the default,
187 * means the current user language, false content language.
188 *
189 * @var bool
190 */
191 protected $interface = true;
192
193 /**
194 * In which language to get this message. Overrides the $interface setting.
195 *
196 * @var Language|bool Explicit language object, or false for user language
197 */
198 protected $language = false;
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 */
209 protected $keysToTry;
210
211 /**
212 * @var array List of parameters which will be substituted into the message.
213 */
214 protected $parameters = [];
215
216 /**
217 * @var string
218 * @deprecated
219 */
220 protected $format = 'parse';
221
222 /**
223 * @var bool Whether database can be used.
224 */
225 protected $useDatabase = true;
226
227 /**
228 * @var Title Title object to use as context.
229 */
230 protected $title = null;
231
232 /**
233 * @var Content Content object representing the message.
234 */
235 protected $content = null;
236
237 /**
238 * @var string
239 */
240 protected $message;
241
242 /**
243 * @since 1.17
244 * @param string|string[]|MessageSpecifier $key Message key, or array of
245 * message keys to try and use the first non-empty message for, or a
246 * MessageSpecifier to copy from.
247 * @param array $params Message parameters.
248 * @param Language|null $language [optional] Language to use (defaults to current user language).
249 * @throws InvalidArgumentException
250 */
251 public function __construct( $key, $params = [], Language $language = null ) {
252 if ( $key instanceof MessageSpecifier ) {
253 if ( $params ) {
254 throw new InvalidArgumentException(
255 '$params must be empty if $key is a MessageSpecifier'
256 );
257 }
258 $params = $key->getParams();
259 $key = $key->getKey();
260 }
261
262 if ( !is_string( $key ) && !is_array( $key ) ) {
263 throw new InvalidArgumentException( '$key must be a string or an array' );
264 }
265
266 $this->keysToTry = (array)$key;
267
268 if ( empty( $this->keysToTry ) ) {
269 throw new InvalidArgumentException( '$key must not be an empty list' );
270 }
271
272 $this->key = reset( $this->keysToTry );
273
274 $this->parameters = array_values( $params );
275 // User language is only resolved in getLanguage(). This helps preserve the
276 // semantic intent of "user language" across serialize() and unserialize().
277 $this->language = $language ?: false;
278 }
279
280 /**
281 * @see Serializable::serialize()
282 * @since 1.26
283 * @return string
284 */
285 public function serialize() {
286 return serialize( [
287 'interface' => $this->interface,
288 'language' => $this->language ? $this->language->getCode() : false,
289 'key' => $this->key,
290 'keysToTry' => $this->keysToTry,
291 'parameters' => $this->parameters,
292 'format' => $this->format,
293 'useDatabase' => $this->useDatabase,
294 'titlestr' => $this->title ? $this->title->getFullText() : null,
295 ] );
296 }
297
298 /**
299 * @see Serializable::unserialize()
300 * @since 1.26
301 * @param string $serialized
302 */
303 public function unserialize( $serialized ) {
304 $data = unserialize( $serialized );
305 if ( !is_array( $data ) ) {
306 throw new InvalidArgumentException( __METHOD__ . ': Invalid serialized data' );
307 }
308
309 $this->interface = $data['interface'];
310 $this->key = $data['key'];
311 $this->keysToTry = $data['keysToTry'];
312 $this->parameters = $data['parameters'];
313 $this->format = $data['format'];
314 $this->useDatabase = $data['useDatabase'];
315 $this->language = $data['language'] ? Language::factory( $data['language'] ) : false;
316
317 if ( isset( $data['titlestr'] ) ) {
318 $this->title = Title::newFromText( $data['titlestr'] );
319 } elseif ( isset( $data['title'] ) && $data['title'] instanceof Title ) {
320 // Old serializations from before December 2018
321 $this->title = $data['title'];
322 } else {
323 $this->title = null; // Explicit for sanity
324 }
325 }
326
327 /**
328 * @since 1.24
329 *
330 * @return bool True if this is a multi-key message, that is, if the key provided to the
331 * constructor was a fallback list of keys to try.
332 */
333 public function isMultiKey() {
334 return count( $this->keysToTry ) > 1;
335 }
336
337 /**
338 * @since 1.24
339 *
340 * @return string[] The list of keys to try when fetching the message text,
341 * in order of preference.
342 */
343 public function getKeysToTry() {
344 return $this->keysToTry;
345 }
346
347 /**
348 * Returns the message key.
349 *
350 * If a list of multiple possible keys was supplied to the constructor, this method may
351 * return any of these keys. After the message has been fetched, this method will return
352 * the key that was actually used to fetch the message.
353 *
354 * @since 1.21
355 *
356 * @return string
357 */
358 public function getKey() {
359 return $this->key;
360 }
361
362 /**
363 * Returns the message parameters.
364 *
365 * @since 1.21
366 *
367 * @return array
368 */
369 public function getParams() {
370 return $this->parameters;
371 }
372
373 /**
374 * Returns the message format.
375 *
376 * @since 1.21
377 *
378 * @return string
379 * @deprecated since 1.29 formatting is not stateful
380 */
381 public function getFormat() {
382 wfDeprecated( __METHOD__, '1.29' );
383 return $this->format;
384 }
385
386 /**
387 * Returns the Language of the Message.
388 *
389 * @since 1.23
390 *
391 * @return Language
392 */
393 public function getLanguage() {
394 // Defaults to false which means current user language
395 return $this->language ?: RequestContext::getMain()->getLanguage();
396 }
397
398 /**
399 * Factory function that is just wrapper for the real constructor. It is
400 * intended to be used instead of the real constructor, because it allows
401 * chaining method calls, while new objects don't.
402 *
403 * @since 1.17
404 *
405 * @param string|string[]|MessageSpecifier $key
406 * @param mixed ...$params Parameters as strings.
407 *
408 * @return Message
409 */
410 public static function newFromKey( $key, ...$params ) {
411 return new self( $key, $params );
412 }
413
414 /**
415 * Transform a MessageSpecifier or a primitive value used interchangeably with
416 * specifiers (a message key string, or a key + params array) into a proper Message.
417 *
418 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
419 * but is an easy error to make due to how StatusValue stores messages internally.
420 * Further array elements are ignored in that case.
421 *
422 * @param string|array|MessageSpecifier $value
423 * @return Message
424 * @throws InvalidArgumentException
425 * @since 1.27
426 */
427 public static function newFromSpecifier( $value ) {
428 $params = [];
429 if ( is_array( $value ) ) {
430 $params = $value;
431 $value = array_shift( $params );
432 }
433
434 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
435 $message = clone $value;
436 } elseif ( $value instanceof MessageSpecifier ) {
437 $message = new Message( $value );
438 } elseif ( is_string( $value ) ) {
439 $message = new Message( $value, $params );
440 } else {
441 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
442 . gettype( $value ) );
443 }
444
445 return $message;
446 }
447
448 /**
449 * Factory function accepting multiple message keys and returning a message instance
450 * for the first message which is non-empty. If all messages are empty then an
451 * instance of the first message key is returned.
452 *
453 * @since 1.18
454 *
455 * @param string|string[] ...$keys Message keys, or first argument as an array of all the
456 * message keys.
457 *
458 * @return Message
459 */
460 public static function newFallbackSequence( ...$keys ) {
461 if ( func_num_args() == 1 ) {
462 if ( is_array( $keys[0] ) ) {
463 // Allow an array to be passed as the first argument instead
464 $keys = array_values( $keys[0] );
465 } else {
466 // Optimize a single string to not need special fallback handling
467 $keys = $keys[0];
468 }
469 }
470 return new self( $keys );
471 }
472
473 /**
474 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
475 * The title will be for the current language, if the message key is in
476 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
477 * language), because Message::inContentLanguage will also return in user language.
478 *
479 * @see $wgForceUIMsgAsContentMsg
480 * @return Title
481 * @since 1.26
482 */
483 public function getTitle() {
484 global $wgForceUIMsgAsContentMsg;
485
486 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
487 $lang = $this->getLanguage();
488 $title = $this->key;
489 if (
490 !$lang->equals( $contLang )
491 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
492 ) {
493 $title .= '/' . $lang->getCode();
494 }
495
496 return Title::makeTitle(
497 NS_MEDIAWIKI, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) );
498 }
499
500 /**
501 * Adds parameters to the parameter list of this message.
502 *
503 * @since 1.17
504 *
505 * @param mixed ...$args Parameters as strings or arrays from
506 * Message::numParam() and the like, or a single array of parameters.
507 *
508 * @return Message $this
509 */
510 public function params( ...$args ) {
511 // If $args has only one entry and it's an array, then it's either a
512 // non-varargs call or it happens to be a call with just a single
513 // "special" parameter. Since the "special" parameters don't have any
514 // numeric keys, we'll test that to differentiate the cases.
515 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
516 if ( $args[0] === [] ) {
517 $args = [];
518 } else {
519 foreach ( $args[0] as $key => $value ) {
520 if ( is_int( $key ) ) {
521 $args = $args[0];
522 break;
523 }
524 }
525 }
526 }
527
528 $this->parameters = array_merge( $this->parameters, array_values( $args ) );
529 return $this;
530 }
531
532 /**
533 * Add parameters that are substituted after parsing or escaping.
534 * In other words the parsing process cannot access the contents
535 * of this type of parameter, and you need to make sure it is
536 * sanitized beforehand. The parser will see "$n", instead.
537 *
538 * @since 1.17
539 *
540 * @param mixed ...$params Raw parameters as strings, or a single argument that is
541 * an array of raw parameters.
542 *
543 * @return Message $this
544 */
545 public function rawParams( ...$params ) {
546 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
547 $params = $params[0];
548 }
549 foreach ( $params as $param ) {
550 $this->parameters[] = self::rawParam( $param );
551 }
552 return $this;
553 }
554
555 /**
556 * Add parameters that are numeric and will be passed through
557 * Language::formatNum before substitution
558 *
559 * @since 1.18
560 *
561 * @param mixed ...$params Numeric parameters, or a single argument that is
562 * an array of numeric parameters.
563 *
564 * @return Message $this
565 */
566 public function numParams( ...$params ) {
567 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
568 $params = $params[0];
569 }
570 foreach ( $params as $param ) {
571 $this->parameters[] = self::numParam( $param );
572 }
573 return $this;
574 }
575
576 /**
577 * Add parameters that are durations of time and will be passed through
578 * Language::formatDuration before substitution
579 *
580 * @since 1.22
581 *
582 * @param int|int[] ...$params Duration parameters, or a single argument that is
583 * an array of duration parameters.
584 *
585 * @return Message $this
586 */
587 public function durationParams( ...$params ) {
588 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
589 $params = $params[0];
590 }
591 foreach ( $params as $param ) {
592 $this->parameters[] = self::durationParam( $param );
593 }
594 return $this;
595 }
596
597 /**
598 * Add parameters that are expiration times and will be passed through
599 * Language::formatExpiry before substitution
600 *
601 * @since 1.22
602 *
603 * @param string|string[] ...$params Expiry parameters, or a single argument that is
604 * an array of expiry parameters.
605 *
606 * @return Message $this
607 */
608 public function expiryParams( ...$params ) {
609 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
610 $params = $params[0];
611 }
612 foreach ( $params as $param ) {
613 $this->parameters[] = self::expiryParam( $param );
614 }
615 return $this;
616 }
617
618 /**
619 * Add parameters that are time periods and will be passed through
620 * Language::formatTimePeriod before substitution
621 *
622 * @since 1.22
623 *
624 * @param int|int[] ...$params Time period parameters, or a single argument that is
625 * an array of time period parameters.
626 *
627 * @return Message $this
628 */
629 public function timeperiodParams( ...$params ) {
630 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
631 $params = $params[0];
632 }
633 foreach ( $params as $param ) {
634 $this->parameters[] = self::timeperiodParam( $param );
635 }
636 return $this;
637 }
638
639 /**
640 * Add parameters that are file sizes and will be passed through
641 * Language::formatSize before substitution
642 *
643 * @since 1.22
644 *
645 * @param int|int[] ...$params Size parameters, or a single argument that is
646 * an array of size parameters.
647 *
648 * @return Message $this
649 */
650 public function sizeParams( ...$params ) {
651 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
652 $params = $params[0];
653 }
654 foreach ( $params as $param ) {
655 $this->parameters[] = self::sizeParam( $param );
656 }
657 return $this;
658 }
659
660 /**
661 * Add parameters that are bitrates and will be passed through
662 * Language::formatBitrate before substitution
663 *
664 * @since 1.22
665 *
666 * @param int|int[] ...$params Bit rate parameters, or a single argument that is
667 * an array of bit rate parameters.
668 *
669 * @return Message $this
670 */
671 public function bitrateParams( ...$params ) {
672 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
673 $params = $params[0];
674 }
675 foreach ( $params as $param ) {
676 $this->parameters[] = self::bitrateParam( $param );
677 }
678 return $this;
679 }
680
681 /**
682 * Add parameters that are plaintext and will be passed through without
683 * the content being evaluated. Plaintext parameters are not valid as
684 * arguments to parser functions. This differs from self::rawParams in
685 * that the Message class handles escaping to match the output format.
686 *
687 * @since 1.25
688 *
689 * @param string|string[] ...$params plaintext parameters, or a single argument that is
690 * an array of plaintext parameters.
691 *
692 * @return Message $this
693 */
694 public function plaintextParams( ...$params ) {
695 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
696 $params = $params[0];
697 }
698 foreach ( $params as $param ) {
699 $this->parameters[] = self::plaintextParam( $param );
700 }
701 return $this;
702 }
703
704 /**
705 * Set the language and the title from a context object
706 *
707 * @since 1.19
708 *
709 * @param IContextSource $context
710 *
711 * @return Message $this
712 */
713 public function setContext( IContextSource $context ) {
714 $this->inLanguage( $context->getLanguage() );
715 $this->title( $context->getTitle() );
716 $this->interface = true;
717
718 return $this;
719 }
720
721 /**
722 * Request the message in any language that is supported.
723 *
724 * As a side effect interface message status is unconditionally
725 * turned off.
726 *
727 * @since 1.17
728 * @param Language|string $lang Language code or Language object.
729 * @return Message $this
730 * @throws MWException
731 */
732 public function inLanguage( $lang ) {
733 $previousLanguage = $this->language;
734
735 if ( $lang instanceof Language ) {
736 $this->language = $lang;
737 } elseif ( is_string( $lang ) ) {
738 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
739 $this->language = Language::factory( $lang );
740 }
741 } elseif ( $lang instanceof StubUserLang ) {
742 $this->language = false;
743 } else {
744 $type = gettype( $lang );
745 throw new MWException( __METHOD__ . " must be "
746 . "passed a String or Language object; $type given"
747 );
748 }
749
750 if ( $this->language !== $previousLanguage ) {
751 // The language has changed. Clear the message cache.
752 $this->message = null;
753 }
754 $this->interface = false;
755 return $this;
756 }
757
758 /**
759 * Request the message in the wiki's content language,
760 * unless it is disabled for this message.
761 *
762 * @since 1.17
763 * @see $wgForceUIMsgAsContentMsg
764 *
765 * @return Message $this
766 */
767 public function inContentLanguage() {
768 global $wgForceUIMsgAsContentMsg;
769 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
770 return $this;
771 }
772
773 $this->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() );
774 return $this;
775 }
776
777 /**
778 * Allows manipulating the interface message flag directly.
779 * Can be used to restore the flag after setting a language.
780 *
781 * @since 1.20
782 *
783 * @param bool $interface
784 *
785 * @return Message $this
786 */
787 public function setInterfaceMessageFlag( $interface ) {
788 $this->interface = (bool)$interface;
789 return $this;
790 }
791
792 /**
793 * Enable or disable database use.
794 *
795 * @since 1.17
796 *
797 * @param bool $useDatabase
798 *
799 * @return Message $this
800 */
801 public function useDatabase( $useDatabase ) {
802 $this->useDatabase = (bool)$useDatabase;
803 $this->message = null;
804 return $this;
805 }
806
807 /**
808 * Set the Title object to use as context when transforming the message
809 *
810 * @since 1.18
811 *
812 * @param Title $title
813 *
814 * @return Message $this
815 */
816 public function title( $title ) {
817 $this->title = $title;
818 return $this;
819 }
820
821 /**
822 * Returns the message as a Content object.
823 *
824 * @return Content
825 */
826 public function content() {
827 if ( !$this->content ) {
828 $this->content = new MessageContent( $this );
829 }
830
831 return $this->content;
832 }
833
834 /**
835 * Returns the message parsed from wikitext to HTML.
836 *
837 * @since 1.17
838 *
839 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
840 * the last time (this is for B/C and should be avoided).
841 *
842 * @return string HTML
843 * @suppress SecurityCheck-DoubleEscaped phan false positive
844 */
845 public function toString( $format = null ) {
846 if ( $format === null ) {
847 $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format );
848 LoggerFactory::getInstance( 'message-format' )->warning(
849 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] );
850 $format = $this->format;
851 }
852 $string = $this->fetchMessage();
853
854 if ( $string === false ) {
855 // Err on the side of safety, ensure that the output
856 // is always html safe in the event the message key is
857 // missing, since in that case its highly likely the
858 // message key is user-controlled.
859 // '⧼' is used instead of '<' to side-step any
860 // double-escaping issues.
861 // (Keep synchronised with mw.Message#toString in JS.)
862 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
863 }
864
865 # Replace $* with a list of parameters for &uselang=qqx.
866 if ( strpos( $string, '$*' ) !== false ) {
867 $paramlist = '';
868 if ( $this->parameters !== [] ) {
869 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
870 }
871 $string = str_replace( '$*', $paramlist, $string );
872 }
873
874 # Replace parameters before text parsing
875 $string = $this->replaceParameters( $string, 'before', $format );
876
877 # Maybe transform using the full parser
878 if ( $format === self::FORMAT_PARSE ) {
879 $string = $this->parseText( $string );
880 $string = Parser::stripOuterParagraph( $string );
881 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
882 $string = $this->parseText( $string );
883 } elseif ( $format === self::FORMAT_TEXT ) {
884 $string = $this->transformText( $string );
885 } elseif ( $format === self::FORMAT_ESCAPED ) {
886 $string = $this->transformText( $string );
887 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
888 }
889
890 # Raw parameter replacement
891 $string = $this->replaceParameters( $string, 'after', $format );
892
893 return $string;
894 }
895
896 /**
897 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
898 * $foo = new Message( $key );
899 * $string = "<abbr>$foo</abbr>";
900 *
901 * @since 1.18
902 *
903 * @return string
904 */
905 public function __toString() {
906 // PHP doesn't allow __toString to throw exceptions and will
907 // trigger a fatal error if it does. So, catch any exceptions.
908
909 try {
910 return $this->toString( self::FORMAT_PARSE );
911 } catch ( Exception $ex ) {
912 try {
913 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
914 . $ex, E_USER_WARNING );
915 } catch ( Exception $ex ) {
916 // Doh! Cause a fatal error after all?
917 }
918
919 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
920 }
921 }
922
923 /**
924 * Fully parse the text from wikitext to HTML.
925 *
926 * @since 1.17
927 *
928 * @return string Parsed HTML.
929 */
930 public function parse() {
931 $this->format = self::FORMAT_PARSE;
932 return $this->toString( self::FORMAT_PARSE );
933 }
934
935 /**
936 * Returns the message text. {{-transformation is done.
937 *
938 * @since 1.17
939 *
940 * @return string Unescaped message text.
941 */
942 public function text() {
943 $this->format = self::FORMAT_TEXT;
944 return $this->toString( self::FORMAT_TEXT );
945 }
946
947 /**
948 * Returns the message text as-is, only parameters are substituted.
949 *
950 * @since 1.17
951 *
952 * @return string Unescaped untransformed message text.
953 */
954 public function plain() {
955 $this->format = self::FORMAT_PLAIN;
956 return $this->toString( self::FORMAT_PLAIN );
957 }
958
959 /**
960 * Returns the parsed message text which is always surrounded by a block element.
961 *
962 * @since 1.17
963 *
964 * @return string HTML
965 */
966 public function parseAsBlock() {
967 $this->format = self::FORMAT_BLOCK_PARSE;
968 return $this->toString( self::FORMAT_BLOCK_PARSE );
969 }
970
971 /**
972 * Returns the message text. {{-transformation is done and the result
973 * is escaped excluding any raw parameters.
974 *
975 * @since 1.17
976 *
977 * @return string Escaped message text.
978 */
979 public function escaped() {
980 $this->format = self::FORMAT_ESCAPED;
981 return $this->toString( self::FORMAT_ESCAPED );
982 }
983
984 /**
985 * Check whether a message key has been defined currently.
986 *
987 * @since 1.17
988 *
989 * @return bool
990 */
991 public function exists() {
992 return $this->fetchMessage() !== false;
993 }
994
995 /**
996 * Check whether a message does not exist, or is an empty string
997 *
998 * @since 1.18
999 * @todo FIXME: Merge with isDisabled()?
1000 *
1001 * @return bool
1002 */
1003 public function isBlank() {
1004 $message = $this->fetchMessage();
1005 return $message === false || $message === '';
1006 }
1007
1008 /**
1009 * Check whether a message does not exist, is an empty string, or is "-".
1010 *
1011 * @since 1.18
1012 *
1013 * @return bool
1014 */
1015 public function isDisabled() {
1016 $message = $this->fetchMessage();
1017 return $message === false || $message === '' || $message === '-';
1018 }
1019
1020 /**
1021 * @since 1.17
1022 *
1023 * @param mixed $raw
1024 *
1025 * @return array Array with a single "raw" key.
1026 */
1027 public static function rawParam( $raw ) {
1028 return [ 'raw' => $raw ];
1029 }
1030
1031 /**
1032 * @since 1.18
1033 *
1034 * @param mixed $num
1035 *
1036 * @return array Array with a single "num" key.
1037 */
1038 public static function numParam( $num ) {
1039 return [ 'num' => $num ];
1040 }
1041
1042 /**
1043 * @since 1.22
1044 *
1045 * @param int $duration
1046 *
1047 * @return int[] Array with a single "duration" key.
1048 */
1049 public static function durationParam( $duration ) {
1050 return [ 'duration' => $duration ];
1051 }
1052
1053 /**
1054 * @since 1.22
1055 *
1056 * @param string $expiry
1057 *
1058 * @return string[] Array with a single "expiry" key.
1059 */
1060 public static function expiryParam( $expiry ) {
1061 return [ 'expiry' => $expiry ];
1062 }
1063
1064 /**
1065 * @since 1.22
1066 *
1067 * @param int $period
1068 *
1069 * @return int[] Array with a single "period" key.
1070 */
1071 public static function timeperiodParam( $period ) {
1072 return [ 'period' => $period ];
1073 }
1074
1075 /**
1076 * @since 1.22
1077 *
1078 * @param int $size
1079 *
1080 * @return int[] Array with a single "size" key.
1081 */
1082 public static function sizeParam( $size ) {
1083 return [ 'size' => $size ];
1084 }
1085
1086 /**
1087 * @since 1.22
1088 *
1089 * @param int $bitrate
1090 *
1091 * @return int[] Array with a single "bitrate" key.
1092 */
1093 public static function bitrateParam( $bitrate ) {
1094 return [ 'bitrate' => $bitrate ];
1095 }
1096
1097 /**
1098 * @since 1.25
1099 *
1100 * @param string $plaintext
1101 *
1102 * @return string[] Array with a single "plaintext" key.
1103 */
1104 public static function plaintextParam( $plaintext ) {
1105 return [ 'plaintext' => $plaintext ];
1106 }
1107
1108 /**
1109 * @since 1.29
1110 *
1111 * @param array $list
1112 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1113 * @return array Array with "list" and "type" keys.
1114 */
1115 public static function listParam( array $list, $type = 'text' ) {
1116 if ( !isset( self::$listTypeMap[$type] ) ) {
1117 throw new InvalidArgumentException(
1118 "Invalid type '$type'. Known types are: " . implode( ', ', array_keys( self::$listTypeMap ) )
1119 );
1120 }
1121 return [ 'list' => $list, 'type' => $type ];
1122 }
1123
1124 /**
1125 * Substitutes any parameters into the message text.
1126 *
1127 * @since 1.17
1128 *
1129 * @param string $message The message text.
1130 * @param string $type Either "before" or "after".
1131 * @param string $format One of the FORMAT_* constants.
1132 *
1133 * @return string
1134 */
1135 protected function replaceParameters( $message, $type, $format ) {
1136 // A temporary marker for $1 parameters that is only valid
1137 // in non-attribute contexts. However if the entire message is escaped
1138 // then we don't want to use it because it will be mangled in all contexts
1139 // and its unnessary as ->escaped() messages aren't html.
1140 $marker = $format === self::FORMAT_ESCAPED ? '$' : '$\'"';
1141 $replacementKeys = [];
1142 foreach ( $this->parameters as $n => $param ) {
1143 list( $paramType, $value ) = $this->extractParam( $param, $format );
1144 if ( $type === 'before' ) {
1145 if ( $paramType === 'before' ) {
1146 $replacementKeys['$' . ( $n + 1 )] = $value;
1147 } else /* $paramType === 'after' */ {
1148 // To protect against XSS from replacing parameters
1149 // inside html attributes, we convert $1 to $'"1.
1150 // In the event that one of the parameters ends up
1151 // in an attribute, either the ' or the " will be
1152 // escaped, breaking the replacement and avoiding XSS.
1153 $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 );
1154 }
1155 } elseif ( $paramType === 'after' ) {
1156 $replacementKeys[$marker . ( $n + 1 )] = $value;
1157 }
1158 }
1159 return strtr( $message, $replacementKeys );
1160 }
1161
1162 /**
1163 * Extracts the parameter type and preprocessed the value if needed.
1164 *
1165 * @since 1.18
1166 *
1167 * @param mixed $param Parameter as defined in this class.
1168 * @param string $format One of the FORMAT_* constants.
1169 *
1170 * @return array Array with the parameter type (either "before" or "after") and the value.
1171 */
1172 protected function extractParam( $param, $format ) {
1173 if ( is_array( $param ) ) {
1174 if ( isset( $param['raw'] ) ) {
1175 return [ 'after', $param['raw'] ];
1176 } elseif ( isset( $param['num'] ) ) {
1177 // Replace number params always in before step for now.
1178 // No support for combined raw and num params
1179 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1180 } elseif ( isset( $param['duration'] ) ) {
1181 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1182 } elseif ( isset( $param['expiry'] ) ) {
1183 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1184 } elseif ( isset( $param['period'] ) ) {
1185 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1186 } elseif ( isset( $param['size'] ) ) {
1187 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1188 } elseif ( isset( $param['bitrate'] ) ) {
1189 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1190 } elseif ( isset( $param['plaintext'] ) ) {
1191 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1192 } elseif ( isset( $param['list'] ) ) {
1193 return $this->formatListParam( $param['list'], $param['type'], $format );
1194 } else {
1195 if ( !is_scalar( $param ) ) {
1196 $param = serialize( $param );
1197 }
1198 LoggerFactory::getInstance( 'Bug58676' )->warning(
1199 'Invalid parameter for message "{msgkey}": {param}',
1200 [
1201 'exception' => new Exception,
1202 'msgkey' => $this->getKey(),
1203 'param' => htmlspecialchars( $param ),
1204 ]
1205 );
1206
1207 return [ 'before', '[INVALID]' ];
1208 }
1209 } elseif ( $param instanceof Message ) {
1210 // Match language, flags, etc. to the current message.
1211 $msg = clone $param;
1212 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1213 // Cache depends on these parameters
1214 $msg->message = null;
1215 }
1216 $msg->interface = $this->interface;
1217 $msg->language = $this->language;
1218 $msg->useDatabase = $this->useDatabase;
1219 $msg->title = $this->title;
1220
1221 // DWIM
1222 if ( $format === 'block-parse' ) {
1223 $format = 'parse';
1224 }
1225 $msg->format = $format;
1226
1227 // Message objects should not be before parameters because
1228 // then they'll get double escaped. If the message needs to be
1229 // escaped, it'll happen right here when we call toString().
1230 return [ 'after', $msg->toString( $format ) ];
1231 } else {
1232 return [ 'before', $param ];
1233 }
1234 }
1235
1236 /**
1237 * Wrapper for what ever method we use to parse wikitext.
1238 *
1239 * @since 1.17
1240 *
1241 * @param string $string Wikitext message contents.
1242 *
1243 * @return string Wikitext parsed into HTML.
1244 */
1245 protected function parseText( $string ) {
1246 $out = MessageCache::singleton()->parse(
1247 $string,
1248 $this->title,
1249 /*linestart*/true,
1250 $this->interface,
1251 $this->getLanguage()
1252 );
1253
1254 return $out instanceof ParserOutput
1255 ? $out->getText( [
1256 'enableSectionEditLinks' => false,
1257 // Wrapping messages in an extra <div> is probably not expected. If
1258 // they're outside the content area they probably shouldn't be
1259 // targeted by CSS that's targeting the parser output, and if
1260 // they're inside they already are from the outer div.
1261 'unwrap' => true,
1262 ] )
1263 : $out;
1264 }
1265
1266 /**
1267 * Wrapper for what ever method we use to {{-transform wikitext.
1268 *
1269 * @since 1.17
1270 *
1271 * @param string $string Wikitext message contents.
1272 *
1273 * @return string Wikitext with {{-constructs replaced with their values.
1274 */
1275 protected function transformText( $string ) {
1276 return MessageCache::singleton()->transform(
1277 $string,
1278 $this->interface,
1279 $this->getLanguage(),
1280 $this->title
1281 );
1282 }
1283
1284 /**
1285 * Wrapper for what ever method we use to get message contents.
1286 *
1287 * @since 1.17
1288 *
1289 * @return string
1290 * @throws MWException If message key array is empty.
1291 */
1292 protected function fetchMessage() {
1293 if ( $this->message === null ) {
1294 $cache = MessageCache::singleton();
1295
1296 foreach ( $this->keysToTry as $key ) {
1297 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1298 if ( $message !== false && $message !== '' ) {
1299 break;
1300 }
1301 }
1302
1303 // NOTE: The constructor makes sure keysToTry isn't empty,
1304 // so we know that $key and $message are initialized.
1305 $this->key = $key;
1306 $this->message = $message;
1307 }
1308 return $this->message;
1309 }
1310
1311 /**
1312 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1313 * the entire string is displayed unchanged when displayed in the output
1314 * format.
1315 *
1316 * @since 1.25
1317 *
1318 * @param string $plaintext String to ensure plaintext output of
1319 * @param string $format One of the FORMAT_* constants.
1320 *
1321 * @return string Input plaintext encoded for output to $format
1322 */
1323 protected function formatPlaintext( $plaintext, $format ) {
1324 switch ( $format ) {
1325 case self::FORMAT_TEXT:
1326 case self::FORMAT_PLAIN:
1327 return $plaintext;
1328
1329 case self::FORMAT_PARSE:
1330 case self::FORMAT_BLOCK_PARSE:
1331 case self::FORMAT_ESCAPED:
1332 default:
1333 return htmlspecialchars( $plaintext, ENT_QUOTES );
1334 }
1335 }
1336
1337 /**
1338 * Formats a list of parameters as a concatenated string.
1339 * @since 1.29
1340 * @param array $params
1341 * @param string $listType
1342 * @param string $format One of the FORMAT_* constants.
1343 * @return array Array with the parameter type (either "before" or "after") and the value.
1344 */
1345 protected function formatListParam( array $params, $listType, $format ) {
1346 if ( !isset( self::$listTypeMap[$listType] ) ) {
1347 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1348 . htmlspecialchars( $listType )
1349 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1350 trigger_error( $warning, E_USER_WARNING );
1351 $e = new Exception;
1352 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1353 return [ 'before', '[INVALID]' ];
1354 }
1355 $func = self::$listTypeMap[$listType];
1356
1357 // Handle an empty list sensibly
1358 if ( !$params ) {
1359 return [ 'before', $this->getLanguage()->$func( [] ) ];
1360 }
1361
1362 // First, determine what kinds of list items we have
1363 $types = [];
1364 $vars = [];
1365 $list = [];
1366 foreach ( $params as $n => $p ) {
1367 list( $type, $value ) = $this->extractParam( $p, $format );
1368 $types[$type] = true;
1369 $list[] = $value;
1370 $vars[] = '$' . ( $n + 1 );
1371 }
1372
1373 // Easy case: all are 'before' or 'after', so just join the
1374 // values and use the same type.
1375 if ( count( $types ) === 1 ) {
1376 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1377 }
1378
1379 // Hard case: We need to process each value per its type, then
1380 // return the concatenated values as 'after'. We handle this by turning
1381 // the list into a RawMessage and processing that as a parameter.
1382 $vars = $this->getLanguage()->$func( $vars );
1383 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1384 }
1385 }