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