Work on Message.php:
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * OBS!!! *EXPERIMENTAL* This class is still under discussion.
4 *
5 * This class provides methods for fetching interface messages and
6 * processing them into variety of formats that are needed in MediaWiki.
7 *
8 * It is intented to replace the old wfMsg* functions that over time grew
9 * unusable.
10 *
11 * Examples:
12 * Fetching a message text for interface message
13 * $button = Xml::button( Message::key( 'submit' )->text() );
14 * Messages can have parameters:
15 * Message::key( 'welcome-to' )->params( $wgSitename )->text();
16 * {{GRAMMAR}} and friends work correctly
17 * Message::key( 'are-friends' )->params( $user, $friend );
18 * Message::key( 'bad-message' )->rawParams( '<script>...</script>' )->escaped()
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * Message::key( 'file-log' )->params( $user, $filename )->inContentLanguage()->text()
21 * Checking if message exists:
22 * Message::key( 'mysterious-message' )->exists()
23 * If you want to use a different language:
24 * Message::key( 'email-header' )->language( $user->getOption( 'language' ) )->plain()
25 * Note that you cannot parse the text except in the content or interface
26 * languages
27 *
28 *
29 * Comparison with old wfMsg* functions:
30 *
31 * Use full parsing.
32 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
33 * === Message::key( 'key' )->params( 'apple' )->parse();
34 * Parseinline is used because it is more useful when pre-building html.
35 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
36 *
37 * Places where html cannot be used. {{-transformation is done.
38 * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
39 * === Message::key( 'key' )->params( 'apple', 'pear' )->text();
40 *
41 * Shortcut for escaping the message too, similar to wfMsgHTML, but
42 * parameters are not replaced after escaping by default.
43 * $escaped = Message::key( 'key' )->rawParams( 'apple' )->escaped();
44 *
45 * TODO:
46 * * test, can we have tests?
47 * * sort out the details marked with fixme
48 * * should we have _m() or similar global wrapper?
49 *
50 * @since 1.17
51 */
52 class Message {
53 /**
54 * In which language to get this message. True, which is the default,
55 * means the current interface language, false content language.
56 */
57 protected $interface = true;
58
59 /**
60 * In which language to get this message. Overrides the $interface
61 * variable.
62 */
63 protected $language = null;
64
65 /**
66 * The message key.
67 */
68 protected $key;
69
70 /**
71 * List of parameters which will be substituted into the message.
72 */
73 protected $parameters = array();
74
75 /**
76 * Some situations need exotic combinations of options to the
77 * underlying Language modules; which can be specified here.
78 * Dependencies:
79 * 'parse' implies 'transform', 'escape'
80 */
81 protected $options = array(
82 # Don't wrap the output in a block-level element
83 'inline' => true,
84 # Expand {{ constructs
85 'transform' => true,
86 # Output will be safe HTML
87 'escape' => true,
88 # Parse the text with the full parser
89 'parse' => true,
90 # Access the database when getting the message text
91 'usedb' => true,
92 );
93
94 /**
95 * Constructor.
96 * @param $key String: message key
97 * @return Message: $this
98 */
99 public function __construct( $key, $params=array(), $options=array() ) {
100 $this->key = $key;
101 if( $params ){
102 $this->params( $params );
103 }
104 if( $options ){
105 $this->options( $options );
106 }
107 }
108
109 /**
110 * Factory function that is just wrapper for the real constructor. It is
111 * intented to be used instead of the real constructor, because it allows
112 * chaining method calls, while new objects don't.
113 * //FIXME: key or get or something else?
114 * @param $key String: message key
115 * @return Message: $this
116 */
117 public function key( $key ) {
118 return new Message( $key );
119 }
120
121 /**
122 * Adds parameters to the parameter list of this message.
123 * @params Vargars: parameters as Strings
124 * @return Message: $this
125 */
126 public function params( /*...*/ ) {
127 $this->parameters += array_values( func_get_args() );
128 return $this;
129 }
130
131 /**
132 * Add parameters that are substituted after parsing or escaping.
133 * In other words the parsing process cannot access the contents
134 * of this type of parameter, and you need to make sure it is
135 * sanitized beforehand. The parser will see "$n", instead.
136 * @param $value Varargs: raw parameters as Strings
137 * @return Message: $this
138 */
139 public function rawParams( /*...*/ ) {
140 $params = func_get_args();
141 foreach( $params as $param ){
142 $this->parameters[] = array( 'raw' => $param );
143 }
144 return $this;
145 }
146
147 /**
148 * Set some of the individual options, if you need to use some
149 * funky combination of them.
150 * @param $options Array $option => $value
151 * @return Message $this
152 */
153 public function options( array $options ){
154 foreach( $options as $key => $value ){
155 if( in_array( $key, $this->options ) ){
156 $this->options[$key] = (bool)$value;
157 }
158 }
159 return $this;
160 }
161
162 /**
163 * Request the message in any language that is supported.
164 * As a side effect interface message status is unconditionally
165 * turned off.
166 * @param $lang Mixed: langauge code or language object.
167 * @return Message: $this
168 */
169 public function language( $lang ) {
170 if( $lang instanceof Language ){
171 $this->language = $lang;
172 } elseif ( is_string( $lang ) ) {
173 $this->language = Language::factory( $lang );
174 } else {
175 $type = gettype( $lang );
176 throw new MWException( "Message::langauge() must be "
177 . "passed a String or Language object; $type given"
178 );
179 }
180 $this->interface = false;
181 return $this;
182 }
183
184 /**
185 * Request the message in the wiki's content language.
186 * @return Message: $this
187 */
188 public function inContentLanguage() {
189 $this->interface = false;
190 $this->language = null;
191 return $this;
192 }
193
194 /**
195 * Returns the message parsed from wikitext to HTML.
196 * TODO: in PHP >= 5.2.0, we can make this a magic method,
197 * and then we can do, eg:
198 * $foo = Message::get($key);
199 * $string = "<abbr>$foo</abbr>";
200 * But we shouldn't implement that while MediaWiki still supports
201 * PHP < 5.2; or people will start using it...
202 * @return String: HTML
203 */
204 public function toString() {
205 $string = $this->getMessageText();
206
207 # Replace parameters before text parsing
208 $string = $this->replaceParameters( $string, 'before' );
209
210 # Maybe transform using the full parser
211 if( $this->options['parse'] ){
212 $string = $this->parseText( $string );
213 } else {
214
215 # Transform {{ constructs
216 if( $this->options['transform'] ){
217 $string = $this->transformText( $string );
218 }
219
220 # Sanitise
221 if( $this->options['escape'] ){
222 # FIXME: Sanitizer method here?
223 $string = htmlspecialchars( $string );
224 }
225 }
226
227 # Strip the block element
228 if( !$this->options['inline'] ){
229 $m = array();
230 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
231 $string = $m[1];
232 }
233 }
234
235 # Raw parameter replacement
236 $string = $this->replaceParameters( $string, 'after' );
237
238 return $string;
239 }
240
241 public function __tostring(){ return $this->toString(); }
242
243 /**
244 * Fully parse the text from wikitext to HTML
245 * @return String parsed HTML
246 */
247 public function parse(){
248 $this->options( array(
249 'parse' => true,
250 ));
251 return $this->tostring();
252 }
253
254 /**
255 * Returns the message text. {{-transformation is done.
256 * @return String: Unescaped message text.
257 */
258 public function text() {
259 $this->options( array(
260 'parse' => false,
261 'transform' => true,
262 'escape' => false,
263 ));
264 return $this->tostring();
265 }
266
267 /**
268 * Returns the message text as-is, only parameters are subsituted.
269 * @return String: Unescaped untransformed message text.
270 */
271 public function plain() {
272 $this->options( array(
273 'parse' => false,
274 'transform' => false,
275 'escape' => false,
276 'inline' => false,
277 ));
278 return $this->tostring();
279 }
280
281 /**
282 * Returns the parsed message text which is always surrounded by a block element.
283 * @return String: HTML
284 */
285 public function parseAsBlock() {
286 $this->options( array(
287 'parse' => true,
288 'inline' => true,
289 ));
290 return $this->tostring();
291 }
292
293 /**
294 * Returns the message text. {{-transformation is done and the result
295 * is excaped excluding any raw parameters.
296 * @return String: Escaped message text.
297 */
298 public function escaped() {
299 $this->options( array(
300 'parse' => false,
301 'transform' => true,
302 'escape' => true,
303 'inline' => false,
304 ));
305 return $this->tostring();
306 }
307
308 /**
309 * Check whether a message key has been defined currently.
310 * @return Bool: true if it is and false if not.
311 */
312 public function exists() {
313 global $wgMessageCache;
314 return $wgMessageCache->get(
315 $this->key,
316 $this->options['usedb'],
317 $this->language
318 ) !== false;
319 }
320
321 /**
322 * Substitutes any paramaters into the message text.
323 * @param $message String, the message text
324 * @param $type String: either before or after
325 * @return String
326 */
327 protected function replaceParameters( $message, $type = 'before' ) {
328 $replacementKeys = array();
329 foreach( $this->parameters as $n => $param ) {
330 if ( $type === 'before' && !is_array( $param ) ) {
331 $replacementKeys['$' . ($n + 1)] = $param;
332 } elseif ( $type === 'after' && isset( $param['raw'] ) ) {
333 $replacementKeys['$' . ($n + 1)] = $param['raw'];
334 }
335 }
336 $message = strtr( $message, $replacementKeys );
337 return $message;
338 }
339
340 /**
341 * Wrapper for what ever method we use to parse wikitext.
342 * @param $string String: Wikitext message contents
343 * @return Wikitext parsed into HTML
344 */
345 protected function parseText( $string ) {
346 global $wgOut;
347 if ( $this->language !== null ) {
348 # FIXME: remove this limitation
349 throw new MWException( 'Can only parse in interface or content language' );
350 }
351 return $wgOut->parse( $string, /*linestart*/true, $this->interface );
352 }
353
354 /**
355 * Wrapper for what ever method we use to {{-transform wikitext.
356 * @param $string String: Wikitext message contents
357 * @return Wikitext with {{-constructs replaced with their values.
358 */
359 protected function transformText( $string ) {
360 global $wgMessageCache;
361 return $wgMessageCache->transform( $string, $this->interface, $this->language );
362 }
363
364 /**
365 * Wrapper for what ever method we use to get message contents
366 * @return Unmodified message contents
367 */
368 protected function getMessageText() {
369 global $wgMessageCache;
370 $message = $wgMessageCache->get( $this->key, $this->options['usedb'], $this->language );
371 return $message === false
372 ? '&lt;' . htmlspecialchars( $this->key ) . '&gt;'
373 : $message;
374 }
375
376 }