Followup rr86304
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * This class provides methods for fetching interface messages and
4 * processing them into variety of formats that are needed in MediaWiki.
5 *
6 * It is intented to replace the old wfMsg* functions that over time grew
7 * unusable.
8 *
9 * Examples:
10 * Fetching a message text for interface message
11 * $button = Xml::button( wfMessage( 'submit' )->text() );
12 * </pre>
13 * Messages can have parameters:
14 * wfMessage( 'welcome-to' )->params( $wgSitename )->text();
15 * {{GRAMMAR}} and friends work correctly
16 * wfMessage( 'are-friends', $user, $friend );
17 * wfMessage( 'bad-message' )->rawParams( '<script>...</script>' )->escaped();
18 * </pre>
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
21 * </pre>
22 * Checking if message exists:
23 * wfMessage( 'mysterious-message' )->exists()
24 * </pre>
25 * If you want to use a different language:
26 * wfMessage( 'email-header' )->inLanguage( $user->getOption( 'language' ) )->plain()
27 * Note that you cannot parse the text except in the content or interface
28 * languages
29 * </pre>
30 *
31 *
32 * Comparison with old wfMsg* functions:
33 *
34 * Use full parsing.
35 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
36 * === wfMessage( 'key', 'apple' )->parse();
37 * </pre>
38 * Parseinline is used because it is more useful when pre-building html.
39 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
40 *
41 * Places where html cannot be used. {{-transformation is done.
42 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
43 * === wfMessage( 'key', 'apple', 'pear' )->text();
44 * </pre>
45 *
46 * Shortcut for escaping the message too, similar to wfMsgHTML, but
47 * parameters are not replaced after escaping by default.
48 * $escaped = wfMessage( 'key' )->rawParams( 'apple' )->escaped();
49 * </pre>
50 *
51 * TODO:
52 * - test, can we have tests?
53 * - sort out the details marked with fixme
54 *
55 * @since 1.17
56 * @author Niklas Laxström
57 */
58 class Message {
59 /**
60 * In which language to get this message. True, which is the default,
61 * means the current interface language, false content language.
62 */
63 protected $interface = true;
64
65 /**
66 * In which language to get this message. Overrides the $interface
67 * variable.
68 *
69 * @var Language
70 */
71 protected $language = null;
72
73 /**
74 * The message key.
75 */
76 protected $key;
77
78 /**
79 * List of parameters which will be substituted into the message.
80 */
81 protected $parameters = array();
82
83 /**
84 * Format for the message.
85 * Supported formats are:
86 * * text (transform)
87 * * escaped (transform+htmlspecialchars)
88 * * block-parse
89 * * parse (default)
90 * * plain
91 */
92 protected $format = 'parse';
93
94 /**
95 * Whether database can be used.
96 */
97 protected $useDatabase = true;
98
99 /**
100 * Title object to use as context
101 */
102 protected $title = null;
103
104 /**
105 * Constructor.
106 * @param $key: message key, or array of message keys to try and use the first non-empty message for
107 * @param $params Array message parameters
108 * @return Message: $this
109 */
110 public function __construct( $key, $params = array() ) {
111 global $wgLang;
112 $this->key = $key;
113 $this->parameters = array_values( $params );
114 $this->language = $wgLang;
115 }
116
117 /**
118 * Factory function that is just wrapper for the real constructor. It is
119 * intented to be used instead of the real constructor, because it allows
120 * chaining method calls, while new objects don't.
121 * @param $key String: message key
122 * @param Varargs: parameters as Strings
123 * @return Message: $this
124 */
125 public static function newFromKey( $key /*...*/ ) {
126 $params = func_get_args();
127 array_shift( $params );
128 return new self( $key, $params );
129 }
130
131 /**
132 * Factory function accepting multiple message keys and returning a message instance
133 * for the first message which is non-empty. If all messages are empty then an
134 * instance of the first message key is returned.
135 * @param Varargs: message keys
136 * @return Message: $this
137 */
138 public static function newFallbackSequence( /*...*/ ) {
139 $keys = func_get_args();
140 if ( func_num_args() == 1 ) {
141 if ( is_array($keys[0]) ) {
142 // Allow an array to be passed as the first argument instead
143 $keys = array_values($keys[0]);
144 } else {
145 // Optimize a single string to not need special fallback handling
146 $keys = $keys[0];
147 }
148 }
149 return new self( $keys );
150 }
151
152 /**
153 * Adds parameters to the parameter list of this message.
154 * @param Varargs: parameters as Strings
155 * @return Message: $this
156 */
157 public function params( /*...*/ ) {
158 $args = func_get_args();
159 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
160 $args = $args[0];
161 }
162 $args_values = array_values( $args );
163 $this->parameters = array_merge( $this->parameters, $args_values );
164 return $this;
165 }
166
167 /**
168 * Add parameters that are substituted after parsing or escaping.
169 * In other words the parsing process cannot access the contents
170 * of this type of parameter, and you need to make sure it is
171 * sanitized beforehand. The parser will see "$n", instead.
172 * @param Varargs: raw parameters as Strings
173 * @return Message: $this
174 */
175 public function rawParams( /*...*/ ) {
176 $params = func_get_args();
177 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
178 $params = $params[0];
179 }
180 foreach( $params as $param ) {
181 $this->parameters[] = self::rawParam( $param );
182 }
183 return $this;
184 }
185
186 /**
187 * Add parameters that are numeric and will be passed through
188 * Language::formatNum before substitution
189 * @param Varargs: numeric parameters
190 * @return Message: $this
191 */
192 public function numParams( /*...*/ ) {
193 $params = func_get_args();
194 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
195 $params = $params[0];
196 }
197 foreach( $params as $param ) {
198 $this->parameters[] = self::numParam( $param );
199 }
200 return $this;
201 }
202
203 /**
204 * Request the message in any language that is supported.
205 * As a side effect interface message status is unconditionally
206 * turned off.
207 * @param $lang Mixed: language code or Language object.
208 * @return Message: $this
209 */
210 public function inLanguage( $lang ) {
211 if ( $lang instanceof Language || $lang instanceof StubContLang || $lang instanceof StubUserLang ) {
212 $this->language = $lang;
213 } elseif ( is_string( $lang ) ) {
214 if( $this->language->getCode() != $lang ) {
215 $this->language = Language::factory( $lang );
216 }
217 } else {
218 $type = gettype( $lang );
219 throw new MWException( __METHOD__ . " must be "
220 . "passed a String or Language object; $type given"
221 );
222 }
223 $this->interface = false;
224 return $this;
225 }
226
227 /**
228 * Request the message in the wiki's content language.
229 * @return Message: $this
230 */
231 public function inContentLanguage() {
232 global $wgContLang;
233 $this->interface = false;
234 $this->language = $wgContLang;
235 return $this;
236 }
237
238 /**
239 * Enable or disable database use.
240 * @param $value Boolean
241 * @return Message: $this
242 */
243 public function useDatabase( $value ) {
244 $this->useDatabase = (bool) $value;
245 return $this;
246 }
247
248 /**
249 * Set the Title object to use as context when transforming the message
250 *
251 * @param $title Title object
252 * @return Message: $this
253 */
254 public function title( $title ) {
255 $this->title = $title;
256 return $this;
257 }
258
259 /**
260 * Returns the message parsed from wikitext to HTML.
261 * @return String: HTML
262 */
263 public function toString() {
264 $string = $this->getMessageText();
265
266 # Replace parameters before text parsing
267 $string = $this->replaceParameters( $string, 'before' );
268
269 # Maybe transform using the full parser
270 if( $this->format === 'parse' ) {
271 $string = $this->parseText( $string );
272 $m = array();
273 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
274 $string = $m[1];
275 }
276 } elseif( $this->format === 'block-parse' ){
277 $string = $this->parseText( $string );
278 } elseif( $this->format === 'text' ){
279 $string = $this->transformText( $string );
280 } elseif( $this->format === 'escaped' ){
281 # FIXME: Sanitizer method here?
282 $string = $this->transformText( $string );
283 $string = htmlspecialchars( $string );
284 }
285
286 # Raw parameter replacement
287 $string = $this->replaceParameters( $string, 'after' );
288
289 return $string;
290 }
291
292 /**
293 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
294 * $foo = Message::get($key);
295 * $string = "<abbr>$foo</abbr>";
296 * @return String
297 */
298 public function __toString() {
299 return $this->toString();
300 }
301
302 /**
303 * Fully parse the text from wikitext to HTML
304 * @return String parsed HTML
305 */
306 public function parse() {
307 $this->format = 'parse';
308 return $this->toString();
309 }
310
311 /**
312 * Returns the message text. {{-transformation is done.
313 * @return String: Unescaped message text.
314 */
315 public function text() {
316 $this->format = 'text';
317 return $this->toString();
318 }
319
320 /**
321 * Returns the message text as-is, only parameters are subsituted.
322 * @return String: Unescaped untransformed message text.
323 */
324 public function plain() {
325 $this->format = 'plain';
326 return $this->toString();
327 }
328
329 /**
330 * Returns the parsed message text which is always surrounded by a block element.
331 * @return String: HTML
332 */
333 public function parseAsBlock() {
334 $this->format = 'block-parse';
335 return $this->toString();
336 }
337
338 /**
339 * Returns the message text. {{-transformation is done and the result
340 * is escaped excluding any raw parameters.
341 * @return String: Escaped message text.
342 */
343 public function escaped() {
344 $this->format = 'escaped';
345 return $this->toString();
346 }
347
348 /**
349 * Check whether a message key has been defined currently.
350 * @return Bool: true if it is and false if not.
351 */
352 public function exists() {
353 return $this->fetchMessage() !== false;
354 }
355
356 /**
357 * Check whether a message does not exist, or is an empty string
358 * @return Bool: true if is is and false if not
359 * @todo Merge with isDisabled()?
360 */
361 public function isBlank() {
362 $message = $this->fetchMessage();
363 return $message === false || $message === '';
364 }
365
366 /**
367 * Check whether a message does not exist, is an empty string, or is "-"
368 * @return Bool: true if is is and false if not
369 */
370 public function isDisabled() {
371 $message = $this->fetchMessage();
372 return $message === false || $message === '' || $message === '-';
373 }
374
375 /**
376 * @param $value
377 * @return array
378 */
379 public static function rawParam( $value ) {
380 return array( 'raw' => $value );
381 }
382
383 /**
384 * @param $value
385 * @return array
386 */
387 public static function numParam( $value ) {
388 return array( 'num' => $value );
389 }
390
391 /**
392 * Substitutes any paramaters into the message text.
393 * @param $message String: the message text
394 * @param $type String: either before or after
395 * @return String
396 */
397 protected function replaceParameters( $message, $type = 'before' ) {
398 $replacementKeys = array();
399 foreach( $this->parameters as $n => $param ) {
400 list( $paramType, $value ) = $this->extractParam( $param );
401 if ( $type === $paramType ) {
402 $replacementKeys['$' . ($n + 1)] = $value;
403 }
404 }
405 $message = strtr( $message, $replacementKeys );
406 return $message;
407 }
408
409 /**
410 * Extracts the parameter type and preprocessed the value if needed.
411 * @param $param String|Array: Parameter as defined in this class.
412 * @return Tuple(type, value)
413 * @throws MWException
414 */
415 protected function extractParam( $param ) {
416 if ( is_array( $param ) && isset( $param['raw'] ) ) {
417 return array( 'after', $param['raw'] );
418 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
419 // Replace number params always in before step for now.
420 // No support for combined raw and num params
421 return array( 'before', $this->language->formatNum( $param['num'] ) );
422 } elseif ( !is_array( $param ) ) {
423 return array( 'before', $param );
424 } else {
425 throw new MWException( "Invalid message parameter" );
426 }
427 }
428
429 /**
430 * Wrapper for what ever method we use to parse wikitext.
431 * @param $string String: Wikitext message contents
432 * @return string Wikitext parsed into HTML
433 */
434 protected function parseText( $string ) {
435 return MessageCache::singleton()->parse( $string, $this->key, /*linestart*/true, $this->interface, $this->language )->getText();
436 }
437
438 /**
439 * Wrapper for what ever method we use to {{-transform wikitext.
440 * @param $string String: Wikitext message contents
441 * @return string Wikitext with {{-constructs replaced with their values.
442 */
443 protected function transformText( $string ) {
444 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
445 }
446
447 /**
448 * Returns the textual value for the message.
449 * @return Message contents or placeholder
450 */
451 protected function getMessageText() {
452 $message = $this->fetchMessage();
453 if ( $message === false ) {
454 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
455 } else {
456 return $message;
457 }
458 }
459
460 /**
461 * Wrapper for what ever method we use to get message contents
462 *
463 * @return string
464 */
465 protected function fetchMessage() {
466 if ( !isset( $this->message ) ) {
467 $cache = MessageCache::singleton();
468 if ( is_array($this->key) ) {
469 foreach ( $this->key as $key ) {
470 $message = $cache->get( $key, $this->useDatabase, $this->language );
471 if ( $message !== false && $message !== '' ) {
472 break;
473 }
474 }
475 $this->message = $message;
476 } else {
477 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
478 }
479 }
480 return $this->message;
481 }
482
483 }