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.
227 public function __construct( $key, $params = array() ) {
230 $this->parameters
= array_values( $params );
231 $this->language
= $wgLang;
235 * Returns the message key or the first from an array of message keys.
241 public function getKey() {
242 if ( is_array( $this->key
) ) {
243 // May happen if some kind of fallback is applied.
244 // For now, just use the first key. We really need a better solution.
245 return $this->key
[0];
252 * Returns the message parameters.
258 public function getParams() {
259 return $this->parameters
;
263 * Returns the message format.
269 public function getFormat() {
270 return $this->format
;
274 * Factory function that is just wrapper for the real constructor. It is
275 * intended to be used instead of the real constructor, because it allows
276 * chaining method calls, while new objects don't.
280 * @param string|string[] $key Message key or array of keys.
281 * @param mixed [$param,...] Parameters as strings.
285 public static function newFromKey( $key /*...*/ ) {
286 $params = func_get_args();
287 array_shift( $params );
288 return new self( $key, $params );
292 * Factory function accepting multiple message keys and returning a message instance
293 * for the first message which is non-empty. If all messages are empty then an
294 * instance of the first message key is returned.
298 * @param string|string[] [$keys,...] Message keys, or first argument as an array of all the
303 public static function newFallbackSequence( /*...*/ ) {
304 $keys = func_get_args();
305 if ( func_num_args() == 1 ) {
306 if ( is_array( $keys[0] ) ) {
307 // Allow an array to be passed as the first argument instead
308 $keys = array_values( $keys[0] );
310 // Optimize a single string to not need special fallback handling
314 return new self( $keys );
318 * Adds parameters to the parameter list of this message.
322 * @param mixed [$params,...] Parameters as strings, or a single argument that is
323 * an array of strings.
325 * @return Message $this
327 public function params( /*...*/ ) {
328 $args = func_get_args();
329 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
332 $args_values = array_values( $args );
333 $this->parameters
= array_merge( $this->parameters
, $args_values );
338 * Add parameters that are substituted after parsing or escaping.
339 * In other words the parsing process cannot access the contents
340 * of this type of parameter, and you need to make sure it is
341 * sanitized beforehand. The parser will see "$n", instead.
345 * @param mixed [$params,...] Raw parameters as strings, or a single argument that is
346 * an array of raw parameters.
348 * @return Message $this
350 public function rawParams( /*...*/ ) {
351 $params = func_get_args();
352 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
353 $params = $params[0];
355 foreach ( $params as $param ) {
356 $this->parameters
[] = self
::rawParam( $param );
362 * Add parameters that are numeric and will be passed through
363 * Language::formatNum before substitution
367 * @param mixed [$param,...] Numeric parameters, or a single argument that is
368 * an array of numeric parameters.
370 * @return Message $this
372 public function numParams( /*...*/ ) {
373 $params = func_get_args();
374 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
375 $params = $params[0];
377 foreach ( $params as $param ) {
378 $this->parameters
[] = self
::numParam( $param );
384 * Add parameters that are durations of time and will be passed through
385 * Language::formatDuration before substitution
389 * @param int|int[] [$param,...] Duration parameters, or a single argument that is
390 * an array of duration parameters.
392 * @return Message $this
394 public function durationParams( /*...*/ ) {
395 $params = func_get_args();
396 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
397 $params = $params[0];
399 foreach ( $params as $param ) {
400 $this->parameters
[] = self
::durationParam( $param );
406 * Add parameters that are expiration times and will be passed through
407 * Language::formatExpiry before substitution
411 * @param string|string[] [$param,...] Expiry parameters, or a single argument that is
412 * an array of expiry parameters.
414 * @return Message $this
416 public function expiryParams( /*...*/ ) {
417 $params = func_get_args();
418 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
419 $params = $params[0];
421 foreach ( $params as $param ) {
422 $this->parameters
[] = self
::expiryParam( $param );
428 * Add parameters that are time periods and will be passed through
429 * Language::formatTimePeriod before substitution
433 * @param number|number[] [$param,...] Time period parameters, or a single argument that is
434 * an array of time period parameters.
436 * @return Message $this
438 public function timeperiodParams( /*...*/ ) {
439 $params = func_get_args();
440 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
441 $params = $params[0];
443 foreach ( $params as $param ) {
444 $this->parameters
[] = self
::timeperiodParam( $param );
450 * Add parameters that are file sizes and will be passed through
451 * Language::formatSize before substitution
455 * @param int|int[] [$param,...] Size parameters, or a single argument that is
456 * an array of size parameters.
458 * @return Message $this
460 public function sizeParams( /*...*/ ) {
461 $params = func_get_args();
462 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
463 $params = $params[0];
465 foreach ( $params as $param ) {
466 $this->parameters
[] = self
::sizeParam( $param );
472 * Add parameters that are bitrates and will be passed through
473 * Language::formatBitrate before substitution
477 * @param int|int[] [$param,...] Bit rate parameters, or a single argument that is
478 * an array of bit rate parameters.
480 * @return Message $this
482 public function bitrateParams( /*...*/ ) {
483 $params = func_get_args();
484 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
485 $params = $params[0];
487 foreach ( $params as $param ) {
488 $this->parameters
[] = self
::bitrateParam( $param );
494 * Set the language and the title from a context object
498 * @param $context IContextSource
500 * @return Message $this
502 public function setContext( IContextSource
$context ) {
503 $this->inLanguage( $context->getLanguage() );
504 $this->title( $context->getTitle() );
505 $this->interface = true;
511 * Request the message in any language that is supported.
512 * As a side effect interface message status is unconditionally
517 * @param Language|string $lang Language code or Language object.
519 * @return Message $this
520 * @throws MWException
522 public function inLanguage( $lang ) {
523 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
524 $this->language
= $lang;
525 } elseif ( is_string( $lang ) ) {
526 if ( $this->language
->getCode() != $lang ) {
527 $this->language
= Language
::factory( $lang );
530 $type = gettype( $lang );
531 throw new MWException( __METHOD__
. " must be "
532 . "passed a String or Language object; $type given"
535 $this->interface = false;
540 * Request the message in the wiki's content language,
541 * unless it is disabled for this message.
544 * @see $wgForceUIMsgAsContentMsg
546 * @return Message $this
548 public function inContentLanguage() {
549 global $wgForceUIMsgAsContentMsg;
550 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
555 $this->interface = false;
556 $this->language
= $wgContLang;
561 * Allows manipulating the interface message flag directly.
562 * Can be used to restore the flag after setting a language.
566 * @param bool $interface
568 * @return Message $this
570 public function setInterfaceMessageFlag( $interface ) {
571 $this->interface = (bool)$interface;
576 * Enable or disable database use.
580 * @param bool $useDatabase
582 * @return Message $this
584 public function useDatabase( $useDatabase ) {
585 $this->useDatabase
= (bool)$useDatabase;
590 * Set the Title object to use as context when transforming the message
594 * @param $title Title object
596 * @return Message $this
598 public function title( $title ) {
599 $this->title
= $title;
604 * Returns the message as a Content object.
608 public function content() {
609 if ( !$this->content
) {
610 $this->content
= new MessageContent( $this );
613 return $this->content
;
617 * Returns the message parsed from wikitext to HTML.
621 * @return string HTML
623 public function toString() {
624 $string = $this->fetchMessage();
626 if ( $string === false ) {
627 $key = htmlspecialchars( is_array( $this->key
) ?
$this->key
[0] : $this->key
);
628 if ( $this->format
=== 'plain' ) {
629 return '<' . $key . '>';
631 return '<' . $key . '>';
634 # Replace $* with a list of parameters for &uselang=qqx.
635 if ( strpos( $string, '$*' ) !== false ) {
637 if ( $this->parameters
!== array() ) {
638 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
640 $string = str_replace( '$*', $paramlist, $string );
643 # Replace parameters before text parsing
644 $string = $this->replaceParameters( $string, 'before' );
646 # Maybe transform using the full parser
647 if ( $this->format
=== 'parse' ) {
648 $string = $this->parseText( $string );
650 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
653 } elseif ( $this->format
=== 'block-parse' ) {
654 $string = $this->parseText( $string );
655 } elseif ( $this->format
=== 'text' ) {
656 $string = $this->transformText( $string );
657 } elseif ( $this->format
=== 'escaped' ) {
658 $string = $this->transformText( $string );
659 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
662 # Raw parameter replacement
663 $string = $this->replaceParameters( $string, 'after' );
669 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
670 * $foo = Message::get( $key );
671 * $string = "<abbr>$foo</abbr>";
677 public function __toString() {
678 // PHP doesn't allow __toString to throw exceptions and will
679 // trigger a fatal error if it does. So, catch any exceptions.
682 return $this->toString();
683 } catch ( Exception
$ex ) {
685 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
686 . $ex, E_USER_WARNING
);
687 } catch ( Exception
$ex ) {
688 // Doh! Cause a fatal error after all?
691 if ( $this->format
=== 'plain' ) {
692 return '<' . $this->key
. '>';
694 return '<' . $this->key
. '>';
699 * Fully parse the text from wikitext to HTML.
703 * @return string Parsed HTML.
705 public function parse() {
706 $this->format
= 'parse';
707 return $this->toString();
711 * Returns the message text. {{-transformation is done.
715 * @return string Unescaped message text.
717 public function text() {
718 $this->format
= 'text';
719 return $this->toString();
723 * Returns the message text as-is, only parameters are substituted.
727 * @return string Unescaped untransformed message text.
729 public function plain() {
730 $this->format
= 'plain';
731 return $this->toString();
735 * Returns the parsed message text which is always surrounded by a block element.
739 * @return string HTML
741 public function parseAsBlock() {
742 $this->format
= 'block-parse';
743 return $this->toString();
747 * Returns the message text. {{-transformation is done and the result
748 * is escaped excluding any raw parameters.
752 * @return string Escaped message text.
754 public function escaped() {
755 $this->format
= 'escaped';
756 return $this->toString();
760 * Check whether a message key has been defined currently.
766 public function exists() {
767 return $this->fetchMessage() !== false;
771 * Check whether a message does not exist, or is an empty string
774 * @todo FIXME: Merge with isDisabled()?
778 public function isBlank() {
779 $message = $this->fetchMessage();
780 return $message === false ||
$message === '';
784 * Check whether a message does not exist, is an empty string, or is "-".
790 public function isDisabled() {
791 $message = $this->fetchMessage();
792 return $message === false ||
$message === '' ||
$message === '-';
800 * @return array Array with a single "raw" key.
802 public static function rawParam( $raw ) {
803 return array( 'raw' => $raw );
811 * @return array Array with a single "num" key.
813 public static function numParam( $num ) {
814 return array( 'num' => $num );
820 * @param int $duration
822 * @return int[] Array with a single "duration" key.
824 public static function durationParam( $duration ) {
825 return array( 'duration' => $duration );
831 * @param string $expiry
833 * @return string[] Array with a single "expiry" key.
835 public static function expiryParam( $expiry ) {
836 return array( 'expiry' => $expiry );
842 * @param number $period
844 * @return number[] Array with a single "period" key.
846 public static function timeperiodParam( $period ) {
847 return array( 'period' => $period );
855 * @return int[] Array with a single "size" key.
857 public static function sizeParam( $size ) {
858 return array( 'size' => $size );
864 * @param int $bitrate
866 * @return int[] Array with a single "bitrate" key.
868 public static function bitrateParam( $bitrate ) {
869 return array( 'bitrate' => $bitrate );
873 * Substitutes any parameters into the message text.
877 * @param string $message The message text.
878 * @param string $type Either "before" or "after".
882 protected function replaceParameters( $message, $type = 'before' ) {
883 $replacementKeys = array();
884 foreach ( $this->parameters
as $n => $param ) {
885 list( $paramType, $value ) = $this->extractParam( $param );
886 if ( $type === $paramType ) {
887 $replacementKeys['$' . ( $n +
1 )] = $value;
890 $message = strtr( $message, $replacementKeys );
895 * Extracts the parameter type and preprocessed the value if needed.
899 * @param mixed $param Parameter as defined in this class.
901 * @return array Array with the parameter type (either "before" or "after") and the value.
903 protected function extractParam( $param ) {
904 if ( is_array( $param ) ) {
905 if ( isset( $param['raw'] ) ) {
906 return array( 'after', $param['raw'] );
907 } elseif ( isset( $param['num'] ) ) {
908 // Replace number params always in before step for now.
909 // No support for combined raw and num params
910 return array( 'before', $this->language
->formatNum( $param['num'] ) );
911 } elseif ( isset( $param['duration'] ) ) {
912 return array( 'before', $this->language
->formatDuration( $param['duration'] ) );
913 } elseif ( isset( $param['expiry'] ) ) {
914 return array( 'before', $this->language
->formatExpiry( $param['expiry'] ) );
915 } elseif ( isset( $param['period'] ) ) {
916 return array( 'before', $this->language
->formatTimePeriod( $param['period'] ) );
917 } elseif ( isset( $param['size'] ) ) {
918 return array( 'before', $this->language
->formatSize( $param['size'] ) );
919 } elseif ( isset( $param['bitrate'] ) ) {
920 return array( 'before', $this->language
->formatBitrate( $param['bitrate'] ) );
922 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
923 htmlspecialchars( serialize( $param ) );
924 trigger_error( $warning, E_USER_WARNING
);
926 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
928 return array( 'before', '[INVALID]' );
930 } elseif ( $param instanceof Message
) {
931 // Message objects should not be before parameters because
932 // then they'll get double escaped. If the message needs to be
933 // escaped, it'll happen right here when we call toString().
934 return array( 'after', $param->toString() );
936 return array( 'before', $param );
941 * Wrapper for what ever method we use to parse wikitext.
945 * @param string $string Wikitext message contents.
947 * @return string Wikitext parsed into HTML.
949 protected function parseText( $string ) {
950 $out = MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
);
951 return $out instanceof ParserOutput ?
$out->getText() : $out;
955 * Wrapper for what ever method we use to {{-transform wikitext.
959 * @param string $string Wikitext message contents.
961 * @return string Wikitext with {{-constructs replaced with their values.
963 protected function transformText( $string ) {
964 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
968 * Wrapper for what ever method we use to get message contents.
973 * @throws MWException If message key array is empty.
975 protected function fetchMessage() {
976 if ( !isset( $this->message
) ) {
977 $cache = MessageCache
::singleton();
978 if ( is_array( $this->key
) ) {
979 if ( !count( $this->key
) ) {
980 throw new MWException( "Given empty message key array." );
982 foreach ( $this->key
as $key ) {
983 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
984 if ( $message !== false && $message !== '' ) {
988 $this->message
= $message;
990 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
993 return $this->message
;
999 * Variant of the Message class.
1001 * Rather than treating the message key as a lookup
1002 * value (which is passed to the MessageCache and
1003 * translated as necessary), a RawMessage key is
1004 * treated as the actual message.
1006 * All other functionality (parsing, escaping, etc.)
1011 class RawMessage
extends Message
{
1014 * Call the parent constructor, then store the key as
1017 * @see Message::__construct
1019 * @param string|string[] $key Message to use.
1020 * @param array $params Parameters for the message.
1022 public function __construct( $key, $params = array() ) {
1023 parent
::__construct( $key, $params );
1024 // The key is the message.
1025 $this->message
= $key;
1029 * Fetch the message (in this case, the key).
1033 public function fetchMessage() {
1034 // Just in case the message is unset somewhere.
1035 if ( !isset( $this->message
) ) {
1036 $this->message
= $this->key
;
1038 return $this->message
;