Fix for bug 29274 - Message class ignores $wgForceUIMsgAsContentMsg
[lhc/web/wiklou.git] / includes / Message.php
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.
5 *
6 * It is intented to replace the old wfMsg* functions that over time grew
7 * unusable.
8 *
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>
30 *
31 *
32 * Comparison with old wfMsg* functions:
33 *
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.
40 *
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>
45 *
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>
50 *
51 * @todo
52 * - test, can we have tests?
53 *
54 * @since 1.17
55 * @author Niklas Laxström
56 */
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.
61 */
62 protected $interface = true;
63
64 /**
65 * In which language to get this message. Overrides the $interface
66 * variable.
67 *
68 * @var Language
69 */
70 protected $language = null;
71
72 /**
73 * The message key.
74 */
75 protected $key;
76
77 /**
78 * List of parameters which will be substituted into the message.
79 */
80 protected $parameters = array();
81
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
90 */
91 protected $format = 'parse';
92
93 /**
94 * Whether database can be used.
95 */
96 protected $useDatabase = true;
97
98 /**
99 * Title object to use as context
100 */
101 protected $title = null;
102
103 /**
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
108 */
109 public function __construct( $key, $params = array() ) {
110 global $wgLang;
111 $this->key = $key;
112 $this->parameters = array_values( $params );
113 $this->language = $wgLang;
114 }
115
116 /**
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
123 */
124 public static function newFromKey( $key /*...*/ ) {
125 $params = func_get_args();
126 array_shift( $params );
127 return new self( $key, $params );
128 }
129
130 /**
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
136 */
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];
146 }
147 }
148 return new self( $keys );
149 }
150
151 /**
152 * Adds parameters to the parameter list of this message.
153 * @param Varargs: parameters as Strings
154 * @return Message: $this
155 */
156 public function params( /*...*/ ) {
157 $args = func_get_args();
158 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
159 $args = $args[0];
160 }
161 $args_values = array_values( $args );
162 $this->parameters = array_merge( $this->parameters, $args_values );
163 return $this;
164 }
165
166 /**
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
173 */
174 public function rawParams( /*...*/ ) {
175 $params = func_get_args();
176 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
177 $params = $params[0];
178 }
179 foreach( $params as $param ) {
180 $this->parameters[] = self::rawParam( $param );
181 }
182 return $this;
183 }
184
185 /**
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
190 */
191 public function numParams( /*...*/ ) {
192 $params = func_get_args();
193 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
194 $params = $params[0];
195 }
196 foreach( $params as $param ) {
197 $this->parameters[] = self::numParam( $param );
198 }
199 return $this;
200 }
201
202 /**
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
208 */
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 );
215 }
216 } else {
217 $type = gettype( $lang );
218 throw new MWException( __METHOD__ . " must be "
219 . "passed a String or Language object; $type given"
220 );
221 }
222 $this->interface = false;
223 return $this;
224 }
225
226 /**
227 * Request the message in the wiki's content language.
228 * @see $wgForceUIMsgAsContentMsg
229 * @return Message: $this
230 */
231 public function inContentLanguage() {
232 global $wgForceUIMsgAsContentMsg;
233 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
234 return $this;
235 }
236
237 global $wgContLang;
238 $this->interface = false;
239 $this->language = $wgContLang;
240 return $this;
241 }
242
243 /**
244 * Enable or disable database use.
245 * @param $value Boolean
246 * @return Message: $this
247 */
248 public function useDatabase( $value ) {
249 $this->useDatabase = (bool) $value;
250 return $this;
251 }
252
253 /**
254 * Set the Title object to use as context when transforming the message
255 *
256 * @param $title Title object
257 * @return Message: $this
258 */
259 public function title( $title ) {
260 $this->title = $title;
261 return $this;
262 }
263
264 /**
265 * Returns the message parsed from wikitext to HTML.
266 * @return String: HTML
267 */
268 public function toString() {
269 $string = $this->getMessageText();
270
271 # Replace parameters before text parsing
272 $string = $this->replaceParameters( $string, 'before' );
273
274 # Maybe transform using the full parser
275 if( $this->format === 'parse' ) {
276 $string = $this->parseText( $string );
277 $m = array();
278 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
279 $string = $m[1];
280 }
281 } elseif( $this->format === 'block-parse' ){
282 $string = $this->parseText( $string );
283 } elseif( $this->format === 'text' ){
284 $string = $this->transformText( $string );
285 } elseif( $this->format === 'escaped' ){
286 $string = $this->transformText( $string );
287 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
288 }
289
290 # Raw parameter replacement
291 $string = $this->replaceParameters( $string, 'after' );
292
293 return $string;
294 }
295
296 /**
297 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
298 * $foo = Message::get($key);
299 * $string = "<abbr>$foo</abbr>";
300 * @return String
301 */
302 public function __toString() {
303 return $this->toString();
304 }
305
306 /**
307 * Fully parse the text from wikitext to HTML
308 * @return String parsed HTML
309 */
310 public function parse() {
311 $this->format = 'parse';
312 return $this->toString();
313 }
314
315 /**
316 * Returns the message text. {{-transformation is done.
317 * @return String: Unescaped message text.
318 */
319 public function text() {
320 $this->format = 'text';
321 return $this->toString();
322 }
323
324 /**
325 * Returns the message text as-is, only parameters are subsituted.
326 * @return String: Unescaped untransformed message text.
327 */
328 public function plain() {
329 $this->format = 'plain';
330 return $this->toString();
331 }
332
333 /**
334 * Returns the parsed message text which is always surrounded by a block element.
335 * @return String: HTML
336 */
337 public function parseAsBlock() {
338 $this->format = 'block-parse';
339 return $this->toString();
340 }
341
342 /**
343 * Returns the message text. {{-transformation is done and the result
344 * is escaped excluding any raw parameters.
345 * @return String: Escaped message text.
346 */
347 public function escaped() {
348 $this->format = 'escaped';
349 return $this->toString();
350 }
351
352 /**
353 * Check whether a message key has been defined currently.
354 * @return Bool: true if it is and false if not.
355 */
356 public function exists() {
357 return $this->fetchMessage() !== false;
358 }
359
360 /**
361 * Check whether a message does not exist, or is an empty string
362 * @return Bool: true if is is and false if not
363 * @todo FIXME: Merge with isDisabled()?
364 */
365 public function isBlank() {
366 $message = $this->fetchMessage();
367 return $message === false || $message === '';
368 }
369
370 /**
371 * Check whether a message does not exist, is an empty string, or is "-"
372 * @return Bool: true if is is and false if not
373 */
374 public function isDisabled() {
375 $message = $this->fetchMessage();
376 return $message === false || $message === '' || $message === '-';
377 }
378
379 /**
380 * @param $value
381 * @return array
382 */
383 public static function rawParam( $value ) {
384 return array( 'raw' => $value );
385 }
386
387 /**
388 * @param $value
389 * @return array
390 */
391 public static function numParam( $value ) {
392 return array( 'num' => $value );
393 }
394
395 /**
396 * Substitutes any paramaters into the message text.
397 * @param $message String: the message text
398 * @param $type String: either before or after
399 * @return String
400 */
401 protected function replaceParameters( $message, $type = 'before' ) {
402 $replacementKeys = array();
403 foreach( $this->parameters as $n => $param ) {
404 list( $paramType, $value ) = $this->extractParam( $param );
405 if ( $type === $paramType ) {
406 $replacementKeys['$' . ($n + 1)] = $value;
407 }
408 }
409 $message = strtr( $message, $replacementKeys );
410 return $message;
411 }
412
413 /**
414 * Extracts the parameter type and preprocessed the value if needed.
415 * @param $param String|Array: Parameter as defined in this class.
416 * @return Tuple(type, value)
417 * @throws MWException
418 */
419 protected function extractParam( $param ) {
420 if ( is_array( $param ) && isset( $param['raw'] ) ) {
421 return array( 'after', $param['raw'] );
422 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
423 // Replace number params always in before step for now.
424 // No support for combined raw and num params
425 return array( 'before', $this->language->formatNum( $param['num'] ) );
426 } elseif ( !is_array( $param ) ) {
427 return array( 'before', $param );
428 } else {
429 throw new MWException( "Invalid message parameter" );
430 }
431 }
432
433 /**
434 * Wrapper for what ever method we use to parse wikitext.
435 * @param $string String: Wikitext message contents
436 * @return string Wikitext parsed into HTML
437 */
438 protected function parseText( $string ) {
439 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
440 }
441
442 /**
443 * Wrapper for what ever method we use to {{-transform wikitext.
444 * @param $string String: Wikitext message contents
445 * @return string Wikitext with {{-constructs replaced with their values.
446 */
447 protected function transformText( $string ) {
448 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
449 }
450
451 /**
452 * Returns the textual value for the message.
453 * @return Message contents or placeholder
454 */
455 protected function getMessageText() {
456 $message = $this->fetchMessage();
457 if ( $message === false ) {
458 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
459 } else {
460 return $message;
461 }
462 }
463
464 /**
465 * Wrapper for what ever method we use to get message contents
466 *
467 * @return string
468 */
469 protected function fetchMessage() {
470 if ( !isset( $this->message ) ) {
471 $cache = MessageCache::singleton();
472 if ( is_array($this->key) ) {
473 foreach ( $this->key as $key ) {
474 $message = $cache->get( $key, $this->useDatabase, $this->language );
475 if ( $message !== false && $message !== '' ) {
476 break;
477 }
478 }
479 $this->message = $message;
480 } else {
481 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
482 }
483 }
484 return $this->message;
485 }
486
487 }