Rename messages from r90670
[mediawiki.git] / includes / Message.php
blob87349ff5fa10c16e269b975019cef26d7e8b36a8
1 <?php
2 /**
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
7 * unusable.
9 * Examples:
10 * Fetching a message text for interface message
11 * $button = Xml::button( wfMessage( 'submit' )->text() );
12 * </pre>
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();
18 * </pre>
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
21 * </pre>
22 * Checking if message exists:
23 * wfMessage( 'mysterious-message' )->exists()
24 * </pre>
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
28 * languages
29 * </pre>
32 * Comparison with old wfMsg* functions:
34 * Use full parsing.
35 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
36 * === wfMessage( 'key', 'apple' )->parse();
37 * </pre>
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();
44 * </pre>
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();
49 * </pre>
51 * @todo
52 * - test, can we have tests?
54 * @since 1.17
55 * @author Niklas Laxström
57 class Message {
58 /**
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;
64 /**
65 * In which language to get this message. Overrides the $interface
66 * variable.
68 * @var Language
70 protected $language = null;
72 /**
73 * The message key.
75 protected $key;
77 /**
78 * List of parameters which will be substituted into the message.
80 protected $parameters = array();
82 /**
83 * Format for the message.
84 * Supported formats are:
85 * * text (transform)
86 * * escaped (transform+htmlspecialchars)
87 * * block-parse
88 * * parse (default)
89 * * plain
91 protected $format = 'parse';
93 /**
94 * Whether database can be used.
96 protected $useDatabase = true;
98 /**
99 * Title object to use as context
101 protected $title = null;
104 * Constructor.
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() ) {
110 global $wgLang;
111 $this->key = $key;
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]);
143 } else {
144 // Optimize a single string to not need special fallback handling
145 $keys = $keys[0];
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] ) ) {
159 $args = $args[0];
161 $args_values = array_values( $args );
162 $this->parameters = array_merge( $this->parameters, $args_values );
163 return $this;
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 );
182 return $this;
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 );
199 return $this;
203 * Request the message in any language that is supported.
204 * As a side effect interface message status is unconditionally
205 * turned off.
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 );
216 } else {
217 $type = gettype( $lang );
218 throw new MWException( __METHOD__ . " must be "
219 . "passed a String or Language object; $type given"
222 $this->interface = false;
223 return $this;
227 * Request the message in the wiki's content language,
228 * unless it is disabled for this message.
229 * @see $wgForceUIMsgAsContentMsg
230 * @return Message: $this
232 public function inContentLanguage() {
233 global $wgForceUIMsgAsContentMsg;
234 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
235 return $this;
238 global $wgContLang;
239 $this->interface = false;
240 $this->language = $wgContLang;
241 return $this;
245 * Enable or disable database use.
246 * @param $value Boolean
247 * @return Message: $this
249 public function useDatabase( $value ) {
250 $this->useDatabase = (bool) $value;
251 return $this;
255 * Set the Title object to use as context when transforming the message
257 * @param $title Title object
258 * @return Message: $this
260 public function title( $title ) {
261 $this->title = $title;
262 return $this;
266 * Returns the message parsed from wikitext to HTML.
267 * @return String: HTML
269 public function toString() {
270 $string = $this->getMessageText();
272 # Replace parameters before text parsing
273 $string = $this->replaceParameters( $string, 'before' );
275 # Maybe transform using the full parser
276 if( $this->format === 'parse' ) {
277 $string = $this->parseText( $string );
278 $m = array();
279 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
280 $string = $m[1];
282 } elseif( $this->format === 'block-parse' ){
283 $string = $this->parseText( $string );
284 } elseif( $this->format === 'text' ){
285 $string = $this->transformText( $string );
286 } elseif( $this->format === 'escaped' ){
287 $string = $this->transformText( $string );
288 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
291 # Raw parameter replacement
292 $string = $this->replaceParameters( $string, 'after' );
294 return $string;
298 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
299 * $foo = Message::get($key);
300 * $string = "<abbr>$foo</abbr>";
301 * @return String
303 public function __toString() {
304 return $this->toString();
308 * Fully parse the text from wikitext to HTML
309 * @return String parsed HTML
311 public function parse() {
312 $this->format = 'parse';
313 return $this->toString();
317 * Returns the message text. {{-transformation is done.
318 * @return String: Unescaped message text.
320 public function text() {
321 $this->format = 'text';
322 return $this->toString();
326 * Returns the message text as-is, only parameters are subsituted.
327 * @return String: Unescaped untransformed message text.
329 public function plain() {
330 $this->format = 'plain';
331 return $this->toString();
335 * Returns the parsed message text which is always surrounded by a block element.
336 * @return String: HTML
338 public function parseAsBlock() {
339 $this->format = 'block-parse';
340 return $this->toString();
344 * Returns the message text. {{-transformation is done and the result
345 * is escaped excluding any raw parameters.
346 * @return String: Escaped message text.
348 public function escaped() {
349 $this->format = 'escaped';
350 return $this->toString();
354 * Check whether a message key has been defined currently.
355 * @return Bool: true if it is and false if not.
357 public function exists() {
358 return $this->fetchMessage() !== false;
362 * Check whether a message does not exist, or is an empty string
363 * @return Bool: true if is is and false if not
364 * @todo FIXME: Merge with isDisabled()?
366 public function isBlank() {
367 $message = $this->fetchMessage();
368 return $message === false || $message === '';
372 * Check whether a message does not exist, is an empty string, or is "-"
373 * @return Bool: true if is is and false if not
375 public function isDisabled() {
376 $message = $this->fetchMessage();
377 return $message === false || $message === '' || $message === '-';
381 * @param $value
382 * @return array
384 public static function rawParam( $value ) {
385 return array( 'raw' => $value );
389 * @param $value
390 * @return array
392 public static function numParam( $value ) {
393 return array( 'num' => $value );
397 * Substitutes any paramaters into the message text.
398 * @param $message String: the message text
399 * @param $type String: either before or after
400 * @return String
402 protected function replaceParameters( $message, $type = 'before' ) {
403 $replacementKeys = array();
404 foreach( $this->parameters as $n => $param ) {
405 list( $paramType, $value ) = $this->extractParam( $param );
406 if ( $type === $paramType ) {
407 $replacementKeys['$' . ($n + 1)] = $value;
410 $message = strtr( $message, $replacementKeys );
411 return $message;
415 * Extracts the parameter type and preprocessed the value if needed.
416 * @param $param String|Array: Parameter as defined in this class.
417 * @return Tuple(type, value)
418 * @throws MWException
420 protected function extractParam( $param ) {
421 if ( is_array( $param ) && isset( $param['raw'] ) ) {
422 return array( 'after', $param['raw'] );
423 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
424 // Replace number params always in before step for now.
425 // No support for combined raw and num params
426 return array( 'before', $this->language->formatNum( $param['num'] ) );
427 } elseif ( !is_array( $param ) ) {
428 return array( 'before', $param );
429 } else {
430 throw new MWException( "Invalid message parameter" );
435 * Wrapper for what ever method we use to parse wikitext.
436 * @param $string String: Wikitext message contents
437 * @return string Wikitext parsed into HTML
439 protected function parseText( $string ) {
440 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
444 * Wrapper for what ever method we use to {{-transform wikitext.
445 * @param $string String: Wikitext message contents
446 * @return string Wikitext with {{-constructs replaced with their values.
448 protected function transformText( $string ) {
449 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
453 * Returns the textual value for the message.
454 * @return Message contents or placeholder
456 protected function getMessageText() {
457 $message = $this->fetchMessage();
458 if ( $message === false ) {
459 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
460 } else {
461 return $message;
466 * Wrapper for what ever method we use to get message contents
468 * @return string
470 protected function fetchMessage() {
471 if ( !isset( $this->message ) ) {
472 $cache = MessageCache::singleton();
473 if ( is_array($this->key) ) {
474 foreach ( $this->key as $key ) {
475 $message = $cache->get( $key, $this->useDatabase, $this->language );
476 if ( $message !== false && $message !== '' ) {
477 break;
480 $this->message = $message;
481 } else {
482 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
485 return $this->message;