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 cannot parse the text except in the content or interface
96 * @section message_compare_old Comparison with old wfMsg* functions:
102 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
104 * wfMessage( 'key', 'apple' )->parse();
107 * Parseinline is used because it is more useful when pre-building HTML.
108 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
110 * Places where HTML cannot be used. {{-transformation is done.
113 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
115 * wfMessage( 'key', 'apple', 'pear' )->text();
118 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
119 * parameters are not replaced after escaping by default.
121 * $escaped = wfMessage( 'key' )
122 * ->rawParams( 'apple' )
126 * @section message_appendix Appendix:
129 * - test, can we have tests?
130 * - this documentation needs to be extended
132 * @see https://www.mediawiki.org/wiki/WfMessage()
133 * @see https://www.mediawiki.org/wiki/New_messages_API
134 * @see https://www.mediawiki.org/wiki/Localisation
137 * @author Niklas Laxström
141 * In which language to get this message. True, which is the default,
142 * means the current interface language, false content language.
144 protected $interface = true;
147 * In which language to get this message. Overrides the $interface
152 protected $language = null;
160 * List of parameters which will be substituted into the message.
162 protected $parameters = array();
165 * Format for the message.
166 * Supported formats are:
168 * * escaped (transform+htmlspecialchars)
173 protected $format = 'parse';
176 * Whether database can be used.
178 protected $useDatabase = true;
181 * Title object to use as context
183 protected $title = null;
192 * @param $key: message key, or array of message keys to try and use the first non-empty message for
193 * @param $params Array message parameters
194 * @return Message: $this
196 public function __construct( $key, $params = array() ) {
199 $this->parameters
= array_values( $params );
200 $this->language
= $wgLang;
204 * Factory function that is just wrapper for the real constructor. It is
205 * intented to be used instead of the real constructor, because it allows
206 * chaining method calls, while new objects don't.
207 * @param $key String: message key
208 * @param Varargs: parameters as Strings
209 * @return Message: $this
211 public static function newFromKey( $key /*...*/ ) {
212 $params = func_get_args();
213 array_shift( $params );
214 return new self( $key, $params );
218 * Factory function accepting multiple message keys and returning a message instance
219 * for the first message which is non-empty. If all messages are empty then an
220 * instance of the first message key is returned.
221 * @param Varargs: message keys (or first arg as an array of all the message keys)
222 * @return Message: $this
224 public static function newFallbackSequence( /*...*/ ) {
225 $keys = func_get_args();
226 if ( func_num_args() == 1 ) {
227 if ( is_array($keys[0]) ) {
228 // Allow an array to be passed as the first argument instead
229 $keys = array_values($keys[0]);
231 // Optimize a single string to not need special fallback handling
235 return new self( $keys );
239 * Adds parameters to the parameter list of this message.
240 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
241 * @return Message: $this
243 public function params( /*...*/ ) {
244 $args = func_get_args();
245 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
248 $args_values = array_values( $args );
249 $this->parameters
= array_merge( $this->parameters
, $args_values );
254 * Add parameters that are substituted after parsing or escaping.
255 * In other words the parsing process cannot access the contents
256 * of this type of parameter, and you need to make sure it is
257 * sanitized beforehand. The parser will see "$n", instead.
258 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
259 * @return Message: $this
261 public function rawParams( /*...*/ ) {
262 $params = func_get_args();
263 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
264 $params = $params[0];
266 foreach( $params as $param ) {
267 $this->parameters
[] = self
::rawParam( $param );
273 * Add parameters that are numeric and will be passed through
274 * Language::formatNum before substitution
275 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
276 * @return Message: $this
278 public function numParams( /*...*/ ) {
279 $params = func_get_args();
280 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
281 $params = $params[0];
283 foreach( $params as $param ) {
284 $this->parameters
[] = self
::numParam( $param );
290 * Set the language and the title from a context object
292 * @param $context IContextSource
293 * @return Message: $this
295 public function setContext( IContextSource
$context ) {
296 $this->inLanguage( $context->getLanguage() );
297 $this->title( $context->getTitle() );
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 * Enable or disable database use.
346 * @param $value Boolean
347 * @return Message: $this
349 public function useDatabase( $value ) {
350 $this->useDatabase
= (bool) $value;
355 * Set the Title object to use as context when transforming the message
357 * @param $title Title object
358 * @return Message: $this
360 public function title( $title ) {
361 $this->title
= $title;
366 * Returns the message parsed from wikitext to HTML.
367 * @return String: HTML
369 public function toString() {
370 $string = $this->getMessageText();
372 # Replace parameters before text parsing
373 $string = $this->replaceParameters( $string, 'before' );
375 # Maybe transform using the full parser
376 if( $this->format
=== 'parse' ) {
377 $string = $this->parseText( $string );
379 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
382 } elseif( $this->format
=== 'block-parse' ){
383 $string = $this->parseText( $string );
384 } elseif( $this->format
=== 'text' ){
385 $string = $this->transformText( $string );
386 } elseif( $this->format
=== 'escaped' ){
387 $string = $this->transformText( $string );
388 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
391 # Raw parameter replacement
392 $string = $this->replaceParameters( $string, 'after' );
398 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
399 * $foo = Message::get($key);
400 * $string = "<abbr>$foo</abbr>";
403 public function __toString() {
404 return $this->toString();
408 * Fully parse the text from wikitext to HTML
409 * @return String parsed HTML
411 public function parse() {
412 $this->format
= 'parse';
413 return $this->toString();
417 * Returns the message text. {{-transformation is done.
418 * @return String: Unescaped message text.
420 public function text() {
421 $this->format
= 'text';
422 return $this->toString();
426 * Returns the message text as-is, only parameters are subsituted.
427 * @return String: Unescaped untransformed message text.
429 public function plain() {
430 $this->format
= 'plain';
431 return $this->toString();
435 * Returns the parsed message text which is always surrounded by a block element.
436 * @return String: HTML
438 public function parseAsBlock() {
439 $this->format
= 'block-parse';
440 return $this->toString();
444 * Returns the message text. {{-transformation is done and the result
445 * is escaped excluding any raw parameters.
446 * @return String: Escaped message text.
448 public function escaped() {
449 $this->format
= 'escaped';
450 return $this->toString();
454 * Check whether a message key has been defined currently.
455 * @return Bool: true if it is and false if not.
457 public function exists() {
458 return $this->fetchMessage() !== false;
462 * Check whether a message does not exist, or is an empty string
463 * @return Bool: true if is is and false if not
464 * @todo FIXME: Merge with isDisabled()?
466 public function isBlank() {
467 $message = $this->fetchMessage();
468 return $message === false ||
$message === '';
472 * Check whether a message does not exist, is an empty string, or is "-"
473 * @return Bool: true if is is and false if not
475 public function isDisabled() {
476 $message = $this->fetchMessage();
477 return $message === false ||
$message === '' ||
$message === '-';
484 public static function rawParam( $value ) {
485 return array( 'raw' => $value );
492 public static function numParam( $value ) {
493 return array( 'num' => $value );
497 * Substitutes any paramaters into the message text.
498 * @param $message String: the message text
499 * @param $type String: either before or after
502 protected function replaceParameters( $message, $type = 'before' ) {
503 $replacementKeys = array();
504 foreach( $this->parameters
as $n => $param ) {
505 list( $paramType, $value ) = $this->extractParam( $param );
506 if ( $type === $paramType ) {
507 $replacementKeys['$' . ($n +
1)] = $value;
510 $message = strtr( $message, $replacementKeys );
515 * Extracts the parameter type and preprocessed the value if needed.
516 * @param $param String|Array: Parameter as defined in this class.
517 * @return Tuple(type, value)
518 * @throws MWException
520 protected function extractParam( $param ) {
521 if ( is_array( $param ) && isset( $param['raw'] ) ) {
522 return array( 'after', $param['raw'] );
523 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
524 // Replace number params always in before step for now.
525 // No support for combined raw and num params
526 return array( 'before', $this->language
->formatNum( $param['num'] ) );
527 } elseif ( !is_array( $param ) ) {
528 return array( 'before', $param );
530 throw new MWException( "Invalid message parameter" );
535 * Wrapper for what ever method we use to parse wikitext.
536 * @param $string String: Wikitext message contents
537 * @return string Wikitext parsed into HTML
539 protected function parseText( $string ) {
540 return MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
)->getText();
544 * Wrapper for what ever method we use to {{-transform wikitext.
545 * @param $string String: Wikitext message contents
546 * @return string Wikitext with {{-constructs replaced with their values.
548 protected function transformText( $string ) {
549 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
553 * Returns the textual value for the message.
554 * @return Message contents or placeholder
556 protected function getMessageText() {
557 $message = $this->fetchMessage();
558 if ( $message === false ) {
559 return '<' . htmlspecialchars( is_array($this->key
) ?
$this->key
[0] : $this->key
) . '>';
566 * Wrapper for what ever method we use to get message contents
570 protected function fetchMessage() {
571 if ( !isset( $this->message
) ) {
572 $cache = MessageCache
::singleton();
573 if ( is_array( $this->key
) ) {
574 if ( !count( $this->key
) ) {
575 throw new MWException( "Given empty message key array." );
577 foreach ( $this->key
as $key ) {
578 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
579 if ( $message !== false && $message !== '' ) {
583 $this->message
= $message;
585 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
588 return $this->message
;