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