* (bug 29116) Fix regression breaking CheckUser extension
[mediawiki.git] / includes / Message.php
blob5f6e9af42934d5c199b33d751c13890792723fd4
1 <?php
2 /**
3 * This class provides methods for fetching interface messages and
4 * processing them into variety of formats that are needed in MediaWiki.
6 * It is intented to replace the old wfMsg* functions that over time grew
7 * unusable.
9 * Examples:
10 * Fetching a message text for interface message
11 * $button = Xml::button( wfMessage( 'submit' )->text() );
12 * </pre>
13 * Messages can have parameters:
14 * wfMessage( 'welcome-to' )->params( $wgSitename )->text();
15 * {{GRAMMAR}} and friends work correctly
16 * wfMessage( 'are-friends', $user, $friend );
17 * wfMessage( 'bad-message' )->rawParams( '<script>...</script>' )->escaped();
18 * </pre>
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
21 * </pre>
22 * Checking if message exists:
23 * wfMessage( 'mysterious-message' )->exists()
24 * </pre>
25 * If you want to use a different language:
26 * wfMessage( 'email-header' )->inLanguage( $user->getOption( 'language' ) )->plain()
27 * Note that you cannot parse the text except in the content or interface
28 * languages
29 * </pre>
32 * Comparison with old wfMsg* functions:
34 * Use full parsing.
35 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
36 * === wfMessage( 'key', 'apple' )->parse();
37 * </pre>
38 * Parseinline is used because it is more useful when pre-building html.
39 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
41 * Places where html cannot be used. {{-transformation is done.
42 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
43 * === wfMessage( 'key', 'apple', 'pear' )->text();
44 * </pre>
46 * Shortcut for escaping the message too, similar to wfMsgHTML, but
47 * parameters are not replaced after escaping by default.
48 * $escaped = wfMessage( 'key' )->rawParams( 'apple' )->escaped();
49 * </pre>
51 * @todo
52 * - test, can we have tests?
54 * @since 1.17
55 * @author Niklas Laxström
57 class Message {
58 /**
59 * In which language to get this message. True, which is the default,
60 * means the current interface language, false content language.
62 protected $interface = true;
64 /**
65 * In which language to get this message. Overrides the $interface
66 * variable.
68 * @var Language
70 protected $language = null;
72 /**
73 * The message key.
75 protected $key;
77 /**
78 * List of parameters which will be substituted into the message.
80 protected $parameters = array();
82 /**
83 * Format for the message.
84 * Supported formats are:
85 * * text (transform)
86 * * escaped (transform+htmlspecialchars)
87 * * block-parse
88 * * parse (default)
89 * * plain
91 protected $format = 'parse';
93 /**
94 * Whether database can be used.
96 protected $useDatabase = true;
98 /**
99 * Title object to use as context
101 protected $title = null;
104 * Constructor.
105 * @param $key: message key, or array of message keys to try and use the first non-empty message for
106 * @param $params Array message parameters
107 * @return Message: $this
109 public function __construct( $key, $params = array() ) {
110 global $wgLang;
111 $this->key = $key;
112 $this->parameters = array_values( $params );
113 $this->language = $wgLang;
117 * Factory function that is just wrapper for the real constructor. It is
118 * intented to be used instead of the real constructor, because it allows
119 * chaining method calls, while new objects don't.
120 * @param $key String: message key
121 * @param Varargs: parameters as Strings
122 * @return Message: $this
124 public static function newFromKey( $key /*...*/ ) {
125 $params = func_get_args();
126 array_shift( $params );
127 return new self( $key, $params );
131 * Factory function accepting multiple message keys and returning a message instance
132 * for the first message which is non-empty. If all messages are empty then an
133 * instance of the first message key is returned.
134 * @param Varargs: message keys
135 * @return Message: $this
137 public static function newFallbackSequence( /*...*/ ) {
138 $keys = func_get_args();
139 if ( func_num_args() == 1 ) {
140 if ( is_array($keys[0]) ) {
141 // Allow an array to be passed as the first argument instead
142 $keys = array_values($keys[0]);
143 } else {
144 // Optimize a single string to not need special fallback handling
145 $keys = $keys[0];
148 return new self( $keys );
152 * Adds parameters to the parameter list of this message.
153 * @param Varargs: parameters as Strings
154 * @return Message: $this
156 public function params( /*...*/ ) {
157 $args = func_get_args();
158 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
159 $args = $args[0];
161 $args_values = array_values( $args );
162 $this->parameters = array_merge( $this->parameters, $args_values );
163 return $this;
167 * Add parameters that are substituted after parsing or escaping.
168 * In other words the parsing process cannot access the contents
169 * of this type of parameter, and you need to make sure it is
170 * sanitized beforehand. The parser will see "$n", instead.
171 * @param Varargs: raw parameters as Strings
172 * @return Message: $this
174 public function rawParams( /*...*/ ) {
175 $params = func_get_args();
176 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
177 $params = $params[0];
179 foreach( $params as $param ) {
180 $this->parameters[] = self::rawParam( $param );
182 return $this;
186 * Add parameters that are numeric and will be passed through
187 * Language::formatNum before substitution
188 * @param Varargs: numeric parameters
189 * @return Message: $this
191 public function numParams( /*...*/ ) {
192 $params = func_get_args();
193 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
194 $params = $params[0];
196 foreach( $params as $param ) {
197 $this->parameters[] = self::numParam( $param );
199 return $this;
203 * Request the message in any language that is supported.
204 * As a side effect interface message status is unconditionally
205 * turned off.
206 * @param $lang Mixed: language code or Language object.
207 * @return Message: $this
209 public function inLanguage( $lang ) {
210 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
211 $this->language = $lang;
212 } elseif ( is_string( $lang ) ) {
213 if( $this->language->getCode() != $lang ) {
214 $this->language = Language::factory( $lang );
216 } else {
217 $type = gettype( $lang );
218 throw new MWException( __METHOD__ . " must be "
219 . "passed a String or Language object; $type given"
222 $this->interface = false;
223 return $this;
227 * Request the message in the wiki's content language.
228 * @return Message: $this
230 public function inContentLanguage() {
231 global $wgContLang;
232 $this->interface = false;
233 $this->language = $wgContLang;
234 return $this;
238 * Enable or disable database use.
239 * @param $value Boolean
240 * @return Message: $this
242 public function useDatabase( $value ) {
243 $this->useDatabase = (bool) $value;
244 return $this;
248 * Set the Title object to use as context when transforming the message
250 * @param $title Title object
251 * @return Message: $this
253 public function title( $title ) {
254 $this->title = $title;
255 return $this;
259 * Returns the message parsed from wikitext to HTML.
260 * @return String: HTML
262 public function toString() {
263 $string = $this->getMessageText();
265 # Replace parameters before text parsing
266 $string = $this->replaceParameters( $string, 'before' );
268 # Maybe transform using the full parser
269 if( $this->format === 'parse' ) {
270 $string = $this->parseText( $string );
271 $m = array();
272 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
273 $string = $m[1];
275 } elseif( $this->format === 'block-parse' ){
276 $string = $this->parseText( $string );
277 } elseif( $this->format === 'text' ){
278 $string = $this->transformText( $string );
279 } elseif( $this->format === 'escaped' ){
280 $string = $this->transformText( $string );
281 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
284 # Raw parameter replacement
285 $string = $this->replaceParameters( $string, 'after' );
287 return $string;
291 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
292 * $foo = Message::get($key);
293 * $string = "<abbr>$foo</abbr>";
294 * @return String
296 public function __toString() {
297 return $this->toString();
301 * Fully parse the text from wikitext to HTML
302 * @return String parsed HTML
304 public function parse() {
305 $this->format = 'parse';
306 return $this->toString();
310 * Returns the message text. {{-transformation is done.
311 * @return String: Unescaped message text.
313 public function text() {
314 $this->format = 'text';
315 return $this->toString();
319 * Returns the message text as-is, only parameters are subsituted.
320 * @return String: Unescaped untransformed message text.
322 public function plain() {
323 $this->format = 'plain';
324 return $this->toString();
328 * Returns the parsed message text which is always surrounded by a block element.
329 * @return String: HTML
331 public function parseAsBlock() {
332 $this->format = 'block-parse';
333 return $this->toString();
337 * Returns the message text. {{-transformation is done and the result
338 * is escaped excluding any raw parameters.
339 * @return String: Escaped message text.
341 public function escaped() {
342 $this->format = 'escaped';
343 return $this->toString();
347 * Check whether a message key has been defined currently.
348 * @return Bool: true if it is and false if not.
350 public function exists() {
351 return $this->fetchMessage() !== false;
355 * Check whether a message does not exist, or is an empty string
356 * @return Bool: true if is is and false if not
357 * @todo FIXME: Merge with isDisabled()?
359 public function isBlank() {
360 $message = $this->fetchMessage();
361 return $message === false || $message === '';
365 * Check whether a message does not exist, is an empty string, or is "-"
366 * @return Bool: true if is is and false if not
368 public function isDisabled() {
369 $message = $this->fetchMessage();
370 return $message === false || $message === '' || $message === '-';
374 * @param $value
375 * @return array
377 public static function rawParam( $value ) {
378 return array( 'raw' => $value );
382 * @param $value
383 * @return array
385 public static function numParam( $value ) {
386 return array( 'num' => $value );
390 * Substitutes any paramaters into the message text.
391 * @param $message String: the message text
392 * @param $type String: either before or after
393 * @return String
395 protected function replaceParameters( $message, $type = 'before' ) {
396 $replacementKeys = array();
397 foreach( $this->parameters as $n => $param ) {
398 list( $paramType, $value ) = $this->extractParam( $param );
399 if ( $type === $paramType ) {
400 $replacementKeys['$' . ($n + 1)] = $value;
403 $message = strtr( $message, $replacementKeys );
404 return $message;
408 * Extracts the parameter type and preprocessed the value if needed.
409 * @param $param String|Array: Parameter as defined in this class.
410 * @return Tuple(type, value)
411 * @throws MWException
413 protected function extractParam( $param ) {
414 if ( is_array( $param ) && isset( $param['raw'] ) ) {
415 return array( 'after', $param['raw'] );
416 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
417 // Replace number params always in before step for now.
418 // No support for combined raw and num params
419 return array( 'before', $this->language->formatNum( $param['num'] ) );
420 } elseif ( !is_array( $param ) ) {
421 return array( 'before', $param );
422 } else {
423 throw new MWException( "Invalid message parameter" );
428 * Wrapper for what ever method we use to parse wikitext.
429 * @param $string String: Wikitext message contents
430 * @return string Wikitext parsed into HTML
432 protected function parseText( $string ) {
433 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
437 * Wrapper for what ever method we use to {{-transform wikitext.
438 * @param $string String: Wikitext message contents
439 * @return string Wikitext with {{-constructs replaced with their values.
441 protected function transformText( $string ) {
442 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
446 * Returns the textual value for the message.
447 * @return Message contents or placeholder
449 protected function getMessageText() {
450 $message = $this->fetchMessage();
451 if ( $message === false ) {
452 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
453 } else {
454 return $message;
459 * Wrapper for what ever method we use to get message contents
461 * @return string
463 protected function fetchMessage() {
464 if ( !isset( $this->message ) ) {
465 $cache = MessageCache::singleton();
466 if ( is_array($this->key) ) {
467 foreach ( $this->key as $key ) {
468 $message = $cache->get( $key, $this->useDatabase, $this->language );
469 if ( $message !== false && $message !== '' ) {
470 break;
473 $this->message = $message;
474 } else {
475 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
478 return $this->message;