(bug 31565) Option to use group members on Special:UserRights
[mediawiki.git] / includes / Message.php
blob2feaed2b715dcfd0c34ade2116303997e3be1a85
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 fullfil 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 intented 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 $params Array 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 * Factory function that is just wrapper for the real constructor. It is
231 * intented to be used instead of the real constructor, because it allows
232 * chaining method calls, while new objects don't.
233 * @since 1.17
234 * @param $key String: message key
235 * @param Varargs: parameters as Strings
236 * @return Message: $this
238 public static function newFromKey( $key /*...*/ ) {
239 $params = func_get_args();
240 array_shift( $params );
241 return new self( $key, $params );
245 * Factory function accepting multiple message keys and returning a message instance
246 * for the first message which is non-empty. If all messages are empty then an
247 * instance of the first message key is returned.
248 * @since 1.18
249 * @param Varargs: message keys (or first arg as an array of all the message keys)
250 * @return Message: $this
252 public static function newFallbackSequence( /*...*/ ) {
253 $keys = func_get_args();
254 if ( func_num_args() == 1 ) {
255 if ( is_array($keys[0]) ) {
256 // Allow an array to be passed as the first argument instead
257 $keys = array_values($keys[0]);
258 } else {
259 // Optimize a single string to not need special fallback handling
260 $keys = $keys[0];
263 return new self( $keys );
267 * Adds parameters to the parameter list of this message.
268 * @since 1.17
269 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
270 * @return Message: $this
272 public function params( /*...*/ ) {
273 $args = func_get_args();
274 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
275 $args = $args[0];
277 $args_values = array_values( $args );
278 $this->parameters = array_merge( $this->parameters, $args_values );
279 return $this;
283 * Add parameters that are substituted after parsing or escaping.
284 * In other words the parsing process cannot access the contents
285 * of this type of parameter, and you need to make sure it is
286 * sanitized beforehand. The parser will see "$n", instead.
287 * @since 1.17
288 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
289 * @return Message: $this
291 public function rawParams( /*...*/ ) {
292 $params = func_get_args();
293 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
294 $params = $params[0];
296 foreach( $params as $param ) {
297 $this->parameters[] = self::rawParam( $param );
299 return $this;
303 * Add parameters that are numeric and will be passed through
304 * Language::formatNum before substitution
305 * @since 1.18
306 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
307 * @return Message: $this
309 public function numParams( /*...*/ ) {
310 $params = func_get_args();
311 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
312 $params = $params[0];
314 foreach( $params as $param ) {
315 $this->parameters[] = self::numParam( $param );
317 return $this;
321 * Set the language and the title from a context object
322 * @since 1.19
323 * @param $context IContextSource
324 * @return Message: $this
326 public function setContext( IContextSource $context ) {
327 $this->inLanguage( $context->getLanguage() );
328 $this->title( $context->getTitle() );
329 $this->interface = true;
331 return $this;
335 * Request the message in any language that is supported.
336 * As a side effect interface message status is unconditionally
337 * turned off.
338 * @since 1.17
339 * @param $lang Mixed: language code or Language object.
340 * @throws MWException
341 * @return Message: $this
343 public function inLanguage( $lang ) {
344 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
345 $this->language = $lang;
346 } elseif ( is_string( $lang ) ) {
347 if( $this->language->getCode() != $lang ) {
348 $this->language = Language::factory( $lang );
350 } else {
351 $type = gettype( $lang );
352 throw new MWException( __METHOD__ . " must be "
353 . "passed a String or Language object; $type given"
356 $this->interface = false;
357 return $this;
361 * Request the message in the wiki's content language,
362 * unless it is disabled for this message.
363 * @since 1.17
364 * @see $wgForceUIMsgAsContentMsg
365 * @return Message: $this
367 public function inContentLanguage() {
368 global $wgForceUIMsgAsContentMsg;
369 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
370 return $this;
373 global $wgContLang;
374 $this->interface = false;
375 $this->language = $wgContLang;
376 return $this;
380 * Allows manipulating the interface message flag directly.
381 * Can be used to restore the flag after setting a language.
382 * @param $value bool
383 * @return Message: $this
384 * @since 1.20
386 public function setInterfaceMessageFlag( $value ) {
387 $this->interface = (bool) $value;
388 return $this;
392 * Enable or disable database use.
393 * @since 1.17
394 * @param $value Boolean
395 * @return Message: $this
397 public function useDatabase( $value ) {
398 $this->useDatabase = (bool) $value;
399 return $this;
403 * Set the Title object to use as context when transforming the message
404 * @since 1.18
405 * @param $title Title object
406 * @return Message: $this
408 public function title( $title ) {
409 $this->title = $title;
410 return $this;
414 * Returns the message as a Content object.
415 * @return Content
417 public function content() {
418 if ( !$this->content ) {
419 $this->content = new MessageContent( $this->key );
422 return $this->content;
426 * Returns the message parsed from wikitext to HTML.
427 * @since 1.17
428 * @return String: HTML
430 public function toString() {
431 $string = $this->fetchMessage();
433 if ( $string === false ) {
434 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
435 if ( $this->format === 'plain' ) {
436 return '<' . $key . '>';
438 return '&lt;' . $key . '&gt;';
441 # Replace $* with a list of parameters for &uselang=qqx.
442 if ( strpos( $string, '$*' ) !== false ) {
443 $paramlist = '';
444 if ( $this->parameters !== array() ) {
445 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
447 $string = str_replace( '$*', $paramlist, $string );
450 # Replace parameters before text parsing
451 $string = $this->replaceParameters( $string, 'before' );
453 # Maybe transform using the full parser
454 if( $this->format === 'parse' ) {
455 $string = $this->parseText( $string );
456 $m = array();
457 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
458 $string = $m[1];
460 } elseif( $this->format === 'block-parse' ){
461 $string = $this->parseText( $string );
462 } elseif( $this->format === 'text' ){
463 $string = $this->transformText( $string );
464 } elseif( $this->format === 'escaped' ){
465 $string = $this->transformText( $string );
466 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
469 # Raw parameter replacement
470 $string = $this->replaceParameters( $string, 'after' );
472 return $string;
476 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
477 * $foo = Message::get($key);
478 * $string = "<abbr>$foo</abbr>";
479 * @since 1.18
480 * @return String
482 public function __toString() {
483 return $this->toString();
487 * Fully parse the text from wikitext to HTML
488 * @since 1.17
489 * @return String parsed HTML
491 public function parse() {
492 $this->format = 'parse';
493 return $this->toString();
497 * Returns the message text. {{-transformation is done.
498 * @since 1.17
499 * @return String: Unescaped message text.
501 public function text() {
502 $this->format = 'text';
503 return $this->toString();
507 * Returns the message text as-is, only parameters are subsituted.
508 * @since 1.17
509 * @return String: Unescaped untransformed message text.
511 public function plain() {
512 $this->format = 'plain';
513 return $this->toString();
517 * Returns the parsed message text which is always surrounded by a block element.
518 * @since 1.17
519 * @return String: HTML
521 public function parseAsBlock() {
522 $this->format = 'block-parse';
523 return $this->toString();
527 * Returns the message text. {{-transformation is done and the result
528 * is escaped excluding any raw parameters.
529 * @since 1.17
530 * @return String: Escaped message text.
532 public function escaped() {
533 $this->format = 'escaped';
534 return $this->toString();
538 * Check whether a message key has been defined currently.
539 * @since 1.17
540 * @return Bool: true if it is and false if not.
542 public function exists() {
543 return $this->fetchMessage() !== false;
547 * Check whether a message does not exist, or is an empty string
548 * @since 1.18
549 * @return Bool: true if is is and false if not
550 * @todo FIXME: Merge with isDisabled()?
552 public function isBlank() {
553 $message = $this->fetchMessage();
554 return $message === false || $message === '';
558 * Check whether a message does not exist, is an empty string, or is "-"
559 * @since 1.18
560 * @return Bool: true if it is and false if not
562 public function isDisabled() {
563 $message = $this->fetchMessage();
564 return $message === false || $message === '' || $message === '-';
568 * @since 1.17
569 * @param $value
570 * @return array
572 public static function rawParam( $value ) {
573 return array( 'raw' => $value );
577 * @since 1.18
578 * @param $value
579 * @return array
581 public static function numParam( $value ) {
582 return array( 'num' => $value );
586 * Substitutes any paramaters into the message text.
587 * @since 1.17
588 * @param $message String: the message text
589 * @param $type String: either before or after
590 * @return String
592 protected function replaceParameters( $message, $type = 'before' ) {
593 $replacementKeys = array();
594 foreach( $this->parameters as $n => $param ) {
595 list( $paramType, $value ) = $this->extractParam( $param );
596 if ( $type === $paramType ) {
597 $replacementKeys['$' . ($n + 1)] = $value;
600 $message = strtr( $message, $replacementKeys );
601 return $message;
605 * Extracts the parameter type and preprocessed the value if needed.
606 * @since 1.18
607 * @param $param String|Array: Parameter as defined in this class.
608 * @return Tuple(type, value)
609 * @throws MWException
611 protected function extractParam( $param ) {
612 if ( is_array( $param ) && isset( $param['raw'] ) ) {
613 return array( 'after', $param['raw'] );
614 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
615 // Replace number params always in before step for now.
616 // No support for combined raw and num params
617 return array( 'before', $this->language->formatNum( $param['num'] ) );
618 } elseif ( !is_array( $param ) ) {
619 return array( 'before', $param );
620 } else {
621 throw new MWException( "Invalid message parameter: " . serialize( $param ) );
626 * Wrapper for what ever method we use to parse wikitext.
627 * @since 1.17
628 * @param $string String: Wikitext message contents
629 * @return string Wikitext parsed into HTML
631 protected function parseText( $string ) {
632 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
636 * Wrapper for what ever method we use to {{-transform wikitext.
637 * @since 1.17
638 * @param $string String: Wikitext message contents
639 * @return string Wikitext with {{-constructs replaced with their values.
641 protected function transformText( $string ) {
642 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
646 * Wrapper for what ever method we use to get message contents
647 * @since 1.17
648 * @throws MWException
649 * @return string
651 protected function fetchMessage() {
652 if ( !isset( $this->message ) ) {
653 $cache = MessageCache::singleton();
654 if ( is_array( $this->key ) ) {
655 if ( !count( $this->key ) ) {
656 throw new MWException( "Given empty message key array." );
658 foreach ( $this->key as $key ) {
659 $message = $cache->get( $key, $this->useDatabase, $this->language );
660 if ( $message !== false && $message !== '' ) {
661 break;
664 $this->message = $message;
665 } else {
666 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
669 return $this->message;