Reverted r111188: backport conflict fodder
[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 cannot parse the text except in the content or interface
94 * @note languages
95 *
96 * @section message_compare_old Comparison with old wfMsg* functions:
97 *
98 * Use full parsing:
99 *
100 * @code
101 * // old style:
102 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
103 * // new style:
104 * wfMessage( 'key', 'apple' )->parse();
105 * @endcode
106 *
107 * Parseinline is used because it is more useful when pre-building HTML.
108 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
109 *
110 * Places where HTML cannot be used. {{-transformation is done.
111 * @code
112 * // old style:
113 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
114 * // new style:
115 * wfMessage( 'key', 'apple', 'pear' )->text();
116 * @endcode
117 *
118 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
119 * parameters are not replaced after escaping by default.
120 * @code
121 * $escaped = wfMessage( 'key' )
122 * ->rawParams( 'apple' )
123 * ->escaped();
124 * @endcode
125 *
126 * @section message_appendix Appendix:
127 *
128 * @todo
129 * - test, can we have tests?
130 * - this documentation needs to be extended
131 *
132 * @see https://www.mediawiki.org/wiki/WfMessage()
133 * @see https://www.mediawiki.org/wiki/New_messages_API
134 * @see https://www.mediawiki.org/wiki/Localisation
135 *
136 * @since 1.17
137 * @author Niklas Laxström
138 */
139 class Message {
140 /**
141 * In which language to get this message. True, which is the default,
142 * means the current interface language, false content language.
143 */
144 protected $interface = true;
145
146 /**
147 * In which language to get this message. Overrides the $interface
148 * variable.
149 *
150 * @var Language
151 */
152 protected $language = null;
153
154 /**
155 * The message key.
156 */
157 protected $key;
158
159 /**
160 * List of parameters which will be substituted into the message.
161 */
162 protected $parameters = array();
163
164 /**
165 * Format for the message.
166 * Supported formats are:
167 * * text (transform)
168 * * escaped (transform+htmlspecialchars)
169 * * block-parse
170 * * parse (default)
171 * * plain
172 */
173 protected $format = 'parse';
174
175 /**
176 * Whether database can be used.
177 */
178 protected $useDatabase = true;
179
180 /**
181 * Title object to use as context
182 */
183 protected $title = null;
184
185 /**
186 * @var string
187 */
188 protected $message;
189
190 /**
191 * Constructor.
192 * @param $key: message key, or array of message keys to try and use the first non-empty message for
193 * @param $params Array message parameters
194 * @return Message: $this
195 */
196 public function __construct( $key, $params = array() ) {
197 global $wgLang;
198 $this->key = $key;
199 $this->parameters = array_values( $params );
200 $this->language = $wgLang;
201 }
202
203 /**
204 * Factory function that is just wrapper for the real constructor. It is
205 * intented to be used instead of the real constructor, because it allows
206 * chaining method calls, while new objects don't.
207 * @param $key String: message key
208 * @param Varargs: parameters as Strings
209 * @return Message: $this
210 */
211 public static function newFromKey( $key /*...*/ ) {
212 $params = func_get_args();
213 array_shift( $params );
214 return new self( $key, $params );
215 }
216
217 /**
218 * Factory function accepting multiple message keys and returning a message instance
219 * for the first message which is non-empty. If all messages are empty then an
220 * instance of the first message key is returned.
221 * @param Varargs: message keys (or first arg as an array of all the message keys)
222 * @return Message: $this
223 */
224 public static function newFallbackSequence( /*...*/ ) {
225 $keys = func_get_args();
226 if ( func_num_args() == 1 ) {
227 if ( is_array($keys[0]) ) {
228 // Allow an array to be passed as the first argument instead
229 $keys = array_values($keys[0]);
230 } else {
231 // Optimize a single string to not need special fallback handling
232 $keys = $keys[0];
233 }
234 }
235 return new self( $keys );
236 }
237
238 /**
239 * Adds parameters to the parameter list of this message.
240 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
241 * @return Message: $this
242 */
243 public function params( /*...*/ ) {
244 $args = func_get_args();
245 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
246 $args = $args[0];
247 }
248 $args_values = array_values( $args );
249 $this->parameters = array_merge( $this->parameters, $args_values );
250 return $this;
251 }
252
253 /**
254 * Add parameters that are substituted after parsing or escaping.
255 * In other words the parsing process cannot access the contents
256 * of this type of parameter, and you need to make sure it is
257 * sanitized beforehand. The parser will see "$n", instead.
258 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
259 * @return Message: $this
260 */
261 public function rawParams( /*...*/ ) {
262 $params = func_get_args();
263 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
264 $params = $params[0];
265 }
266 foreach( $params as $param ) {
267 $this->parameters[] = self::rawParam( $param );
268 }
269 return $this;
270 }
271
272 /**
273 * Add parameters that are numeric and will be passed through
274 * Language::formatNum before substitution
275 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
276 * @return Message: $this
277 */
278 public function numParams( /*...*/ ) {
279 $params = func_get_args();
280 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
281 $params = $params[0];
282 }
283 foreach( $params as $param ) {
284 $this->parameters[] = self::numParam( $param );
285 }
286 return $this;
287 }
288
289 /**
290 * Set the language and the title from a context object
291 *
292 * @param $context IContextSource
293 * @return Message: $this
294 */
295 public function setContext( IContextSource $context ) {
296 $this->inLanguage( $context->getLanguage() );
297 $this->title( $context->getTitle() );
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 * Enable or disable database use.
346 * @param $value Boolean
347 * @return Message: $this
348 */
349 public function useDatabase( $value ) {
350 $this->useDatabase = (bool) $value;
351 return $this;
352 }
353
354 /**
355 * Set the Title object to use as context when transforming the message
356 *
357 * @param $title Title object
358 * @return Message: $this
359 */
360 public function title( $title ) {
361 $this->title = $title;
362 return $this;
363 }
364
365 /**
366 * Returns the message parsed from wikitext to HTML.
367 * @return String: HTML
368 */
369 public function toString() {
370 $string = $this->getMessageText();
371
372 # Replace parameters before text parsing
373 $string = $this->replaceParameters( $string, 'before' );
374
375 # Maybe transform using the full parser
376 if( $this->format === 'parse' ) {
377 $string = $this->parseText( $string );
378 $m = array();
379 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
380 $string = $m[1];
381 }
382 } elseif( $this->format === 'block-parse' ){
383 $string = $this->parseText( $string );
384 } elseif( $this->format === 'text' ){
385 $string = $this->transformText( $string );
386 } elseif( $this->format === 'escaped' ){
387 $string = $this->transformText( $string );
388 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
389 }
390
391 # Raw parameter replacement
392 $string = $this->replaceParameters( $string, 'after' );
393
394 return $string;
395 }
396
397 /**
398 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
399 * $foo = Message::get($key);
400 * $string = "<abbr>$foo</abbr>";
401 * @return String
402 */
403 public function __toString() {
404 return $this->toString();
405 }
406
407 /**
408 * Fully parse the text from wikitext to HTML
409 * @return String parsed HTML
410 */
411 public function parse() {
412 $this->format = 'parse';
413 return $this->toString();
414 }
415
416 /**
417 * Returns the message text. {{-transformation is done.
418 * @return String: Unescaped message text.
419 */
420 public function text() {
421 $this->format = 'text';
422 return $this->toString();
423 }
424
425 /**
426 * Returns the message text as-is, only parameters are subsituted.
427 * @return String: Unescaped untransformed message text.
428 */
429 public function plain() {
430 $this->format = 'plain';
431 return $this->toString();
432 }
433
434 /**
435 * Returns the parsed message text which is always surrounded by a block element.
436 * @return String: HTML
437 */
438 public function parseAsBlock() {
439 $this->format = 'block-parse';
440 return $this->toString();
441 }
442
443 /**
444 * Returns the message text. {{-transformation is done and the result
445 * is escaped excluding any raw parameters.
446 * @return String: Escaped message text.
447 */
448 public function escaped() {
449 $this->format = 'escaped';
450 return $this->toString();
451 }
452
453 /**
454 * Check whether a message key has been defined currently.
455 * @return Bool: true if it is and false if not.
456 */
457 public function exists() {
458 return $this->fetchMessage() !== false;
459 }
460
461 /**
462 * Check whether a message does not exist, or is an empty string
463 * @return Bool: true if is is and false if not
464 * @todo FIXME: Merge with isDisabled()?
465 */
466 public function isBlank() {
467 $message = $this->fetchMessage();
468 return $message === false || $message === '';
469 }
470
471 /**
472 * Check whether a message does not exist, is an empty string, or is "-"
473 * @return Bool: true if is is and false if not
474 */
475 public function isDisabled() {
476 $message = $this->fetchMessage();
477 return $message === false || $message === '' || $message === '-';
478 }
479
480 /**
481 * @param $value
482 * @return array
483 */
484 public static function rawParam( $value ) {
485 return array( 'raw' => $value );
486 }
487
488 /**
489 * @param $value
490 * @return array
491 */
492 public static function numParam( $value ) {
493 return array( 'num' => $value );
494 }
495
496 /**
497 * Substitutes any paramaters into the message text.
498 * @param $message String: the message text
499 * @param $type String: either before or after
500 * @return String
501 */
502 protected function replaceParameters( $message, $type = 'before' ) {
503 $replacementKeys = array();
504 foreach( $this->parameters as $n => $param ) {
505 list( $paramType, $value ) = $this->extractParam( $param );
506 if ( $type === $paramType ) {
507 $replacementKeys['$' . ($n + 1)] = $value;
508 }
509 }
510 $message = strtr( $message, $replacementKeys );
511 return $message;
512 }
513
514 /**
515 * Extracts the parameter type and preprocessed the value if needed.
516 * @param $param String|Array: Parameter as defined in this class.
517 * @return Tuple(type, value)
518 * @throws MWException
519 */
520 protected function extractParam( $param ) {
521 if ( is_array( $param ) && isset( $param['raw'] ) ) {
522 return array( 'after', $param['raw'] );
523 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
524 // Replace number params always in before step for now.
525 // No support for combined raw and num params
526 return array( 'before', $this->language->formatNum( $param['num'] ) );
527 } elseif ( !is_array( $param ) ) {
528 return array( 'before', $param );
529 } else {
530 throw new MWException( "Invalid message parameter" );
531 }
532 }
533
534 /**
535 * Wrapper for what ever method we use to parse wikitext.
536 * @param $string String: Wikitext message contents
537 * @return string Wikitext parsed into HTML
538 */
539 protected function parseText( $string ) {
540 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
541 }
542
543 /**
544 * Wrapper for what ever method we use to {{-transform wikitext.
545 * @param $string String: Wikitext message contents
546 * @return string Wikitext with {{-constructs replaced with their values.
547 */
548 protected function transformText( $string ) {
549 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
550 }
551
552 /**
553 * Returns the textual value for the message.
554 * @return Message contents or placeholder
555 */
556 protected function getMessageText() {
557 $message = $this->fetchMessage();
558 if ( $message === false ) {
559 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
560 } else {
561 return $message;
562 }
563 }
564
565 /**
566 * Wrapper for what ever method we use to get message contents
567 *
568 * @return string
569 */
570 protected function fetchMessage() {
571 if ( !isset( $this->message ) ) {
572 $cache = MessageCache::singleton();
573 if ( is_array( $this->key ) ) {
574 if ( !count( $this->key ) ) {
575 throw new MWException( "Given empty message key array." );
576 }
577 foreach ( $this->key as $key ) {
578 $message = $cache->get( $key, $this->useDatabase, $this->language );
579 if ( $message !== false && $message !== '' ) {
580 break;
581 }
582 }
583 $this->message = $message;
584 } else {
585 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
586 }
587 }
588 return $this->message;
589 }
590
591 }