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