merged master
[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 /**
404 * Returns the message as a Content object.
405 * @return Content
406 */
407 public function content() {
408 if ( !$this->content ) {
409 $this->content = new MessageContent( $this->key );
410 }
411
412 return $this->content;
413 }
414
415 /**
416 * Returns the message parsed from wikitext to HTML.
417 * @return String: HTML
418 */
419 public function toString() {
420 $string = $this->fetchMessage();
421
422 if ( $string === false ) {
423 $key = htmlspecialchars( is_array( $this->key ) ? $this->key[0] : $this->key );
424 if ( $this->format === 'plain' ) {
425 return '<' . $key . '>';
426 }
427 return '&lt;' . $key . '&gt;';
428 }
429
430 # Replace parameters before text parsing
431 $string = $this->replaceParameters( $string, 'before' );
432
433 # Maybe transform using the full parser
434 if( $this->format === 'parse' ) {
435 $string = $this->parseText( $string );
436 $m = array();
437 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
438 $string = $m[1];
439 }
440 } elseif( $this->format === 'block-parse' ){
441 $string = $this->parseText( $string );
442 } elseif( $this->format === 'text' ){
443 $string = $this->transformText( $string );
444 } elseif( $this->format === 'escaped' ){
445 $string = $this->transformText( $string );
446 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
447 }
448
449 # Raw parameter replacement
450 $string = $this->replaceParameters( $string, 'after' );
451
452 return $string;
453 }
454
455 /**
456 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
457 * $foo = Message::get($key);
458 * $string = "<abbr>$foo</abbr>";
459 * @return String
460 */
461 public function __toString() {
462 return $this->toString();
463 }
464
465 /**
466 * Fully parse the text from wikitext to HTML
467 * @return String parsed HTML
468 */
469 public function parse() {
470 $this->format = 'parse';
471 return $this->toString();
472 }
473
474 /**
475 * Returns the message text. {{-transformation is done.
476 * @return String: Unescaped message text.
477 */
478 public function text() {
479 $this->format = 'text';
480 return $this->toString();
481 }
482
483 /**
484 * Returns the message text as-is, only parameters are subsituted.
485 * @return String: Unescaped untransformed message text.
486 */
487 public function plain() {
488 $this->format = 'plain';
489 return $this->toString();
490 }
491
492 /**
493 * Returns the parsed message text which is always surrounded by a block element.
494 * @return String: HTML
495 */
496 public function parseAsBlock() {
497 $this->format = 'block-parse';
498 return $this->toString();
499 }
500
501 /**
502 * Returns the message text. {{-transformation is done and the result
503 * is escaped excluding any raw parameters.
504 * @return String: Escaped message text.
505 */
506 public function escaped() {
507 $this->format = 'escaped';
508 return $this->toString();
509 }
510
511 /**
512 * Check whether a message key has been defined currently.
513 * @return Bool: true if it is and false if not.
514 */
515 public function exists() {
516 return $this->fetchMessage() !== false;
517 }
518
519 /**
520 * Check whether a message does not exist, or is an empty string
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 * @return Bool: true if is is and false if not
532 */
533 public function isDisabled() {
534 $message = $this->fetchMessage();
535 return $message === false || $message === '' || $message === '-';
536 }
537
538 /**
539 * @param $value
540 * @return array
541 */
542 public static function rawParam( $value ) {
543 return array( 'raw' => $value );
544 }
545
546 /**
547 * @param $value
548 * @return array
549 */
550 public static function numParam( $value ) {
551 return array( 'num' => $value );
552 }
553
554 /**
555 * Substitutes any paramaters into the message text.
556 * @param $message String: the message text
557 * @param $type String: either before or after
558 * @return String
559 */
560 protected function replaceParameters( $message, $type = 'before' ) {
561 $replacementKeys = array();
562 foreach( $this->parameters as $n => $param ) {
563 list( $paramType, $value ) = $this->extractParam( $param );
564 if ( $type === $paramType ) {
565 $replacementKeys['$' . ($n + 1)] = $value;
566 }
567 }
568 $message = strtr( $message, $replacementKeys );
569 return $message;
570 }
571
572 /**
573 * Extracts the parameter type and preprocessed the value if needed.
574 * @param $param String|Array: Parameter as defined in this class.
575 * @return Tuple(type, value)
576 * @throws MWException
577 */
578 protected function extractParam( $param ) {
579 if ( is_array( $param ) && isset( $param['raw'] ) ) {
580 return array( 'after', $param['raw'] );
581 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
582 // Replace number params always in before step for now.
583 // No support for combined raw and num params
584 return array( 'before', $this->language->formatNum( $param['num'] ) );
585 } elseif ( !is_array( $param ) ) {
586 return array( 'before', $param );
587 } else {
588 throw new MWException( "Invalid message parameter" );
589 }
590 }
591
592 /**
593 * Wrapper for what ever method we use to parse wikitext.
594 * @param $string String: Wikitext message contents
595 * @return string Wikitext parsed into HTML
596 */
597 protected function parseText( $string ) {
598 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
599 }
600
601 /**
602 * Wrapper for what ever method we use to {{-transform wikitext.
603 * @param $string String: Wikitext message contents
604 * @return string Wikitext with {{-constructs replaced with their values.
605 */
606 protected function transformText( $string ) {
607 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
608 }
609
610 /**
611 * Wrapper for what ever method we use to get message contents
612 *
613 * @return string
614 */
615 protected function fetchMessage() {
616 if ( !isset( $this->message ) ) {
617 $cache = MessageCache::singleton();
618 if ( is_array( $this->key ) ) {
619 if ( !count( $this->key ) ) {
620 throw new MWException( "Given empty message key array." );
621 }
622 foreach ( $this->key as $key ) {
623 $message = $cache->get( $key, $this->useDatabase, $this->language );
624 if ( $message !== false && $message !== '' ) {
625 break;
626 }
627 }
628 $this->message = $message;
629 } else {
630 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
631 }
632 }
633 return $this->message;
634 }
635
636 }