MediaWiki  master
Status.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Status;
24 
25 use ApiMessage;
26 use ApiRawMessage;
27 use Language;
31 use Message;
34 use ParserOutput;
35 use RuntimeException;
36 use StatusValue;
37 use UnexpectedValueException;
38 
58 class Status extends StatusValue {
60  public $cleanCallback = false;
61 
63  protected $messageLocalizer;
64 
76  public static function wrap( $sv ) {
77  if ( $sv instanceof static ) {
78  return $sv;
79  }
80 
81  $result = new static();
82  $result->ok =& $sv->ok;
83  $result->errors =& $sv->errors;
84  $result->value =& $sv->value;
85  $result->successCount =& $sv->successCount;
86  $result->failCount =& $sv->failCount;
87  $result->success =& $sv->success;
88 
89  return $result;
90  }
91 
99  public function __get( $name ) {
100  if ( $name === 'ok' ) {
101  return $this->isOK();
102  }
103  if ( $name === 'errors' ) {
104  return $this->getErrors();
105  }
106 
107  throw new RuntimeException( "Cannot get '$name' property." );
108  }
109 
118  public function __set( $name, $value ) {
119  if ( $name === 'ok' ) {
120  $this->setOK( $value );
121  } elseif ( !property_exists( $this, $name ) ) {
122  // Caller is using undeclared ad-hoc properties
123  $this->$name = $value;
124  } else {
125  throw new RuntimeException( "Cannot set '$name' property." );
126  }
127  }
128 
140  $this->messageLocalizer = $messageLocalizer;
141  }
142 
154  public function splitByErrorType() {
155  [ $errorsOnlyStatus, $warningsOnlyStatus ] = parent::splitByErrorType();
156  // phan/phan#2133?
157  '@phan-var Status $errorsOnlyStatus';
158  '@phan-var Status $warningsOnlyStatus';
159 
160  if ( $this->messageLocalizer ) {
161  $errorsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
162  $warningsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
163  }
164  $errorsOnlyStatus->cleanCallback = $warningsOnlyStatus->cleanCallback = $this->cleanCallback;
165 
166  return [ $errorsOnlyStatus, $warningsOnlyStatus ];
167  }
168 
174  public function getStatusValue() {
175  return $this;
176  }
177 
182  protected function cleanParams( array $params ) {
183  if ( !$this->cleanCallback ) {
184  return $params;
185  }
186  $cleanParams = [];
187  foreach ( $params as $i => $param ) {
188  $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
189  }
190  return $cleanParams;
191  }
192 
202  public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
203  $rawErrors = $this->getErrors();
204  if ( count( $rawErrors ) === 0 ) {
205  if ( $this->isOK() ) {
206  $this->fatal(
207  'internalerror_info',
208  __METHOD__ . " called for a good result, this is incorrect\n"
209  );
210  } else {
211  $this->fatal(
212  'internalerror_info',
213  __METHOD__ . ": Invalid result object: no error text but not OK\n"
214  );
215  }
216  $rawErrors = $this->getErrors(); // just added a fatal
217  }
218  if ( count( $rawErrors ) === 1 ) {
219  $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
220  if ( $shortContext ) {
221  $s = $this->msgInLang( $shortContext, $lang, $s )->plain();
222  } elseif ( $longContext ) {
223  $s = $this->msgInLang( $longContext, $lang, "* $s\n" )->plain();
224  }
225  } else {
226  $errors = $this->getErrorMessageArray( $rawErrors, $lang );
227  foreach ( $errors as &$error ) {
228  $error = $error->plain();
229  }
230  $s = '* ' . implode( "\n* ", $errors ) . "\n";
231  if ( $longContext ) {
232  $s = $this->msgInLang( $longContext, $lang, $s )->plain();
233  } elseif ( $shortContext ) {
234  $s = $this->msgInLang( $shortContext, $lang, "\n$s\n" )->plain();
235  }
236  }
237  return $s;
238  }
239 
260  public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
261  $rawErrors = $this->getErrors();
262  if ( count( $rawErrors ) === 0 ) {
263  if ( $this->isOK() ) {
264  $this->fatal(
265  'internalerror_info',
266  __METHOD__ . " called for a good result, this is incorrect\n"
267  );
268  } else {
269  $this->fatal(
270  'internalerror_info',
271  __METHOD__ . ": Invalid result object: no error text but not OK\n"
272  );
273  }
274  $rawErrors = $this->getErrors(); // just added a fatal
275  }
276  if ( count( $rawErrors ) === 1 ) {
277  $s = $this->getErrorMessage( $rawErrors[0], $lang );
278  if ( $shortContext ) {
279  $s = $this->msgInLang( $shortContext, $lang, $s );
280  } elseif ( $longContext ) {
281  $wrapper = new RawMessage( "* \$1\n" );
282  $wrapper->params( $s )->parse();
283  $s = $this->msgInLang( $longContext, $lang, $wrapper );
284  }
285  } else {
286  $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
287  $msgCount = count( $msgs );
288 
289  $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
290  $s->params( $msgs )->parse();
291 
292  if ( $longContext ) {
293  $s = $this->msgInLang( $longContext, $lang, $s );
294  } elseif ( $shortContext ) {
295  $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
296  $wrapper->parse();
297  $s = $this->msgInLang( $shortContext, $lang, $wrapper );
298  }
299  }
300 
301  return $s;
302  }
303 
312  public function getPsr3MessageAndContext(): array {
313  if ( count( $this->errors ) === 1 ) {
314  // identical to getMessage( false, false, 'en' ) when there's just one error
315  $message = $this->getErrorMessage( $this->errors[0], 'en' );
316 
317  $text = null;
318  if ( in_array( get_class( $message ), [ Message::class, ApiMessage::class ], true ) ) {
319  // Fall back to getWikiText for rawmessage, which is just a placeholder for non-translated text.
320  // Turning the entire message into a context parameter wouldn't be useful.
321  if ( $message->getKey() === 'rawmessage' ) {
322  return [ $this->getWikiText( false, false, 'en' ), [] ];
323  }
324  // $1,$2... will be left as-is when no parameters are provided.
325  $text = $this->msgInLang( $message->getKey(), 'en' )->plain();
326  } elseif ( in_array( get_class( $message ), [ RawMessage::class, ApiRawMessage::class ], true ) ) {
327  $text = $message->getKey();
328  } else {
329  // Unknown Message subclass, we can't be sure how it marks parameters. Fall back to getWikiText.
330  return [ $this->getWikiText( false, false, 'en' ), [] ];
331  }
332 
333  $context = [];
334  $i = 1;
335  foreach ( $message->getParams() as $param ) {
336  if ( is_array( $param ) && count( $param ) === 1 ) {
337  // probably Message::numParam() or similar
338  $param = reset( $param );
339  }
340  if ( is_int( $param ) || is_float( $param ) || is_string( $param ) ) {
341  $context["parameter$i"] = $param;
342  } else {
343  // Parameter is not of a safe type, fall back to getWikiText.
344  return [ $this->getWikiText( false, false, 'en' ), [] ];
345  }
346 
347  $text = str_replace( "\$$i", "{parameter$i}", $text );
348 
349  $i++;
350  }
351 
352  return [ $text, $context ];
353  }
354  // Parameters cannot be easily extracted, fall back to getWikiText,
355  return [ $this->getWikiText( false, false, 'en' ), [] ];
356  }
357 
368  protected function getErrorMessage( $error, $lang = null ) {
369  if ( is_array( $error ) ) {
370  if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
371  // Apply context from MessageLocalizer even if we have a Message object already
372  $msg = $this->msg( $error['message'] );
373  } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
374  $msg = $this->msg(
375  $error['message'],
376  array_map( static function ( $param ) {
377  return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
378  }, $this->cleanParams( $error['params'] ) )
379  );
380  } else {
381  $msgName = array_shift( $error );
382  $msg = $this->msg(
383  $msgName,
384  array_map( static function ( $param ) {
385  return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
386  }, $this->cleanParams( $error ) )
387  );
388  }
389  } elseif ( is_string( $error ) ) {
390  $msg = $this->msg( $error );
391  } else {
392  throw new UnexpectedValueException( 'Got ' . get_class( $error ) . ' for key.' );
393  }
394 
395  if ( $lang ) {
396  $msg->inLanguage( $lang );
397  }
398  return $msg;
399  }
400 
409  public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
410  $text = $this->getWikiText( $shortContext, $longContext, $lang );
411  $out = MediaWikiServices::getInstance()->getMessageCache()
412  ->parse( $text, null, true, true, $lang );
413  return $out instanceof ParserOutput
414  ? $out->getText( [ 'enableSectionEditLinks' => false ] )
415  : $out;
416  }
417 
424  protected function getErrorMessageArray( $errors, $lang = null ) {
425  return array_map( function ( $e ) use ( $lang ) {
426  return $this->getErrorMessage( $e, $lang );
427  }, $errors );
428  }
429 
437  public function getErrorsArray() {
438  return $this->getStatusArray( 'error' );
439  }
440 
448  public function getWarningsArray() {
449  return $this->getStatusArray( 'warning' );
450  }
451 
459  public function __sleep() {
460  $keys = array_keys( get_object_vars( $this ) );
461  return array_diff( $keys, [ 'cleanCallback', 'messageLocalizer' ] );
462  }
463 
467  public function __wakeup() {
468  $this->cleanCallback = false;
469  $this->messageLocalizer = null;
470  }
471 
477  private function msg( $key, ...$params ): Message {
478  if ( $this->messageLocalizer ) {
479  return $this->messageLocalizer->msg( $key, ...$params );
480  } else {
481  return wfMessage( $key, ...$params );
482  }
483  }
484 
491  private function msgInLang( $key, $lang, ...$params ): Message {
492  $msg = $this->msg( $key, ...$params );
493  if ( $lang ) {
494  $msg->inLanguage( $lang );
495  }
496  return $msg;
497  }
498 }
499 
503 class_alias( Status::class, 'Status' );
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
if(!defined('MW_SETUP_CALLBACK'))
Definition: WebStart.php:88
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:29
Extension of RawMessage implementing IApiMessage.
Base class for language-specific code.
Definition: Language.php:61
Variant of the Message class.
Definition: RawMessage.php:40
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:58
getWikiText( $shortContext=false, $longContext=false, $lang=null)
Get the error list as a wikitext formatted list.
Definition: Status.php:202
splitByErrorType()
Splits this Status object into two new Status objects, one which contains only the error messages,...
Definition: Status.php:154
cleanParams(array $params)
Definition: Status.php:182
getWarningsArray()
Get the list of warnings (but not errors)
Definition: Status.php:448
__set( $name, $value)
Change operation result Backwards compatibility logic.
Definition: Status.php:118
getMessage( $shortContext=false, $longContext=false, $lang=null)
Get a bullet list of the errors as a Message object.
Definition: Status.php:260
__sleep()
Don't save the callback when serializing, because Closures can't be serialized and we're going to cle...
Definition: Status.php:459
getErrorMessageArray( $errors, $lang=null)
Return an array with a Message object for each error.
Definition: Status.php:424
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:76
getErrorMessage( $error, $lang=null)
Return the message for a single error.
Definition: Status.php:368
callable false $cleanCallback
Definition: Status.php:60
__wakeup()
Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
Definition: Status.php:467
getHTML( $shortContext=false, $longContext=false, $lang=null)
Get the error message as HTML.
Definition: Status.php:409
getErrorsArray()
Get the list of errors (but not warnings)
Definition: Status.php:437
getStatusValue()
Returns the wrapped StatusValue object.
Definition: Status.php:174
__get( $name)
Backwards compatibility logic.
Definition: Status.php:99
getPsr3MessageAndContext()
Try to convert the status to a PSR-3 friendly format.
Definition: Status.php:312
setMessageLocalizer(MessageLocalizer $messageLocalizer)
Makes this Status object use the given localizer instead of the global one.
Definition: Status.php:139
MessageLocalizer null $messageLocalizer
Definition: Status.php:63
Stub object for the user language.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:144
inLanguage( $lang)
Request the message in any language that is supported.
Definition: Message.php:837
getText( $options=[])
Get the output HTML.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: StatusValue.php:46
array[] $errors
Definition: StatusValue.php:52
getErrors()
Get the list of errors.
setOK( $ok)
Change operation status.
isOK()
Returns whether the operation completed.
fatal( $message,... $parameters)
Add an error and set OK to false, indicating that the operation as a whole was fatal.
mixed $value
Definition: StatusValue.php:55
Interface for localizing messages in MediaWiki.