Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / Message.php
blobfd67613e28d2ab7faf73d5e3866ff48fcf20c4bf
1 <?php
2 /**
3 * Fetching and processing of interface messages.
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.
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.
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
20 * @file
21 * @author Niklas Laxström
24 /**
25 * The Message class provides methods which fulfil two basic services:
26 * - fetching interface messages
27 * - processing messages into a variety of formats
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.
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.
37 * The most basic usage cases would be:
39 * @code
40 * // Initialize a Message object using the 'some_key' message key
41 * $message = wfMessage( 'some_key' );
43 * // Using two parameters those values are strings 'value1' and 'value2':
44 * $message = wfMessage( 'some_key',
45 * 'value1', 'value2'
46 * );
47 * @endcode
49 * @section message_global_fn Global function wrapper:
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.
55 * Fetching a message text for interface message:
57 * @code
58 * $button = Xml::button(
59 * wfMessage( 'submit' )->text()
60 * );
61 * @endcode
63 * A Message instance can be passed parameters after it has been constructed,
64 * use the params() method to do so:
66 * @code
67 * wfMessage( 'welcome-to' )
68 * ->params( $wgSitename )
69 * ->text();
70 * @endcode
72 * {{GRAMMAR}} and friends work correctly:
74 * @code
75 * wfMessage( 'are-friends',
76 * $user, $friend
77 * );
78 * wfMessage( 'bad-message' )
79 * ->rawParams( '<script>...</script>' )
80 * ->escaped();
81 * @endcode
83 * @section message_language Changing language:
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()
90 * Sometimes the message text ends up in the database, so content language is
91 * needed:
93 * @code
94 * wfMessage( 'file-log',
95 * $user, $filename
96 * )->inContentLanguage()->text();
97 * @endcode
99 * Checking whether a message exists:
101 * @code
102 * wfMessage( 'mysterious-message' )->exists()
103 * // returns a boolean whether the 'mysterious-message' key exist.
104 * @endcode
106 * If you want to use a different language:
108 * @code
109 * $userLanguage = $user->getOption( 'language' );
110 * wfMessage( 'email-header' )
111 * ->inLanguage( $userLanguage )
112 * ->plain();
113 * @endcode
115 * @note You can parse the text only in the content or interface languages
117 * @section message_compare_old Comparison with old wfMsg* functions:
119 * Use full parsing:
121 * @code
122 * // old style:
123 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
124 * // new style:
125 * wfMessage( 'key', 'apple' )->parse();
126 * @endcode
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.
131 * Places where HTML cannot be used. {{-transformation is done.
132 * @code
133 * // old style:
134 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
135 * // new style:
136 * wfMessage( 'key', 'apple', 'pear' )->text();
137 * @endcode
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
147 * @section message_appendix Appendix:
149 * @todo
150 * - test, can we have tests?
151 * - this documentation needs to be extended
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
157 * @since 1.17
159 class Message implements MessageSpecifier, Serializable {
160 /** Use message text as-is */
161 const FORMAT_PLAIN = 'plain';
162 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
163 const FORMAT_BLOCK_PARSE = 'block-parse';
164 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
165 const FORMAT_PARSE = 'parse';
166 /** Transform {{..}} constructs but don't transform to HTML */
167 const FORMAT_TEXT = 'text';
168 /** Transform {{..}} constructs, HTML-escape the result */
169 const FORMAT_ESCAPED = 'escaped';
172 * Mapping from Message::listParam() types to Language methods.
173 * @var array
175 protected static $listTypeMap = [
176 'comma' => 'commaList',
177 'semicolon' => 'semicolonList',
178 'pipe' => 'pipeList',
179 'text' => 'listToText',
183 * In which language to get this message. True, which is the default,
184 * means the current user language, false content language.
186 * @var bool
188 protected $interface = true;
191 * In which language to get this message. Overrides the $interface setting.
193 * @var Language|bool Explicit language object, or false for user language
195 protected $language = false;
198 * @var string The message key. If $keysToTry has more than one element,
199 * this may change to one of the keys to try when fetching the message text.
201 protected $key;
204 * @var string[] List of keys to try when fetching the message.
206 protected $keysToTry;
209 * @var array List of parameters which will be substituted into the message.
211 protected $parameters = [];
214 * @var string
215 * @deprecated
217 protected $format = 'parse';
220 * @var bool Whether database can be used.
222 protected $useDatabase = true;
225 * @var Title Title object to use as context.
227 protected $title = null;
230 * @var Content Content object representing the message.
232 protected $content = null;
235 * @var string
237 protected $message;
240 * @since 1.17
241 * @param string|string[]|MessageSpecifier $key Message key, or array of
242 * message keys to try and use the first non-empty message for, or a
243 * MessageSpecifier to copy from.
244 * @param array $params Message parameters.
245 * @param Language $language [optional] Language to use (defaults to current user language).
246 * @throws InvalidArgumentException
248 public function __construct( $key, $params = [], Language $language = null ) {
249 if ( $key instanceof MessageSpecifier ) {
250 if ( $params ) {
251 throw new InvalidArgumentException(
252 '$params must be empty if $key is a MessageSpecifier'
255 $params = $key->getParams();
256 $key = $key->getKey();
259 if ( !is_string( $key ) && !is_array( $key ) ) {
260 throw new InvalidArgumentException( '$key must be a string or an array' );
263 $this->keysToTry = (array)$key;
265 if ( empty( $this->keysToTry ) ) {
266 throw new InvalidArgumentException( '$key must not be an empty list' );
269 $this->key = reset( $this->keysToTry );
271 $this->parameters = array_values( $params );
272 // User language is only resolved in getLanguage(). This helps preserve the
273 // semantic intent of "user language" across serialize() and unserialize().
274 $this->language = $language ?: false;
278 * @see Serializable::serialize()
279 * @since 1.26
280 * @return string
282 public function serialize() {
283 return serialize( [
284 'interface' => $this->interface,
285 'language' => $this->language ? $this->language->getCode() : false,
286 'key' => $this->key,
287 'keysToTry' => $this->keysToTry,
288 'parameters' => $this->parameters,
289 'format' => $this->format,
290 'useDatabase' => $this->useDatabase,
291 'title' => $this->title,
292 ] );
296 * @see Serializable::unserialize()
297 * @since 1.26
298 * @param string $serialized
300 public function unserialize( $serialized ) {
301 $data = unserialize( $serialized );
302 $this->interface = $data['interface'];
303 $this->key = $data['key'];
304 $this->keysToTry = $data['keysToTry'];
305 $this->parameters = $data['parameters'];
306 $this->format = $data['format'];
307 $this->useDatabase = $data['useDatabase'];
308 $this->language = $data['language'] ? Language::factory( $data['language'] ) : false;
309 $this->title = $data['title'];
313 * @since 1.24
315 * @return bool True if this is a multi-key message, that is, if the key provided to the
316 * constructor was a fallback list of keys to try.
318 public function isMultiKey() {
319 return count( $this->keysToTry ) > 1;
323 * @since 1.24
325 * @return string[] The list of keys to try when fetching the message text,
326 * in order of preference.
328 public function getKeysToTry() {
329 return $this->keysToTry;
333 * Returns the message key.
335 * If a list of multiple possible keys was supplied to the constructor, this method may
336 * return any of these keys. After the message has been fetched, this method will return
337 * the key that was actually used to fetch the message.
339 * @since 1.21
341 * @return string
343 public function getKey() {
344 return $this->key;
348 * Returns the message parameters.
350 * @since 1.21
352 * @return array
354 public function getParams() {
355 return $this->parameters;
359 * Returns the message format.
361 * @since 1.21
363 * @return string
364 * @deprecated since 1.29 formatting is not stateful
366 public function getFormat() {
367 wfDeprecated( __METHOD__, '1.29' );
368 return $this->format;
372 * Returns the Language of the Message.
374 * @since 1.23
376 * @return Language
378 public function getLanguage() {
379 // Defaults to false which means current user language
380 return $this->language ?: RequestContext::getMain()->getLanguage();
384 * Factory function that is just wrapper for the real constructor. It is
385 * intended to be used instead of the real constructor, because it allows
386 * chaining method calls, while new objects don't.
388 * @since 1.17
390 * @param string|string[]|MessageSpecifier $key
391 * @param mixed $param,... Parameters as strings.
393 * @return Message
395 public static function newFromKey( $key /*...*/ ) {
396 $params = func_get_args();
397 array_shift( $params );
398 return new self( $key, $params );
402 * Transform a MessageSpecifier or a primitive value used interchangeably with
403 * specifiers (a message key string, or a key + params array) into a proper Message.
405 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
406 * but is an easy error to make due to how StatusValue stores messages internally.
407 * Further array elements are ignored in that case.
409 * @param string|array|MessageSpecifier $value
410 * @return Message
411 * @throws InvalidArgumentException
412 * @since 1.27
414 public static function newFromSpecifier( $value ) {
415 $params = [];
416 if ( is_array( $value ) ) {
417 $params = $value;
418 $value = array_shift( $params );
421 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
422 $message = clone( $value );
423 } elseif ( $value instanceof MessageSpecifier ) {
424 $message = new Message( $value );
425 } elseif ( is_string( $value ) ) {
426 $message = new Message( $value, $params );
427 } else {
428 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
429 . gettype( $value ) );
432 return $message;
436 * Factory function accepting multiple message keys and returning a message instance
437 * for the first message which is non-empty. If all messages are empty then an
438 * instance of the first message key is returned.
440 * @since 1.18
442 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
443 * message keys.
445 * @return Message
447 public static function newFallbackSequence( /*...*/ ) {
448 $keys = func_get_args();
449 if ( func_num_args() == 1 ) {
450 if ( is_array( $keys[0] ) ) {
451 // Allow an array to be passed as the first argument instead
452 $keys = array_values( $keys[0] );
453 } else {
454 // Optimize a single string to not need special fallback handling
455 $keys = $keys[0];
458 return new self( $keys );
462 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
463 * The title will be for the current language, if the message key is in
464 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
465 * language), because Message::inContentLanguage will also return in user language.
467 * @see $wgForceUIMsgAsContentMsg
468 * @return Title
469 * @since 1.26
471 public function getTitle() {
472 global $wgContLang, $wgForceUIMsgAsContentMsg;
474 $title = $this->key;
475 if (
476 !$this->language->equals( $wgContLang )
477 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
479 $code = $this->language->getCode();
480 $title .= '/' . $code;
483 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
487 * Adds parameters to the parameter list of this message.
489 * @since 1.17
491 * @param mixed ... Parameters as strings or arrays from
492 * Message::numParam() and the like, or a single array of parameters.
494 * @return Message $this
496 public function params( /*...*/ ) {
497 $args = func_get_args();
499 // If $args has only one entry and it's an array, then it's either a
500 // non-varargs call or it happens to be a call with just a single
501 // "special" parameter. Since the "special" parameters don't have any
502 // numeric keys, we'll test that to differentiate the cases.
503 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
504 if ( $args[0] === [] ) {
505 $args = [];
506 } else {
507 foreach ( $args[0] as $key => $value ) {
508 if ( is_int( $key ) ) {
509 $args = $args[0];
510 break;
516 $this->parameters = array_merge( $this->parameters, array_values( $args ) );
517 return $this;
521 * Add parameters that are substituted after parsing or escaping.
522 * In other words the parsing process cannot access the contents
523 * of this type of parameter, and you need to make sure it is
524 * sanitized beforehand. The parser will see "$n", instead.
526 * @since 1.17
528 * @param mixed $params,... Raw parameters as strings, or a single argument that is
529 * an array of raw parameters.
531 * @return Message $this
533 public function rawParams( /*...*/ ) {
534 $params = func_get_args();
535 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
536 $params = $params[0];
538 foreach ( $params as $param ) {
539 $this->parameters[] = self::rawParam( $param );
541 return $this;
545 * Add parameters that are numeric and will be passed through
546 * Language::formatNum before substitution
548 * @since 1.18
550 * @param mixed $param,... Numeric parameters, or a single argument that is
551 * an array of numeric parameters.
553 * @return Message $this
555 public function numParams( /*...*/ ) {
556 $params = func_get_args();
557 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
558 $params = $params[0];
560 foreach ( $params as $param ) {
561 $this->parameters[] = self::numParam( $param );
563 return $this;
567 * Add parameters that are durations of time and will be passed through
568 * Language::formatDuration before substitution
570 * @since 1.22
572 * @param int|int[] $param,... Duration parameters, or a single argument that is
573 * an array of duration parameters.
575 * @return Message $this
577 public function durationParams( /*...*/ ) {
578 $params = func_get_args();
579 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
580 $params = $params[0];
582 foreach ( $params as $param ) {
583 $this->parameters[] = self::durationParam( $param );
585 return $this;
589 * Add parameters that are expiration times and will be passed through
590 * Language::formatExpiry before substitution
592 * @since 1.22
594 * @param string|string[] $param,... Expiry parameters, or a single argument that is
595 * an array of expiry parameters.
597 * @return Message $this
599 public function expiryParams( /*...*/ ) {
600 $params = func_get_args();
601 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
602 $params = $params[0];
604 foreach ( $params as $param ) {
605 $this->parameters[] = self::expiryParam( $param );
607 return $this;
611 * Add parameters that are time periods and will be passed through
612 * Language::formatTimePeriod before substitution
614 * @since 1.22
616 * @param int|int[] $param,... Time period parameters, or a single argument that is
617 * an array of time period parameters.
619 * @return Message $this
621 public function timeperiodParams( /*...*/ ) {
622 $params = func_get_args();
623 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
624 $params = $params[0];
626 foreach ( $params as $param ) {
627 $this->parameters[] = self::timeperiodParam( $param );
629 return $this;
633 * Add parameters that are file sizes and will be passed through
634 * Language::formatSize before substitution
636 * @since 1.22
638 * @param int|int[] $param,... Size parameters, or a single argument that is
639 * an array of size parameters.
641 * @return Message $this
643 public function sizeParams( /*...*/ ) {
644 $params = func_get_args();
645 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
646 $params = $params[0];
648 foreach ( $params as $param ) {
649 $this->parameters[] = self::sizeParam( $param );
651 return $this;
655 * Add parameters that are bitrates and will be passed through
656 * Language::formatBitrate before substitution
658 * @since 1.22
660 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
661 * an array of bit rate parameters.
663 * @return Message $this
665 public function bitrateParams( /*...*/ ) {
666 $params = func_get_args();
667 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
668 $params = $params[0];
670 foreach ( $params as $param ) {
671 $this->parameters[] = self::bitrateParam( $param );
673 return $this;
677 * Add parameters that are plaintext and will be passed through without
678 * the content being evaluated. Plaintext parameters are not valid as
679 * arguments to parser functions. This differs from self::rawParams in
680 * that the Message class handles escaping to match the output format.
682 * @since 1.25
684 * @param string|string[] $param,... plaintext parameters, or a single argument that is
685 * an array of plaintext parameters.
687 * @return Message $this
689 public function plaintextParams( /*...*/ ) {
690 $params = func_get_args();
691 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
692 $params = $params[0];
694 foreach ( $params as $param ) {
695 $this->parameters[] = self::plaintextParam( $param );
697 return $this;
701 * Set the language and the title from a context object
703 * @since 1.19
705 * @param IContextSource $context
707 * @return Message $this
709 public function setContext( IContextSource $context ) {
710 $this->inLanguage( $context->getLanguage() );
711 $this->title( $context->getTitle() );
712 $this->interface = true;
714 return $this;
718 * Request the message in any language that is supported.
720 * As a side effect interface message status is unconditionally
721 * turned off.
723 * @since 1.17
724 * @param Language|string $lang Language code or Language object.
725 * @return Message $this
726 * @throws MWException
728 public function inLanguage( $lang ) {
729 if ( $lang instanceof Language ) {
730 $this->language = $lang;
731 } elseif ( is_string( $lang ) ) {
732 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
733 $this->language = Language::factory( $lang );
735 } elseif ( $lang instanceof StubUserLang ) {
736 $this->language = false;
737 } else {
738 $type = gettype( $lang );
739 throw new MWException( __METHOD__ . " must be "
740 . "passed a String or Language object; $type given"
743 $this->message = null;
744 $this->interface = false;
745 return $this;
749 * Request the message in the wiki's content language,
750 * unless it is disabled for this message.
752 * @since 1.17
753 * @see $wgForceUIMsgAsContentMsg
755 * @return Message $this
757 public function inContentLanguage() {
758 global $wgForceUIMsgAsContentMsg;
759 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
760 return $this;
763 global $wgContLang;
764 $this->inLanguage( $wgContLang );
765 return $this;
769 * Allows manipulating the interface message flag directly.
770 * Can be used to restore the flag after setting a language.
772 * @since 1.20
774 * @param bool $interface
776 * @return Message $this
778 public function setInterfaceMessageFlag( $interface ) {
779 $this->interface = (bool)$interface;
780 return $this;
784 * Enable or disable database use.
786 * @since 1.17
788 * @param bool $useDatabase
790 * @return Message $this
792 public function useDatabase( $useDatabase ) {
793 $this->useDatabase = (bool)$useDatabase;
794 $this->message = null;
795 return $this;
799 * Set the Title object to use as context when transforming the message
801 * @since 1.18
803 * @param Title $title
805 * @return Message $this
807 public function title( $title ) {
808 $this->title = $title;
809 return $this;
813 * Returns the message as a Content object.
815 * @return Content
817 public function content() {
818 if ( !$this->content ) {
819 $this->content = new MessageContent( $this );
822 return $this->content;
826 * Returns the message parsed from wikitext to HTML.
828 * @since 1.17
830 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
831 * the last time (this is for B/C and should be avoided).
833 * @return string HTML
835 public function toString( $format = null ) {
836 if ( $format === null ) {
837 $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format );
838 \MediaWiki\Logger\LoggerFactory::getInstance( 'message-format' )->warning(
839 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] );
840 $format = $this->format;
842 $string = $this->fetchMessage();
844 if ( $string === false ) {
845 // Err on the side of safety, ensure that the output
846 // is always html safe in the event the message key is
847 // missing, since in that case its highly likely the
848 // message key is user-controlled.
849 // '⧼' is used instead of '<' to side-step any
850 // double-escaping issues.
851 // (Keep synchronised with mw.Message#toString in JS.)
852 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
855 # Replace $* with a list of parameters for &uselang=qqx.
856 if ( strpos( $string, '$*' ) !== false ) {
857 $paramlist = '';
858 if ( $this->parameters !== [] ) {
859 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
861 $string = str_replace( '$*', $paramlist, $string );
864 # Replace parameters before text parsing
865 $string = $this->replaceParameters( $string, 'before', $format );
867 # Maybe transform using the full parser
868 if ( $format === self::FORMAT_PARSE ) {
869 $string = $this->parseText( $string );
870 $string = Parser::stripOuterParagraph( $string );
871 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
872 $string = $this->parseText( $string );
873 } elseif ( $format === self::FORMAT_TEXT ) {
874 $string = $this->transformText( $string );
875 } elseif ( $format === self::FORMAT_ESCAPED ) {
876 $string = $this->transformText( $string );
877 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
880 # Raw parameter replacement
881 $string = $this->replaceParameters( $string, 'after', $format );
883 return $string;
887 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
888 * $foo = new Message( $key );
889 * $string = "<abbr>$foo</abbr>";
891 * @since 1.18
893 * @return string
895 public function __toString() {
896 // PHP doesn't allow __toString to throw exceptions and will
897 // trigger a fatal error if it does. So, catch any exceptions.
899 try {
900 return $this->toString( self::FORMAT_PARSE );
901 } catch ( Exception $ex ) {
902 try {
903 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
904 . $ex, E_USER_WARNING );
905 } catch ( Exception $ex ) {
906 // Doh! Cause a fatal error after all?
909 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
914 * Fully parse the text from wikitext to HTML.
916 * @since 1.17
918 * @return string Parsed HTML.
920 public function parse() {
921 $this->format = self::FORMAT_PARSE;
922 return $this->toString( self::FORMAT_PARSE );
926 * Returns the message text. {{-transformation is done.
928 * @since 1.17
930 * @return string Unescaped message text.
932 public function text() {
933 $this->format = self::FORMAT_TEXT;
934 return $this->toString( self::FORMAT_TEXT );
938 * Returns the message text as-is, only parameters are substituted.
940 * @since 1.17
942 * @return string Unescaped untransformed message text.
944 public function plain() {
945 $this->format = self::FORMAT_PLAIN;
946 return $this->toString( self::FORMAT_PLAIN );
950 * Returns the parsed message text which is always surrounded by a block element.
952 * @since 1.17
954 * @return string HTML
956 public function parseAsBlock() {
957 $this->format = self::FORMAT_BLOCK_PARSE;
958 return $this->toString( self::FORMAT_BLOCK_PARSE );
962 * Returns the message text. {{-transformation is done and the result
963 * is escaped excluding any raw parameters.
965 * @since 1.17
967 * @return string Escaped message text.
969 public function escaped() {
970 $this->format = self::FORMAT_ESCAPED;
971 return $this->toString( self::FORMAT_ESCAPED );
975 * Check whether a message key has been defined currently.
977 * @since 1.17
979 * @return bool
981 public function exists() {
982 return $this->fetchMessage() !== false;
986 * Check whether a message does not exist, or is an empty string
988 * @since 1.18
989 * @todo FIXME: Merge with isDisabled()?
991 * @return bool
993 public function isBlank() {
994 $message = $this->fetchMessage();
995 return $message === false || $message === '';
999 * Check whether a message does not exist, is an empty string, or is "-".
1001 * @since 1.18
1003 * @return bool
1005 public function isDisabled() {
1006 $message = $this->fetchMessage();
1007 return $message === false || $message === '' || $message === '-';
1011 * @since 1.17
1013 * @param mixed $raw
1015 * @return array Array with a single "raw" key.
1017 public static function rawParam( $raw ) {
1018 return [ 'raw' => $raw ];
1022 * @since 1.18
1024 * @param mixed $num
1026 * @return array Array with a single "num" key.
1028 public static function numParam( $num ) {
1029 return [ 'num' => $num ];
1033 * @since 1.22
1035 * @param int $duration
1037 * @return int[] Array with a single "duration" key.
1039 public static function durationParam( $duration ) {
1040 return [ 'duration' => $duration ];
1044 * @since 1.22
1046 * @param string $expiry
1048 * @return string[] Array with a single "expiry" key.
1050 public static function expiryParam( $expiry ) {
1051 return [ 'expiry' => $expiry ];
1055 * @since 1.22
1057 * @param int $period
1059 * @return int[] Array with a single "period" key.
1061 public static function timeperiodParam( $period ) {
1062 return [ 'period' => $period ];
1066 * @since 1.22
1068 * @param int $size
1070 * @return int[] Array with a single "size" key.
1072 public static function sizeParam( $size ) {
1073 return [ 'size' => $size ];
1077 * @since 1.22
1079 * @param int $bitrate
1081 * @return int[] Array with a single "bitrate" key.
1083 public static function bitrateParam( $bitrate ) {
1084 return [ 'bitrate' => $bitrate ];
1088 * @since 1.25
1090 * @param string $plaintext
1092 * @return string[] Array with a single "plaintext" key.
1094 public static function plaintextParam( $plaintext ) {
1095 return [ 'plaintext' => $plaintext ];
1099 * @since 1.29
1101 * @param array $list
1102 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1103 * @return array Array with "list" and "type" keys.
1105 public static function listParam( array $list, $type = 'text' ) {
1106 if ( !isset( self::$listTypeMap[$type] ) ) {
1107 throw new InvalidArgumentException(
1108 "Invalid type '$type'. Known types are: " . join( ', ', array_keys( self::$listTypeMap ) )
1111 return [ 'list' => $list, 'type' => $type ];
1115 * Substitutes any parameters into the message text.
1117 * @since 1.17
1119 * @param string $message The message text.
1120 * @param string $type Either "before" or "after".
1121 * @param string $format One of the FORMAT_* constants.
1123 * @return string
1125 protected function replaceParameters( $message, $type = 'before', $format ) {
1126 $replacementKeys = [];
1127 foreach ( $this->parameters as $n => $param ) {
1128 list( $paramType, $value ) = $this->extractParam( $param, $format );
1129 if ( $type === $paramType ) {
1130 $replacementKeys['$' . ( $n + 1 )] = $value;
1133 $message = strtr( $message, $replacementKeys );
1134 return $message;
1138 * Extracts the parameter type and preprocessed the value if needed.
1140 * @since 1.18
1142 * @param mixed $param Parameter as defined in this class.
1143 * @param string $format One of the FORMAT_* constants.
1145 * @return array Array with the parameter type (either "before" or "after") and the value.
1147 protected function extractParam( $param, $format ) {
1148 if ( is_array( $param ) ) {
1149 if ( isset( $param['raw'] ) ) {
1150 return [ 'after', $param['raw'] ];
1151 } elseif ( isset( $param['num'] ) ) {
1152 // Replace number params always in before step for now.
1153 // No support for combined raw and num params
1154 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1155 } elseif ( isset( $param['duration'] ) ) {
1156 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1157 } elseif ( isset( $param['expiry'] ) ) {
1158 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1159 } elseif ( isset( $param['period'] ) ) {
1160 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1161 } elseif ( isset( $param['size'] ) ) {
1162 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1163 } elseif ( isset( $param['bitrate'] ) ) {
1164 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1165 } elseif ( isset( $param['plaintext'] ) ) {
1166 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1167 } elseif ( isset( $param['list'] ) ) {
1168 return $this->formatListParam( $param['list'], $param['type'], $format );
1169 } else {
1170 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
1171 htmlspecialchars( serialize( $param ) );
1172 trigger_error( $warning, E_USER_WARNING );
1173 $e = new Exception;
1174 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1176 return [ 'before', '[INVALID]' ];
1178 } elseif ( $param instanceof Message ) {
1179 // Match language, flags, etc. to the current message.
1180 $msg = clone $param;
1181 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1182 // Cache depends on these parameters
1183 $msg->message = null;
1185 $msg->interface = $this->interface;
1186 $msg->language = $this->language;
1187 $msg->useDatabase = $this->useDatabase;
1188 $msg->title = $this->title;
1190 // DWIM
1191 if ( $format === 'block-parse' ) {
1192 $format = 'parse';
1194 $msg->format = $format;
1196 // Message objects should not be before parameters because
1197 // then they'll get double escaped. If the message needs to be
1198 // escaped, it'll happen right here when we call toString().
1199 return [ 'after', $msg->toString( $format ) ];
1200 } else {
1201 return [ 'before', $param ];
1206 * Wrapper for what ever method we use to parse wikitext.
1208 * @since 1.17
1210 * @param string $string Wikitext message contents.
1212 * @return string Wikitext parsed into HTML.
1214 protected function parseText( $string ) {
1215 $out = MessageCache::singleton()->parse(
1216 $string,
1217 $this->title,
1218 /*linestart*/true,
1219 $this->interface,
1220 $this->getLanguage()
1223 return $out instanceof ParserOutput ? $out->getText() : $out;
1227 * Wrapper for what ever method we use to {{-transform wikitext.
1229 * @since 1.17
1231 * @param string $string Wikitext message contents.
1233 * @return string Wikitext with {{-constructs replaced with their values.
1235 protected function transformText( $string ) {
1236 return MessageCache::singleton()->transform(
1237 $string,
1238 $this->interface,
1239 $this->getLanguage(),
1240 $this->title
1245 * Wrapper for what ever method we use to get message contents.
1247 * @since 1.17
1249 * @return string
1250 * @throws MWException If message key array is empty.
1252 protected function fetchMessage() {
1253 if ( $this->message === null ) {
1254 $cache = MessageCache::singleton();
1256 foreach ( $this->keysToTry as $key ) {
1257 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1258 if ( $message !== false && $message !== '' ) {
1259 break;
1263 // NOTE: The constructor makes sure keysToTry isn't empty,
1264 // so we know that $key and $message are initialized.
1265 $this->key = $key;
1266 $this->message = $message;
1268 return $this->message;
1272 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1273 * the entire string is displayed unchanged when displayed in the output
1274 * format.
1276 * @since 1.25
1278 * @param string $plaintext String to ensure plaintext output of
1279 * @param string $format One of the FORMAT_* constants.
1281 * @return string Input plaintext encoded for output to $format
1283 protected function formatPlaintext( $plaintext, $format ) {
1284 switch ( $format ) {
1285 case self::FORMAT_TEXT:
1286 case self::FORMAT_PLAIN:
1287 return $plaintext;
1289 case self::FORMAT_PARSE:
1290 case self::FORMAT_BLOCK_PARSE:
1291 case self::FORMAT_ESCAPED:
1292 default:
1293 return htmlspecialchars( $plaintext, ENT_QUOTES );
1299 * Formats a list of parameters as a concatenated string.
1300 * @since 1.29
1301 * @param array $params
1302 * @param string $listType
1303 * @param string $format One of the FORMAT_* constants.
1304 * @return array Array with the parameter type (either "before" or "after") and the value.
1306 protected function formatListParam( array $params, $listType, $format ) {
1307 if ( !isset( self::$listTypeMap[$listType] ) ) {
1308 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1309 . htmlspecialchars( $listType )
1310 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1311 trigger_error( $warning, E_USER_WARNING );
1312 $e = new Exception;
1313 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1314 return [ 'before', '[INVALID]' ];
1316 $func = self::$listTypeMap[$listType];
1318 // Handle an empty list sensibly
1319 if ( !$params ) {
1320 return [ 'before', $this->getLanguage()->$func( [] ) ];
1323 // First, determine what kinds of list items we have
1324 $types = [];
1325 $vars = [];
1326 $list = [];
1327 foreach ( $params as $n => $p ) {
1328 list( $type, $value ) = $this->extractParam( $p, $format );
1329 $types[$type] = true;
1330 $list[] = $value;
1331 $vars[] = '$' . ( $n + 1 );
1334 // Easy case: all are 'before' or 'after', so just join the
1335 // values and use the same type.
1336 if ( count( $types ) === 1 ) {
1337 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1340 // Hard case: We need to process each value per its type, then
1341 // return the concatenated values as 'after'. We handle this by turning
1342 // the list into a RawMessage and processing that as a parameter.
1343 $vars = $this->getLanguage()->$func( $vars );
1344 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1349 * Variant of the Message class.
1351 * Rather than treating the message key as a lookup
1352 * value (which is passed to the MessageCache and
1353 * translated as necessary), a RawMessage key is
1354 * treated as the actual message.
1356 * All other functionality (parsing, escaping, etc.)
1357 * is preserved.
1359 * @since 1.21
1361 class RawMessage extends Message {
1364 * Call the parent constructor, then store the key as
1365 * the message.
1367 * @see Message::__construct
1369 * @param string $text Message to use.
1370 * @param array $params Parameters for the message.
1372 * @throws InvalidArgumentException
1374 public function __construct( $text, $params = [] ) {
1375 if ( !is_string( $text ) ) {
1376 throw new InvalidArgumentException( '$text must be a string' );
1379 parent::__construct( $text, $params );
1381 // The key is the message.
1382 $this->message = $text;
1386 * Fetch the message (in this case, the key).
1388 * @return string
1390 public function fetchMessage() {
1391 // Just in case the message is unset somewhere.
1392 if ( $this->message === null ) {
1393 $this->message = $this->key;
1396 return $this->message;