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