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