Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / Message.php
blob5719f83090429afbe6154338190d21dded1decc2
1 <?php
2 /**
3 * Fetching and processing of interface messages.
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.
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.
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
20 * @file
21 * @author Niklas Laxström
24 /**
25 * The Message class provides methods which fulfil two basic services:
26 * - fetching interface messages
27 * - processing messages into a variety of formats
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.
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.
37 * The most basic usage cases would be:
39 * @code
40 * // Initialize a Message object using the 'some_key' message key
41 * $message = wfMessage( 'some_key' );
43 * // Using two parameters those values are strings 'value1' and 'value2':
44 * $message = wfMessage( 'some_key',
45 * 'value1', 'value2'
46 * );
47 * @endcode
49 * @section message_global_fn Global function wrapper:
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.
55 * Fetching a message text for interface message:
57 * @code
58 * $button = Xml::button(
59 * wfMessage( 'submit' )->text()
60 * );
61 * @endcode
63 * A Message instance can be passed parameters after it has been constructed,
64 * use the params() method to do so:
66 * @code
67 * wfMessage( 'welcome-to' )
68 * ->params( $wgSitename )
69 * ->text();
70 * @endcode
72 * {{GRAMMAR}} and friends work correctly:
74 * @code
75 * wfMessage( 'are-friends',
76 * $user, $friend
77 * );
78 * wfMessage( 'bad-message' )
79 * ->rawParams( '<script>...</script>' )
80 * ->escaped();
81 * @endcode
83 * @section message_language Changing language:
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()
90 * Sometimes the message text ends up in the database, so content language is
91 * needed:
93 * @code
94 * wfMessage( 'file-log',
95 * $user, $filename
96 * )->inContentLanguage()->text();
97 * @endcode
99 * Checking whether a message exists:
101 * @code
102 * wfMessage( 'mysterious-message' )->exists()
103 * // returns a boolean whether the 'mysterious-message' key exist.
104 * @endcode
106 * If you want to use a different language:
108 * @code
109 * $userLanguage = $user->getOption( 'language' );
110 * wfMessage( 'email-header' )
111 * ->inLanguage( $userLanguage )
112 * ->plain();
113 * @endcode
115 * @note You can parse the text only in the content or interface languages
117 * @section message_compare_old Comparison with old wfMsg* functions:
119 * Use full parsing:
121 * @code
122 * // old style:
123 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
124 * // new style:
125 * wfMessage( 'key', 'apple' )->parse();
126 * @endcode
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.
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
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
147 * @section message_appendix Appendix:
149 * @todo
150 * - test, can we have tests?
151 * - this documentation needs to be extended
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
157 * @since 1.17
159 class Message {
161 * In which language to get this message. True, which is the default,
162 * means the current interface language, false content language.
164 protected $interface = true;
167 * In which language to get this message. Overrides the $interface
168 * variable.
170 * @var Language
172 protected $language = null;
175 * The message key.
177 protected $key;
180 * List of parameters which will be substituted into the message.
182 protected $parameters = array();
185 * Format for the message.
186 * Supported formats are:
187 * * text (transform)
188 * * escaped (transform+htmlspecialchars)
189 * * block-parse
190 * * parse (default)
191 * * plain
193 protected $format = 'parse';
196 * Whether database can be used.
198 protected $useDatabase = true;
201 * Title object to use as context
203 protected $title = null;
206 * Content object representing the message
208 protected $content = null;
211 * @var string
213 protected $message;
216 * Constructor.
217 * @since 1.17
218 * @param $key: message key, or array of message keys to try and use the first non-empty message for
219 * @param array $params message parameters
220 * @return Message: $this
222 public function __construct( $key, $params = array() ) {
223 global $wgLang;
224 $this->key = $key;
225 $this->parameters = array_values( $params );
226 $this->language = $wgLang;
230 * Returns the message key
232 * @since 1.21
234 * @return string
236 public function getKey() {
237 return $this->key;
241 * Returns the message parameters
243 * @since 1.21
245 * @return string[]
247 public function getParams() {
248 return $this->parameters;
252 * Returns the message format
254 * @since 1.21
256 * @return string
258 public function getFormat() {
259 return $this->format;
263 * Factory function that is just wrapper for the real constructor. It is
264 * intended to be used instead of the real constructor, because it allows
265 * chaining method calls, while new objects don't.
266 * @since 1.17
267 * @param string $key message key
268 * @param Varargs: parameters as Strings
269 * @return Message: $this
271 public static function newFromKey( $key /*...*/ ) {
272 $params = func_get_args();
273 array_shift( $params );
274 return new self( $key, $params );
278 * Factory function accepting multiple message keys and returning a message instance
279 * for the first message which is non-empty. If all messages are empty then an
280 * instance of the first message key is returned.
281 * @since 1.18
282 * @param Varargs: message keys (or first arg as an array of all the message keys)
283 * @return Message: $this
285 public static function newFallbackSequence( /*...*/ ) {
286 $keys = func_get_args();
287 if ( func_num_args() == 1 ) {
288 if ( is_array( $keys[0] ) ) {
289 // Allow an array to be passed as the first argument instead
290 $keys = array_values( $keys[0] );
291 } else {
292 // Optimize a single string to not need special fallback handling
293 $keys = $keys[0];
296 return new self( $keys );
300 * Adds parameters to the parameter list of this message.
301 * @since 1.17
302 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
303 * @return Message: $this
305 public function params( /*...*/ ) {
306 $args = func_get_args();
307 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
308 $args = $args[0];
310 $args_values = array_values( $args );
311 $this->parameters = array_merge( $this->parameters, $args_values );
312 return $this;
316 * Add parameters that are substituted after parsing or escaping.
317 * In other words the parsing process cannot access the contents
318 * of this type of parameter, and you need to make sure it is
319 * sanitized beforehand. The parser will see "$n", instead.
320 * @since 1.17
321 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
322 * @return Message: $this
324 public function rawParams( /*...*/ ) {
325 $params = func_get_args();
326 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
327 $params = $params[0];
329 foreach( $params as $param ) {
330 $this->parameters[] = self::rawParam( $param );
332 return $this;
336 * Add parameters that are numeric and will be passed through
337 * Language::formatNum before substitution
338 * @since 1.18
339 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
340 * @return Message: $this
342 public function numParams( /*...*/ ) {
343 $params = func_get_args();
344 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
345 $params = $params[0];
347 foreach( $params as $param ) {
348 $this->parameters[] = self::numParam( $param );
350 return $this;
354 * Set the language and the title from a context object
355 * @since 1.19
356 * @param $context IContextSource
357 * @return Message: $this
359 public function setContext( IContextSource $context ) {
360 $this->inLanguage( $context->getLanguage() );
361 $this->title( $context->getTitle() );
362 $this->interface = true;
364 return $this;
368 * Request the message in any language that is supported.
369 * As a side effect interface message status is unconditionally
370 * turned off.
371 * @since 1.17
372 * @param $lang Mixed: language code or Language object.
373 * @throws MWException
374 * @return Message: $this
376 public function inLanguage( $lang ) {
377 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
378 $this->language = $lang;
379 } elseif ( is_string( $lang ) ) {
380 if( $this->language->getCode() != $lang ) {
381 $this->language = Language::factory( $lang );
383 } else {
384 $type = gettype( $lang );
385 throw new MWException( __METHOD__ . " must be "
386 . "passed a String or Language object; $type given"
389 $this->interface = false;
390 return $this;
394 * Request the message in the wiki's content language,
395 * unless it is disabled for this message.
396 * @since 1.17
397 * @see $wgForceUIMsgAsContentMsg
398 * @return Message: $this
400 public function inContentLanguage() {
401 global $wgForceUIMsgAsContentMsg;
402 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
403 return $this;
406 global $wgContLang;
407 $this->interface = false;
408 $this->language = $wgContLang;
409 return $this;
413 * Allows manipulating the interface message flag directly.
414 * Can be used to restore the flag after setting a language.
415 * @param $value bool
416 * @return Message: $this
417 * @since 1.20
419 public function setInterfaceMessageFlag( $value ) {
420 $this->interface = (bool) $value;
421 return $this;
425 * Enable or disable database use.
426 * @since 1.17
427 * @param $value Boolean
428 * @return Message: $this
430 public function useDatabase( $value ) {
431 $this->useDatabase = (bool) $value;
432 return $this;
436 * Set the Title object to use as context when transforming the message
437 * @since 1.18
438 * @param $title Title object
439 * @return Message: $this
441 public function title( $title ) {
442 $this->title = $title;
443 return $this;
447 * Returns the message as a Content object.
448 * @return Content
450 public function content() {
451 if ( !$this->content ) {
452 $this->content = new MessageContent( $this );
455 return $this->content;
459 * Returns the message parsed from wikitext to HTML.
460 * @since 1.17
461 * @return String: HTML
463 public function toString() {
464 $string = $this->fetchMessage();
466 if ( $string === false ) {
467 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
468 if ( $this->format === 'plain' ) {
469 return '<' . $key . '>';
471 return '&lt;' . $key . '&gt;';
474 # Replace $* with a list of parameters for &uselang=qqx.
475 if ( strpos( $string, '$*' ) !== false ) {
476 $paramlist = '';
477 if ( $this->parameters !== array() ) {
478 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
480 $string = str_replace( '$*', $paramlist, $string );
483 # Replace parameters before text parsing
484 $string = $this->replaceParameters( $string, 'before' );
486 # Maybe transform using the full parser
487 if( $this->format === 'parse' ) {
488 $string = $this->parseText( $string );
489 $m = array();
490 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
491 $string = $m[1];
493 } elseif( $this->format === 'block-parse' ) {
494 $string = $this->parseText( $string );
495 } elseif( $this->format === 'text' ) {
496 $string = $this->transformText( $string );
497 } elseif( $this->format === 'escaped' ) {
498 $string = $this->transformText( $string );
499 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
502 # Raw parameter replacement
503 $string = $this->replaceParameters( $string, 'after' );
505 return $string;
509 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
510 * $foo = Message::get( $key );
511 * $string = "<abbr>$foo</abbr>";
512 * @since 1.18
513 * @return String
515 public function __toString() {
516 // PHP doesn't allow __toString to throw exceptions and will
517 // trigger a fatal error if it does. So, catch any exceptions.
519 try {
520 return $this->toString();
521 } catch ( Exception $ex ) {
522 try {
523 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
524 . $ex, E_USER_WARNING );
525 } catch ( Exception $ex ) {
526 // Doh! Cause a fatal error after all?
529 if ( $this->format === 'plain' ) {
530 return '<' . $this->key . '>';
532 return '&lt;' . $this->key . '&gt;';
537 * Fully parse the text from wikitext to HTML
538 * @since 1.17
539 * @return String parsed HTML
541 public function parse() {
542 $this->format = 'parse';
543 return $this->toString();
547 * Returns the message text. {{-transformation is done.
548 * @since 1.17
549 * @return String: Unescaped message text.
551 public function text() {
552 $this->format = 'text';
553 return $this->toString();
557 * Returns the message text as-is, only parameters are substituted.
558 * @since 1.17
559 * @return String: Unescaped untransformed message text.
561 public function plain() {
562 $this->format = 'plain';
563 return $this->toString();
567 * Returns the parsed message text which is always surrounded by a block element.
568 * @since 1.17
569 * @return String: HTML
571 public function parseAsBlock() {
572 $this->format = 'block-parse';
573 return $this->toString();
577 * Returns the message text. {{-transformation is done and the result
578 * is escaped excluding any raw parameters.
579 * @since 1.17
580 * @return String: Escaped message text.
582 public function escaped() {
583 $this->format = 'escaped';
584 return $this->toString();
588 * Check whether a message key has been defined currently.
589 * @since 1.17
590 * @return Bool: true if it is and false if not.
592 public function exists() {
593 return $this->fetchMessage() !== false;
597 * Check whether a message does not exist, or is an empty string
598 * @since 1.18
599 * @return Bool: true if is is and false if not
600 * @todo FIXME: Merge with isDisabled()?
602 public function isBlank() {
603 $message = $this->fetchMessage();
604 return $message === false || $message === '';
608 * Check whether a message does not exist, is an empty string, or is "-"
609 * @since 1.18
610 * @return Bool: true if it is and false if not
612 public function isDisabled() {
613 $message = $this->fetchMessage();
614 return $message === false || $message === '' || $message === '-';
618 * @since 1.17
619 * @param $value
620 * @return array
622 public static function rawParam( $value ) {
623 return array( 'raw' => $value );
627 * @since 1.18
628 * @param $value
629 * @return array
631 public static function numParam( $value ) {
632 return array( 'num' => $value );
636 * Substitutes any parameters into the message text.
637 * @since 1.17
638 * @param string $message the message text
639 * @param string $type either before or after
640 * @return String
642 protected function replaceParameters( $message, $type = 'before' ) {
643 $replacementKeys = array();
644 foreach( $this->parameters as $n => $param ) {
645 list( $paramType, $value ) = $this->extractParam( $param );
646 if ( $type === $paramType ) {
647 $replacementKeys['$' . ($n + 1)] = $value;
650 $message = strtr( $message, $replacementKeys );
651 return $message;
655 * Extracts the parameter type and preprocessed the value if needed.
656 * @since 1.18
657 * @param string|array $param Parameter as defined in this class.
658 * @return Tuple(type, value)
660 protected function extractParam( $param ) {
661 if ( is_array( $param ) && isset( $param['raw'] ) ) {
662 return array( 'after', $param['raw'] );
663 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
664 // Replace number params always in before step for now.
665 // No support for combined raw and num params
666 return array( 'before', $this->language->formatNum( $param['num'] ) );
667 } elseif ( !is_array( $param ) ) {
668 return array( 'before', $param );
669 } else {
670 trigger_error(
671 "Invalid message parameter: " . htmlspecialchars( serialize( $param ) ),
672 E_USER_WARNING
674 return array( 'before', '[INVALID]' );
679 * Wrapper for what ever method we use to parse wikitext.
680 * @since 1.17
681 * @param string $string Wikitext message contents
682 * @return string Wikitext parsed into HTML
684 protected function parseText( $string ) {
685 $out = MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language );
686 return is_object( $out ) ? $out->getText() : $out;
690 * Wrapper for what ever method we use to {{-transform wikitext.
691 * @since 1.17
692 * @param string $string Wikitext message contents
693 * @return string Wikitext with {{-constructs replaced with their values.
695 protected function transformText( $string ) {
696 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
700 * Wrapper for what ever method we use to get message contents
701 * @since 1.17
702 * @throws MWException
703 * @return string
705 protected function fetchMessage() {
706 if ( !isset( $this->message ) ) {
707 $cache = MessageCache::singleton();
708 if ( is_array( $this->key ) ) {
709 if ( !count( $this->key ) ) {
710 throw new MWException( "Given empty message key array." );
712 foreach ( $this->key as $key ) {
713 $message = $cache->get( $key, $this->useDatabase, $this->language );
714 if ( $message !== false && $message !== '' ) {
715 break;
718 $this->message = $message;
719 } else {
720 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
723 return $this->message;
729 * Variant of the Message class.
731 * Rather than treating the message key as a lookup
732 * value (which is passed to the MessageCache and
733 * translated as necessary), a RawMessage key is
734 * treated as the actual message.
736 * All other functionality (parsing, escaping, etc.)
737 * is preserved.
739 * @since 1.21
741 class RawMessage extends Message {
743 * Call the parent constructor, then store the key as
744 * the message.
746 * @param string $key Message to use
747 * @param array $params Parameters for the message
748 * @see Message::__construct
750 public function __construct( $key, $params = array() ) {
751 parent::__construct( $key, $params );
752 // The key is the message.
753 $this->message = $key;
757 * Fetch the message (in this case, the key).
759 * @return string
761 public function fetchMessage() {
762 // Just in case the message is unset somewhere.
763 if( !isset( $this->message ) ) {
764 $this->message = $this->key;
766 return $this->message;