MediaWiki  master
Status.php
Go to the documentation of this file.
1 <?php
26 
46 class Status extends StatusValue {
48  public $cleanCallback = false;
49 
51  protected $messageLocalizer;
52 
64  public static function wrap( $sv ) {
65  if ( $sv instanceof static ) {
66  return $sv;
67  }
68 
69  $result = new static();
70  $result->ok =& $sv->ok;
71  $result->errors =& $sv->errors;
72  $result->value =& $sv->value;
73  $result->successCount =& $sv->successCount;
74  $result->failCount =& $sv->failCount;
75  $result->success =& $sv->success;
76 
77  return $result;
78  }
79 
87  public function __get( $name ) {
88  if ( $name === 'ok' ) {
89  return $this->isOK();
90  }
91  if ( $name === 'errors' ) {
92  return $this->getErrors();
93  }
94 
95  throw new RuntimeException( "Cannot get '$name' property." );
96  }
97 
106  public function __set( $name, $value ) {
107  if ( $name === 'ok' ) {
108  $this->setOK( $value );
109  } elseif ( !property_exists( $this, $name ) ) {
110  // Caller is using undeclared ad-hoc properties
111  $this->$name = $value;
112  } else {
113  throw new RuntimeException( "Cannot set '$name' property." );
114  }
115  }
116 
128  $this->messageLocalizer = $messageLocalizer;
129  }
130 
142  public function splitByErrorType() {
143  [ $errorsOnlyStatus, $warningsOnlyStatus ] = parent::splitByErrorType();
144  // phan/phan#2133?
145  '@phan-var Status $errorsOnlyStatus';
146  '@phan-var Status $warningsOnlyStatus';
147 
148  if ( $this->messageLocalizer ) {
149  $errorsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
150  $warningsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
151  }
152  $errorsOnlyStatus->cleanCallback =
153  $warningsOnlyStatus->cleanCallback = $this->cleanCallback;
154 
155  return [ $errorsOnlyStatus, $warningsOnlyStatus ];
156  }
157 
163  public function getStatusValue() {
164  return $this;
165  }
166 
171  protected function cleanParams( array $params ) {
172  if ( !$this->cleanCallback ) {
173  return $params;
174  }
175  $cleanParams = [];
176  foreach ( $params as $i => $param ) {
177  $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
178  }
179  return $cleanParams;
180  }
181 
191  public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
192  $rawErrors = $this->getErrors();
193  if ( count( $rawErrors ) === 0 ) {
194  if ( $this->isOK() ) {
195  $this->fatal( 'internalerror_info',
196  __METHOD__ . " called for a good result, this is incorrect\n" );
197  } else {
198  $this->fatal( 'internalerror_info',
199  __METHOD__ . ": Invalid result object: no error text but not OK\n" );
200  }
201  $rawErrors = $this->getErrors(); // just added a fatal
202  }
203  if ( count( $rawErrors ) === 1 ) {
204  $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
205  if ( $shortContext ) {
206  $s = $this->msgInLang( $shortContext, $lang, $s )->plain();
207  } elseif ( $longContext ) {
208  $s = $this->msgInLang( $longContext, $lang, "* $s\n" )->plain();
209  }
210  } else {
211  $errors = $this->getErrorMessageArray( $rawErrors, $lang );
212  foreach ( $errors as &$error ) {
213  $error = $error->plain();
214  }
215  $s = '* ' . implode( "\n* ", $errors ) . "\n";
216  if ( $longContext ) {
217  $s = $this->msgInLang( $longContext, $lang, $s )->plain();
218  } elseif ( $shortContext ) {
219  $s = $this->msgInLang( $shortContext, $lang, "\n$s\n" )->plain();
220  }
221  }
222  return $s;
223  }
224 
245  public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
246  $rawErrors = $this->getErrors();
247  if ( count( $rawErrors ) === 0 ) {
248  if ( $this->isOK() ) {
249  $this->fatal( 'internalerror_info',
250  __METHOD__ . " called for a good result, this is incorrect\n" );
251  } else {
252  $this->fatal( 'internalerror_info',
253  __METHOD__ . ": Invalid result object: no error text but not OK\n" );
254  }
255  $rawErrors = $this->getErrors(); // just added a fatal
256  }
257  if ( count( $rawErrors ) === 1 ) {
258  $s = $this->getErrorMessage( $rawErrors[0], $lang );
259  if ( $shortContext ) {
260  $s = $this->msgInLang( $shortContext, $lang, $s );
261  } elseif ( $longContext ) {
262  $wrapper = new RawMessage( "* \$1\n" );
263  $wrapper->params( $s )->parse();
264  $s = $this->msgInLang( $longContext, $lang, $wrapper );
265  }
266  } else {
267  $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
268  $msgCount = count( $msgs );
269 
270  $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
271  $s->params( $msgs )->parse();
272 
273  if ( $longContext ) {
274  $s = $this->msgInLang( $longContext, $lang, $s );
275  } elseif ( $shortContext ) {
276  $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
277  $wrapper->parse();
278  $s = $this->msgInLang( $shortContext, $lang, $wrapper );
279  }
280  }
281 
282  return $s;
283  }
284 
293  public function getPsr3MessageAndContext(): array {
294  if ( count( $this->errors ) === 1 ) {
295  // identical to getMessage( false, false, 'en' ) when there's just one error
296  $message = $this->getErrorMessage( $this->errors[0], 'en' );
297 
298  $text = null;
299  if ( in_array( get_class( $message ), [ Message::class, ApiMessage::class ], true ) ) {
300  // Fall back to getWikiText for rawmessage, which is just a placeholder for non-translated text.
301  // Turning the entire message into a context parameter wouldn't be useful.
302  if ( $message->getKey() === 'rawmessage' ) {
303  return [ $this->getWikiText( false, false, 'en' ), [] ];
304  }
305  // $1,$2... will be left as-is when no parameters are provided.
306  $text = $this->msgInLang( $message->getKey(), 'en' )->plain();
307  } elseif ( in_array( get_class( $message ), [ RawMessage::class, ApiRawMessage::class ], true ) ) {
308  $text = $message->getKey();
309  } else {
310  // Unknown Message subclass, we can't be sure how it marks parameters. Fall back to getWikiText.
311  return [ $this->getWikiText( false, false, 'en' ), [] ];
312  }
313 
314  $context = [];
315  $i = 1;
316  foreach ( $message->getParams() as $param ) {
317  if ( is_array( $param ) && count( $param ) === 1 ) {
318  // probably Message::numParam() or similar
319  $param = reset( $param );
320  }
321  if ( is_int( $param ) || is_float( $param ) || is_string( $param ) ) {
322  $context["parameter$i"] = $param;
323  } else {
324  // Parameter is not of a safe type, fall back to getWikiText.
325  return [ $this->getWikiText( false, false, 'en' ), [] ];
326  }
327 
328  $text = str_replace( "\$$i", "{parameter$i}", $text );
329 
330  $i++;
331  }
332 
333  return [ $text, $context ];
334  }
335  // Parameters cannot be easily extracted, fall back to getWikiText,
336  return [ $this->getWikiText( false, false, 'en' ), [] ];
337  }
338 
349  protected function getErrorMessage( $error, $lang = null ) {
350  if ( is_array( $error ) ) {
351  if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
352  // Apply context from MessageLocalizer even if we have a Message object already
353  $msg = $this->msg( $error['message'] );
354  } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
355  $msg = $this->msg( $error['message'], array_map( static function ( $param ) {
356  return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
357  }, $this->cleanParams( $error['params'] ) ) );
358  } else {
359  $msgName = array_shift( $error );
360  $msg = $this->msg( $msgName, array_map( static function ( $param ) {
361  return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
362  }, $this->cleanParams( $error ) ) );
363  }
364  } elseif ( is_string( $error ) ) {
365  $msg = $this->msg( $error );
366  } else {
367  throw new UnexpectedValueException( 'Got ' . get_class( $error ) . ' for key.' );
368  }
369 
370  if ( $lang ) {
371  $msg->inLanguage( $lang );
372  }
373  return $msg;
374  }
375 
384  public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
385  $text = $this->getWikiText( $shortContext, $longContext, $lang );
386  $out = MediaWikiServices::getInstance()->getMessageCache()
387  ->parse( $text, null, true, true, $lang );
388  return $out instanceof ParserOutput
389  ? $out->getText( [ 'enableSectionEditLinks' => false ] )
390  : $out;
391  }
392 
399  protected function getErrorMessageArray( $errors, $lang = null ) {
400  return array_map( function ( $e ) use ( $lang ) {
401  return $this->getErrorMessage( $e, $lang );
402  }, $errors );
403  }
404 
412  public function getErrorsArray() {
413  return $this->getStatusArray( 'error' );
414  }
415 
423  public function getWarningsArray() {
424  return $this->getStatusArray( 'warning' );
425  }
426 
434  public function __sleep() {
435  $keys = array_keys( get_object_vars( $this ) );
436  return array_diff( $keys, [ 'cleanCallback', 'messageLocalizer' ] );
437  }
438 
442  public function __wakeup() {
443  $this->cleanCallback = false;
444  $this->messageLocalizer = null;
445  }
446 
452  private function msg( $key, ...$params ): Message {
453  if ( $this->messageLocalizer ) {
454  return $this->messageLocalizer->msg( $key, ...$params );
455  } else {
456  return wfMessage( $key, ...$params );
457  }
458  }
459 
466  private function msgInLang( $key, $lang, ...$params ): Message {
467  $msg = $this->msg( $key, ...$params );
468  if ( $lang ) {
469  $msg->inLanguage( $lang );
470  }
471  return $msg;
472  }
473 }
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
Variant of the Message class.
Definition: RawMessage.php:40
Service locator for MediaWiki core services.
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:835
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
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:46
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:64
setMessageLocalizer(MessageLocalizer $messageLocalizer)
Makes this Status object use the given localizer instead of the global one.
Definition: Status.php:127
getWikiText( $shortContext=false, $longContext=false, $lang=null)
Get the error list as a wikitext formatted list.
Definition: Status.php:191
splitByErrorType()
Splits this Status object into two new Status objects, one which contains only the error messages,...
Definition: Status.php:142
getErrorsArray()
Get the list of errors (but not warnings)
Definition: Status.php:412
getErrorMessage( $error, $lang=null)
Return the message for a single error.
Definition: Status.php:349
callable false $cleanCallback
Definition: Status.php:48
MessageLocalizer null $messageLocalizer
Definition: Status.php:51
getPsr3MessageAndContext()
Try to convert the status to a PSR-3 friendly format.
Definition: Status.php:293
__sleep()
Don't save the callback when serializing, because Closures can't be serialized and we're going to cle...
Definition: Status.php:434
cleanParams(array $params)
Definition: Status.php:171
__set( $name, $value)
Change operation result Backwards compatibility logic.
Definition: Status.php:106
getErrorMessageArray( $errors, $lang=null)
Return an array with a Message object for each error.
Definition: Status.php:399
getWarningsArray()
Get the list of warnings (but not errors)
Definition: Status.php:423
getStatusValue()
Returns the wrapped StatusValue object.
Definition: Status.php:163
getHTML( $shortContext=false, $longContext=false, $lang=null)
Get the error message as HTML.
Definition: Status.php:384
__wakeup()
Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
Definition: Status.php:442
__get( $name)
Backwards compatibility logic.
Definition: Status.php:87
getMessage( $shortContext=false, $longContext=false, $lang=null)
Get a bullet list of the errors as a Message object.
Definition: Status.php:245
Interface for localizing messages in MediaWiki.
if(!isset( $args[0])) $lang