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