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