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