3 * This class provides methods for fetching interface messages and
4 * processing them into variety of formats that are needed in MediaWiki.
6 * It is intented to replace the old wfMsg* functions that over time grew
10 * Fetching a message text for interface message
11 * $button = Xml::button( wfMessage( 'submit' )->text() );
13 * Messages can have parameters:
14 * wfMessage( 'welcome-to' )->params( $wgSitename )->text();
15 * {{GRAMMAR}} and friends work correctly
16 * wfMessage( 'are-friends', $user, $friend );
17 * wfMessage( 'bad-message' )->rawParams( '<script>...</script>' )->escaped();
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
22 * Checking if message exists:
23 * wfMessage( 'mysterious-message' )->exists()
25 * If you want to use a different language:
26 * wfMessage( 'email-header' )->inLanguage( $user->getOption( 'language' ) )->plain()
27 * Note that you cannot parse the text except in the content or interface
32 * Comparison with old wfMsg* functions:
35 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
36 * === wfMessage( 'key', 'apple' )->parse();
38 * Parseinline is used because it is more useful when pre-building html.
39 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
41 * Places where html cannot be used. {{-transformation is done.
42 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
43 * === wfMessage( 'key', 'apple', 'pear' )->text();
46 * Shortcut for escaping the message too, similar to wfMsgHTML, but
47 * parameters are not replaced after escaping by default.
48 * $escaped = wfMessage( 'key' )->rawParams( 'apple' )->escaped();
52 * - test, can we have tests?
55 * @author Niklas Laxström
59 * In which language to get this message. True, which is the default,
60 * means the current interface language, false content language.
62 protected $interface = true;
65 * In which language to get this message. Overrides the $interface
70 protected $language = null;
78 * List of parameters which will be substituted into the message.
80 protected $parameters = array();
83 * Format for the message.
84 * Supported formats are:
86 * * escaped (transform+htmlspecialchars)
91 protected $format = 'parse';
94 * Whether database can be used.
96 protected $useDatabase = true;
99 * Title object to use as context
101 protected $title = null;
110 * @param $key: message key, or array of message keys to try and use the first non-empty message for
111 * @param $params Array message parameters
112 * @return Message: $this
114 public function __construct( $key, $params = array() ) {
117 $this->parameters
= array_values( $params );
118 $this->language
= $wgLang;
122 * Factory function that is just wrapper for the real constructor. It is
123 * intented to be used instead of the real constructor, because it allows
124 * chaining method calls, while new objects don't.
125 * @param $key String: message key
126 * @param Varargs: parameters as Strings
127 * @return Message: $this
129 public static function newFromKey( $key /*...*/ ) {
130 $params = func_get_args();
131 array_shift( $params );
132 return new self( $key, $params );
136 * Factory function accepting multiple message keys and returning a message instance
137 * for the first message which is non-empty. If all messages are empty then an
138 * instance of the first message key is returned.
139 * @param Varargs: message keys
140 * @return Message: $this
142 public static function newFallbackSequence( /*...*/ ) {
143 $keys = func_get_args();
144 if ( func_num_args() == 1 ) {
145 if ( is_array($keys[0]) ) {
146 // Allow an array to be passed as the first argument instead
147 $keys = array_values($keys[0]);
149 // Optimize a single string to not need special fallback handling
153 return new self( $keys );
157 * Adds parameters to the parameter list of this message.
158 * @param Varargs: parameters as Strings
159 * @return Message: $this
161 public function params( /*...*/ ) {
162 $args = func_get_args();
163 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
166 $args_values = array_values( $args );
167 $this->parameters
= array_merge( $this->parameters
, $args_values );
172 * Add parameters that are substituted after parsing or escaping.
173 * In other words the parsing process cannot access the contents
174 * of this type of parameter, and you need to make sure it is
175 * sanitized beforehand. The parser will see "$n", instead.
176 * @param Varargs: raw parameters as Strings
177 * @return Message: $this
179 public function rawParams( /*...*/ ) {
180 $params = func_get_args();
181 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
182 $params = $params[0];
184 foreach( $params as $param ) {
185 $this->parameters
[] = self
::rawParam( $param );
191 * Add parameters that are numeric and will be passed through
192 * Language::formatNum before substitution
193 * @param Varargs: numeric parameters
194 * @return Message: $this
196 public function numParams( /*...*/ ) {
197 $params = func_get_args();
198 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
199 $params = $params[0];
201 foreach( $params as $param ) {
202 $this->parameters
[] = self
::numParam( $param );
208 * Request the message in any language that is supported.
209 * As a side effect interface message status is unconditionally
211 * @param $lang Mixed: language code or Language object.
212 * @return Message: $this
214 public function inLanguage( $lang ) {
215 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
216 $this->language
= $lang;
217 } elseif ( is_string( $lang ) ) {
218 if( $this->language
->getCode() != $lang ) {
219 $this->language
= Language
::factory( $lang );
222 $type = gettype( $lang );
223 throw new MWException( __METHOD__
. " must be "
224 . "passed a String or Language object; $type given"
227 $this->interface = false;
232 * Request the message in the wiki's content language,
233 * unless it is disabled for this message.
234 * @see $wgForceUIMsgAsContentMsg
235 * @return Message: $this
237 public function inContentLanguage() {
238 global $wgForceUIMsgAsContentMsg;
239 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
244 $this->interface = false;
245 $this->language
= $wgContLang;
250 * Enable or disable database use.
251 * @param $value Boolean
252 * @return Message: $this
254 public function useDatabase( $value ) {
255 $this->useDatabase
= (bool) $value;
260 * Set the Title object to use as context when transforming the message
262 * @param $title Title object
263 * @return Message: $this
265 public function title( $title ) {
266 $this->title
= $title;
271 * Returns the message parsed from wikitext to HTML.
272 * @return String: HTML
274 public function toString() {
275 $string = $this->getMessageText();
277 # Replace parameters before text parsing
278 $string = $this->replaceParameters( $string, 'before' );
280 # Maybe transform using the full parser
281 if( $this->format
=== 'parse' ) {
282 $string = $this->parseText( $string );
284 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
287 } elseif( $this->format
=== 'block-parse' ){
288 $string = $this->parseText( $string );
289 } elseif( $this->format
=== 'text' ){
290 $string = $this->transformText( $string );
291 } elseif( $this->format
=== 'escaped' ){
292 $string = $this->transformText( $string );
293 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
296 # Raw parameter replacement
297 $string = $this->replaceParameters( $string, 'after' );
303 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
304 * $foo = Message::get($key);
305 * $string = "<abbr>$foo</abbr>";
308 public function __toString() {
309 return $this->toString();
313 * Fully parse the text from wikitext to HTML
314 * @return String parsed HTML
316 public function parse() {
317 $this->format
= 'parse';
318 return $this->toString();
322 * Returns the message text. {{-transformation is done.
323 * @return String: Unescaped message text.
325 public function text() {
326 $this->format
= 'text';
327 return $this->toString();
331 * Returns the message text as-is, only parameters are subsituted.
332 * @return String: Unescaped untransformed message text.
334 public function plain() {
335 $this->format
= 'plain';
336 return $this->toString();
340 * Returns the parsed message text which is always surrounded by a block element.
341 * @return String: HTML
343 public function parseAsBlock() {
344 $this->format
= 'block-parse';
345 return $this->toString();
349 * Returns the message text. {{-transformation is done and the result
350 * is escaped excluding any raw parameters.
351 * @return String: Escaped message text.
353 public function escaped() {
354 $this->format
= 'escaped';
355 return $this->toString();
359 * Check whether a message key has been defined currently.
360 * @return Bool: true if it is and false if not.
362 public function exists() {
363 return $this->fetchMessage() !== false;
367 * Check whether a message does not exist, or is an empty string
368 * @return Bool: true if is is and false if not
369 * @todo FIXME: Merge with isDisabled()?
371 public function isBlank() {
372 $message = $this->fetchMessage();
373 return $message === false ||
$message === '';
377 * Check whether a message does not exist, is an empty string, or is "-"
378 * @return Bool: true if is is and false if not
380 public function isDisabled() {
381 $message = $this->fetchMessage();
382 return $message === false ||
$message === '' ||
$message === '-';
389 public static function rawParam( $value ) {
390 return array( 'raw' => $value );
397 public static function numParam( $value ) {
398 return array( 'num' => $value );
402 * Substitutes any paramaters into the message text.
403 * @param $message String: the message text
404 * @param $type String: either before or after
407 protected function replaceParameters( $message, $type = 'before' ) {
408 $replacementKeys = array();
409 foreach( $this->parameters
as $n => $param ) {
410 list( $paramType, $value ) = $this->extractParam( $param );
411 if ( $type === $paramType ) {
412 $replacementKeys['$' . ($n +
1)] = $value;
415 $message = strtr( $message, $replacementKeys );
420 * Extracts the parameter type and preprocessed the value if needed.
421 * @param $param String|Array: Parameter as defined in this class.
422 * @return Tuple(type, value)
423 * @throws MWException
425 protected function extractParam( $param ) {
426 if ( is_array( $param ) && isset( $param['raw'] ) ) {
427 return array( 'after', $param['raw'] );
428 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
429 // Replace number params always in before step for now.
430 // No support for combined raw and num params
431 return array( 'before', $this->language
->formatNum( $param['num'] ) );
432 } elseif ( !is_array( $param ) ) {
433 return array( 'before', $param );
435 throw new MWException( "Invalid message parameter" );
440 * Wrapper for what ever method we use to parse wikitext.
441 * @param $string String: Wikitext message contents
442 * @return string Wikitext parsed into HTML
444 protected function parseText( $string ) {
445 return MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
)->getText();
449 * Wrapper for what ever method we use to {{-transform wikitext.
450 * @param $string String: Wikitext message contents
451 * @return string Wikitext with {{-constructs replaced with their values.
453 protected function transformText( $string ) {
454 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
458 * Returns the textual value for the message.
459 * @return Message contents or placeholder
461 protected function getMessageText() {
462 $message = $this->fetchMessage();
463 if ( $message === false ) {
464 return '<' . htmlspecialchars( is_array($this->key
) ?
$this->key
[0] : $this->key
) . '>';
471 * Wrapper for what ever method we use to get message contents
475 protected function fetchMessage() {
476 if ( !isset( $this->message
) ) {
477 $cache = MessageCache
::singleton();
478 if ( is_array($this->key
) ) {
479 foreach ( $this->key
as $key ) {
480 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
481 if ( $message !== false && $message !== '' ) {
485 $this->message
= $message;
487 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
490 return $this->message
;