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