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