Followup r88118. Fix Bug 28979 — “remove some CSS for abbr and acronym
[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 * @return Message: $this
229 */
230 public function inContentLanguage() {
231 global $wgContLang;
232 $this->interface = false;
233 $this->language = $wgContLang;
234 return $this;
235 }
236
237 /**
238 * Enable or disable database use.
239 * @param $value Boolean
240 * @return Message: $this
241 */
242 public function useDatabase( $value ) {
243 $this->useDatabase = (bool) $value;
244 return $this;
245 }
246
247 /**
248 * Set the Title object to use as context when transforming the message
249 *
250 * @param $title Title object
251 * @return Message: $this
252 */
253 public function title( $title ) {
254 $this->title = $title;
255 return $this;
256 }
257
258 /**
259 * Returns the message parsed from wikitext to HTML.
260 * @return String: HTML
261 */
262 public function toString() {
263 $string = $this->getMessageText();
264
265 # Replace parameters before text parsing
266 $string = $this->replaceParameters( $string, 'before' );
267
268 # Maybe transform using the full parser
269 if( $this->format === 'parse' ) {
270 $string = $this->parseText( $string );
271 $m = array();
272 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
273 $string = $m[1];
274 }
275 } elseif( $this->format === 'block-parse' ){
276 $string = $this->parseText( $string );
277 } elseif( $this->format === 'text' ){
278 $string = $this->transformText( $string );
279 } elseif( $this->format === 'escaped' ){
280 $string = $this->transformText( $string );
281 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
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 FIXME: 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 /**
374 * @param $value
375 * @return array
376 */
377 public static function rawParam( $value ) {
378 return array( 'raw' => $value );
379 }
380
381 /**
382 * @param $value
383 * @return array
384 */
385 public static function numParam( $value ) {
386 return array( 'num' => $value );
387 }
388
389 /**
390 * Substitutes any paramaters into the message text.
391 * @param $message String: the message text
392 * @param $type String: either before or after
393 * @return String
394 */
395 protected function replaceParameters( $message, $type = 'before' ) {
396 $replacementKeys = array();
397 foreach( $this->parameters as $n => $param ) {
398 list( $paramType, $value ) = $this->extractParam( $param );
399 if ( $type === $paramType ) {
400 $replacementKeys['$' . ($n + 1)] = $value;
401 }
402 }
403 $message = strtr( $message, $replacementKeys );
404 return $message;
405 }
406
407 /**
408 * Extracts the parameter type and preprocessed the value if needed.
409 * @param $param String|Array: Parameter as defined in this class.
410 * @return Tuple(type, value)
411 * @throws MWException
412 */
413 protected function extractParam( $param ) {
414 if ( is_array( $param ) && isset( $param['raw'] ) ) {
415 return array( 'after', $param['raw'] );
416 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
417 // Replace number params always in before step for now.
418 // No support for combined raw and num params
419 return array( 'before', $this->language->formatNum( $param['num'] ) );
420 } elseif ( !is_array( $param ) ) {
421 return array( 'before', $param );
422 } else {
423 throw new MWException( "Invalid message parameter" );
424 }
425 }
426
427 /**
428 * Wrapper for what ever method we use to parse wikitext.
429 * @param $string String: Wikitext message contents
430 * @return string Wikitext parsed into HTML
431 */
432 protected function parseText( $string ) {
433 return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
434 }
435
436 /**
437 * Wrapper for what ever method we use to {{-transform wikitext.
438 * @param $string String: Wikitext message contents
439 * @return string Wikitext with {{-constructs replaced with their values.
440 */
441 protected function transformText( $string ) {
442 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
443 }
444
445 /**
446 * Returns the textual value for the message.
447 * @return Message contents or placeholder
448 */
449 protected function getMessageText() {
450 $message = $this->fetchMessage();
451 if ( $message === false ) {
452 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
453 } else {
454 return $message;
455 }
456 }
457
458 /**
459 * Wrapper for what ever method we use to get message contents
460 *
461 * @return string
462 */
463 protected function fetchMessage() {
464 if ( !isset( $this->message ) ) {
465 $cache = MessageCache::singleton();
466 if ( is_array($this->key) ) {
467 foreach ( $this->key as $key ) {
468 $message = $cache->get( $key, $this->useDatabase, $this->language );
469 if ( $message !== false && $message !== '' ) {
470 break;
471 }
472 }
473 $this->message = $message;
474 } else {
475 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
476 }
477 }
478 return $this->message;
479 }
480
481 }