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