Follow-up r113223: set the "interface" flag in Message to true by default and set...
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * The Message class provides methods which fullfil two basic services:
4 * - fetching interface messages
5 * - processing messages into a variety of formats
6 *
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.
11 *
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.
14 *
15 * The most basic usage cases would be:
16 *
17 * @code
18 * // Initialize a Message object using the 'some_key' message key
19 * $message = wfMessage( 'some_key' );
20 *
21 * // Using two parameters those values are strings 'value1' and 'value2':
22 * $message = wfMessage( 'some_key',
23 * 'value1', 'value2'
24 * );
25 * @endcode
26 *
27 * @section message_global_fn Global function wrapper:
28 *
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.
32 *
33 * Fetching a message text for interface message:
34 *
35 * @code
36 * $button = Xml::button(
37 * wfMessage( 'submit' )->text()
38 * );
39 * @endcode
40 *
41 * A Message instance can be passed parameters after it has been constructed,
42 * use the params() method to do so:
43 *
44 * @code
45 * wfMessage( 'welcome-to' )
46 * ->params( $wgSitename )
47 * ->text();
48 * @endcode
49 *
50 * {{GRAMMAR}} and friends work correctly:
51 *
52 * @code
53 * wfMessage( 'are-friends',
54 * $user, $friend
55 * );
56 * wfMessage( 'bad-message' )
57 * ->rawParams( '<script>...</script>' )
58 * ->escaped();
59 * @endcode
60 *
61 * @section message_language Changing language:
62 *
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()
67 *
68 * Sometimes the message text ends up in the database, so content language is
69 * needed:
70 *
71 * @code
72 * wfMessage( 'file-log',
73 * $user, $filename
74 * )->inContentLanguage()->text();
75 * @endcode
76 *
77 * Checking whether a message exists:
78 *
79 * @code
80 * wfMessage( 'mysterious-message' )->exists()
81 * // returns a boolean whether the 'mysterious-message' key exist.
82 * @endcode
83 *
84 * If you want to use a different language:
85 *
86 * @code
87 * $userLanguage = $user->getOption( 'language' );
88 * wfMessage( 'email-header' )
89 * ->inLanguage( $userLanguage )
90 * ->plain();
91 * @endcode
92 *
93 * @note You can parse the text only in the content or interface languages
94 *
95 * @section message_compare_old Comparison with old wfMsg* functions:
96 *
97 * Use full parsing:
98 *
99 * @code
100 * // old style:
101 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
102 * // new style:
103 * wfMessage( 'key', 'apple' )->parse();
104 * @endcode
105 *
106 * Parseinline is used because it is more useful when pre-building HTML.
107 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
108 *
109 * Places where HTML cannot be used. {{-transformation is done.
110 * @code
111 * // old style:
112 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
113 * // new style:
114 * wfMessage( 'key', 'apple', 'pear' )->text();
115 * @endcode
116 *
117 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
118 * parameters are not replaced after escaping by default.
119 * @code
120 * $escaped = wfMessage( 'key' )
121 * ->rawParams( 'apple' )
122 * ->escaped();
123 * @endcode
124 *
125 * @section message_appendix Appendix:
126 *
127 * @todo
128 * - test, can we have tests?
129 * - this documentation needs to be extended
130 *
131 * @see https://www.mediawiki.org/wiki/WfMessage()
132 * @see https://www.mediawiki.org/wiki/New_messages_API
133 * @see https://www.mediawiki.org/wiki/Localisation
134 *
135 * @since 1.17
136 * @author Niklas Laxström
137 */
138 class Message {
139 /**
140 * In which language to get this message. True, which is the default,
141 * means the current interface language, false content language.
142 */
143 protected $interface = true;
144
145 /**
146 * In which language to get this message. Overrides the $interface
147 * variable.
148 *
149 * @var Language
150 */
151 protected $language = null;
152
153 /**
154 * The message key.
155 */
156 protected $key;
157
158 /**
159 * List of parameters which will be substituted into the message.
160 */
161 protected $parameters = array();
162
163 /**
164 * Format for the message.
165 * Supported formats are:
166 * * text (transform)
167 * * escaped (transform+htmlspecialchars)
168 * * block-parse
169 * * parse (default)
170 * * plain
171 */
172 protected $format = 'parse';
173
174 /**
175 * Whether database can be used.
176 */
177 protected $useDatabase = true;
178
179 /**
180 * Title object to use as context
181 */
182 protected $title = null;
183
184 /**
185 * @var string
186 */
187 protected $message;
188
189 /**
190 * Constructor.
191 * @param $key: message key, or array of message keys to try and use the first non-empty message for
192 * @param $params Array message parameters
193 * @return Message: $this
194 */
195 public function __construct( $key, $params = array() ) {
196 global $wgLang;
197 $this->key = $key;
198 $this->parameters = array_values( $params );
199 $this->language = $wgLang;
200 }
201
202 /**
203 * Factory function that is just wrapper for the real constructor. It is
204 * intented to be used instead of the real constructor, because it allows
205 * chaining method calls, while new objects don't.
206 * @param $key String: message key
207 * @param Varargs: parameters as Strings
208 * @return Message: $this
209 */
210 public static function newFromKey( $key /*...*/ ) {
211 $params = func_get_args();
212 array_shift( $params );
213 return new self( $key, $params );
214 }
215
216 /**
217 * Factory function accepting multiple message keys and returning a message instance
218 * for the first message which is non-empty. If all messages are empty then an
219 * instance of the first message key is returned.
220 * @param Varargs: message keys (or first arg as an array of all the message keys)
221 * @return Message: $this
222 */
223 public static function newFallbackSequence( /*...*/ ) {
224 $keys = func_get_args();
225 if ( func_num_args() == 1 ) {
226 if ( is_array($keys[0]) ) {
227 // Allow an array to be passed as the first argument instead
228 $keys = array_values($keys[0]);
229 } else {
230 // Optimize a single string to not need special fallback handling
231 $keys = $keys[0];
232 }
233 }
234 return new self( $keys );
235 }
236
237 /**
238 * Adds parameters to the parameter list of this message.
239 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
240 * @return Message: $this
241 */
242 public function params( /*...*/ ) {
243 $args = func_get_args();
244 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
245 $args = $args[0];
246 }
247 $args_values = array_values( $args );
248 $this->parameters = array_merge( $this->parameters, $args_values );
249 return $this;
250 }
251
252 /**
253 * Add parameters that are substituted after parsing or escaping.
254 * In other words the parsing process cannot access the contents
255 * of this type of parameter, and you need to make sure it is
256 * sanitized beforehand. The parser will see "$n", instead.
257 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
258 * @return Message: $this
259 */
260 public function rawParams( /*...*/ ) {
261 $params = func_get_args();
262 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
263 $params = $params[0];
264 }
265 foreach( $params as $param ) {
266 $this->parameters[] = self::rawParam( $param );
267 }
268 return $this;
269 }
270
271 /**
272 * Add parameters that are numeric and will be passed through
273 * Language::formatNum before substitution
274 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
275 * @return Message: $this
276 */
277 public function numParams( /*...*/ ) {
278 $params = func_get_args();
279 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
280 $params = $params[0];
281 }
282 foreach( $params as $param ) {
283 $this->parameters[] = self::numParam( $param );
284 }
285 return $this;
286 }
287
288 /**
289 * Set the language and the title from a context object
290 *
291 * @param $context IContextSource
292 * @return Message: $this
293 */
294 public function setContext( IContextSource $context ) {
295 $this->inLanguage( $context->getLanguage() );
296 $this->title( $context->getTitle() );
297 $this->interface = true;
298
299 return $this;
300 }
301
302 /**
303 * Request the message in any language that is supported.
304 * As a side effect interface message status is unconditionally
305 * turned off.
306 * @param $lang Mixed: language code or Language object.
307 * @return Message: $this
308 */
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 );
315 }
316 } else {
317 $type = gettype( $lang );
318 throw new MWException( __METHOD__ . " must be "
319 . "passed a String or Language object; $type given"
320 );
321 }
322 $this->interface = false;
323 return $this;
324 }
325
326 /**
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
331 */
332 public function inContentLanguage() {
333 global $wgForceUIMsgAsContentMsg;
334 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
335 return $this;
336 }
337
338 global $wgContLang;
339 $this->interface = false;
340 $this->language = $wgContLang;
341 return $this;
342 }
343
344 /**
345 * Allows manipulating the interface message flag directly.
346 * Can be used to restore the flag after setting a language.
347 * @param $value bool
348 * @return Message: $this
349 * @since 1.20
350 */
351 public function setInterfaceMessageFlag( $value ) {
352 $this->interface = (bool) $value;
353 return $this;
354 }
355
356 /**
357 * Enable or disable database use.
358 * @param $value Boolean
359 * @return Message: $this
360 */
361 public function useDatabase( $value ) {
362 $this->useDatabase = (bool) $value;
363 return $this;
364 }
365
366 /**
367 * Set the Title object to use as context when transforming the message
368 *
369 * @param $title Title object
370 * @return Message: $this
371 */
372 public function title( $title ) {
373 $this->title = $title;
374 return $this;
375 }
376
377 /**
378 * Returns the message parsed from wikitext to HTML.
379 * @return String: HTML
380 */
381 public function toString() {
382 $string = $this->getMessageText();
383
384 # Replace parameters before text parsing
385 $string = $this->replaceParameters( $string, 'before' );
386
387 # Maybe transform using the full parser
388 if( $this->format === 'parse' ) {
389 $string = $this->parseText( $string );
390 $m = array();
391 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
392 $string = $m[1];
393 }
394 } elseif( $this->format === 'block-parse' ){
395 $string = $this->parseText( $string );
396 } elseif( $this->format === 'text' ){
397 $string = $this->transformText( $string );
398 } elseif( $this->format === 'escaped' ){
399 $string = $this->transformText( $string );
400 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
401 }
402
403 # Raw parameter replacement
404 $string = $this->replaceParameters( $string, 'after' );
405
406 return $string;
407 }
408
409 /**
410 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
411 * $foo = Message::get($key);
412 * $string = "<abbr>$foo</abbr>";
413 * @return String
414 */
415 public function __toString() {
416 return $this->toString();
417 }
418
419 /**
420 * Fully parse the text from wikitext to HTML
421 * @return String parsed HTML
422 */
423 public function parse() {
424 $this->format = 'parse';
425 return $this->toString();
426 }
427
428 /**
429 * Returns the message text. {{-transformation is done.
430 * @return String: Unescaped message text.
431 */
432 public function text() {
433 $this->format = 'text';
434 return $this->toString();
435 }
436
437 /**
438 * Returns the message text as-is, only parameters are subsituted.
439 * @return String: Unescaped untransformed message text.
440 */
441 public function plain() {
442 $this->format = 'plain';
443 return $this->toString();
444 }
445
446 /**
447 * Returns the parsed message text which is always surrounded by a block element.
448 * @return String: HTML
449 */
450 public function parseAsBlock() {
451 $this->format = 'block-parse';
452 return $this->toString();
453 }
454
455 /**
456 * Returns the message text. {{-transformation is done and the result
457 * is escaped excluding any raw parameters.
458 * @return String: Escaped message text.
459 */
460 public function escaped() {
461 $this->format = 'escaped';
462 return $this->toString();
463 }
464
465 /**
466 * Check whether a message key has been defined currently.
467 * @return Bool: true if it is and false if not.
468 */
469 public function exists() {
470 return $this->fetchMessage() !== false;
471 }
472
473 /**
474 * Check whether a message does not exist, or is an empty string
475 * @return Bool: true if is is and false if not
476 * @todo FIXME: Merge with isDisabled()?
477 */
478 public function isBlank() {
479 $message = $this->fetchMessage();
480 return $message === false || $message === '';
481 }
482
483 /**
484 * Check whether a message does not exist, is an empty string, or is "-"
485 * @return Bool: true if is is and false if not
486 */
487 public function isDisabled() {
488 $message = $this->fetchMessage();
489 return $message === false || $message === '' || $message === '-';
490 }
491
492 /**
493 * @param $value
494 * @return array
495 */
496 public static function rawParam( $value ) {
497 return array( 'raw' => $value );
498 }
499
500 /**
501 * @param $value
502 * @return array
503 */
504 public static function numParam( $value ) {
505 return array( 'num' => $value );
506 }
507
508 /**
509 * Substitutes any paramaters into the message text.
510 * @param $message String: the message text
511 * @param $type String: either before or after
512 * @return String
513 */
514 protected function replaceParameters( $message, $type = 'before' ) {
515 $replacementKeys = array();
516 foreach( $this->parameters as $n => $param ) {
517 list( $paramType, $value ) = $this->extractParam( $param );
518 if ( $type === $paramType ) {
519 $replacementKeys['$' . ($n + 1)] = $value;
520 }
521 }
522 $message = strtr( $message, $replacementKeys );
523 return $message;
524 }
525
526 /**
527 * Extracts the parameter type and preprocessed the value if needed.
528 * @param $param String|Array: Parameter as defined in this class.
529 * @return Tuple(type, value)
530 * @throws MWException
531 */
532 protected function extractParam( $param ) {
533 if ( is_array( $param ) && isset( $param['raw'] ) ) {
534 return array( 'after', $param['raw'] );
535 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
536 // Replace number params always in before step for now.
537 // No support for combined raw and num params
538 return array( 'before', $this->language->formatNum( $param['num'] ) );
539 } elseif ( !is_array( $param ) ) {
540 return array( 'before', $param );
541 } else {
542 throw new MWException( "Invalid message parameter" );
543 }
544 }
545
546 /**
547 * Wrapper for what ever method we use to parse wikitext.
548 * @param $string String: Wikitext message contents
549 * @return string Wikitext parsed into HTML
550 */
551 protected function parseText( $string ) {
552 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
553 }
554
555 /**
556 * Wrapper for what ever method we use to {{-transform wikitext.
557 * @param $string String: Wikitext message contents
558 * @return string Wikitext with {{-constructs replaced with their values.
559 */
560 protected function transformText( $string ) {
561 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
562 }
563
564 /**
565 * Returns the textual value for the message.
566 * @return Message contents or placeholder
567 */
568 protected function getMessageText() {
569 $message = $this->fetchMessage();
570 if ( $message === false ) {
571 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
572 } else {
573 return $message;
574 }
575 }
576
577 /**
578 * Wrapper for what ever method we use to get message contents
579 *
580 * @return string
581 */
582 protected function fetchMessage() {
583 if ( !isset( $this->message ) ) {
584 $cache = MessageCache::singleton();
585 if ( is_array( $this->key ) ) {
586 if ( !count( $this->key ) ) {
587 throw new MWException( "Given empty message key array." );
588 }
589 foreach ( $this->key as $key ) {
590 $message = $cache->get( $key, $this->useDatabase, $this->language );
591 if ( $message !== false && $message !== '' ) {
592 break;
593 }
594 }
595 $this->message = $message;
596 } else {
597 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
598 }
599 }
600 return $this->message;
601 }
602
603 }