3 * The Message class provides methods which fullfil two basic services:
4 * - fetching interface messages
5 * - processing messages into a variety of formats
7 * First implemented with MediaWiki 1.17, the Message class is intented to
8 * replace the old wfMsg* functions that over time grew unusable.
9 * @see https://www.mediawiki.org/wiki/New_messages_API for equivalences
10 * between old and new functions.
12 * You should use the wfMessage() global function which acts as a wrapper for
13 * the Message class. The wrapper let you pass parameters as arguments.
15 * The most basic usage cases would be:
18 * // Initialize a Message object using the 'some_key' message key
19 * $message = wfMessage( 'some_key' );
21 * // Using two parameters those values are strings 'value1' and 'value2':
22 * $message = wfMessage( 'some_key',
27 * @section message_global_fn Global function wrapper:
29 * Since wfMessage() returns a Message instance, you can chain its call with
30 * a method. Some of them return a Message instance too so you can chain them.
31 * You will find below several examples of wfMessage() usage.
33 * Fetching a message text for interface message:
36 * $button = Xml::button(
37 * wfMessage( 'submit' )->text()
41 * A Message instance can be passed parameters after it has been constructed,
42 * use the params() method to do so:
45 * wfMessage( 'welcome-to' )
46 * ->params( $wgSitename )
50 * {{GRAMMAR}} and friends work correctly:
53 * wfMessage( 'are-friends',
56 * wfMessage( 'bad-message' )
57 * ->rawParams( '<script>...</script>' )
61 * @section message_language Changing language:
63 * Messages can be requested in a different language or in whatever current
64 * content language is being used. The methods are:
65 * - Message->inContentLanguage()
66 * - Message->inLanguage()
68 * Sometimes the message text ends up in the database, so content language is
72 * wfMessage( 'file-log',
74 * )->inContentLanguage()->text();
77 * Checking whether a message exists:
80 * wfMessage( 'mysterious-message' )->exists()
81 * // returns a boolean whether the 'mysterious-message' key exist.
84 * If you want to use a different language:
87 * $userLanguage = $user->getOption( 'language' );
88 * wfMessage( 'email-header' )
89 * ->inLanguage( $userLanguage )
93 * @note You can parse the text only in the content or interface languages
95 * @section message_compare_old Comparison with old wfMsg* functions:
101 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
103 * wfMessage( 'key', 'apple' )->parse();
106 * Parseinline is used because it is more useful when pre-building HTML.
107 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
109 * Places where HTML cannot be used. {{-transformation is done.
112 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
114 * wfMessage( 'key', 'apple', 'pear' )->text();
117 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
118 * parameters are not replaced after escaping by default.
120 * $escaped = wfMessage( 'key' )
121 * ->rawParams( 'apple' )
125 * @section message_appendix Appendix:
128 * - test, can we have tests?
129 * - this documentation needs to be extended
131 * @see https://www.mediawiki.org/wiki/WfMessage()
132 * @see https://www.mediawiki.org/wiki/New_messages_API
133 * @see https://www.mediawiki.org/wiki/Localisation
136 * @author Niklas Laxström
140 * In which language to get this message. True, which is the default,
141 * means the current interface language, false content language.
143 protected $interface = true;
146 * In which language to get this message. Overrides the $interface
151 protected $language = null;
159 * List of parameters which will be substituted into the message.
161 protected $parameters = array();
164 * Format for the message.
165 * Supported formats are:
167 * * escaped (transform+htmlspecialchars)
172 protected $format = 'parse';
175 * Whether database can be used.
177 protected $useDatabase = true;
180 * Title object to use as context
182 protected $title = null;
191 * @param $key: message key, or array of message keys to try and use the first non-empty message for
192 * @param $params Array message parameters
193 * @return Message: $this
195 public function __construct( $key, $params = array() ) {
198 $this->parameters
= array_values( $params );
199 $this->language
= $wgLang;
203 * Factory function that is just wrapper for the real constructor. It is
204 * intented to be used instead of the real constructor, because it allows
205 * chaining method calls, while new objects don't.
206 * @param $key String: message key
207 * @param Varargs: parameters as Strings
208 * @return Message: $this
210 public static function newFromKey( $key /*...*/ ) {
211 $params = func_get_args();
212 array_shift( $params );
213 return new self( $key, $params );
217 * Factory function accepting multiple message keys and returning a message instance
218 * for the first message which is non-empty. If all messages are empty then an
219 * instance of the first message key is returned.
220 * @param Varargs: message keys (or first arg as an array of all the message keys)
221 * @return Message: $this
223 public static function newFallbackSequence( /*...*/ ) {
224 $keys = func_get_args();
225 if ( func_num_args() == 1 ) {
226 if ( is_array($keys[0]) ) {
227 // Allow an array to be passed as the first argument instead
228 $keys = array_values($keys[0]);
230 // Optimize a single string to not need special fallback handling
234 return new self( $keys );
238 * Adds parameters to the parameter list of this message.
239 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
240 * @return Message: $this
242 public function params( /*...*/ ) {
243 $args = func_get_args();
244 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
247 $args_values = array_values( $args );
248 $this->parameters
= array_merge( $this->parameters
, $args_values );
253 * Add parameters that are substituted after parsing or escaping.
254 * In other words the parsing process cannot access the contents
255 * of this type of parameter, and you need to make sure it is
256 * sanitized beforehand. The parser will see "$n", instead.
257 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
258 * @return Message: $this
260 public function rawParams( /*...*/ ) {
261 $params = func_get_args();
262 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
263 $params = $params[0];
265 foreach( $params as $param ) {
266 $this->parameters
[] = self
::rawParam( $param );
272 * Add parameters that are numeric and will be passed through
273 * Language::formatNum before substitution
274 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
275 * @return Message: $this
277 public function numParams( /*...*/ ) {
278 $params = func_get_args();
279 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
280 $params = $params[0];
282 foreach( $params as $param ) {
283 $this->parameters
[] = self
::numParam( $param );
289 * Set the language and the title from a context object
291 * @param $context IContextSource
292 * @return Message: $this
294 public function setContext( IContextSource
$context ) {
295 $this->inLanguage( $context->getLanguage() );
296 $this->title( $context->getTitle() );
297 $this->interface = true;
303 * Request the message in any language that is supported.
304 * As a side effect interface message status is unconditionally
306 * @param $lang Mixed: language code or Language object.
307 * @return Message: $this
309 public function inLanguage( $lang ) {
310 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
311 $this->language
= $lang;
312 } elseif ( is_string( $lang ) ) {
313 if( $this->language
->getCode() != $lang ) {
314 $this->language
= Language
::factory( $lang );
317 $type = gettype( $lang );
318 throw new MWException( __METHOD__
. " must be "
319 . "passed a String or Language object; $type given"
322 $this->interface = false;
327 * Request the message in the wiki's content language,
328 * unless it is disabled for this message.
329 * @see $wgForceUIMsgAsContentMsg
330 * @return Message: $this
332 public function inContentLanguage() {
333 global $wgForceUIMsgAsContentMsg;
334 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
339 $this->interface = false;
340 $this->language
= $wgContLang;
345 * Allows manipulating the interface message flag directly.
346 * Can be used to restore the flag after setting a language.
348 * @return Message: $this
351 public function setInterfaceMessageFlag( $value ) {
352 $this->interface = (bool) $value;
357 * Enable or disable database use.
358 * @param $value Boolean
359 * @return Message: $this
361 public function useDatabase( $value ) {
362 $this->useDatabase
= (bool) $value;
367 * Set the Title object to use as context when transforming the message
369 * @param $title Title object
370 * @return Message: $this
372 public function title( $title ) {
373 $this->title
= $title;
378 * Returns the message parsed from wikitext to HTML.
379 * @return String: HTML
381 public function toString() {
382 $string = $this->fetchMessage();
384 if ( $string === false ) {
385 $key = htmlspecialchars( is_array( $this->key
) ?
$this->key
[0] : $this->key
);
386 if ( $this->format
=== 'plain' ) {
387 return '<' . $key . '>';
389 return '<' . $key . '>';
392 # Replace parameters before text parsing
393 $string = $this->replaceParameters( $string, 'before' );
395 # Maybe transform using the full parser
396 if( $this->format
=== 'parse' ) {
397 $string = $this->parseText( $string );
399 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
402 } elseif( $this->format
=== 'block-parse' ){
403 $string = $this->parseText( $string );
404 } elseif( $this->format
=== 'text' ){
405 $string = $this->transformText( $string );
406 } elseif( $this->format
=== 'escaped' ){
407 $string = $this->transformText( $string );
408 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
411 # Raw parameter replacement
412 $string = $this->replaceParameters( $string, 'after' );
418 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
419 * $foo = Message::get($key);
420 * $string = "<abbr>$foo</abbr>";
423 public function __toString() {
424 return $this->toString();
428 * Fully parse the text from wikitext to HTML
429 * @return String parsed HTML
431 public function parse() {
432 $this->format
= 'parse';
433 return $this->toString();
437 * Returns the message text. {{-transformation is done.
438 * @return String: Unescaped message text.
440 public function text() {
441 $this->format
= 'text';
442 return $this->toString();
446 * Returns the message text as-is, only parameters are subsituted.
447 * @return String: Unescaped untransformed message text.
449 public function plain() {
450 $this->format
= 'plain';
451 return $this->toString();
455 * Returns the parsed message text which is always surrounded by a block element.
456 * @return String: HTML
458 public function parseAsBlock() {
459 $this->format
= 'block-parse';
460 return $this->toString();
464 * Returns the message text. {{-transformation is done and the result
465 * is escaped excluding any raw parameters.
466 * @return String: Escaped message text.
468 public function escaped() {
469 $this->format
= 'escaped';
470 return $this->toString();
474 * Check whether a message key has been defined currently.
475 * @return Bool: true if it is and false if not.
477 public function exists() {
478 return $this->fetchMessage() !== false;
482 * Check whether a message does not exist, or is an empty string
483 * @return Bool: true if is is and false if not
484 * @todo FIXME: Merge with isDisabled()?
486 public function isBlank() {
487 $message = $this->fetchMessage();
488 return $message === false ||
$message === '';
492 * Check whether a message does not exist, is an empty string, or is "-"
493 * @return Bool: true if is is and false if not
495 public function isDisabled() {
496 $message = $this->fetchMessage();
497 return $message === false ||
$message === '' ||
$message === '-';
504 public static function rawParam( $value ) {
505 return array( 'raw' => $value );
512 public static function numParam( $value ) {
513 return array( 'num' => $value );
517 * Substitutes any paramaters into the message text.
518 * @param $message String: the message text
519 * @param $type String: either before or after
522 protected function replaceParameters( $message, $type = 'before' ) {
523 $replacementKeys = array();
524 foreach( $this->parameters
as $n => $param ) {
525 list( $paramType, $value ) = $this->extractParam( $param );
526 if ( $type === $paramType ) {
527 $replacementKeys['$' . ($n +
1)] = $value;
530 $message = strtr( $message, $replacementKeys );
535 * Extracts the parameter type and preprocessed the value if needed.
536 * @param $param String|Array: Parameter as defined in this class.
537 * @return Tuple(type, value)
538 * @throws MWException
540 protected function extractParam( $param ) {
541 if ( is_array( $param ) && isset( $param['raw'] ) ) {
542 return array( 'after', $param['raw'] );
543 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
544 // Replace number params always in before step for now.
545 // No support for combined raw and num params
546 return array( 'before', $this->language
->formatNum( $param['num'] ) );
547 } elseif ( !is_array( $param ) ) {
548 return array( 'before', $param );
550 throw new MWException( "Invalid message parameter" );
555 * Wrapper for what ever method we use to parse wikitext.
556 * @param $string String: Wikitext message contents
557 * @return string Wikitext parsed into HTML
559 protected function parseText( $string ) {
560 return MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
)->getText();
564 * Wrapper for what ever method we use to {{-transform wikitext.
565 * @param $string String: Wikitext message contents
566 * @return string Wikitext with {{-constructs replaced with their values.
568 protected function transformText( $string ) {
569 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
573 * Wrapper for what ever method we use to get message contents
577 protected function fetchMessage() {
578 if ( !isset( $this->message
) ) {
579 $cache = MessageCache
::singleton();
580 if ( is_array( $this->key
) ) {
581 if ( !count( $this->key
) ) {
582 throw new MWException( "Given empty message key array." );
584 foreach ( $this->key
as $key ) {
585 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
586 if ( $message !== false && $message !== '' ) {
590 $this->message
= $message;
592 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
595 return $this->message
;