Update git submodules
[mediawiki.git] / includes / Status / Status.php
blob63a79e7d56b1840544c0a79a11927f9d0160e1c8
1 <?php
2 /**
3 * Generic operation result.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 namespace MediaWiki\Status;
25 use ApiMessage;
26 use ApiRawMessage;
27 use Language;
28 use MediaWiki\Language\RawMessage;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\StubObject\StubUserLang;
31 use Message;
32 use MessageLocalizer;
33 use MessageSpecifier;
34 use ParserOutput;
35 use RuntimeException;
36 use StatusValue;
37 use UnexpectedValueException;
39 /**
40 * Generic operation result class
41 * Has warning/error list, boolean status and arbitrary value
43 * "Good" means the operation was completed with no warnings or errors.
45 * "OK" means the operation was partially or wholly completed.
47 * An operation which is not OK should have errors so that the user can be
48 * informed as to what went wrong. Calling the fatal() function sets an error
49 * message and simultaneously switches off the OK flag.
51 * The recommended pattern for Status objects is to return a Status object
52 * unconditionally, i.e. both on success and on failure -- so that the
53 * developer of the calling code is reminded that the function can fail, and
54 * so that a lack of error-handling will be explicit.
56 * @newable
58 class Status extends StatusValue {
59 /** @var callable|false */
60 public $cleanCallback = false;
62 /** @var MessageLocalizer|null */
63 protected $messageLocalizer;
65 /**
66 * Succinct helper method to wrap a StatusValue
68 * This is useful when formatting StatusValue objects:
69 * @code
70 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
71 * @endcode
73 * @param StatusValue|Status $sv
74 * @return Status
76 public static function wrap( $sv ) {
77 if ( $sv instanceof static ) {
78 return $sv;
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 $result->statusData =& $sv->statusData;
90 return $result;
93 /**
94 * Backwards compatibility logic
96 * @param string $name
97 * @return mixed
98 * @throws RuntimeException
100 public function __get( $name ) {
101 if ( $name === 'ok' ) {
102 return $this->isOK();
104 if ( $name === 'errors' ) {
105 return $this->getErrors();
108 throw new RuntimeException( "Cannot get '$name' property." );
112 * Change operation result
113 * Backwards compatibility logic
115 * @param string $name
116 * @param mixed $value
117 * @throws RuntimeException
119 public function __set( $name, $value ) {
120 if ( $name === 'ok' ) {
121 $this->setOK( $value );
122 } elseif ( !property_exists( $this, $name ) ) {
123 // Caller is using undeclared ad-hoc properties
124 $this->$name = $value;
125 } else {
126 throw new RuntimeException( "Cannot set '$name' property." );
131 * Makes this Status object use the given localizer instead of the global one.
132 * If it is an IContextSource or a ResourceLoader Context, it will also be used to
133 * determine the interface language.
134 * @note This setting does not survive serialization. That's usually for the best
135 * (there's no guarantee we'll still have the same localization settings after
136 * unserialization); it is the caller's responsibility to set the localizer again
137 * if needed.
138 * @param MessageLocalizer $messageLocalizer
140 public function setMessageLocalizer( MessageLocalizer $messageLocalizer ) {
141 $this->messageLocalizer = $messageLocalizer;
145 * Splits this Status object into two new Status objects, one which contains only
146 * the error messages, and one that contains the warnings, only. The returned array is
147 * defined as:
149 * 0 => object(Status) # The Status with error messages, only
150 * 1 => object(Status) # The Status with warning messages, only
153 * @return Status[]
155 public function splitByErrorType() {
156 [ $errorsOnlyStatus, $warningsOnlyStatus ] = parent::splitByErrorType();
157 // phan/phan#2133?
158 '@phan-var Status $errorsOnlyStatus';
159 '@phan-var Status $warningsOnlyStatus';
161 if ( $this->messageLocalizer ) {
162 $errorsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
163 $warningsOnlyStatus->setMessageLocalizer( $this->messageLocalizer );
165 $errorsOnlyStatus->cleanCallback = $warningsOnlyStatus->cleanCallback = $this->cleanCallback;
167 return [ $errorsOnlyStatus, $warningsOnlyStatus ];
171 * Returns the wrapped StatusValue object
172 * @return StatusValue
173 * @since 1.27
175 public function getStatusValue() {
176 return $this;
180 * @param array $params
181 * @return array
183 protected function cleanParams( array $params ) {
184 if ( !$this->cleanCallback ) {
185 return $params;
187 $cleanParams = [];
188 foreach ( $params as $i => $param ) {
189 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
191 return $cleanParams;
195 * Get the error list as a wikitext formatted list
197 * @param string|false $shortContext A short enclosing context message name, to
198 * be used when there is a single error
199 * @param string|false $longContext A long enclosing context message name, for a list
200 * @param string|Language|StubUserLang|null $lang Language to use for processing messages
201 * @return string
203 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
204 $rawErrors = $this->getErrors();
205 if ( count( $rawErrors ) === 0 ) {
206 if ( $this->isOK() ) {
207 $this->fatal(
208 'internalerror_info',
209 __METHOD__ . " called for a good result, this is incorrect\n"
211 } else {
212 $this->fatal(
213 'internalerror_info',
214 __METHOD__ . ": Invalid result object: no error text but not OK\n"
217 $rawErrors = $this->getErrors(); // just added a fatal
219 if ( count( $rawErrors ) === 1 ) {
220 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
221 if ( $shortContext ) {
222 $s = $this->msgInLang( $shortContext, $lang, $s )->plain();
223 } elseif ( $longContext ) {
224 $s = $this->msgInLang( $longContext, $lang, "* $s\n" )->plain();
226 } else {
227 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
228 foreach ( $errors as &$error ) {
229 $error = $error->plain();
231 $s = '* ' . implode( "\n* ", $errors ) . "\n";
232 if ( $longContext ) {
233 $s = $this->msgInLang( $longContext, $lang, $s )->plain();
234 } elseif ( $shortContext ) {
235 $s = $this->msgInLang( $shortContext, $lang, "\n$s\n" )->plain();
238 return $s;
242 * Get a bullet list of the errors as a Message object.
244 * $shortContext and $longContext can be used to wrap the error list in some text.
245 * $shortContext will be preferred when there is a single error; $longContext will be
246 * preferred when there are multiple ones. In either case, $1 will be replaced with
247 * the list of errors.
249 * $shortContext is assumed to use $1 as an inline parameter: if there is a single item,
250 * it will not be made into a list; if there are multiple items, newlines will be inserted
251 * around the list.
252 * $longContext is assumed to use $1 as a standalone parameter; it will always receive a list.
254 * If both parameters are missing, and there is only one error, no bullet will be added.
256 * @param string|string[]|false $shortContext A message name or an array of message names.
257 * @param string|string[]|false $longContext A message name or an array of message names.
258 * @param string|Language|StubUserLang|null $lang Language to use for processing messages
259 * @return Message
261 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
262 $rawErrors = $this->getErrors();
263 if ( count( $rawErrors ) === 0 ) {
264 if ( $this->isOK() ) {
265 $this->fatal(
266 'internalerror_info',
267 __METHOD__ . " called for a good result, this is incorrect\n"
269 } else {
270 $this->fatal(
271 'internalerror_info',
272 __METHOD__ . ": Invalid result object: no error text but not OK\n"
275 $rawErrors = $this->getErrors(); // just added a fatal
277 if ( count( $rawErrors ) === 1 ) {
278 $s = $this->getErrorMessage( $rawErrors[0], $lang );
279 if ( $shortContext ) {
280 $s = $this->msgInLang( $shortContext, $lang, $s );
281 } elseif ( $longContext ) {
282 $wrapper = new RawMessage( "* \$1\n" );
283 $wrapper->params( $s )->parse();
284 $s = $this->msgInLang( $longContext, $lang, $wrapper );
286 } else {
287 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
288 $msgCount = count( $msgs );
290 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
291 $s->params( $msgs )->parse();
293 if ( $longContext ) {
294 $s = $this->msgInLang( $longContext, $lang, $s );
295 } elseif ( $shortContext ) {
296 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
297 $wrapper->parse();
298 $s = $this->msgInLang( $shortContext, $lang, $wrapper );
302 return $s;
306 * Try to convert the status to a PSR-3 friendly format. The output will be similar to
307 * getWikiText( false, false, 'en' ), but message parameters will be extracted into the
308 * context array with parameter names 'parameter1' etc. when possible.
310 * @return array A pair of (message, context) suitable for passing to a PSR-3 logger.
311 * @phan-return array{0:string,1:(int|float|string)[]}
313 public function getPsr3MessageAndContext(): array {
314 if ( count( $this->errors ) === 1 ) {
315 // identical to getMessage( false, false, 'en' ) when there's just one error
316 $message = $this->getErrorMessage( $this->errors[0], 'en' );
318 $text = null;
319 if ( in_array( get_class( $message ), [ Message::class, ApiMessage::class ], true ) ) {
320 // Fall back to getWikiText for rawmessage, which is just a placeholder for non-translated text.
321 // Turning the entire message into a context parameter wouldn't be useful.
322 if ( $message->getKey() === 'rawmessage' ) {
323 return [ $this->getWikiText( false, false, 'en' ), [] ];
325 // $1,$2... will be left as-is when no parameters are provided.
326 $text = $this->msgInLang( $message->getKey(), 'en' )->plain();
327 } elseif ( in_array( get_class( $message ), [ RawMessage::class, ApiRawMessage::class ], true ) ) {
328 $text = $message->getKey();
329 } else {
330 // Unknown Message subclass, we can't be sure how it marks parameters. Fall back to getWikiText.
331 return [ $this->getWikiText( false, false, 'en' ), [] ];
334 $context = [];
335 $i = 1;
336 foreach ( $message->getParams() as $param ) {
337 if ( is_array( $param ) && count( $param ) === 1 ) {
338 // probably Message::numParam() or similar
339 $param = reset( $param );
341 if ( is_int( $param ) || is_float( $param ) || is_string( $param ) ) {
342 $context["parameter$i"] = $param;
343 } else {
344 // Parameter is not of a safe type, fall back to getWikiText.
345 return [ $this->getWikiText( false, false, 'en' ), [] ];
348 $text = str_replace( "\$$i", "{parameter$i}", $text );
350 $i++;
353 return [ $text, $context ];
355 // Parameters cannot be easily extracted, fall back to getWikiText,
356 return [ $this->getWikiText( false, false, 'en' ), [] ];
360 * Return the message for a single error
362 * The code string can be used a message key with per-language versions.
363 * If $error is an array, the "params" field is a list of parameters for the message.
365 * @param array|string $error Code string or (key: code string, params: string[]) map
366 * @param string|Language|StubUserLang|null $lang Language to use for processing messages
367 * @return Message
369 protected function getErrorMessage( $error, $lang = null ) {
370 if ( is_array( $error ) ) {
371 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
372 // Apply context from MessageLocalizer even if we have a Message object already
373 $msg = $this->msg( $error['message'] );
374 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
375 $msg = $this->msg(
376 $error['message'],
377 array_map( static function ( $param ) {
378 return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
379 }, $this->cleanParams( $error['params'] ) )
381 } else {
382 $msgName = array_shift( $error );
383 $msg = $this->msg(
384 $msgName,
385 array_map( static function ( $param ) {
386 return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
387 }, $this->cleanParams( $error ) )
390 } elseif ( is_string( $error ) ) {
391 $msg = $this->msg( $error );
392 } else {
393 throw new UnexpectedValueException( 'Got ' . get_class( $error ) . ' for key.' );
396 if ( $lang ) {
397 $msg->inLanguage( $lang );
399 return $msg;
403 * Get the error message as HTML. This is done by parsing the wikitext error message
404 * @param string|false $shortContext A short enclosing context message name, to
405 * be used when there is a single error
406 * @param string|false $longContext A long enclosing context message name, for a list
407 * @param string|Language|StubUserLang|null $lang Language to use for processing messages
408 * @return string
410 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
411 $text = $this->getWikiText( $shortContext, $longContext, $lang );
412 $out = MediaWikiServices::getInstance()->getMessageCache()
413 ->parse( $text, null, true, true, $lang );
414 return $out instanceof ParserOutput
415 ? $out->getText( [ 'enableSectionEditLinks' => false ] )
416 : $out;
420 * Return an array with a Message object for each error.
421 * @param array $errors
422 * @param string|Language|StubUserLang|null $lang Language to use for processing messages
423 * @return Message[]
425 protected function getErrorMessageArray( $errors, $lang = null ) {
426 return array_map( function ( $e ) use ( $lang ) {
427 return $this->getErrorMessage( $e, $lang );
428 }, $errors );
432 * Get the list of errors (but not warnings)
434 * @return array[] A list in which each entry is an array with a message key as its first element.
435 * The remaining array elements are the message parameters.
436 * @phan-return non-empty-array[]
438 public function getErrorsArray() {
439 return $this->getStatusArray( 'error' );
443 * Get the list of warnings (but not errors)
445 * @return array[] A list in which each entry is an array with a message key as its first element.
446 * The remaining array elements are the message parameters.
447 * @phan-return non-empty-array[]
449 public function getWarningsArray() {
450 return $this->getStatusArray( 'warning' );
454 * Don't save the callback when serializing, because Closures can't be
455 * serialized and we're going to clear it in __wakeup anyway.
456 * Don't save the localizer, because it can be pretty much anything. Restoring it is
457 * the caller's responsibility (otherwise it will just fall back to the global request context).
458 * @return array
460 public function __sleep() {
461 $keys = array_keys( get_object_vars( $this ) );
462 return array_diff( $keys, [ 'cleanCallback', 'messageLocalizer' ] );
466 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
468 public function __wakeup() {
469 $this->cleanCallback = false;
470 $this->messageLocalizer = null;
474 * @param string|MessageSpecifier $key
475 * @param string|string[] ...$params
476 * @return Message
478 private function msg( $key, ...$params ): Message {
479 if ( $this->messageLocalizer ) {
480 return $this->messageLocalizer->msg( $key, ...$params );
481 } else {
482 return wfMessage( $key, ...$params );
487 * @param string|MessageSpecifier $key
488 * @param string|Language|StubUserLang|null $lang
489 * @param mixed ...$params
490 * @return Message
492 private function msgInLang( $key, $lang, ...$params ): Message {
493 $msg = $this->msg( $key, ...$params );
494 if ( $lang ) {
495 $msg->inLanguage( $lang );
497 return $msg;
502 * @deprecated since 1.41
504 class_alias( Status::class, 'Status' );