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