Merge "Rank aliases in search in order they appear in the messages file."
[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', [ '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', [ '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 implements MessageSpecifier, Serializable {
160 /** Use message text as-is */
161 const FORMAT_PLAIN = 'plain';
162 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
163 const FORMAT_BLOCK_PARSE = 'block-parse';
164 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
165 const FORMAT_PARSE = 'parse';
166 /** Transform {{..}} constructs but don't transform to HTML */
167 const FORMAT_TEXT = 'text';
168 /** Transform {{..}} constructs, HTML-escape the result */
169 const FORMAT_ESCAPED = 'escaped';
170
171 /**
172 * Mapping from Message::listParam() types to Language methods.
173 * @var array
174 */
175 protected static $listTypeMap = [
176 'comma' => 'commaList',
177 'semicolon' => 'semicolonList',
178 'pipe' => 'pipeList',
179 'text' => 'listToText',
180 ];
181
182 /**
183 * In which language to get this message. True, which is the default,
184 * means the current user language, false content language.
185 *
186 * @var bool
187 */
188 protected $interface = true;
189
190 /**
191 * In which language to get this message. Overrides the $interface setting.
192 *
193 * @var Language|bool Explicit language object, or false for user language
194 */
195 protected $language = false;
196
197 /**
198 * @var string The message key. If $keysToTry has more than one element,
199 * this may change to one of the keys to try when fetching the message text.
200 */
201 protected $key;
202
203 /**
204 * @var string[] List of keys to try when fetching the message.
205 */
206 protected $keysToTry;
207
208 /**
209 * @var array List of parameters which will be substituted into the message.
210 */
211 protected $parameters = [];
212
213 /**
214 * @var string
215 * @deprecated
216 */
217 protected $format = 'parse';
218
219 /**
220 * @var bool Whether database can be used.
221 */
222 protected $useDatabase = true;
223
224 /**
225 * @var Title Title object to use as context.
226 */
227 protected $title = null;
228
229 /**
230 * @var Content Content object representing the message.
231 */
232 protected $content = null;
233
234 /**
235 * @var string
236 */
237 protected $message;
238
239 /**
240 * @since 1.17
241 * @param string|string[]|MessageSpecifier $key Message key, or array of
242 * message keys to try and use the first non-empty message for, or a
243 * MessageSpecifier to copy from.
244 * @param array $params Message parameters.
245 * @param Language $language [optional] Language to use (defaults to current user language).
246 * @throws InvalidArgumentException
247 */
248 public function __construct( $key, $params = [], Language $language = null ) {
249 if ( $key instanceof MessageSpecifier ) {
250 if ( $params ) {
251 throw new InvalidArgumentException(
252 '$params must be empty if $key is a MessageSpecifier'
253 );
254 }
255 $params = $key->getParams();
256 $key = $key->getKey();
257 }
258
259 if ( !is_string( $key ) && !is_array( $key ) ) {
260 throw new InvalidArgumentException( '$key must be a string or an array' );
261 }
262
263 $this->keysToTry = (array)$key;
264
265 if ( empty( $this->keysToTry ) ) {
266 throw new InvalidArgumentException( '$key must not be an empty list' );
267 }
268
269 $this->key = reset( $this->keysToTry );
270
271 $this->parameters = array_values( $params );
272 // User language is only resolved in getLanguage(). This helps preserve the
273 // semantic intent of "user language" across serialize() and unserialize().
274 $this->language = $language ?: false;
275 }
276
277 /**
278 * @see Serializable::serialize()
279 * @since 1.26
280 * @return string
281 */
282 public function serialize() {
283 return serialize( [
284 'interface' => $this->interface,
285 'language' => $this->language ? $this->language->getCode() : false,
286 'key' => $this->key,
287 'keysToTry' => $this->keysToTry,
288 'parameters' => $this->parameters,
289 'format' => $this->format,
290 'useDatabase' => $this->useDatabase,
291 'title' => $this->title,
292 ] );
293 }
294
295 /**
296 * @see Serializable::unserialize()
297 * @since 1.26
298 * @param string $serialized
299 */
300 public function unserialize( $serialized ) {
301 $data = unserialize( $serialized );
302 $this->interface = $data['interface'];
303 $this->key = $data['key'];
304 $this->keysToTry = $data['keysToTry'];
305 $this->parameters = $data['parameters'];
306 $this->format = $data['format'];
307 $this->useDatabase = $data['useDatabase'];
308 $this->language = $data['language'] ? Language::factory( $data['language'] ) : false;
309 $this->title = $data['title'];
310 }
311
312 /**
313 * @since 1.24
314 *
315 * @return bool True if this is a multi-key message, that is, if the key provided to the
316 * constructor was a fallback list of keys to try.
317 */
318 public function isMultiKey() {
319 return count( $this->keysToTry ) > 1;
320 }
321
322 /**
323 * @since 1.24
324 *
325 * @return string[] The list of keys to try when fetching the message text,
326 * in order of preference.
327 */
328 public function getKeysToTry() {
329 return $this->keysToTry;
330 }
331
332 /**
333 * Returns the message key.
334 *
335 * If a list of multiple possible keys was supplied to the constructor, this method may
336 * return any of these keys. After the message has been fetched, this method will return
337 * the key that was actually used to fetch the message.
338 *
339 * @since 1.21
340 *
341 * @return string
342 */
343 public function getKey() {
344 return $this->key;
345 }
346
347 /**
348 * Returns the message parameters.
349 *
350 * @since 1.21
351 *
352 * @return array
353 */
354 public function getParams() {
355 return $this->parameters;
356 }
357
358 /**
359 * Returns the message format.
360 *
361 * @since 1.21
362 *
363 * @return string
364 * @deprecated since 1.29 formatting is not stateful
365 */
366 public function getFormat() {
367 wfDeprecated( __METHOD__, '1.29' );
368 return $this->format;
369 }
370
371 /**
372 * Returns the Language of the Message.
373 *
374 * @since 1.23
375 *
376 * @return Language
377 */
378 public function getLanguage() {
379 // Defaults to false which means current user language
380 return $this->language ?: RequestContext::getMain()->getLanguage();
381 }
382
383 /**
384 * Factory function that is just wrapper for the real constructor. It is
385 * intended to be used instead of the real constructor, because it allows
386 * chaining method calls, while new objects don't.
387 *
388 * @since 1.17
389 *
390 * @param string|string[]|MessageSpecifier $key
391 * @param mixed $param,... Parameters as strings.
392 *
393 * @return Message
394 */
395 public static function newFromKey( $key /*...*/ ) {
396 $params = func_get_args();
397 array_shift( $params );
398 return new self( $key, $params );
399 }
400
401 /**
402 * Transform a MessageSpecifier or a primitive value used interchangeably with
403 * specifiers (a message key string, or a key + params array) into a proper Message.
404 *
405 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
406 * but is an easy error to make due to how StatusValue stores messages internally.
407 * Further array elements are ignored in that case.
408 *
409 * @param string|array|MessageSpecifier $value
410 * @return Message
411 * @throws InvalidArgumentException
412 * @since 1.27
413 */
414 public static function newFromSpecifier( $value ) {
415 $params = [];
416 if ( is_array( $value ) ) {
417 $params = $value;
418 $value = array_shift( $params );
419 }
420
421 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
422 $message = clone( $value );
423 } elseif ( $value instanceof MessageSpecifier ) {
424 $message = new Message( $value );
425 } elseif ( is_string( $value ) ) {
426 $message = new Message( $value, $params );
427 } else {
428 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
429 . gettype( $value ) );
430 }
431
432 return $message;
433 }
434
435 /**
436 * Factory function accepting multiple message keys and returning a message instance
437 * for the first message which is non-empty. If all messages are empty then an
438 * instance of the first message key is returned.
439 *
440 * @since 1.18
441 *
442 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
443 * message keys.
444 *
445 * @return Message
446 */
447 public static function newFallbackSequence( /*...*/ ) {
448 $keys = func_get_args();
449 if ( func_num_args() == 1 ) {
450 if ( is_array( $keys[0] ) ) {
451 // Allow an array to be passed as the first argument instead
452 $keys = array_values( $keys[0] );
453 } else {
454 // Optimize a single string to not need special fallback handling
455 $keys = $keys[0];
456 }
457 }
458 return new self( $keys );
459 }
460
461 /**
462 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
463 * The title will be for the current language, if the message key is in
464 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
465 * language), because Message::inContentLanguage will also return in user language.
466 *
467 * @see $wgForceUIMsgAsContentMsg
468 * @return Title
469 * @since 1.26
470 */
471 public function getTitle() {
472 global $wgContLang, $wgForceUIMsgAsContentMsg;
473
474 $title = $this->key;
475 if (
476 !$this->language->equals( $wgContLang )
477 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
478 ) {
479 $code = $this->language->getCode();
480 $title .= '/' . $code;
481 }
482
483 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( strtr( $title, ' ', '_' ) ) );
484 }
485
486 /**
487 * Adds parameters to the parameter list of this message.
488 *
489 * @since 1.17
490 *
491 * @param mixed ... Parameters as strings, or a single argument that is
492 * an array of strings.
493 *
494 * @return Message $this
495 */
496 public function params( /*...*/ ) {
497 $args = func_get_args();
498 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
499 $args = $args[0];
500 }
501 $args_values = array_values( $args );
502 $this->parameters = array_merge( $this->parameters, $args_values );
503 return $this;
504 }
505
506 /**
507 * Add parameters that are substituted after parsing or escaping.
508 * In other words the parsing process cannot access the contents
509 * of this type of parameter, and you need to make sure it is
510 * sanitized beforehand. The parser will see "$n", instead.
511 *
512 * @since 1.17
513 *
514 * @param mixed $params,... Raw parameters as strings, or a single argument that is
515 * an array of raw parameters.
516 *
517 * @return Message $this
518 */
519 public function rawParams( /*...*/ ) {
520 $params = func_get_args();
521 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
522 $params = $params[0];
523 }
524 foreach ( $params as $param ) {
525 $this->parameters[] = self::rawParam( $param );
526 }
527 return $this;
528 }
529
530 /**
531 * Add parameters that are numeric and will be passed through
532 * Language::formatNum before substitution
533 *
534 * @since 1.18
535 *
536 * @param mixed $param,... Numeric parameters, or a single argument that is
537 * an array of numeric parameters.
538 *
539 * @return Message $this
540 */
541 public function numParams( /*...*/ ) {
542 $params = func_get_args();
543 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
544 $params = $params[0];
545 }
546 foreach ( $params as $param ) {
547 $this->parameters[] = self::numParam( $param );
548 }
549 return $this;
550 }
551
552 /**
553 * Add parameters that are durations of time and will be passed through
554 * Language::formatDuration before substitution
555 *
556 * @since 1.22
557 *
558 * @param int|int[] $param,... Duration parameters, or a single argument that is
559 * an array of duration parameters.
560 *
561 * @return Message $this
562 */
563 public function durationParams( /*...*/ ) {
564 $params = func_get_args();
565 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
566 $params = $params[0];
567 }
568 foreach ( $params as $param ) {
569 $this->parameters[] = self::durationParam( $param );
570 }
571 return $this;
572 }
573
574 /**
575 * Add parameters that are expiration times and will be passed through
576 * Language::formatExpiry before substitution
577 *
578 * @since 1.22
579 *
580 * @param string|string[] $param,... Expiry parameters, or a single argument that is
581 * an array of expiry parameters.
582 *
583 * @return Message $this
584 */
585 public function expiryParams( /*...*/ ) {
586 $params = func_get_args();
587 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
588 $params = $params[0];
589 }
590 foreach ( $params as $param ) {
591 $this->parameters[] = self::expiryParam( $param );
592 }
593 return $this;
594 }
595
596 /**
597 * Add parameters that are time periods and will be passed through
598 * Language::formatTimePeriod before substitution
599 *
600 * @since 1.22
601 *
602 * @param int|int[] $param,... Time period parameters, or a single argument that is
603 * an array of time period parameters.
604 *
605 * @return Message $this
606 */
607 public function timeperiodParams( /*...*/ ) {
608 $params = func_get_args();
609 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
610 $params = $params[0];
611 }
612 foreach ( $params as $param ) {
613 $this->parameters[] = self::timeperiodParam( $param );
614 }
615 return $this;
616 }
617
618 /**
619 * Add parameters that are file sizes and will be passed through
620 * Language::formatSize before substitution
621 *
622 * @since 1.22
623 *
624 * @param int|int[] $param,... Size parameters, or a single argument that is
625 * an array of size parameters.
626 *
627 * @return Message $this
628 */
629 public function sizeParams( /*...*/ ) {
630 $params = func_get_args();
631 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
632 $params = $params[0];
633 }
634 foreach ( $params as $param ) {
635 $this->parameters[] = self::sizeParam( $param );
636 }
637 return $this;
638 }
639
640 /**
641 * Add parameters that are bitrates and will be passed through
642 * Language::formatBitrate before substitution
643 *
644 * @since 1.22
645 *
646 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
647 * an array of bit rate parameters.
648 *
649 * @return Message $this
650 */
651 public function bitrateParams( /*...*/ ) {
652 $params = func_get_args();
653 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
654 $params = $params[0];
655 }
656 foreach ( $params as $param ) {
657 $this->parameters[] = self::bitrateParam( $param );
658 }
659 return $this;
660 }
661
662 /**
663 * Add parameters that are plaintext and will be passed through without
664 * the content being evaluated. Plaintext parameters are not valid as
665 * arguments to parser functions. This differs from self::rawParams in
666 * that the Message class handles escaping to match the output format.
667 *
668 * @since 1.25
669 *
670 * @param string|string[] $param,... plaintext parameters, or a single argument that is
671 * an array of plaintext parameters.
672 *
673 * @return Message $this
674 */
675 public function plaintextParams( /*...*/ ) {
676 $params = func_get_args();
677 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
678 $params = $params[0];
679 }
680 foreach ( $params as $param ) {
681 $this->parameters[] = self::plaintextParam( $param );
682 }
683 return $this;
684 }
685
686 /**
687 * Set the language and the title from a context object
688 *
689 * @since 1.19
690 *
691 * @param IContextSource $context
692 *
693 * @return Message $this
694 */
695 public function setContext( IContextSource $context ) {
696 $this->inLanguage( $context->getLanguage() );
697 $this->title( $context->getTitle() );
698 $this->interface = true;
699
700 return $this;
701 }
702
703 /**
704 * Request the message in any language that is supported.
705 *
706 * As a side effect interface message status is unconditionally
707 * turned off.
708 *
709 * @since 1.17
710 * @param Language|string $lang Language code or Language object.
711 * @return Message $this
712 * @throws MWException
713 */
714 public function inLanguage( $lang ) {
715 if ( $lang instanceof Language ) {
716 $this->language = $lang;
717 } elseif ( is_string( $lang ) ) {
718 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
719 $this->language = Language::factory( $lang );
720 }
721 } elseif ( $lang instanceof StubUserLang ) {
722 $this->language = false;
723 } else {
724 $type = gettype( $lang );
725 throw new MWException( __METHOD__ . " must be "
726 . "passed a String or Language object; $type given"
727 );
728 }
729 $this->message = null;
730 $this->interface = false;
731 return $this;
732 }
733
734 /**
735 * Request the message in the wiki's content language,
736 * unless it is disabled for this message.
737 *
738 * @since 1.17
739 * @see $wgForceUIMsgAsContentMsg
740 *
741 * @return Message $this
742 */
743 public function inContentLanguage() {
744 global $wgForceUIMsgAsContentMsg;
745 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
746 return $this;
747 }
748
749 global $wgContLang;
750 $this->inLanguage( $wgContLang );
751 return $this;
752 }
753
754 /**
755 * Allows manipulating the interface message flag directly.
756 * Can be used to restore the flag after setting a language.
757 *
758 * @since 1.20
759 *
760 * @param bool $interface
761 *
762 * @return Message $this
763 */
764 public function setInterfaceMessageFlag( $interface ) {
765 $this->interface = (bool)$interface;
766 return $this;
767 }
768
769 /**
770 * Enable or disable database use.
771 *
772 * @since 1.17
773 *
774 * @param bool $useDatabase
775 *
776 * @return Message $this
777 */
778 public function useDatabase( $useDatabase ) {
779 $this->useDatabase = (bool)$useDatabase;
780 $this->message = null;
781 return $this;
782 }
783
784 /**
785 * Set the Title object to use as context when transforming the message
786 *
787 * @since 1.18
788 *
789 * @param Title $title
790 *
791 * @return Message $this
792 */
793 public function title( $title ) {
794 $this->title = $title;
795 return $this;
796 }
797
798 /**
799 * Returns the message as a Content object.
800 *
801 * @return Content
802 */
803 public function content() {
804 if ( !$this->content ) {
805 $this->content = new MessageContent( $this );
806 }
807
808 return $this->content;
809 }
810
811 /**
812 * Returns the message parsed from wikitext to HTML.
813 *
814 * @since 1.17
815 *
816 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
817 * the last time (this is for B/C and should be avoided).
818 *
819 * @return string HTML
820 */
821 public function toString( $format = null ) {
822 if ( $format === null ) {
823 $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format );
824 \MediaWiki\Logger\LoggerFactory::getInstance( 'message-format' )->warning(
825 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] );
826 $format = $this->format;
827 }
828 $string = $this->fetchMessage();
829
830 if ( $string === false ) {
831 // Err on the side of safety, ensure that the output
832 // is always html safe in the event the message key is
833 // missing, since in that case its highly likely the
834 // message key is user-controlled.
835 // '⧼' is used instead of '<' to side-step any
836 // double-escaping issues.
837 // (Keep synchronised with mw.Message#toString in JS.)
838 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
839 }
840
841 # Replace $* with a list of parameters for &uselang=qqx.
842 if ( strpos( $string, '$*' ) !== false ) {
843 $paramlist = '';
844 if ( $this->parameters !== [] ) {
845 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
846 }
847 $string = str_replace( '$*', $paramlist, $string );
848 }
849
850 # Replace parameters before text parsing
851 $string = $this->replaceParameters( $string, 'before', $format );
852
853 # Maybe transform using the full parser
854 if ( $format === self::FORMAT_PARSE ) {
855 $string = $this->parseText( $string );
856 $string = Parser::stripOuterParagraph( $string );
857 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
858 $string = $this->parseText( $string );
859 } elseif ( $format === self::FORMAT_TEXT ) {
860 $string = $this->transformText( $string );
861 } elseif ( $format === self::FORMAT_ESCAPED ) {
862 $string = $this->transformText( $string );
863 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
864 }
865
866 # Raw parameter replacement
867 $string = $this->replaceParameters( $string, 'after', $format );
868
869 return $string;
870 }
871
872 /**
873 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
874 * $foo = new Message( $key );
875 * $string = "<abbr>$foo</abbr>";
876 *
877 * @since 1.18
878 *
879 * @return string
880 */
881 public function __toString() {
882 // PHP doesn't allow __toString to throw exceptions and will
883 // trigger a fatal error if it does. So, catch any exceptions.
884
885 try {
886 return $this->toString( self::FORMAT_PARSE );
887 } catch ( Exception $ex ) {
888 try {
889 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
890 . $ex, E_USER_WARNING );
891 } catch ( Exception $ex ) {
892 // Doh! Cause a fatal error after all?
893 }
894
895 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
896 }
897 }
898
899 /**
900 * Fully parse the text from wikitext to HTML.
901 *
902 * @since 1.17
903 *
904 * @return string Parsed HTML.
905 */
906 public function parse() {
907 $this->format = self::FORMAT_PARSE;
908 return $this->toString( self::FORMAT_PARSE );
909 }
910
911 /**
912 * Returns the message text. {{-transformation is done.
913 *
914 * @since 1.17
915 *
916 * @return string Unescaped message text.
917 */
918 public function text() {
919 $this->format = self::FORMAT_TEXT;
920 return $this->toString( self::FORMAT_TEXT );
921 }
922
923 /**
924 * Returns the message text as-is, only parameters are substituted.
925 *
926 * @since 1.17
927 *
928 * @return string Unescaped untransformed message text.
929 */
930 public function plain() {
931 $this->format = self::FORMAT_PLAIN;
932 return $this->toString( self::FORMAT_PLAIN );
933 }
934
935 /**
936 * Returns the parsed message text which is always surrounded by a block element.
937 *
938 * @since 1.17
939 *
940 * @return string HTML
941 */
942 public function parseAsBlock() {
943 $this->format = self::FORMAT_BLOCK_PARSE;
944 return $this->toString( self::FORMAT_BLOCK_PARSE );
945 }
946
947 /**
948 * Returns the message text. {{-transformation is done and the result
949 * is escaped excluding any raw parameters.
950 *
951 * @since 1.17
952 *
953 * @return string Escaped message text.
954 */
955 public function escaped() {
956 $this->format = self::FORMAT_ESCAPED;
957 return $this->toString( self::FORMAT_ESCAPED );
958 }
959
960 /**
961 * Check whether a message key has been defined currently.
962 *
963 * @since 1.17
964 *
965 * @return bool
966 */
967 public function exists() {
968 return $this->fetchMessage() !== false;
969 }
970
971 /**
972 * Check whether a message does not exist, or is an empty string
973 *
974 * @since 1.18
975 * @todo FIXME: Merge with isDisabled()?
976 *
977 * @return bool
978 */
979 public function isBlank() {
980 $message = $this->fetchMessage();
981 return $message === false || $message === '';
982 }
983
984 /**
985 * Check whether a message does not exist, is an empty string, or is "-".
986 *
987 * @since 1.18
988 *
989 * @return bool
990 */
991 public function isDisabled() {
992 $message = $this->fetchMessage();
993 return $message === false || $message === '' || $message === '-';
994 }
995
996 /**
997 * @since 1.17
998 *
999 * @param mixed $raw
1000 *
1001 * @return array Array with a single "raw" key.
1002 */
1003 public static function rawParam( $raw ) {
1004 return [ 'raw' => $raw ];
1005 }
1006
1007 /**
1008 * @since 1.18
1009 *
1010 * @param mixed $num
1011 *
1012 * @return array Array with a single "num" key.
1013 */
1014 public static function numParam( $num ) {
1015 return [ 'num' => $num ];
1016 }
1017
1018 /**
1019 * @since 1.22
1020 *
1021 * @param int $duration
1022 *
1023 * @return int[] Array with a single "duration" key.
1024 */
1025 public static function durationParam( $duration ) {
1026 return [ 'duration' => $duration ];
1027 }
1028
1029 /**
1030 * @since 1.22
1031 *
1032 * @param string $expiry
1033 *
1034 * @return string[] Array with a single "expiry" key.
1035 */
1036 public static function expiryParam( $expiry ) {
1037 return [ 'expiry' => $expiry ];
1038 }
1039
1040 /**
1041 * @since 1.22
1042 *
1043 * @param number $period
1044 *
1045 * @return number[] Array with a single "period" key.
1046 */
1047 public static function timeperiodParam( $period ) {
1048 return [ 'period' => $period ];
1049 }
1050
1051 /**
1052 * @since 1.22
1053 *
1054 * @param int $size
1055 *
1056 * @return int[] Array with a single "size" key.
1057 */
1058 public static function sizeParam( $size ) {
1059 return [ 'size' => $size ];
1060 }
1061
1062 /**
1063 * @since 1.22
1064 *
1065 * @param int $bitrate
1066 *
1067 * @return int[] Array with a single "bitrate" key.
1068 */
1069 public static function bitrateParam( $bitrate ) {
1070 return [ 'bitrate' => $bitrate ];
1071 }
1072
1073 /**
1074 * @since 1.25
1075 *
1076 * @param string $plaintext
1077 *
1078 * @return string[] Array with a single "plaintext" key.
1079 */
1080 public static function plaintextParam( $plaintext ) {
1081 return [ 'plaintext' => $plaintext ];
1082 }
1083
1084 /**
1085 * @since 1.29
1086 *
1087 * @param array $list
1088 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1089 * @return array Array with "list" and "type" keys.
1090 */
1091 public static function listParam( array $list, $type = 'text' ) {
1092 if ( !isset( self::$listTypeMap[$type] ) ) {
1093 throw new InvalidArgumentException(
1094 "Invalid type '$type'. Known types are: " . join( ', ', array_keys( self::$listTypeMap ) )
1095 );
1096 }
1097 return [ 'list' => $list, 'type' => $type ];
1098 }
1099
1100 /**
1101 * Substitutes any parameters into the message text.
1102 *
1103 * @since 1.17
1104 *
1105 * @param string $message The message text.
1106 * @param string $type Either "before" or "after".
1107 * @param string $format One of the FORMAT_* constants.
1108 *
1109 * @return string
1110 */
1111 protected function replaceParameters( $message, $type = 'before', $format ) {
1112 $replacementKeys = [];
1113 foreach ( $this->parameters as $n => $param ) {
1114 list( $paramType, $value ) = $this->extractParam( $param, $format );
1115 if ( $type === $paramType ) {
1116 $replacementKeys['$' . ( $n + 1 )] = $value;
1117 }
1118 }
1119 $message = strtr( $message, $replacementKeys );
1120 return $message;
1121 }
1122
1123 /**
1124 * Extracts the parameter type and preprocessed the value if needed.
1125 *
1126 * @since 1.18
1127 *
1128 * @param mixed $param Parameter as defined in this class.
1129 * @param string $format One of the FORMAT_* constants.
1130 *
1131 * @return array Array with the parameter type (either "before" or "after") and the value.
1132 */
1133 protected function extractParam( $param, $format ) {
1134 if ( is_array( $param ) ) {
1135 if ( isset( $param['raw'] ) ) {
1136 return [ 'after', $param['raw'] ];
1137 } elseif ( isset( $param['num'] ) ) {
1138 // Replace number params always in before step for now.
1139 // No support for combined raw and num params
1140 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1141 } elseif ( isset( $param['duration'] ) ) {
1142 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1143 } elseif ( isset( $param['expiry'] ) ) {
1144 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1145 } elseif ( isset( $param['period'] ) ) {
1146 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1147 } elseif ( isset( $param['size'] ) ) {
1148 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1149 } elseif ( isset( $param['bitrate'] ) ) {
1150 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1151 } elseif ( isset( $param['plaintext'] ) ) {
1152 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1153 } elseif ( isset( $param['list'] ) ) {
1154 return $this->formatListParam( $param['list'], $param['type'], $format );
1155 } else {
1156 $warning = 'Invalid parameter for message "' . $this->getKey() . '": ' .
1157 htmlspecialchars( serialize( $param ) );
1158 trigger_error( $warning, E_USER_WARNING );
1159 $e = new Exception;
1160 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1161
1162 return [ 'before', '[INVALID]' ];
1163 }
1164 } elseif ( $param instanceof Message ) {
1165 // Match language, flags, etc. to the current message.
1166 $msg = clone $param;
1167 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1168 // Cache depends on these parameters
1169 $msg->message = null;
1170 }
1171 $msg->interface = $this->interface;
1172 $msg->language = $this->language;
1173 $msg->useDatabase = $this->useDatabase;
1174 $msg->title = $this->title;
1175
1176 // DWIM
1177 if ( $format === 'block-parse' ) {
1178 $format = 'parse';
1179 }
1180 $msg->format = $format;
1181
1182 // Message objects should not be before parameters because
1183 // then they'll get double escaped. If the message needs to be
1184 // escaped, it'll happen right here when we call toString().
1185 return [ 'after', $msg->toString( $format ) ];
1186 } else {
1187 return [ 'before', $param ];
1188 }
1189 }
1190
1191 /**
1192 * Wrapper for what ever method we use to parse wikitext.
1193 *
1194 * @since 1.17
1195 *
1196 * @param string $string Wikitext message contents.
1197 *
1198 * @return string Wikitext parsed into HTML.
1199 */
1200 protected function parseText( $string ) {
1201 $out = MessageCache::singleton()->parse(
1202 $string,
1203 $this->title,
1204 /*linestart*/true,
1205 $this->interface,
1206 $this->getLanguage()
1207 );
1208
1209 return $out instanceof ParserOutput ? $out->getText() : $out;
1210 }
1211
1212 /**
1213 * Wrapper for what ever method we use to {{-transform wikitext.
1214 *
1215 * @since 1.17
1216 *
1217 * @param string $string Wikitext message contents.
1218 *
1219 * @return string Wikitext with {{-constructs replaced with their values.
1220 */
1221 protected function transformText( $string ) {
1222 return MessageCache::singleton()->transform(
1223 $string,
1224 $this->interface,
1225 $this->getLanguage(),
1226 $this->title
1227 );
1228 }
1229
1230 /**
1231 * Wrapper for what ever method we use to get message contents.
1232 *
1233 * @since 1.17
1234 *
1235 * @return string
1236 * @throws MWException If message key array is empty.
1237 */
1238 protected function fetchMessage() {
1239 if ( $this->message === null ) {
1240 $cache = MessageCache::singleton();
1241
1242 foreach ( $this->keysToTry as $key ) {
1243 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1244 if ( $message !== false && $message !== '' ) {
1245 break;
1246 }
1247 }
1248
1249 // NOTE: The constructor makes sure keysToTry isn't empty,
1250 // so we know that $key and $message are initialized.
1251 $this->key = $key;
1252 $this->message = $message;
1253 }
1254 return $this->message;
1255 }
1256
1257 /**
1258 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1259 * the entire string is displayed unchanged when displayed in the output
1260 * format.
1261 *
1262 * @since 1.25
1263 *
1264 * @param string $plaintext String to ensure plaintext output of
1265 * @param string $format One of the FORMAT_* constants.
1266 *
1267 * @return string Input plaintext encoded for output to $format
1268 */
1269 protected function formatPlaintext( $plaintext, $format ) {
1270 switch ( $format ) {
1271 case self::FORMAT_TEXT:
1272 case self::FORMAT_PLAIN:
1273 return $plaintext;
1274
1275 case self::FORMAT_PARSE:
1276 case self::FORMAT_BLOCK_PARSE:
1277 case self::FORMAT_ESCAPED:
1278 default:
1279 return htmlspecialchars( $plaintext, ENT_QUOTES );
1280
1281 }
1282 }
1283
1284 /**
1285 * Formats a list of parameters as a concatenated string.
1286 * @since 1.29
1287 * @param array $params
1288 * @param string $listType
1289 * @param string $format One of the FORMAT_* constants.
1290 * @return array Array with the parameter type (either "before" or "after") and the value.
1291 */
1292 protected function formatListParam( array $params, $listType, $format ) {
1293 if ( !isset( self::$listTypeMap[$listType] ) ) {
1294 $warning = 'Invalid list type for message "' . $this->getKey() . '": ' .
1295 htmlspecialchars( serialize( $param ) );
1296 trigger_error( $warning, E_USER_WARNING );
1297 $e = new Exception;
1298 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1299 return [ 'before', '[INVALID]' ];
1300 }
1301 $func = self::$listTypeMap[$listType];
1302
1303 // Handle an empty list sensibly
1304 if ( !$params ) {
1305 return [ 'before', $this->getLanguage()->$func( [] ) ];
1306 }
1307
1308 // First, determine what kinds of list items we have
1309 $types = [];
1310 $vars = [];
1311 $list = [];
1312 foreach ( $params as $n => $p ) {
1313 list( $type, $value ) = $this->extractParam( $p, $format );
1314 $types[$type] = true;
1315 $list[] = $value;
1316 $vars[] = '$' . ( $n + 1 );
1317 }
1318
1319 // Easy case: all are 'before' or 'after', so just join the
1320 // values and use the same type.
1321 if ( count( $types ) === 1 ) {
1322 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1323 }
1324
1325 // Hard case: We need to process each value per its type, then
1326 // return the concatenated values as 'after'. We handle this by turning
1327 // the list into a RawMessage and processing that as a parameter.
1328 $vars = $this->getLanguage()->$func( $vars );
1329 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1330 }
1331 }
1332
1333 /**
1334 * Variant of the Message class.
1335 *
1336 * Rather than treating the message key as a lookup
1337 * value (which is passed to the MessageCache and
1338 * translated as necessary), a RawMessage key is
1339 * treated as the actual message.
1340 *
1341 * All other functionality (parsing, escaping, etc.)
1342 * is preserved.
1343 *
1344 * @since 1.21
1345 */
1346 class RawMessage extends Message {
1347
1348 /**
1349 * Call the parent constructor, then store the key as
1350 * the message.
1351 *
1352 * @see Message::__construct
1353 *
1354 * @param string $text Message to use.
1355 * @param array $params Parameters for the message.
1356 *
1357 * @throws InvalidArgumentException
1358 */
1359 public function __construct( $text, $params = [] ) {
1360 if ( !is_string( $text ) ) {
1361 throw new InvalidArgumentException( '$text must be a string' );
1362 }
1363
1364 parent::__construct( $text, $params );
1365
1366 // The key is the message.
1367 $this->message = $text;
1368 }
1369
1370 /**
1371 * Fetch the message (in this case, the key).
1372 *
1373 * @return string
1374 */
1375 public function fetchMessage() {
1376 // Just in case the message is unset somewhere.
1377 if ( $this->message === null ) {
1378 $this->message = $this->key;
1379 }
1380
1381 return $this->message;
1382 }
1383
1384 }