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
21 * @author Niklas Laxström
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:
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',
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:
58 * $button = Xml::button(
59 * wfMessage( 'submit' )->text()
63 * A Message instance can be passed parameters after it has been constructed,
64 * use the params() method to do so:
67 * wfMessage( 'welcome-to' )
68 * ->params( $wgSitename )
72 * {{GRAMMAR}} and friends work correctly:
75 * wfMessage( 'are-friends',
78 * wfMessage( 'bad-message' )
79 * ->rawParams( '<script>...</script>' )
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
94 * wfMessage( 'file-log',
96 * )->inContentLanguage()->text();
99 * Checking whether a message exists:
102 * wfMessage( 'mysterious-message' )->exists()
103 * // returns a boolean whether the 'mysterious-message' key exist.
106 * If you want to use a different language:
109 * $userLanguage = $user->getOption( 'language' );
110 * wfMessage( 'email-header' )
111 * ->inLanguage( $userLanguage )
115 * @note You can parse the text only in the content or interface languages
117 * @section message_compare_old Comparison with old wfMsg* functions:
123 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
125 * wfMessage( 'key', 'apple' )->parse();
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.
134 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
136 * wfMessage( 'key', 'apple', 'pear' )->text();
139 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
140 * parameters are not replaced after escaping by default.
142 * $escaped = wfMessage( 'key' )
143 * ->rawParams( 'apple' )
147 * @section message_appendix Appendix:
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
162 * In which language to get this message. True, which is the default,
163 * means the current interface language, false content language.
167 protected $interface = true;
170 * In which language to get this message. Overrides the $interface
175 protected $language = null;
178 * @var string|string[] The message key or array of keys.
183 * @var array List of parameters which will be substituted into the message.
185 protected $parameters = array();
188 * Format for the message.
189 * Supported formats are:
191 * * escaped (transform+htmlspecialchars)
198 protected $format = 'parse';
201 * @var bool Whether database can be used.
203 protected $useDatabase = true;
206 * @var Title Title object to use as context.
208 protected $title = null;
211 * @var Content Content object representing the message.
213 protected $content = null;
223 * @param string|string[] $key Message key or array of message keys to try and use the first
224 * non-empty message for.
225 * @param array $params Message parameters.
226 * @param Language $language Optional language of the message, defaults to $wgLang.
228 public function __construct( $key, $params = array(), Language
$language = null ) {
232 $this->parameters
= array_values( $params );
233 $this->language
= $language ?
$language : $wgLang;
237 * Returns the message key or the first from an array of message keys.
243 public function getKey() {
244 if ( is_array( $this->key
) ) {
245 // May happen if some kind of fallback is applied.
246 // For now, just use the first key. We really need a better solution.
247 return $this->key
[0];
254 * Returns the message parameters.
260 public function getParams() {
261 return $this->parameters
;
265 * Returns the message format.
271 public function getFormat() {
272 return $this->format
;
276 * Returns the Language of the Message.
282 public function getLanguage() {
283 return $this->language
;
287 * Factory function that is just wrapper for the real constructor. It is
288 * intended to be used instead of the real constructor, because it allows
289 * chaining method calls, while new objects don't.
293 * @param string|string[] $key Message key or array of keys.
294 * @param mixed [$param,...] Parameters as strings.
298 public static function newFromKey( $key /*...*/ ) {
299 $params = func_get_args();
300 array_shift( $params );
301 return new self( $key, $params );
305 * Factory function accepting multiple message keys and returning a message instance
306 * for the first message which is non-empty. If all messages are empty then an
307 * instance of the first message key is returned.
311 * @param string|string[] [$keys,...] Message keys, or first argument as an array of all the
316 public static function newFallbackSequence( /*...*/ ) {
317 $keys = func_get_args();
318 if ( func_num_args() == 1 ) {
319 if ( is_array( $keys[0] ) ) {
320 // Allow an array to be passed as the first argument instead
321 $keys = array_values( $keys[0] );
323 // Optimize a single string to not need special fallback handling
327 return new self( $keys );
331 * Adds parameters to the parameter list of this message.
335 * @param mixed [$params,...] Parameters as strings, or a single argument that is
336 * an array of strings.
338 * @return Message $this
340 public function params( /*...*/ ) {
341 $args = func_get_args();
342 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
345 $args_values = array_values( $args );
346 $this->parameters
= array_merge( $this->parameters
, $args_values );
351 * Add parameters that are substituted after parsing or escaping.
352 * In other words the parsing process cannot access the contents
353 * of this type of parameter, and you need to make sure it is
354 * sanitized beforehand. The parser will see "$n", instead.
358 * @param mixed [$params,...] Raw parameters as strings, or a single argument that is
359 * an array of raw parameters.
361 * @return Message $this
363 public function rawParams( /*...*/ ) {
364 $params = func_get_args();
365 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
366 $params = $params[0];
368 foreach ( $params as $param ) {
369 $this->parameters
[] = self
::rawParam( $param );
375 * Add parameters that are numeric and will be passed through
376 * Language::formatNum before substitution
380 * @param mixed [$param,...] Numeric parameters, or a single argument that is
381 * an array of numeric parameters.
383 * @return Message $this
385 public function numParams( /*...*/ ) {
386 $params = func_get_args();
387 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
388 $params = $params[0];
390 foreach ( $params as $param ) {
391 $this->parameters
[] = self
::numParam( $param );
397 * Add parameters that are durations of time and will be passed through
398 * Language::formatDuration before substitution
402 * @param int|int[] [$param,...] Duration parameters, or a single argument that is
403 * an array of duration parameters.
405 * @return Message $this
407 public function durationParams( /*...*/ ) {
408 $params = func_get_args();
409 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
410 $params = $params[0];
412 foreach ( $params as $param ) {
413 $this->parameters
[] = self
::durationParam( $param );
419 * Add parameters that are expiration times and will be passed through
420 * Language::formatExpiry before substitution
424 * @param string|string[] [$param,...] Expiry parameters, or a single argument that is
425 * an array of expiry parameters.
427 * @return Message $this
429 public function expiryParams( /*...*/ ) {
430 $params = func_get_args();
431 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
432 $params = $params[0];
434 foreach ( $params as $param ) {
435 $this->parameters
[] = self
::expiryParam( $param );
441 * Add parameters that are time periods and will be passed through
442 * Language::formatTimePeriod before substitution
446 * @param int|int[] [$param,...] Time period parameters, or a single argument that is
447 * an array of time period parameters.
449 * @return Message $this
451 public function timeperiodParams( /*...*/ ) {
452 $params = func_get_args();
453 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
454 $params = $params[0];
456 foreach ( $params as $param ) {
457 $this->parameters
[] = self
::timeperiodParam( $param );
463 * Add parameters that are file sizes and will be passed through
464 * Language::formatSize before substitution
468 * @param int|int[] [$param,...] Size parameters, or a single argument that is
469 * an array of size parameters.
471 * @return Message $this
473 public function sizeParams( /*...*/ ) {
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
::sizeParam( $param );
485 * Add parameters that are bitrates and will be passed through
486 * Language::formatBitrate before substitution
490 * @param int|int[] [$param,...] Bit rate parameters, or a single argument that is
491 * an array of bit rate parameters.
493 * @return Message $this
495 public function bitrateParams( /*...*/ ) {
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
::bitrateParam( $param );
507 * Set the language and the title from a context object
511 * @param IContextSource $context
513 * @return Message $this
515 public function setContext( IContextSource
$context ) {
516 $this->inLanguage( $context->getLanguage() );
517 $this->title( $context->getTitle() );
518 $this->interface = true;
524 * Request the message in any language that is supported.
525 * As a side effect interface message status is unconditionally
530 * @param Language|string $lang Language code or Language object.
532 * @return Message $this
533 * @throws MWException
535 public function inLanguage( $lang ) {
536 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
537 $this->language
= $lang;
538 } elseif ( is_string( $lang ) ) {
539 if ( $this->language
->getCode() != $lang ) {
540 $this->language
= Language
::factory( $lang );
543 $type = gettype( $lang );
544 throw new MWException( __METHOD__
. " must be "
545 . "passed a String or Language object; $type given"
548 $this->message
= null;
549 $this->interface = false;
554 * Request the message in the wiki's content language,
555 * unless it is disabled for this message.
558 * @see $wgForceUIMsgAsContentMsg
560 * @return Message $this
562 public function inContentLanguage() {
563 global $wgForceUIMsgAsContentMsg;
564 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
569 $this->inLanguage( $wgContLang );
574 * Allows manipulating the interface message flag directly.
575 * Can be used to restore the flag after setting a language.
579 * @param bool $interface
581 * @return Message $this
583 public function setInterfaceMessageFlag( $interface ) {
584 $this->interface = (bool)$interface;
589 * Enable or disable database use.
593 * @param bool $useDatabase
595 * @return Message $this
597 public function useDatabase( $useDatabase ) {
598 $this->useDatabase
= (bool)$useDatabase;
603 * Set the Title object to use as context when transforming the message
607 * @param Title $title
609 * @return Message $this
611 public function title( $title ) {
612 $this->title
= $title;
617 * Returns the message as a Content object.
621 public function content() {
622 if ( !$this->content
) {
623 $this->content
= new MessageContent( $this );
626 return $this->content
;
630 * Returns the message parsed from wikitext to HTML.
634 * @return string HTML
636 public function toString() {
637 $string = $this->fetchMessage();
639 if ( $string === false ) {
640 $key = htmlspecialchars( is_array( $this->key
) ?
$this->key
[0] : $this->key
);
641 if ( $this->format
=== 'plain' ) {
642 return '<' . $key . '>';
644 return '<' . $key . '>';
647 # Replace $* with a list of parameters for &uselang=qqx.
648 if ( strpos( $string, '$*' ) !== false ) {
650 if ( $this->parameters
!== array() ) {
651 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
653 $string = str_replace( '$*', $paramlist, $string );
656 # Replace parameters before text parsing
657 $string = $this->replaceParameters( $string, 'before' );
659 # Maybe transform using the full parser
660 if ( $this->format
=== 'parse' ) {
661 $string = $this->parseText( $string );
663 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
666 } elseif ( $this->format
=== 'block-parse' ) {
667 $string = $this->parseText( $string );
668 } elseif ( $this->format
=== 'text' ) {
669 $string = $this->transformText( $string );
670 } elseif ( $this->format
=== 'escaped' ) {
671 $string = $this->transformText( $string );
672 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
675 # Raw parameter replacement
676 $string = $this->replaceParameters( $string, 'after' );
682 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
683 * $foo = Message::get( $key );
684 * $string = "<abbr>$foo</abbr>";
690 public function __toString() {
691 // PHP doesn't allow __toString to throw exceptions and will
692 // trigger a fatal error if it does. So, catch any exceptions.
695 return $this->toString();
696 } catch ( Exception
$ex ) {
698 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
699 . $ex, E_USER_WARNING
);
700 } catch ( Exception
$ex ) {
701 // Doh! Cause a fatal error after all?
704 if ( $this->format
=== 'plain' ) {
705 return '<' . $this->key
. '>';
707 return '<' . $this->key
. '>';
712 * Fully parse the text from wikitext to HTML.
716 * @return string Parsed HTML.
718 public function parse() {
719 $this->format
= 'parse';
720 return $this->toString();
724 * Returns the message text. {{-transformation is done.
728 * @return string Unescaped message text.
730 public function text() {
731 $this->format
= 'text';
732 return $this->toString();
736 * Returns the message text as-is, only parameters are substituted.
740 * @return string Unescaped untransformed message text.
742 public function plain() {
743 $this->format
= 'plain';
744 return $this->toString();
748 * Returns the parsed message text which is always surrounded by a block element.
752 * @return string HTML
754 public function parseAsBlock() {
755 $this->format
= 'block-parse';
756 return $this->toString();
760 * Returns the message text. {{-transformation is done and the result
761 * is escaped excluding any raw parameters.
765 * @return string Escaped message text.
767 public function escaped() {
768 $this->format
= 'escaped';
769 return $this->toString();
773 * Check whether a message key has been defined currently.
779 public function exists() {
780 return $this->fetchMessage() !== false;
784 * Check whether a message does not exist, or is an empty string
787 * @todo FIXME: Merge with isDisabled()?
791 public function isBlank() {
792 $message = $this->fetchMessage();
793 return $message === false ||
$message === '';
797 * Check whether a message does not exist, is an empty string, or is "-".
803 public function isDisabled() {
804 $message = $this->fetchMessage();
805 return $message === false ||
$message === '' ||
$message === '-';
813 * @return array Array with a single "raw" key.
815 public static function rawParam( $raw ) {
816 return array( 'raw' => $raw );
824 * @return array Array with a single "num" key.
826 public static function numParam( $num ) {
827 return array( 'num' => $num );
833 * @param int $duration
835 * @return int[] Array with a single "duration" key.
837 public static function durationParam( $duration ) {
838 return array( 'duration' => $duration );
844 * @param string $expiry
846 * @return string[] Array with a single "expiry" key.
848 public static function expiryParam( $expiry ) {
849 return array( 'expiry' => $expiry );
855 * @param number $period
857 * @return number[] Array with a single "period" key.
859 public static function timeperiodParam( $period ) {
860 return array( 'period' => $period );
868 * @return int[] Array with a single "size" key.
870 public static function sizeParam( $size ) {
871 return array( 'size' => $size );
877 * @param int $bitrate
879 * @return int[] Array with a single "bitrate" key.
881 public static function bitrateParam( $bitrate ) {
882 return array( 'bitrate' => $bitrate );
886 * Substitutes any parameters into the message text.
890 * @param string $message The message text.
891 * @param string $type Either "before" or "after".
895 protected function replaceParameters( $message, $type = 'before' ) {
896 $replacementKeys = array();
897 foreach ( $this->parameters
as $n => $param ) {
898 list( $paramType, $value ) = $this->extractParam( $param );
899 if ( $type === $paramType ) {
900 $replacementKeys['$' . ( $n +
1 )] = $value;
903 $message = strtr( $message, $replacementKeys );
908 * Extracts the parameter type and preprocessed the value if needed.
912 * @param mixed $param Parameter as defined in this class.
914 * @return array Array with the parameter type (either "before" or "after") and the value.
916 protected function extractParam( $param ) {
917 if ( is_array( $param ) ) {
918 if ( isset( $param['raw'] ) ) {
919 return array( 'after', $param['raw'] );
920 } elseif ( isset( $param['num'] ) ) {
921 // Replace number params always in before step for now.
922 // No support for combined raw and num params
923 return array( 'before', $this->language
->formatNum( $param['num'] ) );
924 } elseif ( isset( $param['duration'] ) ) {
925 return array( 'before', $this->language
->formatDuration( $param['duration'] ) );
926 } elseif ( isset( $param['expiry'] ) ) {
927 return array( 'before', $this->language
->formatExpiry( $param['expiry'] ) );
928 } elseif ( isset( $param['period'] ) ) {
929 return array( 'before', $this->language
->formatTimePeriod( $param['period'] ) );
930 } elseif ( isset( $param['size'] ) ) {
931 return array( 'before', $this->language
->formatSize( $param['size'] ) );
932 } elseif ( isset( $param['bitrate'] ) ) {
933 return array( 'before', $this->language
->formatBitrate( $param['bitrate'] ) );
935 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
936 htmlspecialchars( serialize( $param ) );
937 trigger_error( $warning, E_USER_WARNING
);
939 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
941 return array( 'before', '[INVALID]' );
943 } elseif ( $param instanceof Message
) {
944 // Message objects should not be before parameters because
945 // then they'll get double escaped. If the message needs to be
946 // escaped, it'll happen right here when we call toString().
947 return array( 'after', $param->toString() );
949 return array( 'before', $param );
954 * Wrapper for what ever method we use to parse wikitext.
958 * @param string $string Wikitext message contents.
960 * @return string Wikitext parsed into HTML.
962 protected function parseText( $string ) {
963 $out = MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
);
964 return $out instanceof ParserOutput ?
$out->getText() : $out;
968 * Wrapper for what ever method we use to {{-transform wikitext.
972 * @param string $string Wikitext message contents.
974 * @return string Wikitext with {{-constructs replaced with their values.
976 protected function transformText( $string ) {
977 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
981 * Wrapper for what ever method we use to get message contents.
986 * @throws MWException If message key array is empty.
988 protected function fetchMessage() {
989 if ( !isset( $this->message
) ) {
990 $cache = MessageCache
::singleton();
991 if ( is_array( $this->key
) ) {
992 if ( !count( $this->key
) ) {
993 throw new MWException( "Given empty message key array." );
995 foreach ( $this->key
as $key ) {
996 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
997 if ( $message !== false && $message !== '' ) {
1001 $this->message
= $message;
1003 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
1006 return $this->message
;
1012 * Variant of the Message class.
1014 * Rather than treating the message key as a lookup
1015 * value (which is passed to the MessageCache and
1016 * translated as necessary), a RawMessage key is
1017 * treated as the actual message.
1019 * All other functionality (parsing, escaping, etc.)
1024 class RawMessage
extends Message
{
1027 * Call the parent constructor, then store the key as
1030 * @see Message::__construct
1032 * @param string|string[] $key Message to use.
1033 * @param array $params Parameters for the message.
1035 public function __construct( $key, $params = array() ) {
1036 parent
::__construct( $key, $params );
1037 // The key is the message.
1038 $this->message
= $key;
1042 * Fetch the message (in this case, the key).
1046 public function fetchMessage() {
1047 // Just in case the message is unset somewhere.
1048 if ( !isset( $this->message
) ) {
1049 $this->message
= $this->key
;
1051 return $this->message
;