Merge "Type hint against LinkTarget in WatchedItemStore"
[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 $param,... Parameters as strings.
407 *
408 * @return Message
409 */
410 public static function newFromKey( $key /*...*/ ) {
411 $params = func_get_args();
412 array_shift( $params );
413 return new self( $key, $params );
414 }
415
416 /**
417 * Transform a MessageSpecifier or a primitive value used interchangeably with
418 * specifiers (a message key string, or a key + params array) into a proper Message.
419 *
420 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
421 * but is an easy error to make due to how StatusValue stores messages internally.
422 * Further array elements are ignored in that case.
423 *
424 * @param string|array|MessageSpecifier $value
425 * @return Message
426 * @throws InvalidArgumentException
427 * @since 1.27
428 */
429 public static function newFromSpecifier( $value ) {
430 $params = [];
431 if ( is_array( $value ) ) {
432 $params = $value;
433 $value = array_shift( $params );
434 }
435
436 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
437 $message = clone $value;
438 } elseif ( $value instanceof MessageSpecifier ) {
439 $message = new Message( $value );
440 } elseif ( is_string( $value ) ) {
441 $message = new Message( $value, $params );
442 } else {
443 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
444 . gettype( $value ) );
445 }
446
447 return $message;
448 }
449
450 /**
451 * Factory function accepting multiple message keys and returning a message instance
452 * for the first message which is non-empty. If all messages are empty then an
453 * instance of the first message key is returned.
454 *
455 * @since 1.18
456 *
457 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
458 * message keys.
459 *
460 * @return Message
461 */
462 public static function newFallbackSequence( /*...*/ ) {
463 $keys = func_get_args();
464 if ( func_num_args() == 1 ) {
465 if ( is_array( $keys[0] ) ) {
466 // Allow an array to be passed as the first argument instead
467 $keys = array_values( $keys[0] );
468 } else {
469 // Optimize a single string to not need special fallback handling
470 $keys = $keys[0];
471 }
472 }
473 return new self( $keys );
474 }
475
476 /**
477 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
478 * The title will be for the current language, if the message key is in
479 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
480 * language), because Message::inContentLanguage will also return in user language.
481 *
482 * @see $wgForceUIMsgAsContentMsg
483 * @return Title
484 * @since 1.26
485 */
486 public function getTitle() {
487 global $wgForceUIMsgAsContentMsg;
488
489 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
490 $lang = $this->getLanguage();
491 $title = $this->key;
492 if (
493 !$lang->equals( $contLang )
494 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
495 ) {
496 $title .= '/' . $lang->getCode();
497 }
498
499 return Title::makeTitle(
500 NS_MEDIAWIKI, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) );
501 }
502
503 /**
504 * Adds parameters to the parameter list of this message.
505 *
506 * @since 1.17
507 *
508 * @param mixed $args,... Parameters as strings or arrays from
509 * Message::numParam() and the like, or a single array of parameters.
510 *
511 * @return Message $this
512 */
513 public function params( /*...*/ ) {
514 $args = func_get_args();
515
516 // If $args has only one entry and it's an array, then it's either a
517 // non-varargs call or it happens to be a call with just a single
518 // "special" parameter. Since the "special" parameters don't have any
519 // numeric keys, we'll test that to differentiate the cases.
520 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
521 if ( $args[0] === [] ) {
522 $args = [];
523 } else {
524 foreach ( $args[0] as $key => $value ) {
525 if ( is_int( $key ) ) {
526 $args = $args[0];
527 break;
528 }
529 }
530 }
531 }
532
533 $this->parameters = array_merge( $this->parameters, array_values( $args ) );
534 return $this;
535 }
536
537 /**
538 * Add parameters that are substituted after parsing or escaping.
539 * In other words the parsing process cannot access the contents
540 * of this type of parameter, and you need to make sure it is
541 * sanitized beforehand. The parser will see "$n", instead.
542 *
543 * @since 1.17
544 *
545 * @param mixed $params,... Raw parameters as strings, or a single argument that is
546 * an array of raw parameters.
547 *
548 * @return Message $this
549 */
550 public function rawParams( /*...*/ ) {
551 $params = func_get_args();
552 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
553 $params = $params[0];
554 }
555 foreach ( $params as $param ) {
556 $this->parameters[] = self::rawParam( $param );
557 }
558 return $this;
559 }
560
561 /**
562 * Add parameters that are numeric and will be passed through
563 * Language::formatNum before substitution
564 *
565 * @since 1.18
566 *
567 * @param mixed $param,... Numeric parameters, or a single argument that is
568 * an array of numeric parameters.
569 *
570 * @return Message $this
571 */
572 public function numParams( /*...*/ ) {
573 $params = func_get_args();
574 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
575 $params = $params[0];
576 }
577 foreach ( $params as $param ) {
578 $this->parameters[] = self::numParam( $param );
579 }
580 return $this;
581 }
582
583 /**
584 * Add parameters that are durations of time and will be passed through
585 * Language::formatDuration before substitution
586 *
587 * @since 1.22
588 *
589 * @param int|int[] $param,... Duration parameters, or a single argument that is
590 * an array of duration parameters.
591 *
592 * @return Message $this
593 */
594 public function durationParams( /*...*/ ) {
595 $params = func_get_args();
596 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
597 $params = $params[0];
598 }
599 foreach ( $params as $param ) {
600 $this->parameters[] = self::durationParam( $param );
601 }
602 return $this;
603 }
604
605 /**
606 * Add parameters that are expiration times and will be passed through
607 * Language::formatExpiry before substitution
608 *
609 * @since 1.22
610 *
611 * @param string|string[] $param,... Expiry parameters, or a single argument that is
612 * an array of expiry parameters.
613 *
614 * @return Message $this
615 */
616 public function expiryParams( /*...*/ ) {
617 $params = func_get_args();
618 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
619 $params = $params[0];
620 }
621 foreach ( $params as $param ) {
622 $this->parameters[] = self::expiryParam( $param );
623 }
624 return $this;
625 }
626
627 /**
628 * Add parameters that are time periods and will be passed through
629 * Language::formatTimePeriod before substitution
630 *
631 * @since 1.22
632 *
633 * @param int|int[] $param,... Time period parameters, or a single argument that is
634 * an array of time period parameters.
635 *
636 * @return Message $this
637 */
638 public function timeperiodParams( /*...*/ ) {
639 $params = func_get_args();
640 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
641 $params = $params[0];
642 }
643 foreach ( $params as $param ) {
644 $this->parameters[] = self::timeperiodParam( $param );
645 }
646 return $this;
647 }
648
649 /**
650 * Add parameters that are file sizes and will be passed through
651 * Language::formatSize before substitution
652 *
653 * @since 1.22
654 *
655 * @param int|int[] $param,... Size parameters, or a single argument that is
656 * an array of size parameters.
657 *
658 * @return Message $this
659 */
660 public function sizeParams( /*...*/ ) {
661 $params = func_get_args();
662 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
663 $params = $params[0];
664 }
665 foreach ( $params as $param ) {
666 $this->parameters[] = self::sizeParam( $param );
667 }
668 return $this;
669 }
670
671 /**
672 * Add parameters that are bitrates and will be passed through
673 * Language::formatBitrate before substitution
674 *
675 * @since 1.22
676 *
677 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
678 * an array of bit rate parameters.
679 *
680 * @return Message $this
681 */
682 public function bitrateParams( /*...*/ ) {
683 $params = func_get_args();
684 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
685 $params = $params[0];
686 }
687 foreach ( $params as $param ) {
688 $this->parameters[] = self::bitrateParam( $param );
689 }
690 return $this;
691 }
692
693 /**
694 * Add parameters that are plaintext and will be passed through without
695 * the content being evaluated. Plaintext parameters are not valid as
696 * arguments to parser functions. This differs from self::rawParams in
697 * that the Message class handles escaping to match the output format.
698 *
699 * @since 1.25
700 *
701 * @param string|string[] $param,... plaintext parameters, or a single argument that is
702 * an array of plaintext parameters.
703 *
704 * @return Message $this
705 */
706 public function plaintextParams( /*...*/ ) {
707 $params = func_get_args();
708 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
709 $params = $params[0];
710 }
711 foreach ( $params as $param ) {
712 $this->parameters[] = self::plaintextParam( $param );
713 }
714 return $this;
715 }
716
717 /**
718 * Set the language and the title from a context object
719 *
720 * @since 1.19
721 *
722 * @param IContextSource $context
723 *
724 * @return Message $this
725 */
726 public function setContext( IContextSource $context ) {
727 $this->inLanguage( $context->getLanguage() );
728 $this->title( $context->getTitle() );
729 $this->interface = true;
730
731 return $this;
732 }
733
734 /**
735 * Request the message in any language that is supported.
736 *
737 * As a side effect interface message status is unconditionally
738 * turned off.
739 *
740 * @since 1.17
741 * @param Language|string $lang Language code or Language object.
742 * @return Message $this
743 * @throws MWException
744 */
745 public function inLanguage( $lang ) {
746 $previousLanguage = $this->language;
747
748 if ( $lang instanceof Language ) {
749 $this->language = $lang;
750 } elseif ( is_string( $lang ) ) {
751 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
752 $this->language = Language::factory( $lang );
753 }
754 } elseif ( $lang instanceof StubUserLang ) {
755 $this->language = false;
756 } else {
757 $type = gettype( $lang );
758 throw new MWException( __METHOD__ . " must be "
759 . "passed a String or Language object; $type given"
760 );
761 }
762
763 if ( $this->language !== $previousLanguage ) {
764 // The language has changed. Clear the message cache.
765 $this->message = null;
766 }
767 $this->interface = false;
768 return $this;
769 }
770
771 /**
772 * Request the message in the wiki's content language,
773 * unless it is disabled for this message.
774 *
775 * @since 1.17
776 * @see $wgForceUIMsgAsContentMsg
777 *
778 * @return Message $this
779 */
780 public function inContentLanguage() {
781 global $wgForceUIMsgAsContentMsg;
782 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
783 return $this;
784 }
785
786 $this->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() );
787 return $this;
788 }
789
790 /**
791 * Allows manipulating the interface message flag directly.
792 * Can be used to restore the flag after setting a language.
793 *
794 * @since 1.20
795 *
796 * @param bool $interface
797 *
798 * @return Message $this
799 */
800 public function setInterfaceMessageFlag( $interface ) {
801 $this->interface = (bool)$interface;
802 return $this;
803 }
804
805 /**
806 * Enable or disable database use.
807 *
808 * @since 1.17
809 *
810 * @param bool $useDatabase
811 *
812 * @return Message $this
813 */
814 public function useDatabase( $useDatabase ) {
815 $this->useDatabase = (bool)$useDatabase;
816 $this->message = null;
817 return $this;
818 }
819
820 /**
821 * Set the Title object to use as context when transforming the message
822 *
823 * @since 1.18
824 *
825 * @param Title $title
826 *
827 * @return Message $this
828 */
829 public function title( $title ) {
830 $this->title = $title;
831 return $this;
832 }
833
834 /**
835 * Returns the message as a Content object.
836 *
837 * @return Content
838 */
839 public function content() {
840 if ( !$this->content ) {
841 $this->content = new MessageContent( $this );
842 }
843
844 return $this->content;
845 }
846
847 /**
848 * Returns the message parsed from wikitext to HTML.
849 *
850 * @since 1.17
851 *
852 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
853 * the last time (this is for B/C and should be avoided).
854 *
855 * @return string HTML
856 * @suppress SecurityCheck-DoubleEscaped phan false positive
857 */
858 public function toString( $format = null ) {
859 if ( $format === null ) {
860 $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format );
861 LoggerFactory::getInstance( 'message-format' )->warning(
862 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] );
863 $format = $this->format;
864 }
865 $string = $this->fetchMessage();
866
867 if ( $string === false ) {
868 // Err on the side of safety, ensure that the output
869 // is always html safe in the event the message key is
870 // missing, since in that case its highly likely the
871 // message key is user-controlled.
872 // '⧼' is used instead of '<' to side-step any
873 // double-escaping issues.
874 // (Keep synchronised with mw.Message#toString in JS.)
875 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
876 }
877
878 # Replace $* with a list of parameters for &uselang=qqx.
879 if ( strpos( $string, '$*' ) !== false ) {
880 $paramlist = '';
881 if ( $this->parameters !== [] ) {
882 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
883 }
884 $string = str_replace( '$*', $paramlist, $string );
885 }
886
887 # Replace parameters before text parsing
888 $string = $this->replaceParameters( $string, 'before', $format );
889
890 # Maybe transform using the full parser
891 if ( $format === self::FORMAT_PARSE ) {
892 $string = $this->parseText( $string );
893 $string = Parser::stripOuterParagraph( $string );
894 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
895 $string = $this->parseText( $string );
896 } elseif ( $format === self::FORMAT_TEXT ) {
897 $string = $this->transformText( $string );
898 } elseif ( $format === self::FORMAT_ESCAPED ) {
899 $string = $this->transformText( $string );
900 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
901 }
902
903 # Raw parameter replacement
904 $string = $this->replaceParameters( $string, 'after', $format );
905
906 return $string;
907 }
908
909 /**
910 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
911 * $foo = new Message( $key );
912 * $string = "<abbr>$foo</abbr>";
913 *
914 * @since 1.18
915 *
916 * @return string
917 */
918 public function __toString() {
919 // PHP doesn't allow __toString to throw exceptions and will
920 // trigger a fatal error if it does. So, catch any exceptions.
921
922 try {
923 return $this->toString( self::FORMAT_PARSE );
924 } catch ( Exception $ex ) {
925 try {
926 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
927 . $ex, E_USER_WARNING );
928 } catch ( Exception $ex ) {
929 // Doh! Cause a fatal error after all?
930 }
931
932 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
933 }
934 }
935
936 /**
937 * Fully parse the text from wikitext to HTML.
938 *
939 * @since 1.17
940 *
941 * @return string Parsed HTML.
942 */
943 public function parse() {
944 $this->format = self::FORMAT_PARSE;
945 return $this->toString( self::FORMAT_PARSE );
946 }
947
948 /**
949 * Returns the message text. {{-transformation is done.
950 *
951 * @since 1.17
952 *
953 * @return string Unescaped message text.
954 */
955 public function text() {
956 $this->format = self::FORMAT_TEXT;
957 return $this->toString( self::FORMAT_TEXT );
958 }
959
960 /**
961 * Returns the message text as-is, only parameters are substituted.
962 *
963 * @since 1.17
964 *
965 * @return string Unescaped untransformed message text.
966 */
967 public function plain() {
968 $this->format = self::FORMAT_PLAIN;
969 return $this->toString( self::FORMAT_PLAIN );
970 }
971
972 /**
973 * Returns the parsed message text which is always surrounded by a block element.
974 *
975 * @since 1.17
976 *
977 * @return string HTML
978 */
979 public function parseAsBlock() {
980 $this->format = self::FORMAT_BLOCK_PARSE;
981 return $this->toString( self::FORMAT_BLOCK_PARSE );
982 }
983
984 /**
985 * Returns the message text. {{-transformation is done and the result
986 * is escaped excluding any raw parameters.
987 *
988 * @since 1.17
989 *
990 * @return string Escaped message text.
991 */
992 public function escaped() {
993 $this->format = self::FORMAT_ESCAPED;
994 return $this->toString( self::FORMAT_ESCAPED );
995 }
996
997 /**
998 * Check whether a message key has been defined currently.
999 *
1000 * @since 1.17
1001 *
1002 * @return bool
1003 */
1004 public function exists() {
1005 return $this->fetchMessage() !== false;
1006 }
1007
1008 /**
1009 * Check whether a message does not exist, or is an empty string
1010 *
1011 * @since 1.18
1012 * @todo FIXME: Merge with isDisabled()?
1013 *
1014 * @return bool
1015 */
1016 public function isBlank() {
1017 $message = $this->fetchMessage();
1018 return $message === false || $message === '';
1019 }
1020
1021 /**
1022 * Check whether a message does not exist, is an empty string, or is "-".
1023 *
1024 * @since 1.18
1025 *
1026 * @return bool
1027 */
1028 public function isDisabled() {
1029 $message = $this->fetchMessage();
1030 return $message === false || $message === '' || $message === '-';
1031 }
1032
1033 /**
1034 * @since 1.17
1035 *
1036 * @param mixed $raw
1037 *
1038 * @return array Array with a single "raw" key.
1039 */
1040 public static function rawParam( $raw ) {
1041 return [ 'raw' => $raw ];
1042 }
1043
1044 /**
1045 * @since 1.18
1046 *
1047 * @param mixed $num
1048 *
1049 * @return array Array with a single "num" key.
1050 */
1051 public static function numParam( $num ) {
1052 return [ 'num' => $num ];
1053 }
1054
1055 /**
1056 * @since 1.22
1057 *
1058 * @param int $duration
1059 *
1060 * @return int[] Array with a single "duration" key.
1061 */
1062 public static function durationParam( $duration ) {
1063 return [ 'duration' => $duration ];
1064 }
1065
1066 /**
1067 * @since 1.22
1068 *
1069 * @param string $expiry
1070 *
1071 * @return string[] Array with a single "expiry" key.
1072 */
1073 public static function expiryParam( $expiry ) {
1074 return [ 'expiry' => $expiry ];
1075 }
1076
1077 /**
1078 * @since 1.22
1079 *
1080 * @param int $period
1081 *
1082 * @return int[] Array with a single "period" key.
1083 */
1084 public static function timeperiodParam( $period ) {
1085 return [ 'period' => $period ];
1086 }
1087
1088 /**
1089 * @since 1.22
1090 *
1091 * @param int $size
1092 *
1093 * @return int[] Array with a single "size" key.
1094 */
1095 public static function sizeParam( $size ) {
1096 return [ 'size' => $size ];
1097 }
1098
1099 /**
1100 * @since 1.22
1101 *
1102 * @param int $bitrate
1103 *
1104 * @return int[] Array with a single "bitrate" key.
1105 */
1106 public static function bitrateParam( $bitrate ) {
1107 return [ 'bitrate' => $bitrate ];
1108 }
1109
1110 /**
1111 * @since 1.25
1112 *
1113 * @param string $plaintext
1114 *
1115 * @return string[] Array with a single "plaintext" key.
1116 */
1117 public static function plaintextParam( $plaintext ) {
1118 return [ 'plaintext' => $plaintext ];
1119 }
1120
1121 /**
1122 * @since 1.29
1123 *
1124 * @param array $list
1125 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1126 * @return array Array with "list" and "type" keys.
1127 */
1128 public static function listParam( array $list, $type = 'text' ) {
1129 if ( !isset( self::$listTypeMap[$type] ) ) {
1130 throw new InvalidArgumentException(
1131 "Invalid type '$type'. Known types are: " . implode( ', ', array_keys( self::$listTypeMap ) )
1132 );
1133 }
1134 return [ 'list' => $list, 'type' => $type ];
1135 }
1136
1137 /**
1138 * Substitutes any parameters into the message text.
1139 *
1140 * @since 1.17
1141 *
1142 * @param string $message The message text.
1143 * @param string $type Either "before" or "after".
1144 * @param string $format One of the FORMAT_* constants.
1145 *
1146 * @return string
1147 */
1148 protected function replaceParameters( $message, $type, $format ) {
1149 // A temporary marker for $1 parameters that is only valid
1150 // in non-attribute contexts. However if the entire message is escaped
1151 // then we don't want to use it because it will be mangled in all contexts
1152 // and its unnessary as ->escaped() messages aren't html.
1153 $marker = $format === self::FORMAT_ESCAPED ? '$' : '$\'"';
1154 $replacementKeys = [];
1155 foreach ( $this->parameters as $n => $param ) {
1156 list( $paramType, $value ) = $this->extractParam( $param, $format );
1157 if ( $type === 'before' ) {
1158 if ( $paramType === 'before' ) {
1159 $replacementKeys['$' . ( $n + 1 )] = $value;
1160 } else /* $paramType === 'after' */ {
1161 // To protect against XSS from replacing parameters
1162 // inside html attributes, we convert $1 to $'"1.
1163 // In the event that one of the parameters ends up
1164 // in an attribute, either the ' or the " will be
1165 // escaped, breaking the replacement and avoiding XSS.
1166 $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 );
1167 }
1168 } elseif ( $paramType === 'after' ) {
1169 $replacementKeys[$marker . ( $n + 1 )] = $value;
1170 }
1171 }
1172 return strtr( $message, $replacementKeys );
1173 }
1174
1175 /**
1176 * Extracts the parameter type and preprocessed the value if needed.
1177 *
1178 * @since 1.18
1179 *
1180 * @param mixed $param Parameter as defined in this class.
1181 * @param string $format One of the FORMAT_* constants.
1182 *
1183 * @return array Array with the parameter type (either "before" or "after") and the value.
1184 */
1185 protected function extractParam( $param, $format ) {
1186 if ( is_array( $param ) ) {
1187 if ( isset( $param['raw'] ) ) {
1188 return [ 'after', $param['raw'] ];
1189 } elseif ( isset( $param['num'] ) ) {
1190 // Replace number params always in before step for now.
1191 // No support for combined raw and num params
1192 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1193 } elseif ( isset( $param['duration'] ) ) {
1194 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1195 } elseif ( isset( $param['expiry'] ) ) {
1196 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1197 } elseif ( isset( $param['period'] ) ) {
1198 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1199 } elseif ( isset( $param['size'] ) ) {
1200 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1201 } elseif ( isset( $param['bitrate'] ) ) {
1202 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1203 } elseif ( isset( $param['plaintext'] ) ) {
1204 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1205 } elseif ( isset( $param['list'] ) ) {
1206 return $this->formatListParam( $param['list'], $param['type'], $format );
1207 } else {
1208 if ( !is_scalar( $param ) ) {
1209 $param = serialize( $param );
1210 }
1211 LoggerFactory::getInstance( 'Bug58676' )->warning(
1212 'Invalid parameter for message "{msgkey}": {param}',
1213 [
1214 'exception' => new Exception,
1215 'msgkey' => $this->getKey(),
1216 'param' => htmlspecialchars( $param ),
1217 ]
1218 );
1219
1220 return [ 'before', '[INVALID]' ];
1221 }
1222 } elseif ( $param instanceof Message ) {
1223 // Match language, flags, etc. to the current message.
1224 $msg = clone $param;
1225 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1226 // Cache depends on these parameters
1227 $msg->message = null;
1228 }
1229 $msg->interface = $this->interface;
1230 $msg->language = $this->language;
1231 $msg->useDatabase = $this->useDatabase;
1232 $msg->title = $this->title;
1233
1234 // DWIM
1235 if ( $format === 'block-parse' ) {
1236 $format = 'parse';
1237 }
1238 $msg->format = $format;
1239
1240 // Message objects should not be before parameters because
1241 // then they'll get double escaped. If the message needs to be
1242 // escaped, it'll happen right here when we call toString().
1243 return [ 'after', $msg->toString( $format ) ];
1244 } else {
1245 return [ 'before', $param ];
1246 }
1247 }
1248
1249 /**
1250 * Wrapper for what ever method we use to parse wikitext.
1251 *
1252 * @since 1.17
1253 *
1254 * @param string $string Wikitext message contents.
1255 *
1256 * @return string Wikitext parsed into HTML.
1257 */
1258 protected function parseText( $string ) {
1259 $out = MessageCache::singleton()->parse(
1260 $string,
1261 $this->title,
1262 /*linestart*/true,
1263 $this->interface,
1264 $this->getLanguage()
1265 );
1266
1267 return $out instanceof ParserOutput
1268 ? $out->getText( [
1269 'enableSectionEditLinks' => false,
1270 // Wrapping messages in an extra <div> is probably not expected. If
1271 // they're outside the content area they probably shouldn't be
1272 // targeted by CSS that's targeting the parser output, and if
1273 // they're inside they already are from the outer div.
1274 'unwrap' => true,
1275 ] )
1276 : $out;
1277 }
1278
1279 /**
1280 * Wrapper for what ever method we use to {{-transform wikitext.
1281 *
1282 * @since 1.17
1283 *
1284 * @param string $string Wikitext message contents.
1285 *
1286 * @return string Wikitext with {{-constructs replaced with their values.
1287 */
1288 protected function transformText( $string ) {
1289 return MessageCache::singleton()->transform(
1290 $string,
1291 $this->interface,
1292 $this->getLanguage(),
1293 $this->title
1294 );
1295 }
1296
1297 /**
1298 * Wrapper for what ever method we use to get message contents.
1299 *
1300 * @since 1.17
1301 *
1302 * @return string
1303 * @throws MWException If message key array is empty.
1304 */
1305 protected function fetchMessage() {
1306 if ( $this->message === null ) {
1307 $cache = MessageCache::singleton();
1308
1309 foreach ( $this->keysToTry as $key ) {
1310 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1311 if ( $message !== false && $message !== '' ) {
1312 break;
1313 }
1314 }
1315
1316 // NOTE: The constructor makes sure keysToTry isn't empty,
1317 // so we know that $key and $message are initialized.
1318 $this->key = $key;
1319 $this->message = $message;
1320 }
1321 return $this->message;
1322 }
1323
1324 /**
1325 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1326 * the entire string is displayed unchanged when displayed in the output
1327 * format.
1328 *
1329 * @since 1.25
1330 *
1331 * @param string $plaintext String to ensure plaintext output of
1332 * @param string $format One of the FORMAT_* constants.
1333 *
1334 * @return string Input plaintext encoded for output to $format
1335 */
1336 protected function formatPlaintext( $plaintext, $format ) {
1337 switch ( $format ) {
1338 case self::FORMAT_TEXT:
1339 case self::FORMAT_PLAIN:
1340 return $plaintext;
1341
1342 case self::FORMAT_PARSE:
1343 case self::FORMAT_BLOCK_PARSE:
1344 case self::FORMAT_ESCAPED:
1345 default:
1346 return htmlspecialchars( $plaintext, ENT_QUOTES );
1347 }
1348 }
1349
1350 /**
1351 * Formats a list of parameters as a concatenated string.
1352 * @since 1.29
1353 * @param array $params
1354 * @param string $listType
1355 * @param string $format One of the FORMAT_* constants.
1356 * @return array Array with the parameter type (either "before" or "after") and the value.
1357 */
1358 protected function formatListParam( array $params, $listType, $format ) {
1359 if ( !isset( self::$listTypeMap[$listType] ) ) {
1360 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1361 . htmlspecialchars( $listType )
1362 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1363 trigger_error( $warning, E_USER_WARNING );
1364 $e = new Exception;
1365 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1366 return [ 'before', '[INVALID]' ];
1367 }
1368 $func = self::$listTypeMap[$listType];
1369
1370 // Handle an empty list sensibly
1371 if ( !$params ) {
1372 return [ 'before', $this->getLanguage()->$func( [] ) ];
1373 }
1374
1375 // First, determine what kinds of list items we have
1376 $types = [];
1377 $vars = [];
1378 $list = [];
1379 foreach ( $params as $n => $p ) {
1380 list( $type, $value ) = $this->extractParam( $p, $format );
1381 $types[$type] = true;
1382 $list[] = $value;
1383 $vars[] = '$' . ( $n + 1 );
1384 }
1385
1386 // Easy case: all are 'before' or 'after', so just join the
1387 // values and use the same type.
1388 if ( count( $types ) === 1 ) {
1389 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1390 }
1391
1392 // Hard case: We need to process each value per its type, then
1393 // return the concatenated values as 'after'. We handle this by turning
1394 // the list into a RawMessage and processing that as a parameter.
1395 $vars = $this->getLanguage()->$func( $vars );
1396 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1397 }
1398 }