Remove unneeded commented code, that I accidently added in r82461
[mediawiki.git] / includes / Message.php
blob550ea7f33a0f97e22a9b3902adc027ccd0be2af3
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.
6 * It is intented to replace the old wfMsg* functions that over time grew
7 * unusable.
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>
32 * Comparison with old wfMsg* functions:
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.
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>
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>
51 * TODO:
52 * - test, can we have tests?
53 * - sort out the details marked with fixme
55 * @since 1.17
56 * @author Niklas Laxström
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.
63 protected $interface = true;
65 /**
66 * In which language to get this message. Overrides the $interface
67 * variable.
69 protected $language = null;
71 /**
72 * The message key.
74 protected $key;
76 /**
77 * List of parameters which will be substituted into the message.
79 protected $parameters = array();
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
90 protected $format = 'parse';
92 /**
93 * Whether database can be used.
95 protected $useDatabase = true;
97 /**
98 * Title object to use as context
100 protected $title = null;
103 * Constructor.
104 * @param $key: message key, or array of message keys to try and use the first non-empty message for
105 * @param $params Array message parameters
106 * @return Message: $this
108 public function __construct( $key, $params = array() ) {
109 global $wgLang;
110 $this->key = $key;
111 $this->parameters = array_values( $params );
112 $this->language = $wgLang;
116 * Factory function that is just wrapper for the real constructor. It is
117 * intented to be used instead of the real constructor, because it allows
118 * chaining method calls, while new objects don't.
119 * @param $key String: message key
120 * @param Varargs: parameters as Strings
121 * @return Message: $this
123 public static function newFromKey( $key /*...*/ ) {
124 $params = func_get_args();
125 array_shift( $params );
126 return new self( $key, $params );
130 * Factory function accepting multiple message keys and returning a message instance
131 * for the first message which is non-empty. If all messages are empty then an
132 * instance of the first message key is returned.
133 * @param Varargs: message keys
134 * @return Message: $this
136 public static function newFallbackSequence( /*...*/ ) {
137 $keys = func_get_args();
138 if ( func_num_args() == 1 ) {
139 if ( is_array($keys[0]) ) {
140 // Allow an array to be passed as the first argument instead
141 $keys = array_values($keys[0]);
142 } else {
143 // Optimize a single string to not need special fallback handling
144 $keys = $keys[0];
147 return new self( $keys );
151 * Adds parameters to the parameter list of this message.
152 * @param Varargs: parameters as Strings
153 * @return Message: $this
155 public function params( /*...*/ ) {
156 $args = func_get_args();
157 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
158 $args = $args[0];
160 $args_values = array_values( $args );
161 $this->parameters = array_merge( $this->parameters, $args_values );
162 return $this;
166 * Add parameters that are substituted after parsing or escaping.
167 * In other words the parsing process cannot access the contents
168 * of this type of parameter, and you need to make sure it is
169 * sanitized beforehand. The parser will see "$n", instead.
170 * @param Varargs: raw parameters as Strings
171 * @return Message: $this
173 public function rawParams( /*...*/ ) {
174 $params = func_get_args();
175 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
176 $params = $params[0];
178 foreach( $params as $param ) {
179 $this->parameters[] = self::rawParam( $param );
181 return $this;
185 * Add parameters that are numeric and will be passed through
186 * Language::formatNum before substitution
187 * @param Varargs: numeric parameters
188 * @return Message: $this
190 public function numParams( /*...*/ ) {
191 $params = func_get_args();
192 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
193 $params = $params[0];
195 foreach( $params as $param ) {
196 $this->parameters[] = self::numParam( $param );
198 return $this;
202 * Request the message in any language that is supported.
203 * As a side effect interface message status is unconditionally
204 * turned off.
205 * @param $lang Mixed: language code or Language object.
206 * @return Message: $this
208 public function inLanguage( $lang ) {
209 if( $lang instanceof Language ){
210 $this->language = $lang;
211 } elseif ( is_string( $lang ) ) {
212 if( $this->language->getCode() != $lang ) {
213 $this->language = Language::factory( $lang );
215 } else {
216 $type = gettype( $lang );
217 throw new MWException( __METHOD__ . " must be "
218 . "passed a String or Language object; $type given"
221 $this->interface = false;
222 return $this;
226 * Request the message in the wiki's content language.
227 * @return Message: $this
229 public function inContentLanguage() {
230 global $wgContLang;
231 $this->interface = false;
232 $this->language = $wgContLang;
233 return $this;
237 * Enable or disable database use.
238 * @param $value Boolean
239 * @return Message: $this
241 public function useDatabase( $value ) {
242 $this->useDatabase = (bool) $value;
243 return $this;
247 * Set the Title object to use as context when transforming the message
249 * @param $title Title object
250 * @return Message: $this
252 public function title( $title ) {
253 $this->title = $title;
254 return $this;
258 * Returns the message parsed from wikitext to HTML.
259 * TODO: in PHP >= 5.2.0, we can make this a magic method,
260 * and then we can do, eg:
261 * $foo = Message::get($key);
262 * $string = "<abbr>$foo</abbr>";
263 * But we shouldn't implement that while MediaWiki still supports
264 * PHP < 5.2; or people will start using it...
265 * @return String: HTML
267 public function toString() {
268 $string = $this->getMessageText();
270 # Replace parameters before text parsing
271 $string = $this->replaceParameters( $string, 'before' );
273 # Maybe transform using the full parser
274 if( $this->format === 'parse' ) {
275 $string = $this->parseText( $string );
276 $m = array();
277 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
278 $string = $m[1];
280 } elseif( $this->format === 'block-parse' ){
281 $string = $this->parseText( $string );
282 } elseif( $this->format === 'text' ){
283 $string = $this->transformText( $string );
284 } elseif( $this->format === 'escaped' ){
285 # FIXME: Sanitizer method here?
286 $string = $this->transformText( $string );
287 $string = htmlspecialchars( $string );
290 # Raw parameter replacement
291 $string = $this->replaceParameters( $string, 'after' );
293 return $string;
297 * Fully parse the text from wikitext to HTML
298 * @return String parsed HTML
300 public function parse() {
301 $this->format = 'parse';
302 return $this->toString();
306 * Returns the message text. {{-transformation is done.
307 * @return String: Unescaped message text.
309 public function text() {
310 $this->format = 'text';
311 return $this->toString();
315 * Returns the message text as-is, only parameters are subsituted.
316 * @return String: Unescaped untransformed message text.
318 public function plain() {
319 $this->format = 'plain';
320 return $this->toString();
324 * Returns the parsed message text which is always surrounded by a block element.
325 * @return String: HTML
327 public function parseAsBlock() {
328 $this->format = 'block-parse';
329 return $this->toString();
333 * Returns the message text. {{-transformation is done and the result
334 * is escaped excluding any raw parameters.
335 * @return String: Escaped message text.
337 public function escaped() {
338 $this->format = 'escaped';
339 return $this->toString();
343 * Check whether a message key has been defined currently.
344 * @return Bool: true if it is and false if not.
346 public function exists() {
347 return $this->fetchMessage() !== false;
351 * Check whether a message does not exist, or is an empty string
352 * @return Bool: true if is is and false if not
353 * @todo Merge with isDisabled()?
355 public function isBlank() {
356 $message = $this->fetchMessage();
357 return $message === false || $message === '';
361 * Check whether a message does not exist, is an empty string, or is "-"
362 * @return Bool: true if is is and false if not
364 public function isDisabled() {
365 $message = $this->fetchMessage();
366 return $message === false || $message === '' || $message === '-';
369 public static function rawParam( $value ) {
370 return array( 'raw' => $value );
373 public static function numParam( $value ) {
374 return array( 'num' => $value );
378 * Substitutes any paramaters into the message text.
379 * @param $message String: the message text
380 * @param $type String: either before or after
381 * @return String
383 protected function replaceParameters( $message, $type = 'before' ) {
384 $replacementKeys = array();
385 foreach( $this->parameters as $n => $param ) {
386 list( $paramType, $value ) = $this->extractParam( $param );
387 if ( $type === $paramType ) {
388 $replacementKeys['$' . ($n + 1)] = $value;
391 $message = strtr( $message, $replacementKeys );
392 return $message;
396 * Extracts the parameter type and preprocessed the value if needed.
397 * @param $param String|Array: Parameter as defined in this class.
398 * @return Tuple(type, value)
399 * @throws MWException
401 protected function extractParam( $param ) {
402 if ( is_array( $param ) && isset( $param['raw'] ) ) {
403 return array( 'after', $param['raw'] );
404 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
405 // Replace number params always in before step for now.
406 // No support for combined raw and num params
407 return array( 'before', $this->language->formatNum( $param['num'] ) );
408 } elseif ( !is_array( $param ) ) {
409 return array( 'before', $param );
410 } else {
411 throw new MWException( "Invalid message parameter" );
416 * Wrapper for what ever method we use to parse wikitext.
417 * @param $string String: Wikitext message contents
418 * @return Wikitext parsed into HTML
420 protected function parseText( $string ) {
421 global $wgOut;
422 return $wgOut->parse( $string, /*linestart*/true, $this->interface, $this->language );
426 * Wrapper for what ever method we use to {{-transform wikitext.
427 * @param $string String: Wikitext message contents
428 * @return Wikitext with {{-constructs replaced with their values.
430 protected function transformText( $string ) {
431 return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
435 * Returns the textual value for the message.
436 * @return Message contents or placeholder
438 protected function getMessageText() {
439 $message = $this->fetchMessage();
440 if ( $message === false ) {
441 return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
442 } else {
443 return $message;
448 * Wrapper for what ever method we use to get message contents
450 protected function fetchMessage() {
451 if ( !isset( $this->message ) ) {
452 $cache = MessageCache::singleton();
453 if ( is_array($this->key) ) {
454 foreach ( $this->key as $key ) {
455 $message = $cache->get( $key, $this->useDatabase, $this->language );
456 if ( $message !== false && $message !== '' ) {
457 break;
460 $this->message = $message;
461 } else {
462 $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
465 return $this->message;