* fixed typo
[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 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 $string = $this->transformText( $string );
282 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
283 }
284
285 # Raw parameter replacement
286 $string = $this->replaceParameters( $string, 'after' );
287
288 return $string;
289 }
290
291 /**
292 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
293 * $foo = Message::get($key);
294 * $string = "<abbr>$foo</abbr>";
295 * @return String
296 */
297 public function __toString() {
298 return $this->toString();
299 }
300
301 /**
302 * Fully parse the text from wikitext to HTML
303 * @return String parsed HTML
304 */
305 public function parse() {
306 $this->format = 'parse';
307 return $this->toString();
308 }
309
310 /**
311 * Returns the message text. {{-transformation is done.
312 * @return String: Unescaped message text.
313 */
314 public function text() {
315 $this->format = 'text';
316 return $this->toString();
317 }
318
319 /**
320 * Returns the message text as-is, only parameters are subsituted.
321 * @return String: Unescaped untransformed message text.
322 */
323 public function plain() {
324 $this->format = 'plain';
325 return $this->toString();
326 }
327
328 /**
329 * Returns the parsed message text which is always surrounded by a block element.
330 * @return String: HTML
331 */
332 public function parseAsBlock() {
333 $this->format = 'block-parse';
334 return $this->toString();
335 }
336
337 /**
338 * Returns the message text. {{-transformation is done and the result
339 * is escaped excluding any raw parameters.
340 * @return String: Escaped message text.
341 */
342 public function escaped() {
343 $this->format = 'escaped';
344 return $this->toString();
345 }
346
347 /**
348 * Check whether a message key has been defined currently.
349 * @return Bool: true if it is and false if not.
350 */
351 public function exists() {
352 return $this->fetchMessage() !== false;
353 }
354
355 /**
356 * Check whether a message does not exist, or is an empty string
357 * @return Bool: true if is is and false if not
358 * @todo Merge with isDisabled()?
359 */
360 public function isBlank() {
361 $message = $this->fetchMessage();
362 return $message === false || $message === '';
363 }
364
365 /**
366 * Check whether a message does not exist, is an empty string, or is "-"
367 * @return Bool: true if is is and false if not
368 */
369 public function isDisabled() {
370 $message = $this->fetchMessage();
371 return $message === false || $message === '' || $message === '-';
372 }
373
374 /**
375 * @param $value
376 * @return array
377 */
378 public static function rawParam( $value ) {
379 return array( 'raw' => $value );
380 }
381
382 /**
383 * @param $value
384 * @return array
385 */
386 public static function numParam( $value ) {
387 return array( 'num' => $value );
388 }
389
390 /**
391 * Substitutes any paramaters into the message text.
392 * @param $message String: the message text
393 * @param $type String: either before or after
394 * @return String
395 */
396 protected function replaceParameters( $message, $type = 'before' ) {
397 $replacementKeys = array();
398 foreach( $this->parameters as $n => $param ) {
399 list( $paramType, $value ) = $this->extractParam( $param );
400 if ( $type === $paramType ) {
401 $replacementKeys['$' . ($n + 1)] = $value;
402 }
403 }
404 $message = strtr( $message, $replacementKeys );
405 return $message;
406 }
407
408 /**
409 * Extracts the parameter type and preprocessed the value if needed.
410 * @param $param String|Array: Parameter as defined in this class.
411 * @return Tuple(type, value)
412 * @throws MWException
413 */
414 protected function extractParam( $param ) {
415 if ( is_array( $param ) && isset( $param['raw'] ) ) {
416 return array( 'after', $param['raw'] );
417 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
418 // Replace number params always in before step for now.
419 // No support for combined raw and num params
420 return array( 'before', $this->language->formatNum( $param['num'] ) );
421 } elseif ( !is_array( $param ) ) {
422 return array( 'before', $param );
423 } else {
424 throw new MWException( "Invalid message parameter" );
425 }
426 }
427
428 /**
429 * Wrapper for what ever method we use to parse wikitext.
430 * @param $string String: Wikitext message contents
431 * @return string Wikitext parsed into HTML
432 */
433 protected function parseText( $string ) {
434 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
435 }
436
437 /**
438 * Wrapper for what ever method we use to {{-transform wikitext.
439 * @param $string String: Wikitext message contents
440 * @return string Wikitext with {{-constructs replaced with their values.
441 */
442 protected function transformText( $string ) {
443 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
444 }
445
446 /**
447 * Returns the textual value for the message.
448 * @return Message contents or placeholder
449 */
450 protected function getMessageText() {
451 $message = $this->fetchMessage();
452 if ( $message === false ) {
453 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
454 } else {
455 return $message;
456 }
457 }
458
459 /**
460 * Wrapper for what ever method we use to get message contents
461 *
462 * @return string
463 */
464 protected function fetchMessage() {
465 if ( !isset( $this->message ) ) {
466 $cache = MessageCache::singleton();
467 if ( is_array($this->key) ) {
468 foreach ( $this->key as $key ) {
469 $message = $cache->get( $key, $this->useDatabase, $this->language );
470 if ( $message !== false && $message !== '' ) {
471 break;
472 }
473 }
474 $this->message = $message;
475 } else {
476 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
477 }
478 }
479 return $this->message;
480 }
481
482 }