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