Merge "Fix possible error texts in action=options"
[mediawiki.git] / includes / Message.php
blob78b9ec2044384dd28f656e06ff1ff98ce983b1d3
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 * @var string
208 protected $message;
211 * Constructor.
212 * @param $key: message key, or array of message keys to try and use the first non-empty message for
213 * @param $params Array message parameters
214 * @return Message: $this
216 public function __construct( $key, $params = array() ) {
217 global $wgLang;
218 $this->key = $key;
219 $this->parameters = array_values( $params );
220 $this->language = $wgLang;
224 * Factory function that is just wrapper for the real constructor. It is
225 * intented to be used instead of the real constructor, because it allows
226 * chaining method calls, while new objects don't.
227 * @param $key String: message key
228 * @param Varargs: parameters as Strings
229 * @return Message: $this
231 public static function newFromKey( $key /*...*/ ) {
232 $params = func_get_args();
233 array_shift( $params );
234 return new self( $key, $params );
238 * Factory function accepting multiple message keys and returning a message instance
239 * for the first message which is non-empty. If all messages are empty then an
240 * instance of the first message key is returned.
241 * @param Varargs: message keys (or first arg as an array of all the message keys)
242 * @return Message: $this
244 public static function newFallbackSequence( /*...*/ ) {
245 $keys = func_get_args();
246 if ( func_num_args() == 1 ) {
247 if ( is_array($keys[0]) ) {
248 // Allow an array to be passed as the first argument instead
249 $keys = array_values($keys[0]);
250 } else {
251 // Optimize a single string to not need special fallback handling
252 $keys = $keys[0];
255 return new self( $keys );
259 * Adds parameters to the parameter list of this message.
260 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
261 * @return Message: $this
263 public function params( /*...*/ ) {
264 $args = func_get_args();
265 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
266 $args = $args[0];
268 $args_values = array_values( $args );
269 $this->parameters = array_merge( $this->parameters, $args_values );
270 return $this;
274 * Add parameters that are substituted after parsing or escaping.
275 * In other words the parsing process cannot access the contents
276 * of this type of parameter, and you need to make sure it is
277 * sanitized beforehand. The parser will see "$n", instead.
278 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
279 * @return Message: $this
281 public function rawParams( /*...*/ ) {
282 $params = func_get_args();
283 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
284 $params = $params[0];
286 foreach( $params as $param ) {
287 $this->parameters[] = self::rawParam( $param );
289 return $this;
293 * Add parameters that are numeric and will be passed through
294 * Language::formatNum before substitution
295 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
296 * @return Message: $this
298 public function numParams( /*...*/ ) {
299 $params = func_get_args();
300 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
301 $params = $params[0];
303 foreach( $params as $param ) {
304 $this->parameters[] = self::numParam( $param );
306 return $this;
310 * Set the language and the title from a context object
312 * @param $context IContextSource
313 * @return Message: $this
315 public function setContext( IContextSource $context ) {
316 $this->inLanguage( $context->getLanguage() );
317 $this->title( $context->getTitle() );
318 $this->interface = true;
320 return $this;
324 * Request the message in any language that is supported.
325 * As a side effect interface message status is unconditionally
326 * turned off.
327 * @param $lang Mixed: language code or Language object.
328 * @return Message: $this
330 public function inLanguage( $lang ) {
331 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
332 $this->language = $lang;
333 } elseif ( is_string( $lang ) ) {
334 if( $this->language->getCode() != $lang ) {
335 $this->language = Language::factory( $lang );
337 } else {
338 $type = gettype( $lang );
339 throw new MWException( __METHOD__ . " must be "
340 . "passed a String or Language object; $type given"
343 $this->interface = false;
344 return $this;
348 * Request the message in the wiki's content language,
349 * unless it is disabled for this message.
350 * @see $wgForceUIMsgAsContentMsg
351 * @return Message: $this
353 public function inContentLanguage() {
354 global $wgForceUIMsgAsContentMsg;
355 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
356 return $this;
359 global $wgContLang;
360 $this->interface = false;
361 $this->language = $wgContLang;
362 return $this;
366 * Allows manipulating the interface message flag directly.
367 * Can be used to restore the flag after setting a language.
368 * @param $value bool
369 * @return Message: $this
370 * @since 1.20
372 public function setInterfaceMessageFlag( $value ) {
373 $this->interface = (bool) $value;
374 return $this;
378 * Enable or disable database use.
379 * @param $value Boolean
380 * @return Message: $this
382 public function useDatabase( $value ) {
383 $this->useDatabase = (bool) $value;
384 return $this;
388 * Set the Title object to use as context when transforming the message
390 * @param $title Title object
391 * @return Message: $this
393 public function title( $title ) {
394 $this->title = $title;
395 return $this;
399 * Returns the message parsed from wikitext to HTML.
400 * @return String: HTML
402 public function toString() {
403 $string = $this->fetchMessage();
405 if ( $string === false ) {
406 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
407 if ( $this->format === 'plain' ) {
408 return '<' . $key . '>';
410 return '&lt;' . $key . '&gt;';
413 # Replace parameters before text parsing
414 $string = $this->replaceParameters( $string, 'before' );
416 # Maybe transform using the full parser
417 if( $this->format === 'parse' ) {
418 $string = $this->parseText( $string );
419 $m = array();
420 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
421 $string = $m[1];
423 } elseif( $this->format === 'block-parse' ){
424 $string = $this->parseText( $string );
425 } elseif( $this->format === 'text' ){
426 $string = $this->transformText( $string );
427 } elseif( $this->format === 'escaped' ){
428 $string = $this->transformText( $string );
429 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
432 # Raw parameter replacement
433 $string = $this->replaceParameters( $string, 'after' );
435 return $string;
439 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
440 * $foo = Message::get($key);
441 * $string = "<abbr>$foo</abbr>";
442 * @return String
444 public function __toString() {
445 return $this->toString();
449 * Fully parse the text from wikitext to HTML
450 * @return String parsed HTML
452 public function parse() {
453 $this->format = 'parse';
454 return $this->toString();
458 * Returns the message text. {{-transformation is done.
459 * @return String: Unescaped message text.
461 public function text() {
462 $this->format = 'text';
463 return $this->toString();
467 * Returns the message text as-is, only parameters are subsituted.
468 * @return String: Unescaped untransformed message text.
470 public function plain() {
471 $this->format = 'plain';
472 return $this->toString();
476 * Returns the parsed message text which is always surrounded by a block element.
477 * @return String: HTML
479 public function parseAsBlock() {
480 $this->format = 'block-parse';
481 return $this->toString();
485 * Returns the message text. {{-transformation is done and the result
486 * is escaped excluding any raw parameters.
487 * @return String: Escaped message text.
489 public function escaped() {
490 $this->format = 'escaped';
491 return $this->toString();
495 * Check whether a message key has been defined currently.
496 * @return Bool: true if it is and false if not.
498 public function exists() {
499 return $this->fetchMessage() !== false;
503 * Check whether a message does not exist, or is an empty string
504 * @return Bool: true if is is and false if not
505 * @todo FIXME: Merge with isDisabled()?
507 public function isBlank() {
508 $message = $this->fetchMessage();
509 return $message === false || $message === '';
513 * Check whether a message does not exist, is an empty string, or is "-"
514 * @return Bool: true if is is and false if not
516 public function isDisabled() {
517 $message = $this->fetchMessage();
518 return $message === false || $message === '' || $message === '-';
522 * @param $value
523 * @return array
525 public static function rawParam( $value ) {
526 return array( 'raw' => $value );
530 * @param $value
531 * @return array
533 public static function numParam( $value ) {
534 return array( 'num' => $value );
538 * Substitutes any paramaters into the message text.
539 * @param $message String: the message text
540 * @param $type String: either before or after
541 * @return String
543 protected function replaceParameters( $message, $type = 'before' ) {
544 $replacementKeys = array();
545 foreach( $this->parameters as $n => $param ) {
546 list( $paramType, $value ) = $this->extractParam( $param );
547 if ( $type === $paramType ) {
548 $replacementKeys['$' . ($n + 1)] = $value;
551 $message = strtr( $message, $replacementKeys );
552 return $message;
556 * Extracts the parameter type and preprocessed the value if needed.
557 * @param $param String|Array: Parameter as defined in this class.
558 * @return Tuple(type, value)
559 * @throws MWException
561 protected function extractParam( $param ) {
562 if ( is_array( $param ) && isset( $param['raw'] ) ) {
563 return array( 'after', $param['raw'] );
564 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
565 // Replace number params always in before step for now.
566 // No support for combined raw and num params
567 return array( 'before', $this->language->formatNum( $param['num'] ) );
568 } elseif ( !is_array( $param ) ) {
569 return array( 'before', $param );
570 } else {
571 throw new MWException( "Invalid message parameter" );
576 * Wrapper for what ever method we use to parse wikitext.
577 * @param $string String: Wikitext message contents
578 * @return string Wikitext parsed into HTML
580 protected function parseText( $string ) {
581 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
585 * Wrapper for what ever method we use to {{-transform wikitext.
586 * @param $string String: Wikitext message contents
587 * @return string Wikitext with {{-constructs replaced with their values.
589 protected function transformText( $string ) {
590 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
594 * Wrapper for what ever method we use to get message contents
596 * @return string
598 protected function fetchMessage() {
599 if ( !isset( $this->message ) ) {
600 $cache = MessageCache::singleton();
601 if ( is_array( $this->key ) ) {
602 if ( !count( $this->key ) ) {
603 throw new MWException( "Given empty message key array." );
605 foreach ( $this->key as $key ) {
606 $message = $cache->get( $key, $this->useDatabase, $this->language );
607 if ( $message !== false && $message !== '' ) {
608 break;
611 $this->message = $message;
612 } else {
613 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
616 return $this->message;