Merge "Enable $wgVectorUseIconWatch by default."
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * Fetching and processing of interface messages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Niklas Laxström
22 */
23
24 /**
25 * The Message class provides methods which fulfil two basic services:
26 * - fetching interface messages
27 * - processing messages into a variety of formats
28 *
29 * First implemented with MediaWiki 1.17, the Message class is intended to
30 * replace the old wfMsg* functions that over time grew unusable.
31 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
32 * between old and new functions.
33 *
34 * You should use the wfMessage() global function which acts as a wrapper for
35 * the Message class. The wrapper let you pass parameters as arguments.
36 *
37 * The most basic usage cases would be:
38 *
39 * @code
40 * // Initialize a Message object using the 'some_key' message key
41 * $message = wfMessage( 'some_key' );
42 *
43 * // Using two parameters those values are strings 'value1' and 'value2':
44 * $message = wfMessage( 'some_key',
45 * 'value1', 'value2'
46 * );
47 * @endcode
48 *
49 * @section message_global_fn Global function wrapper:
50 *
51 * Since wfMessage() returns a Message instance, you can chain its call with
52 * a method. Some of them return a Message instance too so you can chain them.
53 * You will find below several examples of wfMessage() usage.
54 *
55 * Fetching a message text for interface message:
56 *
57 * @code
58 * $button = Xml::button(
59 * wfMessage( 'submit' )->text()
60 * );
61 * @endcode
62 *
63 * A Message instance can be passed parameters after it has been constructed,
64 * use the params() method to do so:
65 *
66 * @code
67 * wfMessage( 'welcome-to' )
68 * ->params( $wgSitename )
69 * ->text();
70 * @endcode
71 *
72 * {{GRAMMAR}} and friends work correctly:
73 *
74 * @code
75 * wfMessage( 'are-friends',
76 * $user, $friend
77 * );
78 * wfMessage( 'bad-message' )
79 * ->rawParams( '<script>...</script>' )
80 * ->escaped();
81 * @endcode
82 *
83 * @section message_language Changing language:
84 *
85 * Messages can be requested in a different language or in whatever current
86 * content language is being used. The methods are:
87 * - Message->inContentLanguage()
88 * - Message->inLanguage()
89 *
90 * Sometimes the message text ends up in the database, so content language is
91 * needed:
92 *
93 * @code
94 * wfMessage( 'file-log',
95 * $user, $filename
96 * )->inContentLanguage()->text();
97 * @endcode
98 *
99 * Checking whether a message exists:
100 *
101 * @code
102 * wfMessage( 'mysterious-message' )->exists()
103 * // returns a boolean whether the 'mysterious-message' key exist.
104 * @endcode
105 *
106 * If you want to use a different language:
107 *
108 * @code
109 * $userLanguage = $user->getOption( 'language' );
110 * wfMessage( 'email-header' )
111 * ->inLanguage( $userLanguage )
112 * ->plain();
113 * @endcode
114 *
115 * @note You can parse the text only in the content or interface languages
116 *
117 * @section message_compare_old Comparison with old wfMsg* functions:
118 *
119 * Use full parsing:
120 *
121 * @code
122 * // old style:
123 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
124 * // new style:
125 * wfMessage( 'key', 'apple' )->parse();
126 * @endcode
127 *
128 * Parseinline is used because it is more useful when pre-building HTML.
129 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
130 *
131 * Places where HTML cannot be used. {{-transformation is done.
132 * @code
133 * // old style:
134 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
135 * // new style:
136 * wfMessage( 'key', 'apple', 'pear' )->text();
137 * @endcode
138 *
139 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
140 * parameters are not replaced after escaping by default.
141 * @code
142 * $escaped = wfMessage( 'key' )
143 * ->rawParams( 'apple' )
144 * ->escaped();
145 * @endcode
146 *
147 * @section message_appendix Appendix:
148 *
149 * @todo
150 * - test, can we have tests?
151 * - this documentation needs to be extended
152 *
153 * @see https://www.mediawiki.org/wiki/WfMessage()
154 * @see https://www.mediawiki.org/wiki/New_messages_API
155 * @see https://www.mediawiki.org/wiki/Localisation
156 *
157 * @since 1.17
158 */
159 class Message {
160 /**
161 * In which language to get this message. True, which is the default,
162 * means the current interface language, false content language.
163 */
164 protected $interface = true;
165
166 /**
167 * In which language to get this message. Overrides the $interface
168 * variable.
169 *
170 * @var Language
171 */
172 protected $language = null;
173
174 /**
175 * The message key.
176 */
177 protected $key;
178
179 /**
180 * List of parameters which will be substituted into the message.
181 */
182 protected $parameters = array();
183
184 /**
185 * Format for the message.
186 * Supported formats are:
187 * * text (transform)
188 * * escaped (transform+htmlspecialchars)
189 * * block-parse
190 * * parse (default)
191 * * plain
192 */
193 protected $format = 'parse';
194
195 /**
196 * Whether database can be used.
197 */
198 protected $useDatabase = true;
199
200 /**
201 * Title object to use as context
202 */
203 protected $title = null;
204
205 /**
206 * Content object representing the message
207 */
208 protected $content = null;
209
210 /**
211 * @var string
212 */
213 protected $message;
214
215 /**
216 * Constructor.
217 * @since 1.17
218 * @param $key: message key, or array of message keys to try and use the first non-empty message for
219 * @param array $params message parameters
220 * @return Message: $this
221 */
222 public function __construct( $key, $params = array() ) {
223 global $wgLang;
224 $this->key = $key;
225 $this->parameters = array_values( $params );
226 $this->language = $wgLang;
227 }
228
229 /**
230 * Returns the message key
231 *
232 * @since 1.21
233 *
234 * @return string
235 */
236 public function getKey() {
237 return $this->key;
238 }
239
240 /**
241 * Returns the message parameters
242 *
243 * @since 1.21
244 *
245 * @return string[]
246 */
247 public function getParams() {
248 return $this->parameters;
249 }
250
251 /**
252 * Returns the message format
253 *
254 * @since 1.21
255 *
256 * @return string
257 */
258 public function getFormat() {
259 return $this->format;
260 }
261
262 /**
263 * Factory function that is just wrapper for the real constructor. It is
264 * intended to be used instead of the real constructor, because it allows
265 * chaining method calls, while new objects don't.
266 * @since 1.17
267 * @param string $key message key
268 * @param Varargs: parameters as Strings
269 * @return Message: $this
270 */
271 public static function newFromKey( $key /*...*/ ) {
272 $params = func_get_args();
273 array_shift( $params );
274 return new self( $key, $params );
275 }
276
277 /**
278 * Factory function accepting multiple message keys and returning a message instance
279 * for the first message which is non-empty. If all messages are empty then an
280 * instance of the first message key is returned.
281 * @since 1.18
282 * @param Varargs: message keys (or first arg as an array of all the message keys)
283 * @return Message: $this
284 */
285 public static function newFallbackSequence( /*...*/ ) {
286 $keys = func_get_args();
287 if ( func_num_args() == 1 ) {
288 if ( is_array( $keys[0] ) ) {
289 // Allow an array to be passed as the first argument instead
290 $keys = array_values( $keys[0] );
291 } else {
292 // Optimize a single string to not need special fallback handling
293 $keys = $keys[0];
294 }
295 }
296 return new self( $keys );
297 }
298
299 /**
300 * Adds parameters to the parameter list of this message.
301 * @since 1.17
302 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
303 * @return Message: $this
304 */
305 public function params( /*...*/ ) {
306 $args = func_get_args();
307 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
308 $args = $args[0];
309 }
310 $args_values = array_values( $args );
311 $this->parameters = array_merge( $this->parameters, $args_values );
312 return $this;
313 }
314
315 /**
316 * Add parameters that are substituted after parsing or escaping.
317 * In other words the parsing process cannot access the contents
318 * of this type of parameter, and you need to make sure it is
319 * sanitized beforehand. The parser will see "$n", instead.
320 * @since 1.17
321 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
322 * @return Message: $this
323 */
324 public function rawParams( /*...*/ ) {
325 $params = func_get_args();
326 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
327 $params = $params[0];
328 }
329 foreach( $params as $param ) {
330 $this->parameters[] = self::rawParam( $param );
331 }
332 return $this;
333 }
334
335 /**
336 * Add parameters that are numeric and will be passed through
337 * Language::formatNum before substitution
338 * @since 1.18
339 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
340 * @return Message: $this
341 */
342 public function numParams( /*...*/ ) {
343 $params = func_get_args();
344 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
345 $params = $params[0];
346 }
347 foreach( $params as $param ) {
348 $this->parameters[] = self::numParam( $param );
349 }
350 return $this;
351 }
352
353 /**
354 * Set the language and the title from a context object
355 * @since 1.19
356 * @param $context IContextSource
357 * @return Message: $this
358 */
359 public function setContext( IContextSource $context ) {
360 $this->inLanguage( $context->getLanguage() );
361 $this->title( $context->getTitle() );
362 $this->interface = true;
363
364 return $this;
365 }
366
367 /**
368 * Request the message in any language that is supported.
369 * As a side effect interface message status is unconditionally
370 * turned off.
371 * @since 1.17
372 * @param $lang Mixed: language code or Language object.
373 * @throws MWException
374 * @return Message: $this
375 */
376 public function inLanguage( $lang ) {
377 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
378 $this->language = $lang;
379 } elseif ( is_string( $lang ) ) {
380 if( $this->language->getCode() != $lang ) {
381 $this->language = Language::factory( $lang );
382 }
383 } else {
384 $type = gettype( $lang );
385 throw new MWException( __METHOD__ . " must be "
386 . "passed a String or Language object; $type given"
387 );
388 }
389 $this->interface = false;
390 return $this;
391 }
392
393 /**
394 * Request the message in the wiki's content language,
395 * unless it is disabled for this message.
396 * @since 1.17
397 * @see $wgForceUIMsgAsContentMsg
398 * @return Message: $this
399 */
400 public function inContentLanguage() {
401 global $wgForceUIMsgAsContentMsg;
402 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
403 return $this;
404 }
405
406 global $wgContLang;
407 $this->interface = false;
408 $this->language = $wgContLang;
409 return $this;
410 }
411
412 /**
413 * Allows manipulating the interface message flag directly.
414 * Can be used to restore the flag after setting a language.
415 * @param $value bool
416 * @return Message: $this
417 * @since 1.20
418 */
419 public function setInterfaceMessageFlag( $value ) {
420 $this->interface = (bool) $value;
421 return $this;
422 }
423
424 /**
425 * Enable or disable database use.
426 * @since 1.17
427 * @param $value Boolean
428 * @return Message: $this
429 */
430 public function useDatabase( $value ) {
431 $this->useDatabase = (bool) $value;
432 return $this;
433 }
434
435 /**
436 * Set the Title object to use as context when transforming the message
437 * @since 1.18
438 * @param $title Title object
439 * @return Message: $this
440 */
441 public function title( $title ) {
442 $this->title = $title;
443 return $this;
444 }
445
446 /**
447 * Returns the message as a Content object.
448 * @return Content
449 */
450 public function content() {
451 if ( !$this->content ) {
452 $this->content = new MessageContent( $this );
453 }
454
455 return $this->content;
456 }
457
458 /**
459 * Returns the message parsed from wikitext to HTML.
460 * @since 1.17
461 * @return String: HTML
462 */
463 public function toString() {
464 $string = $this->fetchMessage();
465
466 if ( $string === false ) {
467 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
468 if ( $this->format === 'plain' ) {
469 return '<' . $key . '>';
470 }
471 return '&lt;' . $key . '&gt;';
472 }
473
474 # Replace $* with a list of parameters for &uselang=qqx.
475 if ( strpos( $string, '$*' ) !== false ) {
476 $paramlist = '';
477 if ( $this->parameters !== array() ) {
478 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
479 }
480 $string = str_replace( '$*', $paramlist, $string );
481 }
482
483 # Replace parameters before text parsing
484 $string = $this->replaceParameters( $string, 'before' );
485
486 # Maybe transform using the full parser
487 if( $this->format === 'parse' ) {
488 $string = $this->parseText( $string );
489 $m = array();
490 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
491 $string = $m[1];
492 }
493 } elseif( $this->format === 'block-parse' ) {
494 $string = $this->parseText( $string );
495 } elseif( $this->format === 'text' ) {
496 $string = $this->transformText( $string );
497 } elseif( $this->format === 'escaped' ) {
498 $string = $this->transformText( $string );
499 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
500 }
501
502 # Raw parameter replacement
503 $string = $this->replaceParameters( $string, 'after' );
504
505 return $string;
506 }
507
508 /**
509 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
510 * $foo = Message::get( $key );
511 * $string = "<abbr>$foo</abbr>";
512 * @since 1.18
513 * @return String
514 */
515 public function __toString() {
516 // PHP doesn't allow __toString to throw exceptions and will
517 // trigger a fatal error if it does. So, catch any exceptions.
518
519 try {
520 return $this->toString();
521 } catch ( Exception $ex ) {
522 try {
523 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
524 . $ex, E_USER_WARNING );
525 } catch ( Exception $ex ) {
526 // Doh! Cause a fatal error after all?
527 }
528
529 if ( $this->format === 'plain' ) {
530 return '<' . $this->key . '>';
531 }
532 return '&lt;' . $this->key . '&gt;';
533 }
534 }
535
536 /**
537 * Fully parse the text from wikitext to HTML
538 * @since 1.17
539 * @return String parsed HTML
540 */
541 public function parse() {
542 $this->format = 'parse';
543 return $this->toString();
544 }
545
546 /**
547 * Returns the message text. {{-transformation is done.
548 * @since 1.17
549 * @return String: Unescaped message text.
550 */
551 public function text() {
552 $this->format = 'text';
553 return $this->toString();
554 }
555
556 /**
557 * Returns the message text as-is, only parameters are substituted.
558 * @since 1.17
559 * @return String: Unescaped untransformed message text.
560 */
561 public function plain() {
562 $this->format = 'plain';
563 return $this->toString();
564 }
565
566 /**
567 * Returns the parsed message text which is always surrounded by a block element.
568 * @since 1.17
569 * @return String: HTML
570 */
571 public function parseAsBlock() {
572 $this->format = 'block-parse';
573 return $this->toString();
574 }
575
576 /**
577 * Returns the message text. {{-transformation is done and the result
578 * is escaped excluding any raw parameters.
579 * @since 1.17
580 * @return String: Escaped message text.
581 */
582 public function escaped() {
583 $this->format = 'escaped';
584 return $this->toString();
585 }
586
587 /**
588 * Check whether a message key has been defined currently.
589 * @since 1.17
590 * @return Bool: true if it is and false if not.
591 */
592 public function exists() {
593 return $this->fetchMessage() !== false;
594 }
595
596 /**
597 * Check whether a message does not exist, or is an empty string
598 * @since 1.18
599 * @return Bool: true if is is and false if not
600 * @todo FIXME: Merge with isDisabled()?
601 */
602 public function isBlank() {
603 $message = $this->fetchMessage();
604 return $message === false || $message === '';
605 }
606
607 /**
608 * Check whether a message does not exist, is an empty string, or is "-"
609 * @since 1.18
610 * @return Bool: true if it is and false if not
611 */
612 public function isDisabled() {
613 $message = $this->fetchMessage();
614 return $message === false || $message === '' || $message === '-';
615 }
616
617 /**
618 * @since 1.17
619 * @param $value
620 * @return array
621 */
622 public static function rawParam( $value ) {
623 return array( 'raw' => $value );
624 }
625
626 /**
627 * @since 1.18
628 * @param $value
629 * @return array
630 */
631 public static function numParam( $value ) {
632 return array( 'num' => $value );
633 }
634
635 /**
636 * Substitutes any parameters into the message text.
637 * @since 1.17
638 * @param string $message the message text
639 * @param string $type either before or after
640 * @return String
641 */
642 protected function replaceParameters( $message, $type = 'before' ) {
643 $replacementKeys = array();
644 foreach( $this->parameters as $n => $param ) {
645 list( $paramType, $value ) = $this->extractParam( $param );
646 if ( $type === $paramType ) {
647 $replacementKeys['$' . ($n + 1)] = $value;
648 }
649 }
650 $message = strtr( $message, $replacementKeys );
651 return $message;
652 }
653
654 /**
655 * Extracts the parameter type and preprocessed the value if needed.
656 * @since 1.18
657 * @param string|array $param Parameter as defined in this class.
658 * @return Tuple(type, value)
659 */
660 protected function extractParam( $param ) {
661 if ( is_array( $param ) && isset( $param['raw'] ) ) {
662 return array( 'after', $param['raw'] );
663 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
664 // Replace number params always in before step for now.
665 // No support for combined raw and num params
666 return array( 'before', $this->language->formatNum( $param['num'] ) );
667 } elseif ( !is_array( $param ) ) {
668 return array( 'before', $param );
669 } else {
670 trigger_error(
671 "Invalid message parameter: " . htmlspecialchars( serialize( $param ) ),
672 E_USER_WARNING
673 );
674 return array( 'before', '[INVALID]' );
675 }
676 }
677
678 /**
679 * Wrapper for what ever method we use to parse wikitext.
680 * @since 1.17
681 * @param string $string Wikitext message contents
682 * @return string Wikitext parsed into HTML
683 */
684 protected function parseText( $string ) {
685 $out = MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language );
686 return is_object( $out ) ? $out->getText() : $out;
687 }
688
689 /**
690 * Wrapper for what ever method we use to {{-transform wikitext.
691 * @since 1.17
692 * @param string $string Wikitext message contents
693 * @return string Wikitext with {{-constructs replaced with their values.
694 */
695 protected function transformText( $string ) {
696 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
697 }
698
699 /**
700 * Wrapper for what ever method we use to get message contents
701 * @since 1.17
702 * @throws MWException
703 * @return string
704 */
705 protected function fetchMessage() {
706 if ( !isset( $this->message ) ) {
707 $cache = MessageCache::singleton();
708 if ( is_array( $this->key ) ) {
709 if ( !count( $this->key ) ) {
710 throw new MWException( "Given empty message key array." );
711 }
712 foreach ( $this->key as $key ) {
713 $message = $cache->get( $key, $this->useDatabase, $this->language );
714 if ( $message !== false && $message !== '' ) {
715 break;
716 }
717 }
718 $this->message = $message;
719 } else {
720 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
721 }
722 }
723 return $this->message;
724 }
725
726 }
727
728 /**
729 * Variant of the Message class.
730 *
731 * Rather than treating the message key as a lookup
732 * value (which is passed to the MessageCache and
733 * translated as necessary), a RawMessage key is
734 * treated as the actual message.
735 *
736 * All other functionality (parsing, escaping, etc.)
737 * is preserved.
738 *
739 * @since 1.21
740 */
741 class RawMessage extends Message {
742 /**
743 * Call the parent constructor, then store the key as
744 * the message.
745 *
746 * @param string $key Message to use
747 * @param array $params Parameters for the message
748 * @see Message::__construct
749 */
750 public function __construct( $key, $params = array() ) {
751 parent::__construct( $key, $params );
752 // The key is the message.
753 $this->message = $key;
754 }
755
756 /**
757 * Fetch the message (in this case, the key).
758 *
759 * @return string
760 */
761 public function fetchMessage() {
762 // Just in case the message is unset somewhere.
763 if( !isset( $this->message ) ) {
764 $this->message = $this->key;
765 }
766 return $this->message;
767 }
768 }