Bug 29524 - Rename RequestContext::getLang to getLanguage
[lhc/web/wiklou.git] / includes / Message.php
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.
5 *
6 * It is intented to replace the old wfMsg* functions that over time grew
7 * unusable.
8 *
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>
30 *
31 *
32 * Comparison with old wfMsg* functions:
33 *
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.
40 *
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>
45 *
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>
50 *
51 * @todo
52 * - test, can we have tests?
53 *
54 * @since 1.17
55 * @author Niklas Laxström
56 */
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.
61 */
62 protected $interface = true;
63
64 /**
65 * In which language to get this message. Overrides the $interface
66 * variable.
67 *
68 * @var Language
69 */
70 protected $language = null;
71
72 /**
73 * The message key.
74 */
75 protected $key;
76
77 /**
78 * List of parameters which will be substituted into the message.
79 */
80 protected $parameters = array();
81
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
90 */
91 protected $format = 'parse';
92
93 /**
94 * Whether database can be used.
95 */
96 protected $useDatabase = true;
97
98 /**
99 * Title object to use as context
100 */
101 protected $title = null;
102
103 /**
104 * @var string
105 */
106 protected $message;
107
108 /**
109 * Constructor.
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
113 */
114 public function __construct( $key, $params = array() ) {
115 global $wgLang;
116 $this->key = $key;
117 $this->parameters = array_values( $params );
118 $this->language = $wgLang;
119 }
120
121 /**
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
128 */
129 public static function newFromKey( $key /*...*/ ) {
130 $params = func_get_args();
131 array_shift( $params );
132 return new self( $key, $params );
133 }
134
135 /**
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
141 */
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]);
148 } else {
149 // Optimize a single string to not need special fallback handling
150 $keys = $keys[0];
151 }
152 }
153 return new self( $keys );
154 }
155
156 /**
157 * Adds parameters to the parameter list of this message.
158 * @param Varargs: parameters as Strings
159 * @return Message: $this
160 */
161 public function params( /*...*/ ) {
162 $args = func_get_args();
163 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
164 $args = $args[0];
165 }
166 $args_values = array_values( $args );
167 $this->parameters = array_merge( $this->parameters, $args_values );
168 return $this;
169 }
170
171 /**
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
178 */
179 public function rawParams( /*...*/ ) {
180 $params = func_get_args();
181 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
182 $params = $params[0];
183 }
184 foreach( $params as $param ) {
185 $this->parameters[] = self::rawParam( $param );
186 }
187 return $this;
188 }
189
190 /**
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
195 */
196 public function numParams( /*...*/ ) {
197 $params = func_get_args();
198 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
199 $params = $params[0];
200 }
201 foreach( $params as $param ) {
202 $this->parameters[] = self::numParam( $param );
203 }
204 return $this;
205 }
206
207 /**
208 * Set the language and the title from a context object
209 *
210 * @param $context IContextSource
211 * @return Message: $this
212 */
213 public function setContext( IContextSource $context ) {
214 $this->inLanguage( $context->getLanguage() );
215 $this->title( $context->getTitle() );
216
217 return $this;
218 }
219
220 /**
221 * Request the message in any language that is supported.
222 * As a side effect interface message status is unconditionally
223 * turned off.
224 * @param $lang Mixed: language code or Language object.
225 * @return Message: $this
226 */
227 public function inLanguage( $lang ) {
228 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
229 $this->language = $lang;
230 } elseif ( is_string( $lang ) ) {
231 if( $this->language->getCode() != $lang ) {
232 $this->language = Language::factory( $lang );
233 }
234 } else {
235 $type = gettype( $lang );
236 throw new MWException( __METHOD__ . " must be "
237 . "passed a String or Language object; $type given"
238 );
239 }
240 $this->interface = false;
241 return $this;
242 }
243
244 /**
245 * Request the message in the wiki's content language,
246 * unless it is disabled for this message.
247 * @see $wgForceUIMsgAsContentMsg
248 * @return Message: $this
249 */
250 public function inContentLanguage() {
251 global $wgForceUIMsgAsContentMsg;
252 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
253 return $this;
254 }
255
256 global $wgContLang;
257 $this->interface = false;
258 $this->language = $wgContLang;
259 return $this;
260 }
261
262 /**
263 * Enable or disable database use.
264 * @param $value Boolean
265 * @return Message: $this
266 */
267 public function useDatabase( $value ) {
268 $this->useDatabase = (bool) $value;
269 return $this;
270 }
271
272 /**
273 * Set the Title object to use as context when transforming the message
274 *
275 * @param $title Title object
276 * @return Message: $this
277 */
278 public function title( $title ) {
279 $this->title = $title;
280 return $this;
281 }
282
283 /**
284 * Returns the message parsed from wikitext to HTML.
285 * @return String: HTML
286 */
287 public function toString() {
288 $string = $this->getMessageText();
289
290 # Replace parameters before text parsing
291 $string = $this->replaceParameters( $string, 'before' );
292
293 # Maybe transform using the full parser
294 if( $this->format === 'parse' ) {
295 $string = $this->parseText( $string );
296 $m = array();
297 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
298 $string = $m[1];
299 }
300 } elseif( $this->format === 'block-parse' ){
301 $string = $this->parseText( $string );
302 } elseif( $this->format === 'text' ){
303 $string = $this->transformText( $string );
304 } elseif( $this->format === 'escaped' ){
305 $string = $this->transformText( $string );
306 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
307 }
308
309 # Raw parameter replacement
310 $string = $this->replaceParameters( $string, 'after' );
311
312 return $string;
313 }
314
315 /**
316 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
317 * $foo = Message::get($key);
318 * $string = "<abbr>$foo</abbr>";
319 * @return String
320 */
321 public function __toString() {
322 return $this->toString();
323 }
324
325 /**
326 * Fully parse the text from wikitext to HTML
327 * @return String parsed HTML
328 */
329 public function parse() {
330 $this->format = 'parse';
331 return $this->toString();
332 }
333
334 /**
335 * Returns the message text. {{-transformation is done.
336 * @return String: Unescaped message text.
337 */
338 public function text() {
339 $this->format = 'text';
340 return $this->toString();
341 }
342
343 /**
344 * Returns the message text as-is, only parameters are subsituted.
345 * @return String: Unescaped untransformed message text.
346 */
347 public function plain() {
348 $this->format = 'plain';
349 return $this->toString();
350 }
351
352 /**
353 * Returns the parsed message text which is always surrounded by a block element.
354 * @return String: HTML
355 */
356 public function parseAsBlock() {
357 $this->format = 'block-parse';
358 return $this->toString();
359 }
360
361 /**
362 * Returns the message text. {{-transformation is done and the result
363 * is escaped excluding any raw parameters.
364 * @return String: Escaped message text.
365 */
366 public function escaped() {
367 $this->format = 'escaped';
368 return $this->toString();
369 }
370
371 /**
372 * Check whether a message key has been defined currently.
373 * @return Bool: true if it is and false if not.
374 */
375 public function exists() {
376 return $this->fetchMessage() !== false;
377 }
378
379 /**
380 * Check whether a message does not exist, or is an empty string
381 * @return Bool: true if is is and false if not
382 * @todo FIXME: Merge with isDisabled()?
383 */
384 public function isBlank() {
385 $message = $this->fetchMessage();
386 return $message === false || $message === '';
387 }
388
389 /**
390 * Check whether a message does not exist, is an empty string, or is "-"
391 * @return Bool: true if is is and false if not
392 */
393 public function isDisabled() {
394 $message = $this->fetchMessage();
395 return $message === false || $message === '' || $message === '-';
396 }
397
398 /**
399 * @param $value
400 * @return array
401 */
402 public static function rawParam( $value ) {
403 return array( 'raw' => $value );
404 }
405
406 /**
407 * @param $value
408 * @return array
409 */
410 public static function numParam( $value ) {
411 return array( 'num' => $value );
412 }
413
414 /**
415 * Substitutes any paramaters into the message text.
416 * @param $message String: the message text
417 * @param $type String: either before or after
418 * @return String
419 */
420 protected function replaceParameters( $message, $type = 'before' ) {
421 $replacementKeys = array();
422 foreach( $this->parameters as $n => $param ) {
423 list( $paramType, $value ) = $this->extractParam( $param );
424 if ( $type === $paramType ) {
425 $replacementKeys['$' . ($n + 1)] = $value;
426 }
427 }
428 $message = strtr( $message, $replacementKeys );
429 return $message;
430 }
431
432 /**
433 * Extracts the parameter type and preprocessed the value if needed.
434 * @param $param String|Array: Parameter as defined in this class.
435 * @return Tuple(type, value)
436 * @throws MWException
437 */
438 protected function extractParam( $param ) {
439 if ( is_array( $param ) && isset( $param['raw'] ) ) {
440 return array( 'after', $param['raw'] );
441 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
442 // Replace number params always in before step for now.
443 // No support for combined raw and num params
444 return array( 'before', $this->language->formatNum( $param['num'] ) );
445 } elseif ( !is_array( $param ) ) {
446 return array( 'before', $param );
447 } else {
448 throw new MWException( "Invalid message parameter" );
449 }
450 }
451
452 /**
453 * Wrapper for what ever method we use to parse wikitext.
454 * @param $string String: Wikitext message contents
455 * @return string Wikitext parsed into HTML
456 */
457 protected function parseText( $string ) {
458 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
459 }
460
461 /**
462 * Wrapper for what ever method we use to {{-transform wikitext.
463 * @param $string String: Wikitext message contents
464 * @return string Wikitext with {{-constructs replaced with their values.
465 */
466 protected function transformText( $string ) {
467 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
468 }
469
470 /**
471 * Returns the textual value for the message.
472 * @return Message contents or placeholder
473 */
474 protected function getMessageText() {
475 $message = $this->fetchMessage();
476 if ( $message === false ) {
477 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
478 } else {
479 return $message;
480 }
481 }
482
483 /**
484 * Wrapper for what ever method we use to get message contents
485 *
486 * @return string
487 */
488 protected function fetchMessage() {
489 if ( !isset( $this->message ) ) {
490 $cache = MessageCache::singleton();
491 if ( is_array($this->key) ) {
492 foreach ( $this->key as $key ) {
493 $message = $cache->get( $key, $this->useDatabase, $this->language );
494 if ( $message !== false && $message !== '' ) {
495 break;
496 }
497 }
498 $this->message = $message;
499 } else {
500 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
501 }
502 }
503 return $this->message;
504 }
505
506 }