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;
105 * @param $key: message key, or array of message keys to try and use the first non-empty message for
106 * @param $params Array message parameters
107 * @return Message: $this
109 public function __construct( $key, $params = array() ) {
112 $this->parameters
= array_values( $params );
113 $this->language
= $wgLang;
117 * Factory function that is just wrapper for the real constructor. It is
118 * intented to be used instead of the real constructor, because it allows
119 * chaining method calls, while new objects don't.
120 * @param $key String: message key
121 * @param Varargs: parameters as Strings
122 * @return Message: $this
124 public static function newFromKey( $key /*...*/ ) {
125 $params = func_get_args();
126 array_shift( $params );
127 return new self( $key, $params );
131 * Factory function accepting multiple message keys and returning a message instance
132 * for the first message which is non-empty. If all messages are empty then an
133 * instance of the first message key is returned.
134 * @param Varargs: message keys
135 * @return Message: $this
137 public static function newFallbackSequence( /*...*/ ) {
138 $keys = func_get_args();
139 if ( func_num_args() == 1 ) {
140 if ( is_array($keys[0]) ) {
141 // Allow an array to be passed as the first argument instead
142 $keys = array_values($keys[0]);
144 // Optimize a single string to not need special fallback handling
148 return new self( $keys );
152 * Adds parameters to the parameter list of this message.
153 * @param Varargs: parameters as Strings
154 * @return Message: $this
156 public function params( /*...*/ ) {
157 $args = func_get_args();
158 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
161 $args_values = array_values( $args );
162 $this->parameters
= array_merge( $this->parameters
, $args_values );
167 * Add parameters that are substituted after parsing or escaping.
168 * In other words the parsing process cannot access the contents
169 * of this type of parameter, and you need to make sure it is
170 * sanitized beforehand. The parser will see "$n", instead.
171 * @param Varargs: raw parameters as Strings
172 * @return Message: $this
174 public function rawParams( /*...*/ ) {
175 $params = func_get_args();
176 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
177 $params = $params[0];
179 foreach( $params as $param ) {
180 $this->parameters
[] = self
::rawParam( $param );
186 * Add parameters that are numeric and will be passed through
187 * Language::formatNum before substitution
188 * @param Varargs: numeric parameters
189 * @return Message: $this
191 public function numParams( /*...*/ ) {
192 $params = func_get_args();
193 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
194 $params = $params[0];
196 foreach( $params as $param ) {
197 $this->parameters
[] = self
::numParam( $param );
203 * Request the message in any language that is supported.
204 * As a side effect interface message status is unconditionally
206 * @param $lang Mixed: language code or Language object.
207 * @return Message: $this
209 public function inLanguage( $lang ) {
210 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
211 $this->language
= $lang;
212 } elseif ( is_string( $lang ) ) {
213 if( $this->language
->getCode() != $lang ) {
214 $this->language
= Language
::factory( $lang );
217 $type = gettype( $lang );
218 throw new MWException( __METHOD__
. " must be "
219 . "passed a String or Language object; $type given"
222 $this->interface = false;
227 * Request the message in the wiki's content language.
228 * @see $wgForceUIMsgAsContentMsg
229 * @return Message: $this
231 public function inContentLanguage() {
232 global $wgForceUIMsgAsContentMsg;
233 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
238 $this->interface = false;
239 $this->language
= $wgContLang;
244 * Enable or disable database use.
245 * @param $value Boolean
246 * @return Message: $this
248 public function useDatabase( $value ) {
249 $this->useDatabase
= (bool) $value;
254 * Set the Title object to use as context when transforming the message
256 * @param $title Title object
257 * @return Message: $this
259 public function title( $title ) {
260 $this->title
= $title;
265 * Returns the message parsed from wikitext to HTML.
266 * @return String: HTML
268 public function toString() {
269 $string = $this->getMessageText();
271 # Replace parameters before text parsing
272 $string = $this->replaceParameters( $string, 'before' );
274 # Maybe transform using the full parser
275 if( $this->format
=== 'parse' ) {
276 $string = $this->parseText( $string );
278 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
281 } elseif( $this->format
=== 'block-parse' ){
282 $string = $this->parseText( $string );
283 } elseif( $this->format
=== 'text' ){
284 $string = $this->transformText( $string );
285 } elseif( $this->format
=== 'escaped' ){
286 $string = $this->transformText( $string );
287 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
290 # Raw parameter replacement
291 $string = $this->replaceParameters( $string, 'after' );
297 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
298 * $foo = Message::get($key);
299 * $string = "<abbr>$foo</abbr>";
302 public function __toString() {
303 return $this->toString();
307 * Fully parse the text from wikitext to HTML
308 * @return String parsed HTML
310 public function parse() {
311 $this->format
= 'parse';
312 return $this->toString();
316 * Returns the message text. {{-transformation is done.
317 * @return String: Unescaped message text.
319 public function text() {
320 $this->format
= 'text';
321 return $this->toString();
325 * Returns the message text as-is, only parameters are subsituted.
326 * @return String: Unescaped untransformed message text.
328 public function plain() {
329 $this->format
= 'plain';
330 return $this->toString();
334 * Returns the parsed message text which is always surrounded by a block element.
335 * @return String: HTML
337 public function parseAsBlock() {
338 $this->format
= 'block-parse';
339 return $this->toString();
343 * Returns the message text. {{-transformation is done and the result
344 * is escaped excluding any raw parameters.
345 * @return String: Escaped message text.
347 public function escaped() {
348 $this->format
= 'escaped';
349 return $this->toString();
353 * Check whether a message key has been defined currently.
354 * @return Bool: true if it is and false if not.
356 public function exists() {
357 return $this->fetchMessage() !== false;
361 * Check whether a message does not exist, or is an empty string
362 * @return Bool: true if is is and false if not
363 * @todo FIXME: Merge with isDisabled()?
365 public function isBlank() {
366 $message = $this->fetchMessage();
367 return $message === false ||
$message === '';
371 * Check whether a message does not exist, is an empty string, or is "-"
372 * @return Bool: true if is is and false if not
374 public function isDisabled() {
375 $message = $this->fetchMessage();
376 return $message === false ||
$message === '' ||
$message === '-';
383 public static function rawParam( $value ) {
384 return array( 'raw' => $value );
391 public static function numParam( $value ) {
392 return array( 'num' => $value );
396 * Substitutes any paramaters into the message text.
397 * @param $message String: the message text
398 * @param $type String: either before or after
401 protected function replaceParameters( $message, $type = 'before' ) {
402 $replacementKeys = array();
403 foreach( $this->parameters
as $n => $param ) {
404 list( $paramType, $value ) = $this->extractParam( $param );
405 if ( $type === $paramType ) {
406 $replacementKeys['$' . ($n +
1)] = $value;
409 $message = strtr( $message, $replacementKeys );
414 * Extracts the parameter type and preprocessed the value if needed.
415 * @param $param String|Array: Parameter as defined in this class.
416 * @return Tuple(type, value)
417 * @throws MWException
419 protected function extractParam( $param ) {
420 if ( is_array( $param ) && isset( $param['raw'] ) ) {
421 return array( 'after', $param['raw'] );
422 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
423 // Replace number params always in before step for now.
424 // No support for combined raw and num params
425 return array( 'before', $this->language
->formatNum( $param['num'] ) );
426 } elseif ( !is_array( $param ) ) {
427 return array( 'before', $param );
429 throw new MWException( "Invalid message parameter" );
434 * Wrapper for what ever method we use to parse wikitext.
435 * @param $string String: Wikitext message contents
436 * @return string Wikitext parsed into HTML
438 protected function parseText( $string ) {
439 return MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
)->getText();
443 * Wrapper for what ever method we use to {{-transform wikitext.
444 * @param $string String: Wikitext message contents
445 * @return string Wikitext with {{-constructs replaced with their values.
447 protected function transformText( $string ) {
448 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
452 * Returns the textual value for the message.
453 * @return Message contents or placeholder
455 protected function getMessageText() {
456 $message = $this->fetchMessage();
457 if ( $message === false ) {
458 return '<' . htmlspecialchars( is_array($this->key
) ?
$this->key
[0] : $this->key
) . '>';
465 * Wrapper for what ever method we use to get message contents
469 protected function fetchMessage() {
470 if ( !isset( $this->message
) ) {
471 $cache = MessageCache
::singleton();
472 if ( is_array($this->key
) ) {
473 foreach ( $this->key
as $key ) {
474 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
475 if ( $message !== false && $message !== '' ) {
479 $this->message
= $message;
481 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
484 return $this->message
;