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