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