Merge "[FileRepo] Split out store/purge functions for thumbnails and made them skip...
[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 $this->interface = true;
298
299 return $this;
300 }
301
302 /**
303 * Request the message in any language that is supported.
304 * As a side effect interface message status is unconditionally
305 * turned off.
306 * @param $lang Mixed: language code or Language object.
307 * @return Message: $this
308 */
309 public function inLanguage( $lang ) {
310 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
311 $this->language = $lang;
312 } elseif ( is_string( $lang ) ) {
313 if( $this->language->getCode() != $lang ) {
314 $this->language = Language::factory( $lang );
315 }
316 } else {
317 $type = gettype( $lang );
318 throw new MWException( __METHOD__ . " must be "
319 . "passed a String or Language object; $type given"
320 );
321 }
322 $this->interface = false;
323 return $this;
324 }
325
326 /**
327 * Request the message in the wiki's content language,
328 * unless it is disabled for this message.
329 * @see $wgForceUIMsgAsContentMsg
330 * @return Message: $this
331 */
332 public function inContentLanguage() {
333 global $wgForceUIMsgAsContentMsg;
334 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
335 return $this;
336 }
337
338 global $wgContLang;
339 $this->interface = false;
340 $this->language = $wgContLang;
341 return $this;
342 }
343
344 /**
345 * Allows manipulating the interface message flag directly.
346 * Can be used to restore the flag after setting a language.
347 * @param $value bool
348 * @return Message: $this
349 * @since 1.20
350 */
351 public function setInterfaceMessageFlag( $value ) {
352 $this->interface = (bool) $value;
353 return $this;
354 }
355
356 /**
357 * Enable or disable database use.
358 * @param $value Boolean
359 * @return Message: $this
360 */
361 public function useDatabase( $value ) {
362 $this->useDatabase = (bool) $value;
363 return $this;
364 }
365
366 /**
367 * Set the Title object to use as context when transforming the message
368 *
369 * @param $title Title object
370 * @return Message: $this
371 */
372 public function title( $title ) {
373 $this->title = $title;
374 return $this;
375 }
376
377 /**
378 * Returns the message parsed from wikitext to HTML.
379 * @return String: HTML
380 */
381 public function toString() {
382 $string = $this->fetchMessage();
383
384 if ( $string === false ) {
385 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
386 if ( $this->format === 'plain' ) {
387 return '<' . $key . '>';
388 }
389 return '&lt;' . $key . '&gt;';
390 }
391
392 # Replace parameters before text parsing
393 $string = $this->replaceParameters( $string, 'before' );
394
395 # Maybe transform using the full parser
396 if( $this->format === 'parse' ) {
397 $string = $this->parseText( $string );
398 $m = array();
399 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
400 $string = $m[1];
401 }
402 } elseif( $this->format === 'block-parse' ){
403 $string = $this->parseText( $string );
404 } elseif( $this->format === 'text' ){
405 $string = $this->transformText( $string );
406 } elseif( $this->format === 'escaped' ){
407 $string = $this->transformText( $string );
408 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
409 }
410
411 # Raw parameter replacement
412 $string = $this->replaceParameters( $string, 'after' );
413
414 return $string;
415 }
416
417 /**
418 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
419 * $foo = Message::get($key);
420 * $string = "<abbr>$foo</abbr>";
421 * @return String
422 */
423 public function __toString() {
424 return $this->toString();
425 }
426
427 /**
428 * Fully parse the text from wikitext to HTML
429 * @return String parsed HTML
430 */
431 public function parse() {
432 $this->format = 'parse';
433 return $this->toString();
434 }
435
436 /**
437 * Returns the message text. {{-transformation is done.
438 * @return String: Unescaped message text.
439 */
440 public function text() {
441 $this->format = 'text';
442 return $this->toString();
443 }
444
445 /**
446 * Returns the message text as-is, only parameters are subsituted.
447 * @return String: Unescaped untransformed message text.
448 */
449 public function plain() {
450 $this->format = 'plain';
451 return $this->toString();
452 }
453
454 /**
455 * Returns the parsed message text which is always surrounded by a block element.
456 * @return String: HTML
457 */
458 public function parseAsBlock() {
459 $this->format = 'block-parse';
460 return $this->toString();
461 }
462
463 /**
464 * Returns the message text. {{-transformation is done and the result
465 * is escaped excluding any raw parameters.
466 * @return String: Escaped message text.
467 */
468 public function escaped() {
469 $this->format = 'escaped';
470 return $this->toString();
471 }
472
473 /**
474 * Check whether a message key has been defined currently.
475 * @return Bool: true if it is and false if not.
476 */
477 public function exists() {
478 return $this->fetchMessage() !== false;
479 }
480
481 /**
482 * Check whether a message does not exist, or is an empty string
483 * @return Bool: true if is is and false if not
484 * @todo FIXME: Merge with isDisabled()?
485 */
486 public function isBlank() {
487 $message = $this->fetchMessage();
488 return $message === false || $message === '';
489 }
490
491 /**
492 * Check whether a message does not exist, is an empty string, or is "-"
493 * @return Bool: true if is is and false if not
494 */
495 public function isDisabled() {
496 $message = $this->fetchMessage();
497 return $message === false || $message === '' || $message === '-';
498 }
499
500 /**
501 * @param $value
502 * @return array
503 */
504 public static function rawParam( $value ) {
505 return array( 'raw' => $value );
506 }
507
508 /**
509 * @param $value
510 * @return array
511 */
512 public static function numParam( $value ) {
513 return array( 'num' => $value );
514 }
515
516 /**
517 * Substitutes any paramaters into the message text.
518 * @param $message String: the message text
519 * @param $type String: either before or after
520 * @return String
521 */
522 protected function replaceParameters( $message, $type = 'before' ) {
523 $replacementKeys = array();
524 foreach( $this->parameters as $n => $param ) {
525 list( $paramType, $value ) = $this->extractParam( $param );
526 if ( $type === $paramType ) {
527 $replacementKeys['$' . ($n + 1)] = $value;
528 }
529 }
530 $message = strtr( $message, $replacementKeys );
531 return $message;
532 }
533
534 /**
535 * Extracts the parameter type and preprocessed the value if needed.
536 * @param $param String|Array: Parameter as defined in this class.
537 * @return Tuple(type, value)
538 * @throws MWException
539 */
540 protected function extractParam( $param ) {
541 if ( is_array( $param ) && isset( $param['raw'] ) ) {
542 return array( 'after', $param['raw'] );
543 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
544 // Replace number params always in before step for now.
545 // No support for combined raw and num params
546 return array( 'before', $this->language->formatNum( $param['num'] ) );
547 } elseif ( !is_array( $param ) ) {
548 return array( 'before', $param );
549 } else {
550 throw new MWException( "Invalid message parameter" );
551 }
552 }
553
554 /**
555 * Wrapper for what ever method we use to parse wikitext.
556 * @param $string String: Wikitext message contents
557 * @return string Wikitext parsed into HTML
558 */
559 protected function parseText( $string ) {
560 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
561 }
562
563 /**
564 * Wrapper for what ever method we use to {{-transform wikitext.
565 * @param $string String: Wikitext message contents
566 * @return string Wikitext with {{-constructs replaced with their values.
567 */
568 protected function transformText( $string ) {
569 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
570 }
571
572 /**
573 * Wrapper for what ever method we use to get message contents
574 *
575 * @return string
576 */
577 protected function fetchMessage() {
578 if ( !isset( $this->message ) ) {
579 $cache = MessageCache::singleton();
580 if ( is_array( $this->key ) ) {
581 if ( !count( $this->key ) ) {
582 throw new MWException( "Given empty message key array." );
583 }
584 foreach ( $this->key as $key ) {
585 $message = $cache->get( $key, $this->useDatabase, $this->language );
586 if ( $message !== false && $message !== '' ) {
587 break;
588 }
589 }
590 $this->message = $message;
591 } else {
592 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
593 }
594 }
595 return $this->message;
596 }
597
598 }