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