My proposed fix to bug 34987: gender not working in many special pages.
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * The Message class provides methods which fullfil two basic services:
4 * - fetching interface messages
5 * - processing messages into a variety of formats
6 *
7 * First implemented with MediaWiki 1.17, the Message class is intented to
8 * replace the old wfMsg* functions that over time grew unusable.
9 * @see https://www.mediawiki.org/wiki/New_messages_API for equivalences
10 * between old and new functions.
11 *
12 * You should use the wfMessage() global function which acts as a wrapper for
13 * the Message class. The wrapper let you pass parameters as arguments.
14 *
15 * The most basic usage cases would be:
16 *
17 * @code
18 * // Initialize a Message object using the 'some_key' message key
19 * $message = wfMessage( 'some_key' );
20 *
21 * // Using two parameters those values are strings 'value1' and 'value2':
22 * $message = wfMessage( 'some_key',
23 * 'value1', 'value2'
24 * );
25 * @endcode
26 *
27 * @section message_global_fn Global function wrapper:
28 *
29 * Since wfMessage() returns a Message instance, you can chain its call with
30 * a method. Some of them return a Message instance too so you can chain them.
31 * You will find below several examples of wfMessage() usage.
32 *
33 * Fetching a message text for interface message:
34 *
35 * @code
36 * $button = Xml::button(
37 * wfMessage( 'submit' )->text()
38 * );
39 * @endcode
40 *
41 * A Message instance can be passed parameters after it has been constructed,
42 * use the params() method to do so:
43 *
44 * @code
45 * wfMessage( 'welcome-to' )
46 * ->params( $wgSitename )
47 * ->text();
48 * @endcode
49 *
50 * {{GRAMMAR}} and friends work correctly:
51 *
52 * @code
53 * wfMessage( 'are-friends',
54 * $user, $friend
55 * );
56 * wfMessage( 'bad-message' )
57 * ->rawParams( '<script>...</script>' )
58 * ->escaped();
59 * @endcode
60 *
61 * @section message_language Changing language:
62 *
63 * Messages can be requested in a different language or in whatever current
64 * content language is being used. The methods are:
65 * - Message->inContentLanguage()
66 * - Message->inLanguage()
67 *
68 * Sometimes the message text ends up in the database, so content language is
69 * needed:
70 *
71 * @code
72 * wfMessage( 'file-log',
73 * $user, $filename
74 * )->inContentLanguage()->text();
75 * @endcode
76 *
77 * Checking whether a message exists:
78 *
79 * @code
80 * wfMessage( 'mysterious-message' )->exists()
81 * // returns a boolean whether the 'mysterious-message' key exist.
82 * @endcode
83 *
84 * If you want to use a different language:
85 *
86 * @code
87 * $userLanguage = $user->getOption( 'language' );
88 * wfMessage( 'email-header' )
89 * ->inLanguage( $userLanguage )
90 * ->plain();
91 * @endcode
92 *
93 * @note You can parse the text only in the content or interface languages
94 *
95 * @section message_compare_old Comparison with old wfMsg* functions:
96 *
97 * Use full parsing:
98 *
99 * @code
100 * // old style:
101 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
102 * // new style:
103 * wfMessage( 'key', 'apple' )->parse();
104 * @endcode
105 *
106 * Parseinline is used because it is more useful when pre-building HTML.
107 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
108 *
109 * Places where HTML cannot be used. {{-transformation is done.
110 * @code
111 * // old style:
112 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
113 * // new style:
114 * wfMessage( 'key', 'apple', 'pear' )->text();
115 * @endcode
116 *
117 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
118 * parameters are not replaced after escaping by default.
119 * @code
120 * $escaped = wfMessage( 'key' )
121 * ->rawParams( 'apple' )
122 * ->escaped();
123 * @endcode
124 *
125 * @section message_appendix Appendix:
126 *
127 * @todo
128 * - test, can we have tests?
129 * - this documentation needs to be extended
130 *
131 * @see https://www.mediawiki.org/wiki/WfMessage()
132 * @see https://www.mediawiki.org/wiki/New_messages_API
133 * @see https://www.mediawiki.org/wiki/Localisation
134 *
135 * @since 1.17
136 * @author Niklas Laxström
137 */
138 class Message {
139 /**
140 * In which language to get this message. True, which is the default,
141 * means the current interface language, false content language.
142 */
143 protected $interface = true;
144
145 /**
146 * In which language to get this message. Overrides the $interface
147 * variable.
148 *
149 * @var Language
150 */
151 protected $language = null;
152
153 /**
154 * The message key.
155 */
156 protected $key;
157
158 /**
159 * List of parameters which will be substituted into the message.
160 */
161 protected $parameters = array();
162
163 /**
164 * Format for the message.
165 * Supported formats are:
166 * * text (transform)
167 * * escaped (transform+htmlspecialchars)
168 * * block-parse
169 * * parse (default)
170 * * plain
171 */
172 protected $format = 'parse';
173
174 /**
175 * Whether database can be used.
176 */
177 protected $useDatabase = true;
178
179 /**
180 * Title object to use as context
181 */
182 protected $title = null;
183
184 /**
185 * @var string
186 */
187 protected $message;
188
189 /**
190 * Constructor.
191 * @param $key: message key, or array of message keys to try and use the first non-empty message for
192 * @param $params Array message parameters
193 * @return Message: $this
194 */
195 public function __construct( $key, $params = array() ) {
196 global $wgLang;
197 $this->key = $key;
198 $this->parameters = array_values( $params );
199 $this->language = $wgLang;
200 }
201
202 /**
203 * Factory function that is just wrapper for the real constructor. It is
204 * intented to be used instead of the real constructor, because it allows
205 * chaining method calls, while new objects don't.
206 * @param $key String: message key
207 * @param Varargs: parameters as Strings
208 * @return Message: $this
209 */
210 public static function newFromKey( $key /*...*/ ) {
211 $params = func_get_args();
212 array_shift( $params );
213 return new self( $key, $params );
214 }
215
216 /**
217 * Factory function accepting multiple message keys and returning a message instance
218 * for the first message which is non-empty. If all messages are empty then an
219 * instance of the first message key is returned.
220 * @param Varargs: message keys (or first arg as an array of all the message keys)
221 * @return Message: $this
222 */
223 public static function newFallbackSequence( /*...*/ ) {
224 $keys = func_get_args();
225 if ( func_num_args() == 1 ) {
226 if ( is_array($keys[0]) ) {
227 // Allow an array to be passed as the first argument instead
228 $keys = array_values($keys[0]);
229 } else {
230 // Optimize a single string to not need special fallback handling
231 $keys = $keys[0];
232 }
233 }
234 return new self( $keys );
235 }
236
237 /**
238 * Adds parameters to the parameter list of this message.
239 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
240 * @return Message: $this
241 */
242 public function params( /*...*/ ) {
243 $args = func_get_args();
244 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
245 $args = $args[0];
246 }
247 $args_values = array_values( $args );
248 $this->parameters = array_merge( $this->parameters, $args_values );
249 return $this;
250 }
251
252 /**
253 * Add parameters that are substituted after parsing or escaping.
254 * In other words the parsing process cannot access the contents
255 * of this type of parameter, and you need to make sure it is
256 * sanitized beforehand. The parser will see "$n", instead.
257 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
258 * @return Message: $this
259 */
260 public function rawParams( /*...*/ ) {
261 $params = func_get_args();
262 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
263 $params = $params[0];
264 }
265 foreach( $params as $param ) {
266 $this->parameters[] = self::rawParam( $param );
267 }
268 return $this;
269 }
270
271 /**
272 * Add parameters that are numeric and will be passed through
273 * Language::formatNum before substitution
274 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
275 * @return Message: $this
276 */
277 public function numParams( /*...*/ ) {
278 $params = func_get_args();
279 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
280 $params = $params[0];
281 }
282 foreach( $params as $param ) {
283 $this->parameters[] = self::numParam( $param );
284 }
285 return $this;
286 }
287
288 /**
289 * Set the language and the title from a context object
290 *
291 * @param $context IContextSource
292 * @return Message: $this
293 */
294 public function setContext( IContextSource $context ) {
295 $this->inLanguage( $context->getLanguage() );
296 $this->title( $context->getTitle() );
297
298 return $this;
299 }
300
301 /**
302 * Request the message in any language that is supported.
303 * As a side effect interface message status is unconditionally
304 * turned off.
305 * @param $lang Mixed: language code or Language object.
306 * @return Message: $this
307 */
308 public function inLanguage( $lang ) {
309 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
310 $this->language = $lang;
311 } elseif ( is_string( $lang ) ) {
312 if( $this->language->getCode() != $lang ) {
313 $this->language = Language::factory( $lang );
314 }
315 } else {
316 $type = gettype( $lang );
317 throw new MWException( __METHOD__ . " must be "
318 . "passed a String or Language object; $type given"
319 );
320 }
321 $this->interface = false;
322 return $this;
323 }
324
325 /**
326 * Request the message in the wiki's content language,
327 * unless it is disabled for this message.
328 * @see $wgForceUIMsgAsContentMsg
329 * @return Message: $this
330 */
331 public function inContentLanguage() {
332 global $wgForceUIMsgAsContentMsg;
333 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
334 return $this;
335 }
336
337 global $wgContLang;
338 $this->interface = false;
339 $this->language = $wgContLang;
340 return $this;
341 }
342
343 /**
344 * Allows manipulating the interface message flag directly.
345 * Can be used to restore the flag after setting a language.
346 * @param $value bool
347 * @return Message: $this
348 * @since 1.20
349 */
350 public function setInterfaceMessageFlag( $value ) {
351 $this->interface = (bool) $value;
352 return $this;
353 }
354
355 /**
356 * Enable or disable database use.
357 * @param $value Boolean
358 * @return Message: $this
359 */
360 public function useDatabase( $value ) {
361 $this->useDatabase = (bool) $value;
362 return $this;
363 }
364
365 /**
366 * Set the Title object to use as context when transforming the message
367 *
368 * @param $title Title object
369 * @return Message: $this
370 */
371 public function title( $title ) {
372 $this->title = $title;
373 return $this;
374 }
375
376 /**
377 * Returns the message parsed from wikitext to HTML.
378 * @return String: HTML
379 */
380 public function toString() {
381 $string = $this->getMessageText();
382
383 # Replace parameters before text parsing
384 $string = $this->replaceParameters( $string, 'before' );
385
386 # Maybe transform using the full parser
387 if( $this->format === 'parse' ) {
388 $string = $this->parseText( $string );
389 $m = array();
390 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
391 $string = $m[1];
392 }
393 } elseif( $this->format === 'block-parse' ){
394 $string = $this->parseText( $string );
395 } elseif( $this->format === 'text' ){
396 $string = $this->transformText( $string );
397 } elseif( $this->format === 'escaped' ){
398 $string = $this->transformText( $string );
399 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
400 }
401
402 # Raw parameter replacement
403 $string = $this->replaceParameters( $string, 'after' );
404
405 return $string;
406 }
407
408 /**
409 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
410 * $foo = Message::get($key);
411 * $string = "<abbr>$foo</abbr>";
412 * @return String
413 */
414 public function __toString() {
415 return $this->toString();
416 }
417
418 /**
419 * Fully parse the text from wikitext to HTML
420 * @return String parsed HTML
421 */
422 public function parse() {
423 $this->format = 'parse';
424 return $this->toString();
425 }
426
427 /**
428 * Returns the message text. {{-transformation is done.
429 * @return String: Unescaped message text.
430 */
431 public function text() {
432 $this->format = 'text';
433 return $this->toString();
434 }
435
436 /**
437 * Returns the message text as-is, only parameters are subsituted.
438 * @return String: Unescaped untransformed message text.
439 */
440 public function plain() {
441 $this->format = 'plain';
442 return $this->toString();
443 }
444
445 /**
446 * Returns the parsed message text which is always surrounded by a block element.
447 * @return String: HTML
448 */
449 public function parseAsBlock() {
450 $this->format = 'block-parse';
451 return $this->toString();
452 }
453
454 /**
455 * Returns the message text. {{-transformation is done and the result
456 * is escaped excluding any raw parameters.
457 * @return String: Escaped message text.
458 */
459 public function escaped() {
460 $this->format = 'escaped';
461 return $this->toString();
462 }
463
464 /**
465 * Check whether a message key has been defined currently.
466 * @return Bool: true if it is and false if not.
467 */
468 public function exists() {
469 return $this->fetchMessage() !== false;
470 }
471
472 /**
473 * Check whether a message does not exist, or is an empty string
474 * @return Bool: true if is is and false if not
475 * @todo FIXME: Merge with isDisabled()?
476 */
477 public function isBlank() {
478 $message = $this->fetchMessage();
479 return $message === false || $message === '';
480 }
481
482 /**
483 * Check whether a message does not exist, is an empty string, or is "-"
484 * @return Bool: true if is is and false if not
485 */
486 public function isDisabled() {
487 $message = $this->fetchMessage();
488 return $message === false || $message === '' || $message === '-';
489 }
490
491 /**
492 * @param $value
493 * @return array
494 */
495 public static function rawParam( $value ) {
496 return array( 'raw' => $value );
497 }
498
499 /**
500 * @param $value
501 * @return array
502 */
503 public static function numParam( $value ) {
504 return array( 'num' => $value );
505 }
506
507 /**
508 * Substitutes any paramaters into the message text.
509 * @param $message String: the message text
510 * @param $type String: either before or after
511 * @return String
512 */
513 protected function replaceParameters( $message, $type = 'before' ) {
514 $replacementKeys = array();
515 foreach( $this->parameters as $n => $param ) {
516 list( $paramType, $value ) = $this->extractParam( $param );
517 if ( $type === $paramType ) {
518 $replacementKeys['$' . ($n + 1)] = $value;
519 }
520 }
521 $message = strtr( $message, $replacementKeys );
522 return $message;
523 }
524
525 /**
526 * Extracts the parameter type and preprocessed the value if needed.
527 * @param $param String|Array: Parameter as defined in this class.
528 * @return Tuple(type, value)
529 * @throws MWException
530 */
531 protected function extractParam( $param ) {
532 if ( is_array( $param ) && isset( $param['raw'] ) ) {
533 return array( 'after', $param['raw'] );
534 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
535 // Replace number params always in before step for now.
536 // No support for combined raw and num params
537 return array( 'before', $this->language->formatNum( $param['num'] ) );
538 } elseif ( !is_array( $param ) ) {
539 return array( 'before', $param );
540 } else {
541 throw new MWException( "Invalid message parameter" );
542 }
543 }
544
545 /**
546 * Wrapper for what ever method we use to parse wikitext.
547 * @param $string String: Wikitext message contents
548 * @return string Wikitext parsed into HTML
549 */
550 protected function parseText( $string ) {
551 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
552 }
553
554 /**
555 * Wrapper for what ever method we use to {{-transform wikitext.
556 * @param $string String: Wikitext message contents
557 * @return string Wikitext with {{-constructs replaced with their values.
558 */
559 protected function transformText( $string ) {
560 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
561 }
562
563 /**
564 * Returns the textual value for the message.
565 * @return Message contents or placeholder
566 */
567 protected function getMessageText() {
568 $message = $this->fetchMessage();
569 if ( $message === false ) {
570 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
571 } else {
572 return $message;
573 }
574 }
575
576 /**
577 * Wrapper for what ever method we use to get message contents
578 *
579 * @return string
580 */
581 protected function fetchMessage() {
582 if ( !isset( $this->message ) ) {
583 $cache = MessageCache::singleton();
584 if ( is_array( $this->key ) ) {
585 if ( !count( $this->key ) ) {
586 throw new MWException( "Given empty message key array." );
587 }
588 foreach ( $this->key as $key ) {
589 $message = $cache->get( $key, $this->useDatabase, $this->language );
590 if ( $message !== false && $message !== '' ) {
591 break;
592 }
593 }
594 $this->message = $message;
595 } else {
596 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
597 }
598 }
599 return $this->message;
600 }
601
602 }