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