merge latest master into Wikidata branch
[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 * Content object representing the message
207 */
208 protected $content = null;
209
210 /**
211 * @var string
212 */
213 protected $message;
214
215 /**
216 * Constructor.
217 * @since 1.17
218 * @param $key: message key, or array of message keys to try and use the first non-empty message for
219 * @param $params Array message parameters
220 * @return Message: $this
221 */
222 public function __construct( $key, $params = array() ) {
223 global $wgLang;
224 $this->key = $key;
225 $this->parameters = array_values( $params );
226 $this->language = $wgLang;
227 }
228
229 /**
230 * Factory function that is just wrapper for the real constructor. It is
231 * intented to be used instead of the real constructor, because it allows
232 * chaining method calls, while new objects don't.
233 * @since 1.17
234 * @param $key String: message key
235 * @param Varargs: parameters as Strings
236 * @return Message: $this
237 */
238 public static function newFromKey( $key /*...*/ ) {
239 $params = func_get_args();
240 array_shift( $params );
241 return new self( $key, $params );
242 }
243
244 /**
245 * Factory function accepting multiple message keys and returning a message instance
246 * for the first message which is non-empty. If all messages are empty then an
247 * instance of the first message key is returned.
248 * @since 1.18
249 * @param Varargs: message keys (or first arg as an array of all the message keys)
250 * @return Message: $this
251 */
252 public static function newFallbackSequence( /*...*/ ) {
253 $keys = func_get_args();
254 if ( func_num_args() == 1 ) {
255 if ( is_array($keys[0]) ) {
256 // Allow an array to be passed as the first argument instead
257 $keys = array_values($keys[0]);
258 } else {
259 // Optimize a single string to not need special fallback handling
260 $keys = $keys[0];
261 }
262 }
263 return new self( $keys );
264 }
265
266 /**
267 * Adds parameters to the parameter list of this message.
268 * @since 1.17
269 * @param Varargs: parameters as Strings, or a single argument that is an array of Strings
270 * @return Message: $this
271 */
272 public function params( /*...*/ ) {
273 $args = func_get_args();
274 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
275 $args = $args[0];
276 }
277 $args_values = array_values( $args );
278 $this->parameters = array_merge( $this->parameters, $args_values );
279 return $this;
280 }
281
282 /**
283 * Add parameters that are substituted after parsing or escaping.
284 * In other words the parsing process cannot access the contents
285 * of this type of parameter, and you need to make sure it is
286 * sanitized beforehand. The parser will see "$n", instead.
287 * @since 1.17
288 * @param Varargs: raw parameters as Strings (or single argument that is an array of raw parameters)
289 * @return Message: $this
290 */
291 public function rawParams( /*...*/ ) {
292 $params = func_get_args();
293 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
294 $params = $params[0];
295 }
296 foreach( $params as $param ) {
297 $this->parameters[] = self::rawParam( $param );
298 }
299 return $this;
300 }
301
302 /**
303 * Add parameters that are numeric and will be passed through
304 * Language::formatNum before substitution
305 * @since 1.18
306 * @param Varargs: numeric parameters (or single argument that is array of numeric parameters)
307 * @return Message: $this
308 */
309 public function numParams( /*...*/ ) {
310 $params = func_get_args();
311 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
312 $params = $params[0];
313 }
314 foreach( $params as $param ) {
315 $this->parameters[] = self::numParam( $param );
316 }
317 return $this;
318 }
319
320 /**
321 * Set the language and the title from a context object
322 * @since 1.19
323 * @param $context IContextSource
324 * @return Message: $this
325 */
326 public function setContext( IContextSource $context ) {
327 $this->inLanguage( $context->getLanguage() );
328 $this->title( $context->getTitle() );
329 $this->interface = true;
330
331 return $this;
332 }
333
334 /**
335 * Request the message in any language that is supported.
336 * As a side effect interface message status is unconditionally
337 * turned off.
338 * @since 1.17
339 * @param $lang Mixed: language code or Language object.
340 * @return Message: $this
341 */
342 public function inLanguage( $lang ) {
343 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
344 $this->language = $lang;
345 } elseif ( is_string( $lang ) ) {
346 if( $this->language->getCode() != $lang ) {
347 $this->language = Language::factory( $lang );
348 }
349 } else {
350 $type = gettype( $lang );
351 throw new MWException( __METHOD__ . " must be "
352 . "passed a String or Language object; $type given"
353 );
354 }
355 $this->interface = false;
356 return $this;
357 }
358
359 /**
360 * Request the message in the wiki's content language,
361 * unless it is disabled for this message.
362 * @since 1.17
363 * @see $wgForceUIMsgAsContentMsg
364 * @return Message: $this
365 */
366 public function inContentLanguage() {
367 global $wgForceUIMsgAsContentMsg;
368 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
369 return $this;
370 }
371
372 global $wgContLang;
373 $this->interface = false;
374 $this->language = $wgContLang;
375 return $this;
376 }
377
378 /**
379 * Allows manipulating the interface message flag directly.
380 * Can be used to restore the flag after setting a language.
381 * @param $value bool
382 * @return Message: $this
383 * @since 1.20
384 */
385 public function setInterfaceMessageFlag( $value ) {
386 $this->interface = (bool) $value;
387 return $this;
388 }
389
390 /**
391 * Enable or disable database use.
392 * @since 1.17
393 * @param $value Boolean
394 * @return Message: $this
395 */
396 public function useDatabase( $value ) {
397 $this->useDatabase = (bool) $value;
398 return $this;
399 }
400
401 /**
402 * Set the Title object to use as context when transforming the message
403 * @since 1.18
404 * @param $title Title object
405 * @return Message: $this
406 */
407 public function title( $title ) {
408 $this->title = $title;
409 return $this;
410 }
411
412 /**
413 * Returns the message as a Content object.
414 * @return Content
415 */
416 public function content() {
417 if ( !$this->content ) {
418 $this->content = new MessageContent( $this->key );
419 }
420
421 return $this->content;
422 }
423
424 /**
425 * Returns the message parsed from wikitext to HTML.
426 * @since 1.17
427 * @return String: HTML
428 */
429 public function toString() {
430 $string = $this->fetchMessage();
431
432 if ( $string === false ) {
433 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
434 if ( $this->format === 'plain' ) {
435 return '<' . $key . '>';
436 }
437 return '&lt;' . $key . '&gt;';
438 }
439
440 # Replace parameters before text parsing
441 $string = $this->replaceParameters( $string, 'before' );
442
443 # Maybe transform using the full parser
444 if( $this->format === 'parse' ) {
445 $string = $this->parseText( $string );
446 $m = array();
447 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
448 $string = $m[1];
449 }
450 } elseif( $this->format === 'block-parse' ){
451 $string = $this->parseText( $string );
452 } elseif( $this->format === 'text' ){
453 $string = $this->transformText( $string );
454 } elseif( $this->format === 'escaped' ){
455 $string = $this->transformText( $string );
456 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
457 }
458
459 # Raw parameter replacement
460 $string = $this->replaceParameters( $string, 'after' );
461
462 return $string;
463 }
464
465 /**
466 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
467 * $foo = Message::get($key);
468 * $string = "<abbr>$foo</abbr>";
469 * @since 1.18
470 * @return String
471 */
472 public function __toString() {
473 return $this->toString();
474 }
475
476 /**
477 * Fully parse the text from wikitext to HTML
478 * @since 1.17
479 * @return String parsed HTML
480 */
481 public function parse() {
482 $this->format = 'parse';
483 return $this->toString();
484 }
485
486 /**
487 * Returns the message text. {{-transformation is done.
488 * @since 1.17
489 * @return String: Unescaped message text.
490 */
491 public function text() {
492 $this->format = 'text';
493 return $this->toString();
494 }
495
496 /**
497 * Returns the message text as-is, only parameters are subsituted.
498 * @since 1.17
499 * @return String: Unescaped untransformed message text.
500 */
501 public function plain() {
502 $this->format = 'plain';
503 return $this->toString();
504 }
505
506 /**
507 * Returns the parsed message text which is always surrounded by a block element.
508 * @since 1.17
509 * @return String: HTML
510 */
511 public function parseAsBlock() {
512 $this->format = 'block-parse';
513 return $this->toString();
514 }
515
516 /**
517 * Returns the message text. {{-transformation is done and the result
518 * is escaped excluding any raw parameters.
519 * @since 1.17
520 * @return String: Escaped message text.
521 */
522 public function escaped() {
523 $this->format = 'escaped';
524 return $this->toString();
525 }
526
527 /**
528 * Check whether a message key has been defined currently.
529 * @since 1.17
530 * @return Bool: true if it is and false if not.
531 */
532 public function exists() {
533 return $this->fetchMessage() !== false;
534 }
535
536 /**
537 * Check whether a message does not exist, or is an empty string
538 * @since 1.18
539 * @return Bool: true if is is and false if not
540 * @todo FIXME: Merge with isDisabled()?
541 */
542 public function isBlank() {
543 $message = $this->fetchMessage();
544 return $message === false || $message === '';
545 }
546
547 /**
548 * Check whether a message does not exist, is an empty string, or is "-"
549 * @since 1.18
550 * @return Bool: true if it is and false if not
551 */
552 public function isDisabled() {
553 $message = $this->fetchMessage();
554 return $message === false || $message === '' || $message === '-';
555 }
556
557 /**
558 * @since 1.17
559 * @param $value
560 * @return array
561 */
562 public static function rawParam( $value ) {
563 return array( 'raw' => $value );
564 }
565
566 /**
567 * @since 1.18
568 * @param $value
569 * @return array
570 */
571 public static function numParam( $value ) {
572 return array( 'num' => $value );
573 }
574
575 /**
576 * Substitutes any paramaters into the message text.
577 * @since 1.17
578 * @param $message String: the message text
579 * @param $type String: either before or after
580 * @return String
581 */
582 protected function replaceParameters( $message, $type = 'before' ) {
583 $replacementKeys = array();
584 foreach( $this->parameters as $n => $param ) {
585 list( $paramType, $value ) = $this->extractParam( $param );
586 if ( $type === $paramType ) {
587 $replacementKeys['$' . ($n + 1)] = $value;
588 }
589 }
590 $message = strtr( $message, $replacementKeys );
591 return $message;
592 }
593
594 /**
595 * Extracts the parameter type and preprocessed the value if needed.
596 * @since 1.18
597 * @param $param String|Array: Parameter as defined in this class.
598 * @return Tuple(type, value)
599 * @throws MWException
600 */
601 protected function extractParam( $param ) {
602 if ( is_array( $param ) && isset( $param['raw'] ) ) {
603 return array( 'after', $param['raw'] );
604 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
605 // Replace number params always in before step for now.
606 // No support for combined raw and num params
607 return array( 'before', $this->language->formatNum( $param['num'] ) );
608 } elseif ( !is_array( $param ) ) {
609 return array( 'before', $param );
610 } else {
611 throw new MWException( "Invalid message parameter" );
612 }
613 }
614
615 /**
616 * Wrapper for what ever method we use to parse wikitext.
617 * @since 1.17
618 * @param $string String: Wikitext message contents
619 * @return string Wikitext parsed into HTML
620 */
621 protected function parseText( $string ) {
622 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
623 }
624
625 /**
626 * Wrapper for what ever method we use to {{-transform wikitext.
627 * @since 1.17
628 * @param $string String: Wikitext message contents
629 * @return string Wikitext with {{-constructs replaced with their values.
630 */
631 protected function transformText( $string ) {
632 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
633 }
634
635 /**
636 * Wrapper for what ever method we use to get message contents
637 * @since 1.17
638 * @return string
639 */
640 protected function fetchMessage() {
641 if ( !isset( $this->message ) ) {
642 $cache = MessageCache::singleton();
643 if ( is_array( $this->key ) ) {
644 if ( !count( $this->key ) ) {
645 throw new MWException( "Given empty message key array." );
646 }
647 foreach ( $this->key as $key ) {
648 $message = $cache->get( $key, $this->useDatabase, $this->language );
649 if ( $message !== false && $message !== '' ) {
650 break;
651 }
652 }
653 $this->message = $message;
654 } else {
655 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
656 }
657 }
658 return $this->message;
659 }
660
661 }