578e5f10e0fe77ec065284ed5f3b6918040f71ee
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
10 * Fetching a message text for interface message
11 * $button = Xml::button( wfMessage( 'submit' )->text() );
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();
19 * Sometimes the message text ends up in the database, so content language is needed.
20 * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
22 * Checking if message exists:
23 * wfMessage( 'mysterious-message' )->exists()
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
32 * Comparison with old wfMsg* functions:
35 * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
36 * === wfMessage( 'key', 'apple' )->parse();
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();
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();
52 * - test, can we have tests?
55 * @author Niklas Laxström
59 * In which language to get this message. True, which is the default,
60 * means the current interface language, false content language.
62 protected $interface = true;
65 * In which language to get this message. Overrides the $interface
70 protected $language = null;
78 * List of parameters which will be substituted into the message.
80 protected $parameters = array();
83 * Format for the message.
84 * Supported formats are:
86 * * escaped (transform+htmlspecialchars)
91 protected $format = 'parse';
94 * Whether database can be used.
96 protected $useDatabase = true;
99 * Title object to use as context
101 protected $title = null;
110 * @param $key: message key, or array of message keys to try and use the first non-empty message for
111 * @param $params Array message parameters
112 * @return Message: $this
114 public function __construct( $key, $params = array() ) {
117 $this->parameters
= array_values( $params );
118 $this->language
= $wgLang;
122 * Factory function that is just wrapper for the real constructor. It is
123 * intented to be used instead of the real constructor, because it allows
124 * chaining method calls, while new objects don't.
125 * @param $key String: message key
126 * @param Varargs: parameters as Strings
127 * @return Message: $this
129 public static function newFromKey( $key /*...*/ ) {
130 $params = func_get_args();
131 array_shift( $params );
132 return new self( $key, $params );
136 * Factory function accepting multiple message keys and returning a message instance
137 * for the first message which is non-empty. If all messages are empty then an
138 * instance of the first message key is returned.
139 * @param Varargs: message keys
140 * @return Message: $this
142 public static function newFallbackSequence( /*...*/ ) {
143 $keys = func_get_args();
144 if ( func_num_args() == 1 ) {
145 if ( is_array($keys[0]) ) {
146 // Allow an array to be passed as the first argument instead
147 $keys = array_values($keys[0]);
149 // Optimize a single string to not need special fallback handling
153 return new self( $keys );
157 * Adds parameters to the parameter list of this message.
158 * @param Varargs: parameters as Strings
159 * @return Message: $this
161 public function params( /*...*/ ) {
162 $args = func_get_args();
163 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
166 $args_values = array_values( $args );
167 $this->parameters
= array_merge( $this->parameters
, $args_values );
172 * Add parameters that are substituted after parsing or escaping.
173 * In other words the parsing process cannot access the contents
174 * of this type of parameter, and you need to make sure it is
175 * sanitized beforehand. The parser will see "$n", instead.
176 * @param Varargs: raw parameters as Strings
177 * @return Message: $this
179 public function rawParams( /*...*/ ) {
180 $params = func_get_args();
181 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
182 $params = $params[0];
184 foreach( $params as $param ) {
185 $this->parameters
[] = self
::rawParam( $param );
191 * Add parameters that are numeric and will be passed through
192 * Language::formatNum before substitution
193 * @param Varargs: numeric parameters
194 * @return Message: $this
196 public function numParams( /*...*/ ) {
197 $params = func_get_args();
198 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
199 $params = $params[0];
201 foreach( $params as $param ) {
202 $this->parameters
[] = self
::numParam( $param );
208 * Set the language and the title from a context object
210 * @param $context IContextSource
211 * @return Message: $this
213 public function setContext( IContextSource
$context ) {
214 $this->inLanguage( $context->getLang() );
215 $this->title( $context->getTitle() );
221 * Request the message in any language that is supported.
222 * As a side effect interface message status is unconditionally
224 * @param $lang Mixed: language code or Language object.
225 * @return Message: $this
227 public function inLanguage( $lang ) {
228 if ( $lang instanceof Language ||
$lang instanceof StubUserLang
) {
229 $this->language
= $lang;
230 } elseif ( is_string( $lang ) ) {
231 if( $this->language
->getCode() != $lang ) {
232 $this->language
= Language
::factory( $lang );
235 $type = gettype( $lang );
236 throw new MWException( __METHOD__
. " must be "
237 . "passed a String or Language object; $type given"
240 $this->interface = false;
245 * Request the message in the wiki's content language,
246 * unless it is disabled for this message.
247 * @see $wgForceUIMsgAsContentMsg
248 * @return Message: $this
250 public function inContentLanguage() {
251 global $wgForceUIMsgAsContentMsg;
252 if ( in_array( $this->key
, (array)$wgForceUIMsgAsContentMsg ) ) {
257 $this->interface = false;
258 $this->language
= $wgContLang;
263 * Enable or disable database use.
264 * @param $value Boolean
265 * @return Message: $this
267 public function useDatabase( $value ) {
268 $this->useDatabase
= (bool) $value;
273 * Set the Title object to use as context when transforming the message
275 * @param $title Title object
276 * @return Message: $this
278 public function title( $title ) {
279 $this->title
= $title;
284 * Returns the message parsed from wikitext to HTML.
285 * @return String: HTML
287 public function toString() {
288 $string = $this->getMessageText();
290 # Replace parameters before text parsing
291 $string = $this->replaceParameters( $string, 'before' );
293 # Maybe transform using the full parser
294 if( $this->format
=== 'parse' ) {
295 $string = $this->parseText( $string );
297 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
300 } elseif( $this->format
=== 'block-parse' ){
301 $string = $this->parseText( $string );
302 } elseif( $this->format
=== 'text' ){
303 $string = $this->transformText( $string );
304 } elseif( $this->format
=== 'escaped' ){
305 $string = $this->transformText( $string );
306 $string = htmlspecialchars( $string, ENT_QUOTES
, 'UTF-8', false );
309 # Raw parameter replacement
310 $string = $this->replaceParameters( $string, 'after' );
316 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
317 * $foo = Message::get($key);
318 * $string = "<abbr>$foo</abbr>";
321 public function __toString() {
322 return $this->toString();
326 * Fully parse the text from wikitext to HTML
327 * @return String parsed HTML
329 public function parse() {
330 $this->format
= 'parse';
331 return $this->toString();
335 * Returns the message text. {{-transformation is done.
336 * @return String: Unescaped message text.
338 public function text() {
339 $this->format
= 'text';
340 return $this->toString();
344 * Returns the message text as-is, only parameters are subsituted.
345 * @return String: Unescaped untransformed message text.
347 public function plain() {
348 $this->format
= 'plain';
349 return $this->toString();
353 * Returns the parsed message text which is always surrounded by a block element.
354 * @return String: HTML
356 public function parseAsBlock() {
357 $this->format
= 'block-parse';
358 return $this->toString();
362 * Returns the message text. {{-transformation is done and the result
363 * is escaped excluding any raw parameters.
364 * @return String: Escaped message text.
366 public function escaped() {
367 $this->format
= 'escaped';
368 return $this->toString();
372 * Check whether a message key has been defined currently.
373 * @return Bool: true if it is and false if not.
375 public function exists() {
376 return $this->fetchMessage() !== false;
380 * Check whether a message does not exist, or is an empty string
381 * @return Bool: true if is is and false if not
382 * @todo FIXME: Merge with isDisabled()?
384 public function isBlank() {
385 $message = $this->fetchMessage();
386 return $message === false ||
$message === '';
390 * Check whether a message does not exist, is an empty string, or is "-"
391 * @return Bool: true if is is and false if not
393 public function isDisabled() {
394 $message = $this->fetchMessage();
395 return $message === false ||
$message === '' ||
$message === '-';
402 public static function rawParam( $value ) {
403 return array( 'raw' => $value );
410 public static function numParam( $value ) {
411 return array( 'num' => $value );
415 * Substitutes any paramaters into the message text.
416 * @param $message String: the message text
417 * @param $type String: either before or after
420 protected function replaceParameters( $message, $type = 'before' ) {
421 $replacementKeys = array();
422 foreach( $this->parameters
as $n => $param ) {
423 list( $paramType, $value ) = $this->extractParam( $param );
424 if ( $type === $paramType ) {
425 $replacementKeys['$' . ($n +
1)] = $value;
428 $message = strtr( $message, $replacementKeys );
433 * Extracts the parameter type and preprocessed the value if needed.
434 * @param $param String|Array: Parameter as defined in this class.
435 * @return Tuple(type, value)
436 * @throws MWException
438 protected function extractParam( $param ) {
439 if ( is_array( $param ) && isset( $param['raw'] ) ) {
440 return array( 'after', $param['raw'] );
441 } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
442 // Replace number params always in before step for now.
443 // No support for combined raw and num params
444 return array( 'before', $this->language
->formatNum( $param['num'] ) );
445 } elseif ( !is_array( $param ) ) {
446 return array( 'before', $param );
448 throw new MWException( "Invalid message parameter" );
453 * Wrapper for what ever method we use to parse wikitext.
454 * @param $string String: Wikitext message contents
455 * @return string Wikitext parsed into HTML
457 protected function parseText( $string ) {
458 return MessageCache
::singleton()->parse( $string, $this->title
, /*linestart*/true, $this->interface, $this->language
)->getText();
462 * Wrapper for what ever method we use to {{-transform wikitext.
463 * @param $string String: Wikitext message contents
464 * @return string Wikitext with {{-constructs replaced with their values.
466 protected function transformText( $string ) {
467 return MessageCache
::singleton()->transform( $string, $this->interface, $this->language
, $this->title
);
471 * Returns the textual value for the message.
472 * @return Message contents or placeholder
474 protected function getMessageText() {
475 $message = $this->fetchMessage();
476 if ( $message === false ) {
477 return '<' . htmlspecialchars( is_array($this->key
) ?
$this->key
[0] : $this->key
) . '>';
484 * Wrapper for what ever method we use to get message contents
488 protected function fetchMessage() {
489 if ( !isset( $this->message
) ) {
490 $cache = MessageCache
::singleton();
491 if ( is_array($this->key
) ) {
492 foreach ( $this->key
as $key ) {
493 $message = $cache->get( $key, $this->useDatabase
, $this->language
);
494 if ( $message !== false && $message !== '' ) {
498 $this->message
= $message;
500 $this->message
= $cache->get( $this->key
, $this->useDatabase
, $this->language
);
503 return $this->message
;