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