Fix bug 14267 by adding support for a MediaWiki:Mainpage-nstab.
[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 global $wgMessageCache;
133 $keys = func_get_args();
134 if ( func_num_args() == 1 ) {
135 if ( is_array($keys[0]) ) {
136 // Allow an array to be passed as the first argument instead
137 $keys = array_values($keys[0]);
138 } else {
139 // Optimize a single string to not need special fallback handling
140 $keys = $keys[0];
141 }
142 }
143 return new self( $keys );
144 }
145
146 /**
147 * Adds parameters to the parameter list of this message.
148 * @param Varargs: parameters as Strings
149 * @return Message: $this
150 */
151 public function params( /*...*/ ) {
152 $args_values = array_values( func_get_args() );
153 $this->parameters = array_merge( $this->parameters, $args_values );
154 return $this;
155 }
156
157 /**
158 * Add parameters that are substituted after parsing or escaping.
159 * In other words the parsing process cannot access the contents
160 * of this type of parameter, and you need to make sure it is
161 * sanitized beforehand. The parser will see "$n", instead.
162 * @param Varargs: raw parameters as Strings
163 * @return Message: $this
164 */
165 public function rawParams( /*...*/ ) {
166 $params = func_get_args();
167 foreach( $params as $param ) {
168 $this->parameters[] = self::rawParam( $param );
169 }
170 return $this;
171 }
172
173 /**
174 * Request the message in any language that is supported.
175 * As a side effect interface message status is unconditionally
176 * turned off.
177 * @param $lang Mixed: language code or Language object.
178 * @return Message: $this
179 */
180 public function inLanguage( $lang ) {
181 if( $lang instanceof Language ){
182 $this->language = $lang;
183 } elseif ( is_string( $lang ) ) {
184 if( $this->language->getCode() != $lang ) {
185 $this->language = Language::factory( $lang );
186 }
187 } else {
188 $type = gettype( $lang );
189 throw new MWException( __METHOD__ . " must be "
190 . "passed a String or Language object; $type given"
191 );
192 }
193 $this->interface = false;
194 return $this;
195 }
196
197 /**
198 * Request the message in the wiki's content language.
199 * @return Message: $this
200 */
201 public function inContentLanguage() {
202 global $wgContLang;
203 $this->interface = false;
204 $this->language = $wgContLang;
205 return $this;
206 }
207
208 /**
209 * Enable or disable database use.
210 * @param $value Boolean
211 * @return Message: $this
212 */
213 public function useDatabase( $value ) {
214 $this->useDatabase = (bool) $value;
215 return $this;
216 }
217
218 /**
219 * Returns the message parsed from wikitext to HTML.
220 * TODO: in PHP >= 5.2.0, we can make this a magic method,
221 * and then we can do, eg:
222 * $foo = Message::get($key);
223 * $string = "<abbr>$foo</abbr>";
224 * But we shouldn't implement that while MediaWiki still supports
225 * PHP < 5.2; or people will start using it...
226 * @return String: HTML
227 */
228 public function toString() {
229 $string = $this->getMessageText();
230
231 # Replace parameters before text parsing
232 $string = $this->replaceParameters( $string, 'before' );
233
234 # Maybe transform using the full parser
235 if( $this->format === 'parse' ) {
236 $string = $this->parseText( $string );
237 $m = array();
238 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
239 $string = $m[1];
240 }
241 } elseif( $this->format === 'block-parse' ){
242 $string = $this->parseText( $string );
243 } elseif( $this->format === 'text' ){
244 $string = $this->transformText( $string );
245 } elseif( $this->format === 'escaped' ){
246 # FIXME: Sanitizer method here?
247 $string = $this->transformText( $string );
248 $string = htmlspecialchars( $string );
249 }
250
251 # Raw parameter replacement
252 $string = $this->replaceParameters( $string, 'after' );
253
254 return $string;
255 }
256
257 /**
258 * Fully parse the text from wikitext to HTML
259 * @return String parsed HTML
260 */
261 public function parse() {
262 $this->format = 'parse';
263 return $this->toString();
264 }
265
266 /**
267 * Returns the message text. {{-transformation is done.
268 * @return String: Unescaped message text.
269 */
270 public function text() {
271 $this->format = 'text';
272 return $this->toString();
273 }
274
275 /**
276 * Returns the message text as-is, only parameters are subsituted.
277 * @return String: Unescaped untransformed message text.
278 */
279 public function plain() {
280 $this->format = 'plain';
281 return $this->toString();
282 }
283
284 /**
285 * Returns the parsed message text which is always surrounded by a block element.
286 * @return String: HTML
287 */
288 public function parseAsBlock() {
289 $this->format = 'block-parse';
290 return $this->toString();
291 }
292
293 /**
294 * Returns the message text. {{-transformation is done and the result
295 * is escaped excluding any raw parameters.
296 * @return String: Escaped message text.
297 */
298 public function escaped() {
299 $this->format = 'escaped';
300 return $this->toString();
301 }
302
303 /**
304 * Check whether a message key has been defined currently.
305 * @return Bool: true if it is and false if not.
306 */
307 public function exists() {
308 return $this->fetchMessage() !== false;
309 }
310
311 public static function rawParam( $value ) {
312 return array( 'raw' => $value );
313 }
314
315 /**
316 * Substitutes any paramaters into the message text.
317 * @param $message String, the message text
318 * @param $type String: either before or after
319 * @return String
320 */
321 protected function replaceParameters( $message, $type = 'before' ) {
322 $replacementKeys = array();
323 foreach( $this->parameters as $n => $param ) {
324 if ( $type === 'before' && !is_array( $param ) ) {
325 $replacementKeys['$' . ($n + 1)] = $param;
326 } elseif ( $type === 'after' && isset( $param['raw'] ) ) {
327 $replacementKeys['$' . ($n + 1)] = $param['raw'];
328 }
329 }
330 $message = strtr( $message, $replacementKeys );
331 return $message;
332 }
333
334 /**
335 * Wrapper for what ever method we use to parse wikitext.
336 * @param $string String: Wikitext message contents
337 * @return Wikitext parsed into HTML
338 */
339 protected function parseText( $string ) {
340 global $wgOut;
341 return $wgOut->parse( $string, /*linestart*/true, $this->interface, $this->language );
342 }
343
344 /**
345 * Wrapper for what ever method we use to {{-transform wikitext.
346 * @param $string String: Wikitext message contents
347 * @return Wikitext with {{-constructs replaced with their values.
348 */
349 protected function transformText( $string ) {
350 global $wgMessageCache;
351 return $wgMessageCache->transform( $string, $this->interface, $this->language );
352 }
353
354 /**
355 * Returns the textual value for the message.
356 * @return Message contents or placeholder
357 */
358 protected function getMessageText() {
359 $message = $this->fetchMessage();
360 if ( $message === false ) {
361 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
362 } else {
363 return $message;
364 }
365 }
366
367 /**
368 * Wrapper for what ever method we use to get message contents
369 */
370 protected function fetchMessage() {
371 if ( !isset( $this->message ) ) {
372 global $wgMessageCache;
373 if ( is_array($this->key) ) {
374 foreach ( $this->key as $key ) {
375 $message = $wgMessageCache->get( $key, $this->useDatabase, $this->language );
376 if ( $message !== false && $message !== '' ) {
377 break;
378 }
379 }
380 $this->message = $message;
381 } else {
382 $this->message = $wgMessageCache->get( $this->key, $this->useDatabase, $this->language );
383 }
384 }
385 return $this->message;
386 }
387
388 }