Fix ApiBase::getErrorFromStatus() and ApiMessages
[mediawiki.git] / includes / Message.php
blobc7752aac240b549a28663b9f99735d62f57c7d4f
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', array( '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', array( '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 {
162 * In which language to get this message. True, which is the default,
163 * means the current user language, false content language.
165 * @var bool
167 protected $interface = true;
170 * In which language to get this message. Overrides the $interface setting.
172 * @var Language|bool Explicit language object, or false for user language
174 protected $language = false;
177 * @var string The message key. If $keysToTry has more than one element,
178 * this may change to one of the keys to try when fetching the message text.
180 protected $key;
183 * @var string[] List of keys to try when fetching the message.
185 protected $keysToTry;
188 * @var array List of parameters which will be substituted into the message.
190 protected $parameters = [];
193 * Format for the message.
194 * Supported formats are:
195 * * text (transform)
196 * * escaped (transform+htmlspecialchars)
197 * * block-parse
198 * * parse (default)
199 * * plain
201 * @var string
203 protected $format = 'parse';
206 * @var bool Whether database can be used.
208 protected $useDatabase = true;
211 * @var Title Title object to use as context.
213 protected $title = null;
216 * @var Content Content object representing the message.
218 protected $content = null;
221 * @var string
223 protected $message;
226 * @since 1.17
227 * @param string|string[]|MessageSpecifier $key Message key, or array of
228 * message keys to try and use the first non-empty message for, or a
229 * MessageSpecifier to copy from.
230 * @param array $params Message parameters.
231 * @param Language $language [optional] Language to use (defaults to current user language).
232 * @throws InvalidArgumentException
234 public function __construct( $key, $params = [], Language $language = null ) {
235 if ( $key instanceof MessageSpecifier ) {
236 if ( $params ) {
237 throw new InvalidArgumentException(
238 '$params must be empty if $key is a MessageSpecifier'
241 $params = $key->getParams();
242 $key = $key->getKey();
245 if ( !is_string( $key ) && !is_array( $key ) ) {
246 throw new InvalidArgumentException( '$key must be a string or an array' );
249 $this->keysToTry = (array)$key;
251 if ( empty( $this->keysToTry ) ) {
252 throw new InvalidArgumentException( '$key must not be an empty list' );
255 $this->key = reset( $this->keysToTry );
257 $this->parameters = array_values( $params );
258 // User language is only resolved in getLanguage(). This helps preserve the
259 // semantic intent of "user language" across serialize() and unserialize().
260 $this->language = $language ?: false;
264 * @see Serializable::serialize()
265 * @since 1.26
266 * @return string
268 public function serialize() {
269 return serialize( [
270 'interface' => $this->interface,
271 'language' => $this->language ? $this->language->getCode() : false,
272 'key' => $this->key,
273 'keysToTry' => $this->keysToTry,
274 'parameters' => $this->parameters,
275 'format' => $this->format,
276 'useDatabase' => $this->useDatabase,
277 'title' => $this->title,
278 ] );
282 * @see Serializable::unserialize()
283 * @since 1.26
284 * @param string $serialized
286 public function unserialize( $serialized ) {
287 $data = unserialize( $serialized );
288 $this->interface = $data['interface'];
289 $this->key = $data['key'];
290 $this->keysToTry = $data['keysToTry'];
291 $this->parameters = $data['parameters'];
292 $this->format = $data['format'];
293 $this->useDatabase = $data['useDatabase'];
294 $this->language = $data['language'] ? Language::factory( $data['language'] ) : false;
295 $this->title = $data['title'];
299 * @since 1.24
301 * @return bool True if this is a multi-key message, that is, if the key provided to the
302 * constructor was a fallback list of keys to try.
304 public function isMultiKey() {
305 return count( $this->keysToTry ) > 1;
309 * @since 1.24
311 * @return string[] The list of keys to try when fetching the message text,
312 * in order of preference.
314 public function getKeysToTry() {
315 return $this->keysToTry;
319 * Returns the message key.
321 * If a list of multiple possible keys was supplied to the constructor, this method may
322 * return any of these keys. After the message has been fetched, this method will return
323 * the key that was actually used to fetch the message.
325 * @since 1.21
327 * @return string
329 public function getKey() {
330 return $this->key;
334 * Returns the message parameters.
336 * @since 1.21
338 * @return array
340 public function getParams() {
341 return $this->parameters;
345 * Returns the message format.
347 * @since 1.21
349 * @return string
351 public function getFormat() {
352 return $this->format;
356 * Returns the Language of the Message.
358 * @since 1.23
360 * @return Language
362 public function getLanguage() {
363 // Defaults to false which means current user language
364 return $this->language ?: RequestContext::getMain()->getLanguage();
368 * Factory function that is just wrapper for the real constructor. It is
369 * intended to be used instead of the real constructor, because it allows
370 * chaining method calls, while new objects don't.
372 * @since 1.17
374 * @param string|string[]|MessageSpecifier $key
375 * @param mixed $param,... Parameters as strings.
377 * @return Message
379 public static function newFromKey( $key /*...*/ ) {
380 $params = func_get_args();
381 array_shift( $params );
382 return new self( $key, $params );
386 * Transform a MessageSpecifier or a primitive value used interchangeably with
387 * specifiers (a message key string, or a key + params array) into a proper Message
388 * @param string|array|MessageSpecifier $value
389 * @return Message
390 * @throws InvalidArgumentException
391 * @since 1.27
393 public static function newFromSpecifier( $value ) {
394 if ( $value instanceof RawMessage ) {
395 $message = new RawMessage( $value->getKey(), $value->getParams() );
396 } elseif ( $value instanceof MessageSpecifier ) {
397 $message = new Message( $value );
398 } elseif ( is_array( $value ) ) {
399 $key = array_shift( $value );
400 $message = new Message( $key, $value );
401 } elseif ( is_string( $value ) ) {
402 $message = new Message( $value );
403 } else {
404 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
405 . gettype( $value ) );
408 return $message;
412 * Factory function accepting multiple message keys and returning a message instance
413 * for the first message which is non-empty. If all messages are empty then an
414 * instance of the first message key is returned.
416 * @since 1.18
418 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
419 * message keys.
421 * @return Message
423 public static function newFallbackSequence( /*...*/ ) {
424 $keys = func_get_args();
425 if ( func_num_args() == 1 ) {
426 if ( is_array( $keys[0] ) ) {
427 // Allow an array to be passed as the first argument instead
428 $keys = array_values( $keys[0] );
429 } else {
430 // Optimize a single string to not need special fallback handling
431 $keys = $keys[0];
434 return new self( $keys );
438 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
439 * The title will be for the current language, if the message key is in
440 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
441 * language), because Message::inContentLanguage will also return in user language.
443 * @see $wgForceUIMsgAsContentMsg
444 * @return Title
445 * @since 1.26
447 public function getTitle() {
448 global $wgContLang, $wgForceUIMsgAsContentMsg;
450 $code = $this->getLanguage()->getCode();
451 $title = $this->key;
452 if (
453 $wgContLang->getCode() !== $code
454 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
456 $title .= '/' . $code;
459 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
463 * Adds parameters to the parameter list of this message.
465 * @since 1.17
467 * @param mixed ... Parameters as strings, or a single argument that is
468 * an array of strings.
470 * @return Message $this
472 public function params( /*...*/ ) {
473 $args = func_get_args();
474 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
475 $args = $args[0];
477 $args_values = array_values( $args );
478 $this->parameters = array_merge( $this->parameters, $args_values );
479 return $this;
483 * Add parameters that are substituted after parsing or escaping.
484 * In other words the parsing process cannot access the contents
485 * of this type of parameter, and you need to make sure it is
486 * sanitized beforehand. The parser will see "$n", instead.
488 * @since 1.17
490 * @param mixed $params,... Raw parameters as strings, or a single argument that is
491 * an array of raw parameters.
493 * @return Message $this
495 public function rawParams( /*...*/ ) {
496 $params = func_get_args();
497 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
498 $params = $params[0];
500 foreach ( $params as $param ) {
501 $this->parameters[] = self::rawParam( $param );
503 return $this;
507 * Add parameters that are numeric and will be passed through
508 * Language::formatNum before substitution
510 * @since 1.18
512 * @param mixed $param,... Numeric parameters, or a single argument that is
513 * an array of numeric parameters.
515 * @return Message $this
517 public function numParams( /*...*/ ) {
518 $params = func_get_args();
519 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
520 $params = $params[0];
522 foreach ( $params as $param ) {
523 $this->parameters[] = self::numParam( $param );
525 return $this;
529 * Add parameters that are durations of time and will be passed through
530 * Language::formatDuration before substitution
532 * @since 1.22
534 * @param int|int[] $param,... Duration parameters, or a single argument that is
535 * an array of duration parameters.
537 * @return Message $this
539 public function durationParams( /*...*/ ) {
540 $params = func_get_args();
541 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
542 $params = $params[0];
544 foreach ( $params as $param ) {
545 $this->parameters[] = self::durationParam( $param );
547 return $this;
551 * Add parameters that are expiration times and will be passed through
552 * Language::formatExpiry before substitution
554 * @since 1.22
556 * @param string|string[] $param,... Expiry parameters, or a single argument that is
557 * an array of expiry parameters.
559 * @return Message $this
561 public function expiryParams( /*...*/ ) {
562 $params = func_get_args();
563 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
564 $params = $params[0];
566 foreach ( $params as $param ) {
567 $this->parameters[] = self::expiryParam( $param );
569 return $this;
573 * Add parameters that are time periods and will be passed through
574 * Language::formatTimePeriod before substitution
576 * @since 1.22
578 * @param int|int[] $param,... Time period parameters, or a single argument that is
579 * an array of time period parameters.
581 * @return Message $this
583 public function timeperiodParams( /*...*/ ) {
584 $params = func_get_args();
585 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
586 $params = $params[0];
588 foreach ( $params as $param ) {
589 $this->parameters[] = self::timeperiodParam( $param );
591 return $this;
595 * Add parameters that are file sizes and will be passed through
596 * Language::formatSize before substitution
598 * @since 1.22
600 * @param int|int[] $param,... Size parameters, or a single argument that is
601 * an array of size parameters.
603 * @return Message $this
605 public function sizeParams( /*...*/ ) {
606 $params = func_get_args();
607 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
608 $params = $params[0];
610 foreach ( $params as $param ) {
611 $this->parameters[] = self::sizeParam( $param );
613 return $this;
617 * Add parameters that are bitrates and will be passed through
618 * Language::formatBitrate before substitution
620 * @since 1.22
622 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
623 * an array of bit rate parameters.
625 * @return Message $this
627 public function bitrateParams( /*...*/ ) {
628 $params = func_get_args();
629 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
630 $params = $params[0];
632 foreach ( $params as $param ) {
633 $this->parameters[] = self::bitrateParam( $param );
635 return $this;
639 * Add parameters that are plaintext and will be passed through without
640 * the content being evaluated. Plaintext parameters are not valid as
641 * arguments to parser functions. This differs from self::rawParams in
642 * that the Message class handles escaping to match the output format.
644 * @since 1.25
646 * @param string|string[] $param,... plaintext parameters, or a single argument that is
647 * an array of plaintext parameters.
649 * @return Message $this
651 public function plaintextParams( /*...*/ ) {
652 $params = func_get_args();
653 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
654 $params = $params[0];
656 foreach ( $params as $param ) {
657 $this->parameters[] = self::plaintextParam( $param );
659 return $this;
663 * Set the language and the title from a context object
665 * @since 1.19
667 * @param IContextSource $context
669 * @return Message $this
671 public function setContext( IContextSource $context ) {
672 $this->inLanguage( $context->getLanguage() );
673 $this->title( $context->getTitle() );
674 $this->interface = true;
676 return $this;
680 * Request the message in any language that is supported.
682 * As a side effect interface message status is unconditionally
683 * turned off.
685 * @since 1.17
686 * @param Language|string $lang Language code or Language object.
687 * @return Message $this
688 * @throws MWException
690 public function inLanguage( $lang ) {
691 if ( $lang instanceof Language ) {
692 $this->language = $lang;
693 } elseif ( is_string( $lang ) ) {
694 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
695 $this->language = Language::factory( $lang );
697 } elseif ( $lang instanceof StubUserLang ) {
698 $this->language = false;
699 } else {
700 $type = gettype( $lang );
701 throw new MWException( __METHOD__ . " must be "
702 . "passed a String or Language object; $type given"
705 $this->message = null;
706 $this->interface = false;
707 return $this;
711 * Request the message in the wiki's content language,
712 * unless it is disabled for this message.
714 * @since 1.17
715 * @see $wgForceUIMsgAsContentMsg
717 * @return Message $this
719 public function inContentLanguage() {
720 global $wgForceUIMsgAsContentMsg;
721 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
722 return $this;
725 global $wgContLang;
726 $this->inLanguage( $wgContLang );
727 return $this;
731 * Allows manipulating the interface message flag directly.
732 * Can be used to restore the flag after setting a language.
734 * @since 1.20
736 * @param bool $interface
738 * @return Message $this
740 public function setInterfaceMessageFlag( $interface ) {
741 $this->interface = (bool)$interface;
742 return $this;
746 * Enable or disable database use.
748 * @since 1.17
750 * @param bool $useDatabase
752 * @return Message $this
754 public function useDatabase( $useDatabase ) {
755 $this->useDatabase = (bool)$useDatabase;
756 return $this;
760 * Set the Title object to use as context when transforming the message
762 * @since 1.18
764 * @param Title $title
766 * @return Message $this
768 public function title( $title ) {
769 $this->title = $title;
770 return $this;
774 * Returns the message as a Content object.
776 * @return Content
778 public function content() {
779 if ( !$this->content ) {
780 $this->content = new MessageContent( $this );
783 return $this->content;
787 * Returns the message parsed from wikitext to HTML.
789 * @since 1.17
791 * @return string HTML
793 public function toString() {
794 $string = $this->fetchMessage();
796 if ( $string === false ) {
797 if ( $this->format === 'plain' || $this->format === 'text' ) {
798 return '<' . $this->key . '>';
800 return '&lt;' . htmlspecialchars( $this->key ) . '&gt;';
803 # Replace $* with a list of parameters for &uselang=qqx.
804 if ( strpos( $string, '$*' ) !== false ) {
805 $paramlist = '';
806 if ( $this->parameters !== [] ) {
807 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
809 $string = str_replace( '$*', $paramlist, $string );
812 # Replace parameters before text parsing
813 $string = $this->replaceParameters( $string, 'before' );
815 # Maybe transform using the full parser
816 if ( $this->format === 'parse' ) {
817 $string = $this->parseText( $string );
818 $string = Parser::stripOuterParagraph( $string );
819 } elseif ( $this->format === 'block-parse' ) {
820 $string = $this->parseText( $string );
821 } elseif ( $this->format === 'text' ) {
822 $string = $this->transformText( $string );
823 } elseif ( $this->format === 'escaped' ) {
824 $string = $this->transformText( $string );
825 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
828 # Raw parameter replacement
829 $string = $this->replaceParameters( $string, 'after' );
831 return $string;
835 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
836 * $foo = new Message( $key );
837 * $string = "<abbr>$foo</abbr>";
839 * @since 1.18
841 * @return string
843 public function __toString() {
844 // PHP doesn't allow __toString to throw exceptions and will
845 // trigger a fatal error if it does. So, catch any exceptions.
847 try {
848 return $this->toString();
849 } catch ( Exception $ex ) {
850 try {
851 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
852 . $ex, E_USER_WARNING );
853 } catch ( Exception $ex ) {
854 // Doh! Cause a fatal error after all?
857 if ( $this->format === 'plain' || $this->format === 'text' ) {
858 return '<' . $this->key . '>';
860 return '&lt;' . htmlspecialchars( $this->key ) . '&gt;';
865 * Fully parse the text from wikitext to HTML.
867 * @since 1.17
869 * @return string Parsed HTML.
871 public function parse() {
872 $this->format = 'parse';
873 return $this->toString();
877 * Returns the message text. {{-transformation is done.
879 * @since 1.17
881 * @return string Unescaped message text.
883 public function text() {
884 $this->format = 'text';
885 return $this->toString();
889 * Returns the message text as-is, only parameters are substituted.
891 * @since 1.17
893 * @return string Unescaped untransformed message text.
895 public function plain() {
896 $this->format = 'plain';
897 return $this->toString();
901 * Returns the parsed message text which is always surrounded by a block element.
903 * @since 1.17
905 * @return string HTML
907 public function parseAsBlock() {
908 $this->format = 'block-parse';
909 return $this->toString();
913 * Returns the message text. {{-transformation is done and the result
914 * is escaped excluding any raw parameters.
916 * @since 1.17
918 * @return string Escaped message text.
920 public function escaped() {
921 $this->format = 'escaped';
922 return $this->toString();
926 * Check whether a message key has been defined currently.
928 * @since 1.17
930 * @return bool
932 public function exists() {
933 return $this->fetchMessage() !== false;
937 * Check whether a message does not exist, or is an empty string
939 * @since 1.18
940 * @todo FIXME: Merge with isDisabled()?
942 * @return bool
944 public function isBlank() {
945 $message = $this->fetchMessage();
946 return $message === false || $message === '';
950 * Check whether a message does not exist, is an empty string, or is "-".
952 * @since 1.18
954 * @return bool
956 public function isDisabled() {
957 $message = $this->fetchMessage();
958 return $message === false || $message === '' || $message === '-';
962 * @since 1.17
964 * @param mixed $raw
966 * @return array Array with a single "raw" key.
968 public static function rawParam( $raw ) {
969 return [ 'raw' => $raw ];
973 * @since 1.18
975 * @param mixed $num
977 * @return array Array with a single "num" key.
979 public static function numParam( $num ) {
980 return [ 'num' => $num ];
984 * @since 1.22
986 * @param int $duration
988 * @return int[] Array with a single "duration" key.
990 public static function durationParam( $duration ) {
991 return [ 'duration' => $duration ];
995 * @since 1.22
997 * @param string $expiry
999 * @return string[] Array with a single "expiry" key.
1001 public static function expiryParam( $expiry ) {
1002 return [ 'expiry' => $expiry ];
1006 * @since 1.22
1008 * @param number $period
1010 * @return number[] Array with a single "period" key.
1012 public static function timeperiodParam( $period ) {
1013 return [ 'period' => $period ];
1017 * @since 1.22
1019 * @param int $size
1021 * @return int[] Array with a single "size" key.
1023 public static function sizeParam( $size ) {
1024 return [ 'size' => $size ];
1028 * @since 1.22
1030 * @param int $bitrate
1032 * @return int[] Array with a single "bitrate" key.
1034 public static function bitrateParam( $bitrate ) {
1035 return [ 'bitrate' => $bitrate ];
1039 * @since 1.25
1041 * @param string $plaintext
1043 * @return string[] Array with a single "plaintext" key.
1045 public static function plaintextParam( $plaintext ) {
1046 return [ 'plaintext' => $plaintext ];
1050 * Substitutes any parameters into the message text.
1052 * @since 1.17
1054 * @param string $message The message text.
1055 * @param string $type Either "before" or "after".
1057 * @return string
1059 protected function replaceParameters( $message, $type = 'before' ) {
1060 $replacementKeys = [];
1061 foreach ( $this->parameters as $n => $param ) {
1062 list( $paramType, $value ) = $this->extractParam( $param );
1063 if ( $type === $paramType ) {
1064 $replacementKeys['$' . ( $n + 1 )] = $value;
1067 $message = strtr( $message, $replacementKeys );
1068 return $message;
1072 * Extracts the parameter type and preprocessed the value if needed.
1074 * @since 1.18
1076 * @param mixed $param Parameter as defined in this class.
1078 * @return array Array with the parameter type (either "before" or "after") and the value.
1080 protected function extractParam( $param ) {
1081 if ( is_array( $param ) ) {
1082 if ( isset( $param['raw'] ) ) {
1083 return [ 'after', $param['raw'] ];
1084 } elseif ( isset( $param['num'] ) ) {
1085 // Replace number params always in before step for now.
1086 // No support for combined raw and num params
1087 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1088 } elseif ( isset( $param['duration'] ) ) {
1089 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1090 } elseif ( isset( $param['expiry'] ) ) {
1091 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1092 } elseif ( isset( $param['period'] ) ) {
1093 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1094 } elseif ( isset( $param['size'] ) ) {
1095 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1096 } elseif ( isset( $param['bitrate'] ) ) {
1097 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1098 } elseif ( isset( $param['plaintext'] ) ) {
1099 return [ 'after', $this->formatPlaintext( $param['plaintext'] ) ];
1100 } else {
1101 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
1102 htmlspecialchars( serialize( $param ) );
1103 trigger_error( $warning, E_USER_WARNING );
1104 $e = new Exception;
1105 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1107 return [ 'before', '[INVALID]' ];
1109 } elseif ( $param instanceof Message ) {
1110 // Message objects should not be before parameters because
1111 // then they'll get double escaped. If the message needs to be
1112 // escaped, it'll happen right here when we call toString().
1113 return [ 'after', $param->toString() ];
1114 } else {
1115 return [ 'before', $param ];
1120 * Wrapper for what ever method we use to parse wikitext.
1122 * @since 1.17
1124 * @param string $string Wikitext message contents.
1126 * @return string Wikitext parsed into HTML.
1128 protected function parseText( $string ) {
1129 $out = MessageCache::singleton()->parse(
1130 $string,
1131 $this->title,
1132 /*linestart*/true,
1133 $this->interface,
1134 $this->getLanguage()
1137 return $out instanceof ParserOutput ? $out->getText() : $out;
1141 * Wrapper for what ever method we use to {{-transform wikitext.
1143 * @since 1.17
1145 * @param string $string Wikitext message contents.
1147 * @return string Wikitext with {{-constructs replaced with their values.
1149 protected function transformText( $string ) {
1150 return MessageCache::singleton()->transform(
1151 $string,
1152 $this->interface,
1153 $this->getLanguage(),
1154 $this->title
1159 * Wrapper for what ever method we use to get message contents.
1161 * @since 1.17
1163 * @return string
1164 * @throws MWException If message key array is empty.
1166 protected function fetchMessage() {
1167 if ( $this->message === null ) {
1168 $cache = MessageCache::singleton();
1170 foreach ( $this->keysToTry as $key ) {
1171 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1172 if ( $message !== false && $message !== '' ) {
1173 break;
1177 // NOTE: The constructor makes sure keysToTry isn't empty,
1178 // so we know that $key and $message are initialized.
1179 $this->key = $key;
1180 $this->message = $message;
1182 return $this->message;
1186 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1187 * the entire string is displayed unchanged when displayed in the output
1188 * format.
1190 * @since 1.25
1192 * @param string $plaintext String to ensure plaintext output of
1194 * @return string Input plaintext encoded for output to $this->format
1196 protected function formatPlaintext( $plaintext ) {
1197 switch ( $this->format ) {
1198 case 'text':
1199 case 'plain':
1200 return $plaintext;
1202 case 'parse':
1203 case 'block-parse':
1204 case 'escaped':
1205 default:
1206 return htmlspecialchars( $plaintext, ENT_QUOTES );
1213 * Variant of the Message class.
1215 * Rather than treating the message key as a lookup
1216 * value (which is passed to the MessageCache and
1217 * translated as necessary), a RawMessage key is
1218 * treated as the actual message.
1220 * All other functionality (parsing, escaping, etc.)
1221 * is preserved.
1223 * @since 1.21
1225 class RawMessage extends Message {
1228 * Call the parent constructor, then store the key as
1229 * the message.
1231 * @see Message::__construct
1233 * @param string $text Message to use.
1234 * @param array $params Parameters for the message.
1236 * @throws InvalidArgumentException
1238 public function __construct( $text, $params = [] ) {
1239 if ( !is_string( $text ) ) {
1240 throw new InvalidArgumentException( '$text must be a string' );
1243 parent::__construct( $text, $params );
1245 // The key is the message.
1246 $this->message = $text;
1250 * Fetch the message (in this case, the key).
1252 * @return string
1254 public function fetchMessage() {
1255 // Just in case the message is unset somewhere.
1256 if ( $this->message === null ) {
1257 $this->message = $this->key;
1260 return $this->message;