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 * Factory function that is just wrapper for the real constructor. It is
277 * intended to be used instead of the real constructor, because it allows
278 * chaining method calls, while new objects don't.
282 * @param string|string[] $key Message key or array of keys.
283 * @param mixed [$param,...] Parameters as strings.
287 public static function newFromKey( $key /*...*/ ) {
288 $params = func_get_args();
289 array_shift( $params );
290 return new self( $key, $params );
294 * Factory function accepting multiple message keys and returning a message instance
295 * for the first message which is non-empty. If all messages are empty then an
296 * instance of the first message key is returned.
300 * @param string|string[] [$keys,...] Message keys, or first argument as an array of all the
305 public static function newFallbackSequence( /*...*/ ) {
306 $keys = func_get_args();
307 if ( func_num_args() == 1 ) {
308 if ( is_array( $keys[0] ) ) {
309 // Allow an array to be passed as the first argument instead
310 $keys = array_values( $keys[0] );
312 // Optimize a single string to not need special fallback handling
316 return new self( $keys );
320 * Adds parameters to the parameter list of this message.
324 * @param mixed [$params,...] Parameters as strings, or a single argument that is
325 * an array of strings.
327 * @return Message $this
329 public function params( /*...*/ ) {
330 $args = func_get_args();
331 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
334 $args_values = array_values( $args );
335 $this->parameters
= array_merge( $this->parameters
, $args_values );
340 * Add parameters that are substituted after parsing or escaping.
341 * In other words the parsing process cannot access the contents
342 * of this type of parameter, and you need to make sure it is
343 * sanitized beforehand. The parser will see "$n", instead.
347 * @param mixed [$params,...] Raw parameters as strings, or a single argument that is
348 * an array of raw parameters.
350 * @return Message $this
352 public function rawParams( /*...*/ ) {
353 $params = func_get_args();
354 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
355 $params = $params[0];
357 foreach ( $params as $param ) {
358 $this->parameters
[] = self
::rawParam( $param );
364 * Add parameters that are numeric and will be passed through
365 * Language::formatNum before substitution
369 * @param mixed [$param,...] Numeric parameters, or a single argument that is
370 * an array of numeric parameters.
372 * @return Message $this
374 public function numParams( /*...*/ ) {
375 $params = func_get_args();
376 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
377 $params = $params[0];
379 foreach ( $params as $param ) {
380 $this->parameters
[] = self
::numParam( $param );
386 * Add parameters that are durations of time and will be passed through
387 * Language::formatDuration before substitution
391 * @param int|int[] [$param,...] Duration parameters, or a single argument that is
392 * an array of duration parameters.
394 * @return Message $this
396 public function durationParams( /*...*/ ) {
397 $params = func_get_args();
398 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
399 $params = $params[0];
401 foreach ( $params as $param ) {
402 $this->parameters
[] = self
::durationParam( $param );
408 * Add parameters that are expiration times and will be passed through
409 * Language::formatExpiry before substitution
413 * @param string|string[] [$param,...] Expiry parameters, or a single argument that is
414 * an array of expiry parameters.
416 * @return Message $this
418 public function expiryParams( /*...*/ ) {
419 $params = func_get_args();
420 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
421 $params = $params[0];
423 foreach ( $params as $param ) {
424 $this->parameters
[] = self
::expiryParam( $param );
430 * Add parameters that are time periods and will be passed through
431 * Language::formatTimePeriod before substitution
435 * @param number|number[] [$param,...] Time period parameters, or a single argument that is
436 * an array of time period parameters.
438 * @return Message $this
440 public function timeperiodParams( /*...*/ ) {
441 $params = func_get_args();
442 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
443 $params = $params[0];
445 foreach ( $params as $param ) {
446 $this->parameters
[] = self
::timeperiodParam( $param );
452 * Add parameters that are file sizes and will be passed through
453 * Language::formatSize before substitution
457 * @param int|int[] [$param,...] Size parameters, or a single argument that is
458 * an array of size parameters.
460 * @return Message $this
462 public function sizeParams( /*...*/ ) {
463 $params = func_get_args();
464 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
465 $params = $params[0];
467 foreach ( $params as $param ) {
468 $this->parameters
[] = self
::sizeParam( $param );
474 * Add parameters that are bitrates and will be passed through
475 * Language::formatBitrate before substitution
479 * @param int|int[] [$param,...] Bit rate parameters, or a single argument that is
480 * an array of bit rate parameters.
482 * @return Message $this
484 public function bitrateParams( /*...*/ ) {
485 $params = func_get_args();
486 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
487 $params = $params[0];
489 foreach ( $params as $param ) {
490 $this->parameters
[] = self
::bitrateParam( $param );
496 * Set the language and the title from a context object
500 * @param $context IContextSource
502 * @return Message $this
504 public function setContext( IContextSource
$context ) {
505 $this->inLanguage( $context->getLanguage() );
506 $this->title( $context->getTitle() );
507 $this->interface = true;
513 * Request the message in any language that is supported.
514 * As a side effect interface message status is unconditionally
519 * @param Language|string $lang Language code or Language object.
521 * @return Message $this
522 * @throws MWException
524 public function inLanguage( $lang ) {
525 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
526 $this->language
= $lang;
527 } elseif ( is_string( $lang ) ) {
528 if ( $this->language
->getCode() != $lang ) {
529 $this->language
= Language
::factory( $lang );
532 $type = gettype( $lang );
533 throw new MWException( __METHOD__
. " must be "
534 . "passed a String or Language object; $type given"
537 $this->interface = false;
542 * Request the message in the wiki's content language,
543 * unless it is disabled for this message.
546 * @see $wgForceUIMsgAsContentMsg
548 * @return Message $this
550 public function inContentLanguage() {
551 global $wgForceUIMsgAsContentMsg;
552 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
557 $this->interface = false;
558 $this->language
= $wgContLang;
563 * Allows manipulating the interface message flag directly.
564 * Can be used to restore the flag after setting a language.
568 * @param bool $interface
570 * @return Message $this
572 public function setInterfaceMessageFlag( $interface ) {
573 $this->interface = (bool)$interface;
578 * Enable or disable database use.
582 * @param bool $useDatabase
584 * @return Message $this
586 public function useDatabase( $useDatabase ) {
587 $this->useDatabase
= (bool)$useDatabase;
592 * Set the Title object to use as context when transforming the message
596 * @param $title Title object
598 * @return Message $this
600 public function title( $title ) {
601 $this->title
= $title;
606 * Returns the message as a Content object.
610 public function content() {
611 if ( !$this->content
) {
612 $this->content
= new MessageContent( $this );
615 return $this->content
;
619 * Returns the message parsed from wikitext to HTML.
623 * @return string HTML
625 public function toString() {
626 $string = $this->fetchMessage();
628 if ( $string === false ) {
629 $key = htmlspecialchars( is_array( $this->key
) ?
$this->key
[0] : $this->key
);
630 if ( $this->format
=== 'plain' ) {
631 return '<' . $key . '>';
633 return '<' . $key . '>';
636 # Replace $* with a list of parameters for &uselang=qqx.
637 if ( strpos( $string, '$*' ) !== false ) {
639 if ( $this->parameters
!== array() ) {
640 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters
) ) );
642 $string = str_replace( '$*', $paramlist, $string );
645 # Replace parameters before text parsing
646 $string = $this->replaceParameters( $string, 'before' );
648 # Maybe transform using the full parser
649 if ( $this->format
=== 'parse' ) {
650 $string = $this->parseText( $string );
652 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
655 } elseif ( $this->format
=== 'block-parse' ) {
656 $string = $this->parseText( $string );
657 } elseif ( $this->format
=== 'text' ) {
658 $string = $this->transformText( $string );
659 } elseif ( $this->format
=== 'escaped' ) {
660 $string = $this->transformText( $string );
661 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
664 # Raw parameter replacement
665 $string = $this->replaceParameters( $string, 'after' );
671 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
672 * $foo = Message::get( $key );
673 * $string = "<abbr>$foo</abbr>";
679 public function __toString() {
680 // PHP doesn't allow __toString to throw exceptions and will
681 // trigger a fatal error if it does. So, catch any exceptions.
684 return $this->toString();
685 } catch ( Exception
$ex ) {
687 trigger_error( "Exception caught in " . __METHOD__
. " (message " . $this->key
. "): "
688 . $ex, E_USER_WARNING
);
689 } catch ( Exception
$ex ) {
690 // Doh! Cause a fatal error after all?
693 if ( $this->format
=== 'plain' ) {
694 return '<' . $this->key
. '>';
696 return '<' . $this->key
. '>';
701 * Fully parse the text from wikitext to HTML.
705 * @return string Parsed HTML.
707 public function parse() {
708 $this->format
= 'parse';
709 return $this->toString();
713 * Returns the message text. {{-transformation is done.
717 * @return string Unescaped message text.
719 public function text() {
720 $this->format
= 'text';
721 return $this->toString();
725 * Returns the message text as-is, only parameters are substituted.
729 * @return string Unescaped untransformed message text.
731 public function plain() {
732 $this->format
= 'plain';
733 return $this->toString();
737 * Returns the parsed message text which is always surrounded by a block element.
741 * @return string HTML
743 public function parseAsBlock() {
744 $this->format
= 'block-parse';
745 return $this->toString();
749 * Returns the message text. {{-transformation is done and the result
750 * is escaped excluding any raw parameters.
754 * @return string Escaped message text.
756 public function escaped() {
757 $this->format
= 'escaped';
758 return $this->toString();
762 * Check whether a message key has been defined currently.
768 public function exists() {
769 return $this->fetchMessage() !== false;
773 * Check whether a message does not exist, or is an empty string
776 * @todo FIXME: Merge with isDisabled()?
780 public function isBlank() {
781 $message = $this->fetchMessage();
782 return $message === false ||
$message === '';
786 * Check whether a message does not exist, is an empty string, or is "-".
792 public function isDisabled() {
793 $message = $this->fetchMessage();
794 return $message === false ||
$message === '' ||
$message === '-';
802 * @return array Array with a single "raw" key.
804 public static function rawParam( $raw ) {
805 return array( 'raw' => $raw );
813 * @return array Array with a single "num" key.
815 public static function numParam( $num ) {
816 return array( 'num' => $num );
822 * @param int $duration
824 * @return int[] Array with a single "duration" key.
826 public static function durationParam( $duration ) {
827 return array( 'duration' => $duration );
833 * @param string $expiry
835 * @return string[] Array with a single "expiry" key.
837 public static function expiryParam( $expiry ) {
838 return array( 'expiry' => $expiry );
844 * @param number $period
846 * @return number[] Array with a single "period" key.
848 public static function timeperiodParam( $period ) {
849 return array( 'period' => $period );
857 * @return int[] Array with a single "size" key.
859 public static function sizeParam( $size ) {
860 return array( 'size' => $size );
866 * @param int $bitrate
868 * @return int[] Array with a single "bitrate" key.
870 public static function bitrateParam( $bitrate ) {
871 return array( 'bitrate' => $bitrate );
875 * Substitutes any parameters into the message text.
879 * @param string $message The message text.
880 * @param string $type Either "before" or "after".
884 protected function replaceParameters( $message, $type = 'before' ) {
885 $replacementKeys = array();
886 foreach ( $this->parameters
as $n => $param ) {
887 list( $paramType, $value ) = $this->extractParam( $param );
888 if ( $type === $paramType ) {
889 $replacementKeys['$' . ( $n +
1 )] = $value;
892 $message = strtr( $message, $replacementKeys );
897 * Extracts the parameter type and preprocessed the value if needed.
901 * @param mixed $param Parameter as defined in this class.
903 * @return array Array with the parameter type (either "before" or "after") and the value.
905 protected function extractParam( $param ) {
906 if ( is_array( $param ) ) {
907 if ( isset( $param['raw'] ) ) {
908 return array( 'after', $param['raw'] );
909 } elseif ( isset( $param['num'] ) ) {
910 // Replace number params always in before step for now.
911 // No support for combined raw and num params
912 return array( 'before', $this->language
->formatNum( $param['num'] ) );
913 } elseif ( isset( $param['duration'] ) ) {
914 return array( 'before', $this->language
->formatDuration( $param['duration'] ) );
915 } elseif ( isset( $param['expiry'] ) ) {
916 return array( 'before', $this->language
->formatExpiry( $param['expiry'] ) );
917 } elseif ( isset( $param['period'] ) ) {
918 return array( 'before', $this->language
->formatTimePeriod( $param['period'] ) );
919 } elseif ( isset( $param['size'] ) ) {
920 return array( 'before', $this->language
->formatSize( $param['size'] ) );
921 } elseif ( isset( $param['bitrate'] ) ) {
922 return array( 'before', $this->language
->formatBitrate( $param['bitrate'] ) );
924 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
925 htmlspecialchars( serialize( $param ) );
926 trigger_error( $warning, E_USER_WARNING
);
928 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
930 return array( 'before', '[INVALID]' );
932 } elseif ( $param instanceof Message
) {
933 // Message objects should not be before parameters because
934 // then they'll get double escaped. If the message needs to be
935 // escaped, it'll happen right here when we call toString().
936 return array( 'after', $param->toString() );
938 return array( 'before', $param );
943 * Wrapper for what ever method we use to parse wikitext.
947 * @param string $string Wikitext message contents.
949 * @return string Wikitext parsed into HTML.
951 protected function parseText( $string ) {
952 $out = MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
);
953 return $out instanceof ParserOutput ?
$out->getText() : $out;
957 * Wrapper for what ever method we use to {{-transform wikitext.
961 * @param string $string Wikitext message contents.
963 * @return string Wikitext with {{-constructs replaced with their values.
965 protected function transformText( $string ) {
966 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
970 * Wrapper for what ever method we use to get message contents.
975 * @throws MWException If message key array is empty.
977 protected function fetchMessage() {
978 if ( !isset( $this->message
) ) {
979 $cache = MessageCache
::singleton();
980 if ( is_array( $this->key
) ) {
981 if ( !count( $this->key
) ) {
982 throw new MWException( "Given empty message key array." );
984 foreach ( $this->key
as $key ) {
985 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
986 if ( $message !== false && $message !== '' ) {
990 $this->message
= $message;
992 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
995 return $this->message
;
1001 * Variant of the Message class.
1003 * Rather than treating the message key as a lookup
1004 * value (which is passed to the MessageCache and
1005 * translated as necessary), a RawMessage key is
1006 * treated as the actual message.
1008 * All other functionality (parsing, escaping, etc.)
1013 class RawMessage
extends Message
{
1016 * Call the parent constructor, then store the key as
1019 * @see Message::__construct
1021 * @param string|string[] $key Message to use.
1022 * @param array $params Parameters for the message.
1024 public function __construct( $key, $params = array() ) {
1025 parent
::__construct( $key, $params );
1026 // The key is the message.
1027 $this->message
= $key;
1031 * Fetch the message (in this case, the key).
1035 public function fetchMessage() {
1036 // Just in case the message is unset somewhere.
1037 if ( !isset( $this->message
) ) {
1038 $this->message
= $this->key
;
1040 return $this->message
;