User::isSafeToLoad() should return false if MW_NO_SESSION
[mediawiki.git] / includes / Message.php
blob4056f38da9f4c486a304f52f7dced085e379b5a1
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 interface language, false content language.
165 * @var bool
167 protected $interface = true;
170 * In which language to get this message. Overrides the $interface
171 * variable.
173 * @var Language
175 protected $language = null;
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.
181 protected $key;
184 * @var string[] List of keys to try when fetching the message.
186 protected $keysToTry;
189 * @var array List of parameters which will be substituted into the message.
191 protected $parameters = [];
194 * Format for the message.
195 * Supported formats are:
196 * * text (transform)
197 * * escaped (transform+htmlspecialchars)
198 * * block-parse
199 * * parse (default)
200 * * plain
202 * @var string
204 protected $format = 'parse';
207 * @var bool Whether database can be used.
209 protected $useDatabase = true;
212 * @var Title Title object to use as context.
214 protected $title = null;
217 * @var Content Content object representing the message.
219 protected $content = null;
222 * @var string
224 protected $message;
227 * @since 1.17
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.
235 * @throws InvalidArgumentException
237 public function __construct( $key, $params = [], Language $language = null ) {
238 global $wgLang;
240 if ( $key instanceof MessageSpecifier ) {
241 if ( $params ) {
242 throw new InvalidArgumentException(
243 '$params must be empty if $key is a MessageSpecifier'
246 $params = $key->getParams();
247 $key = $key->getKey();
250 if ( !is_string( $key ) && !is_array( $key ) ) {
251 throw new InvalidArgumentException( '$key must be a string or an array' );
254 $this->keysToTry = (array)$key;
256 if ( empty( $this->keysToTry ) ) {
257 throw new InvalidArgumentException( '$key must not be an empty list' );
260 $this->key = reset( $this->keysToTry );
262 $this->parameters = array_values( $params );
263 $this->language = $language ?: $wgLang;
267 * @see Serializable::serialize()
268 * @since 1.26
269 * @return string
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 ] );
285 * @see Serializable::unserialize()
286 * @since 1.26
287 * @param string $serialized
289 public function unserialize( $serialized ) {
290 global $wgLang;
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'];
304 * @since 1.24
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.
309 public function isMultiKey() {
310 return count( $this->keysToTry ) > 1;
314 * @since 1.24
316 * @return string[] The list of keys to try when fetching the message text,
317 * in order of preference.
319 public function getKeysToTry() {
320 return $this->keysToTry;
324 * Returns the message key.
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.
330 * @since 1.21
332 * @return string
334 public function getKey() {
335 return $this->key;
339 * Returns the message parameters.
341 * @since 1.21
343 * @return array
345 public function getParams() {
346 return $this->parameters;
350 * Returns the message format.
352 * @since 1.21
354 * @return string
356 public function getFormat() {
357 return $this->format;
361 * Returns the Language of the Message.
363 * @since 1.23
365 * @return Language
367 public function getLanguage() {
368 return $this->language;
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.
376 * @since 1.17
378 * @param string|string[]|MessageSpecifier $key
379 * @param mixed $param,... Parameters as strings.
381 * @return Message
383 public static function newFromKey( $key /*...*/ ) {
384 $params = func_get_args();
385 array_shift( $params );
386 return new self( $key, $params );
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.
394 * @since 1.18
396 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
397 * message keys.
399 * @return Message
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];
412 return new self( $keys );
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.
421 * @see $wgForceUIMsgAsContentMsg
422 * @return Title
423 * @since 1.26
425 public function getTitle() {
426 global $wgContLang, $wgForceUIMsgAsContentMsg;
428 $code = $this->language->getCode();
429 $title = $this->key;
430 if (
431 $wgContLang->getCode() !== $code
432 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
434 $title .= '/' . $code;
437 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
441 * Adds parameters to the parameter list of this message.
443 * @since 1.17
445 * @param mixed ... Parameters as strings, or a single argument that is
446 * an array of strings.
448 * @return Message $this
450 public function params( /*...*/ ) {
451 $args = func_get_args();
452 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
453 $args = $args[0];
455 $args_values = array_values( $args );
456 $this->parameters = array_merge( $this->parameters, $args_values );
457 return $this;
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.
466 * @since 1.17
468 * @param mixed $params,... Raw parameters as strings, or a single argument that is
469 * an array of raw parameters.
471 * @return Message $this
473 public function rawParams( /*...*/ ) {
474 $params = func_get_args();
475 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
476 $params = $params[0];
478 foreach ( $params as $param ) {
479 $this->parameters[] = self::rawParam( $param );
481 return $this;
485 * Add parameters that are numeric and will be passed through
486 * Language::formatNum before substitution
488 * @since 1.18
490 * @param mixed $param,... Numeric parameters, or a single argument that is
491 * an array of numeric parameters.
493 * @return Message $this
495 public function numParams( /*...*/ ) {
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::numParam( $param );
503 return $this;
507 * Add parameters that are durations of time and will be passed through
508 * Language::formatDuration before substitution
510 * @since 1.22
512 * @param int|int[] $param,... Duration parameters, or a single argument that is
513 * an array of duration parameters.
515 * @return Message $this
517 public function durationParams( /*...*/ ) {
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::durationParam( $param );
525 return $this;
529 * Add parameters that are expiration times and will be passed through
530 * Language::formatExpiry before substitution
532 * @since 1.22
534 * @param string|string[] $param,... Expiry parameters, or a single argument that is
535 * an array of expiry parameters.
537 * @return Message $this
539 public function expiryParams( /*...*/ ) {
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::expiryParam( $param );
547 return $this;
551 * Add parameters that are time periods and will be passed through
552 * Language::formatTimePeriod before substitution
554 * @since 1.22
556 * @param int|int[] $param,... Time period parameters, or a single argument that is
557 * an array of time period parameters.
559 * @return Message $this
561 public function timeperiodParams( /*...*/ ) {
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::timeperiodParam( $param );
569 return $this;
573 * Add parameters that are file sizes and will be passed through
574 * Language::formatSize before substitution
576 * @since 1.22
578 * @param int|int[] $param,... Size parameters, or a single argument that is
579 * an array of size parameters.
581 * @return Message $this
583 public function sizeParams( /*...*/ ) {
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::sizeParam( $param );
591 return $this;
595 * Add parameters that are bitrates and will be passed through
596 * Language::formatBitrate before substitution
598 * @since 1.22
600 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
601 * an array of bit rate parameters.
603 * @return Message $this
605 public function bitrateParams( /*...*/ ) {
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::bitrateParam( $param );
613 return $this;
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.
622 * @since 1.25
624 * @param string|string[] $param,... plaintext parameters, or a single argument that is
625 * an array of plaintext parameters.
627 * @return Message $this
629 public function plaintextParams( /*...*/ ) {
630 $params = func_get_args();
631 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
632 $params = $params[0];
634 foreach ( $params as $param ) {
635 $this->parameters[] = self::plaintextParam( $param );
637 return $this;
641 * Set the language and the title from a context object
643 * @since 1.19
645 * @param IContextSource $context
647 * @return Message $this
649 public function setContext( IContextSource $context ) {
650 $this->inLanguage( $context->getLanguage() );
651 $this->title( $context->getTitle() );
652 $this->interface = true;
654 return $this;
658 * Request the message in any language that is supported.
659 * As a side effect interface message status is unconditionally
660 * turned off.
662 * @since 1.17
664 * @param Language|string $lang Language code or Language object.
666 * @return Message $this
667 * @throws MWException
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 );
676 } else {
677 $type = gettype( $lang );
678 throw new MWException( __METHOD__ . " must be "
679 . "passed a String or Language object; $type given"
682 $this->message = null;
683 $this->interface = false;
684 return $this;
688 * Request the message in the wiki's content language,
689 * unless it is disabled for this message.
691 * @since 1.17
692 * @see $wgForceUIMsgAsContentMsg
694 * @return Message $this
696 public function inContentLanguage() {
697 global $wgForceUIMsgAsContentMsg;
698 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
699 return $this;
702 global $wgContLang;
703 $this->inLanguage( $wgContLang );
704 return $this;
708 * Allows manipulating the interface message flag directly.
709 * Can be used to restore the flag after setting a language.
711 * @since 1.20
713 * @param bool $interface
715 * @return Message $this
717 public function setInterfaceMessageFlag( $interface ) {
718 $this->interface = (bool)$interface;
719 return $this;
723 * Enable or disable database use.
725 * @since 1.17
727 * @param bool $useDatabase
729 * @return Message $this
731 public function useDatabase( $useDatabase ) {
732 $this->useDatabase = (bool)$useDatabase;
733 return $this;
737 * Set the Title object to use as context when transforming the message
739 * @since 1.18
741 * @param Title $title
743 * @return Message $this
745 public function title( $title ) {
746 $this->title = $title;
747 return $this;
751 * Returns the message as a Content object.
753 * @return Content
755 public function content() {
756 if ( !$this->content ) {
757 $this->content = new MessageContent( $this );
760 return $this->content;
764 * Returns the message parsed from wikitext to HTML.
766 * @since 1.17
768 * @return string HTML
770 public function toString() {
771 $string = $this->fetchMessage();
773 if ( $string === false ) {
774 if ( $this->format === 'plain' || $this->format === 'text' ) {
775 return '<' . $this->key . '>';
777 return '&lt;' . htmlspecialchars( $this->key ) . '&gt;';
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 ) ) );
786 $string = str_replace( '$*', $paramlist, $string );
789 # Replace parameters before text parsing
790 $string = $this->replaceParameters( $string, 'before' );
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 );
805 # Raw parameter replacement
806 $string = $this->replaceParameters( $string, 'after' );
808 return $string;
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>";
816 * @since 1.18
818 * @return string
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.
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?
834 if ( $this->format === 'plain' || $this->format === 'text' ) {
835 return '<' . $this->key . '>';
837 return '&lt;' . htmlspecialchars( $this->key ) . '&gt;';
842 * Fully parse the text from wikitext to HTML.
844 * @since 1.17
846 * @return string Parsed HTML.
848 public function parse() {
849 $this->format = 'parse';
850 return $this->toString();
854 * Returns the message text. {{-transformation is done.
856 * @since 1.17
858 * @return string Unescaped message text.
860 public function text() {
861 $this->format = 'text';
862 return $this->toString();
866 * Returns the message text as-is, only parameters are substituted.
868 * @since 1.17
870 * @return string Unescaped untransformed message text.
872 public function plain() {
873 $this->format = 'plain';
874 return $this->toString();
878 * Returns the parsed message text which is always surrounded by a block element.
880 * @since 1.17
882 * @return string HTML
884 public function parseAsBlock() {
885 $this->format = 'block-parse';
886 return $this->toString();
890 * Returns the message text. {{-transformation is done and the result
891 * is escaped excluding any raw parameters.
893 * @since 1.17
895 * @return string Escaped message text.
897 public function escaped() {
898 $this->format = 'escaped';
899 return $this->toString();
903 * Check whether a message key has been defined currently.
905 * @since 1.17
907 * @return bool
909 public function exists() {
910 return $this->fetchMessage() !== false;
914 * Check whether a message does not exist, or is an empty string
916 * @since 1.18
917 * @todo FIXME: Merge with isDisabled()?
919 * @return bool
921 public function isBlank() {
922 $message = $this->fetchMessage();
923 return $message === false || $message === '';
927 * Check whether a message does not exist, is an empty string, or is "-".
929 * @since 1.18
931 * @return bool
933 public function isDisabled() {
934 $message = $this->fetchMessage();
935 return $message === false || $message === '' || $message === '-';
939 * @since 1.17
941 * @param mixed $raw
943 * @return array Array with a single "raw" key.
945 public static function rawParam( $raw ) {
946 return [ 'raw' => $raw ];
950 * @since 1.18
952 * @param mixed $num
954 * @return array Array with a single "num" key.
956 public static function numParam( $num ) {
957 return [ 'num' => $num ];
961 * @since 1.22
963 * @param int $duration
965 * @return int[] Array with a single "duration" key.
967 public static function durationParam( $duration ) {
968 return [ 'duration' => $duration ];
972 * @since 1.22
974 * @param string $expiry
976 * @return string[] Array with a single "expiry" key.
978 public static function expiryParam( $expiry ) {
979 return [ 'expiry' => $expiry ];
983 * @since 1.22
985 * @param number $period
987 * @return number[] Array with a single "period" key.
989 public static function timeperiodParam( $period ) {
990 return [ 'period' => $period ];
994 * @since 1.22
996 * @param int $size
998 * @return int[] Array with a single "size" key.
1000 public static function sizeParam( $size ) {
1001 return [ 'size' => $size ];
1005 * @since 1.22
1007 * @param int $bitrate
1009 * @return int[] Array with a single "bitrate" key.
1011 public static function bitrateParam( $bitrate ) {
1012 return [ 'bitrate' => $bitrate ];
1016 * @since 1.25
1018 * @param string $plaintext
1020 * @return string[] Array with a single "plaintext" key.
1022 public static function plaintextParam( $plaintext ) {
1023 return [ 'plaintext' => $plaintext ];
1027 * Substitutes any parameters into the message text.
1029 * @since 1.17
1031 * @param string $message The message text.
1032 * @param string $type Either "before" or "after".
1034 * @return string
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;
1044 $message = strtr( $message, $replacementKeys );
1045 return $message;
1049 * Extracts the parameter type and preprocessed the value if needed.
1051 * @since 1.18
1053 * @param mixed $param Parameter as defined in this class.
1055 * @return array Array with the parameter type (either "before" or "after") and the value.
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() );
1084 return [ 'before', '[INVALID]' ];
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 ];
1097 * Wrapper for what ever method we use to parse wikitext.
1099 * @since 1.17
1101 * @param string $string Wikitext message contents.
1103 * @return string Wikitext parsed into HTML.
1105 protected function parseText( $string ) {
1106 $out = MessageCache::singleton()->parse(
1107 $string,
1108 $this->title,
1109 /*linestart*/true,
1110 $this->interface,
1111 $this->language
1114 return $out instanceof ParserOutput ? $out->getText() : $out;
1118 * Wrapper for what ever method we use to {{-transform wikitext.
1120 * @since 1.17
1122 * @param string $string Wikitext message contents.
1124 * @return string Wikitext with {{-constructs replaced with their values.
1126 protected function transformText( $string ) {
1127 return MessageCache::singleton()->transform(
1128 $string,
1129 $this->interface,
1130 $this->language,
1131 $this->title
1136 * Wrapper for what ever method we use to get message contents.
1138 * @since 1.17
1140 * @return string
1141 * @throws MWException If message key array is empty.
1143 protected function fetchMessage() {
1144 if ( $this->message === null ) {
1145 $cache = MessageCache::singleton();
1147 foreach ( $this->keysToTry as $key ) {
1148 $message = $cache->get( $key, $this->useDatabase, $this->language );
1149 if ( $message !== false && $message !== '' ) {
1150 break;
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;
1159 return $this->message;
1163 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1164 * the entire string is displayed unchanged when displayed in the output
1165 * format.
1167 * @since 1.25
1169 * @param string $plaintext String to ensure plaintext output of
1171 * @return string Input plaintext encoded for output to $this->format
1173 protected function formatPlaintext( $plaintext ) {
1174 switch ( $this->format ) {
1175 case 'text':
1176 case 'plain':
1177 return $plaintext;
1179 case 'parse':
1180 case 'block-parse':
1181 case 'escaped':
1182 default:
1183 return htmlspecialchars( $plaintext, ENT_QUOTES );
1190 * Variant of the Message class.
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.
1197 * All other functionality (parsing, escaping, etc.)
1198 * is preserved.
1200 * @since 1.21
1202 class RawMessage extends Message {
1205 * Call the parent constructor, then store the key as
1206 * the message.
1208 * @see Message::__construct
1210 * @param string $text Message to use.
1211 * @param array $params Parameters for the message.
1213 * @throws InvalidArgumentException
1215 public function __construct( $text, $params = [] ) {
1216 if ( !is_string( $text ) ) {
1217 throw new InvalidArgumentException( '$text must be a string' );
1220 parent::__construct( $text, $params );
1222 // The key is the message.
1223 $this->message = $text;
1227 * Fetch the message (in this case, the key).
1229 * @return string
1231 public function fetchMessage() {
1232 // Just in case the message is unset somewhere.
1233 if ( $this->message === null ) {
1234 $this->message = $this->key;
1237 return $this->message;