Don't override action in UI and REDIRECT responses
[mediawiki.git] / includes / Status.php
blobd01f2693f3111337b2082314a632ef6a19430a75
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 /**
24 * Generic operation result class
25 * Has warning/error list, boolean status and arbitrary value
27 * "Good" means the operation was completed with no warnings or errors.
29 * "OK" means the operation was partially or wholly completed.
31 * An operation which is not OK should have errors so that the user can be
32 * informed as to what went wrong. Calling the fatal() function sets an error
33 * message and simultaneously switches off the OK flag.
35 * The recommended pattern for Status objects is to return a Status object
36 * unconditionally, i.e. both on success and on failure -- so that the
37 * developer of the calling code is reminded that the function can fail, and
38 * so that a lack of error-handling will be explicit.
40 class Status {
41 /** @var StatusValue */
42 protected $sv;
44 /** @var mixed */
45 public $value;
46 /** @var array Map of (key => bool) to indicate success of each part of batch operations */
47 public $success = [];
48 /** @var int Counter for batch operations */
49 public $successCount = 0;
50 /** @var int Counter for batch operations */
51 public $failCount = 0;
53 /** @var callable */
54 public $cleanCallback = false;
56 /**
57 * @param StatusValue $sv [optional]
59 public function __construct( StatusValue $sv = null ) {
60 $this->sv = ( $sv === null ) ? new StatusValue() : $sv;
61 // B/C field aliases
62 $this->value =& $this->sv->value;
63 $this->successCount =& $this->sv->successCount;
64 $this->failCount =& $this->sv->failCount;
65 $this->success =& $this->sv->success;
68 /**
69 * Succinct helper method to wrap a StatusValue
71 * This is is useful when formatting StatusValue objects:
72 * @code
73 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
74 * @endcode
76 * @param StatusValue|Status $sv
77 * @return Status
79 public static function wrap( $sv ) {
80 return $sv instanceof Status ? $sv : new self( $sv );
83 /**
84 * Factory function for fatal errors
86 * @param string|Message $message Message name or object
87 * @return Status
89 public static function newFatal( $message /*, parameters...*/ ) {
90 return new self( call_user_func_array(
91 [ 'StatusValue', 'newFatal' ], func_get_args()
92 ) );
95 /**
96 * Factory function for good results
98 * @param mixed $value
99 * @return Status
101 public static function newGood( $value = null ) {
102 $sv = new StatusValue();
103 $sv->value = $value;
105 return new self( $sv );
109 * Change operation result
111 * @param bool $ok Whether the operation completed
112 * @param mixed $value
114 public function setResult( $ok, $value = null ) {
115 $this->sv->setResult( $ok, $value );
119 * Returns the wrapped StatusValue object
120 * @return StatusValue
121 * @since 1.27
123 public function getStatusValue() {
124 return $this->sv;
128 * Returns whether the operation completed and didn't have any error or
129 * warnings
131 * @return bool
133 public function isGood() {
134 return $this->sv->isGood();
138 * Returns whether the operation completed
140 * @return bool
142 public function isOK() {
143 return $this->sv->isOK();
147 * Add a new warning
149 * @param string|Message $message Message name or object
151 public function warning( $message /*, parameters... */ ) {
152 call_user_func_array( [ $this->sv, 'warning' ], func_get_args() );
156 * Add an error, do not set fatal flag
157 * This can be used for non-fatal errors
159 * @param string|Message $message Message name or object
161 public function error( $message /*, parameters... */ ) {
162 call_user_func_array( [ $this->sv, 'error' ], func_get_args() );
166 * Add an error and set OK to false, indicating that the operation
167 * as a whole was fatal
169 * @param string|Message $message Message name or object
171 public function fatal( $message /*, parameters... */ ) {
172 call_user_func_array( [ $this->sv, 'fatal' ], func_get_args() );
176 * @param array $params
177 * @return array
179 protected function cleanParams( array $params ) {
180 if ( !$this->cleanCallback ) {
181 return $params;
183 $cleanParams = [];
184 foreach ( $params as $i => $param ) {
185 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
187 return $cleanParams;
191 * @param string|Language|null $lang Language to use for processing
192 * messages, or null to default to the user language.
193 * @return Language
195 protected function languageFromParam( $lang ) {
196 global $wgLang;
198 if ( $lang === null ) {
199 // @todo: Use RequestContext::getMain()->getLanguage() instead
200 return $wgLang;
201 } elseif ( $lang instanceof Language || $lang instanceof StubUserLang ) {
202 return $lang;
203 } else {
204 return Language::factory( $lang );
209 * Get the error list as a wikitext formatted list
211 * @param string|bool $shortContext A short enclosing context message name, to
212 * be used when there is a single error
213 * @param string|bool $longContext A long enclosing context message name, for a list
214 * @param string|Language $lang Language to use for processing messages
215 * @return string
217 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
218 $lang = $this->languageFromParam( $lang );
220 $rawErrors = $this->sv->getErrors();
221 if ( count( $rawErrors ) == 0 ) {
222 if ( $this->sv->isOK() ) {
223 $this->sv->fatal( 'internalerror_info',
224 __METHOD__ . " called for a good result, this is incorrect\n" );
225 } else {
226 $this->sv->fatal( 'internalerror_info',
227 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
229 $rawErrors = $this->sv->getErrors(); // just added a fatal
231 if ( count( $rawErrors ) == 1 ) {
232 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
233 if ( $shortContext ) {
234 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
235 } elseif ( $longContext ) {
236 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
238 } else {
239 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
240 foreach ( $errors as &$error ) {
241 $error = $error->plain();
243 $s = '* ' . implode( "\n* ", $errors ) . "\n";
244 if ( $longContext ) {
245 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
246 } elseif ( $shortContext ) {
247 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
250 return $s;
254 * Get the error list as a Message object
256 * @param string|string[] $shortContext A short enclosing context message name (or an array of
257 * message names), to be used when there is a single error.
258 * @param string|string[] $longContext A long enclosing context message name (or an array of
259 * message names), for a list.
260 * @param string|Language $lang Language to use for processing messages
261 * @return Message
263 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
264 $lang = $this->languageFromParam( $lang );
266 $rawErrors = $this->sv->getErrors();
267 if ( count( $rawErrors ) == 0 ) {
268 if ( $this->sv->isOK() ) {
269 $this->sv->fatal( 'internalerror_info',
270 __METHOD__ . " called for a good result, this is incorrect\n" );
271 } else {
272 $this->sv->fatal( 'internalerror_info',
273 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
275 $rawErrors = $this->sv->getErrors(); // just added a fatal
277 if ( count( $rawErrors ) == 1 ) {
278 $s = $this->getErrorMessage( $rawErrors[0], $lang );
279 if ( $shortContext ) {
280 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
281 } elseif ( $longContext ) {
282 $wrapper = new RawMessage( "* \$1\n" );
283 $wrapper->params( $s )->parse();
284 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
286 } else {
287 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
288 $msgCount = count( $msgs );
290 if ( $shortContext ) {
291 $msgCount++;
294 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
295 $s->params( $msgs )->parse();
297 if ( $longContext ) {
298 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
299 } elseif ( $shortContext ) {
300 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
301 $wrapper->parse();
302 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
306 return $s;
310 * Return the message for a single error.
311 * @param mixed $error With an array & two values keyed by
312 * 'message' and 'params', use those keys-value pairs.
313 * Otherwise, if its an array, just use the first value as the
314 * message and the remaining items as the params.
315 * @param string|Language $lang Language to use for processing messages
316 * @return Message
318 protected function getErrorMessage( $error, $lang = null ) {
319 if ( is_array( $error ) ) {
320 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
321 $msg = $error['message'];
322 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
323 $msg = wfMessage( $error['message'],
324 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
325 } else {
326 $msgName = array_shift( $error );
327 $msg = wfMessage( $msgName,
328 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
330 } else {
331 $msg = wfMessage( $error );
334 $msg->inLanguage( $this->languageFromParam( $lang ) );
335 return $msg;
339 * Get the error message as HTML. This is done by parsing the wikitext error
340 * message.
341 * @param string $shortContext A short enclosing context message name, to
342 * be used when there is a single error
343 * @param string $longContext A long enclosing context message name, for a list
344 * @param string|Language $lang Language to use for processing messages
345 * @return string
347 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
348 $lang = $this->languageFromParam( $lang );
349 $text = $this->getWikiText( $shortContext, $longContext, $lang );
350 $out = MessageCache::singleton()->parse( $text, null, true, true, $lang );
351 return $out instanceof ParserOutput ? $out->getText() : $out;
355 * Return an array with a Message object for each error.
356 * @param array $errors
357 * @param string|Language $lang Language to use for processing messages
358 * @return Message[]
360 protected function getErrorMessageArray( $errors, $lang = null ) {
361 $lang = $this->languageFromParam( $lang );
362 return array_map( function ( $e ) use ( $lang ) {
363 return $this->getErrorMessage( $e, $lang );
364 }, $errors );
368 * Merge another status object into this one
370 * @param Status $other Other Status object
371 * @param bool $overwriteValue Whether to override the "value" member
373 public function merge( $other, $overwriteValue = false ) {
374 $this->sv->merge( $other->sv, $overwriteValue );
378 * Get the list of errors (but not warnings)
380 * @return array A list in which each entry is an array with a message key as its first element.
381 * The remaining array elements are the message parameters.
382 * @deprecated 1.25
384 public function getErrorsArray() {
385 return $this->getStatusArray( 'error' );
389 * Get the list of warnings (but not errors)
391 * @return array A list in which each entry is an array with a message key as its first element.
392 * The remaining array elements are the message parameters.
393 * @deprecated 1.25
395 public function getWarningsArray() {
396 return $this->getStatusArray( 'warning' );
400 * Returns a list of status messages of the given type (or all if false)
402 * @note: this handles RawMessage poorly
404 * @param string|bool $type
405 * @return array
407 protected function getStatusArray( $type = false ) {
408 $result = [];
410 foreach ( $this->sv->getErrors() as $error ) {
411 if ( $type === false || $error['type'] === $type ) {
412 if ( $error['message'] instanceof MessageSpecifier ) {
413 $result[] = array_merge(
414 [ $error['message']->getKey() ],
415 $error['message']->getParams()
417 } elseif ( $error['params'] ) {
418 $result[] = array_merge( [ $error['message'] ], $error['params'] );
419 } else {
420 $result[] = [ $error['message'] ];
425 return $result;
429 * Returns a list of status messages of the given type, with message and
430 * params left untouched, like a sane version of getStatusArray
432 * Each entry is a map of:
433 * - message: string message key or MessageSpecifier
434 * - params: array list of parameters
436 * @param string $type
437 * @return array
439 public function getErrorsByType( $type ) {
440 return $this->sv->getErrorsByType( $type );
444 * Returns true if the specified message is present as a warning or error
446 * @param string|Message $message Message key or object to search for
448 * @return bool
450 public function hasMessage( $message ) {
451 return $this->sv->hasMessage( $message );
455 * If the specified source message exists, replace it with the specified
456 * destination message, but keep the same parameters as in the original error.
458 * Note, due to the lack of tools for comparing Message objects, this
459 * function will not work when using a Message object as the search parameter.
461 * @param Message|string $source Message key or object to search for
462 * @param Message|string $dest Replacement message key or object
463 * @return bool Return true if the replacement was done, false otherwise.
465 public function replaceMessage( $source, $dest ) {
466 return $this->sv->replaceMessage( $source, $dest );
470 * @return mixed
472 public function getValue() {
473 return $this->sv->getValue();
477 * Backwards compatibility logic
479 * @param string $name
481 function __get( $name ) {
482 if ( $name === 'ok' ) {
483 return $this->sv->isOK();
484 } elseif ( $name === 'errors' ) {
485 return $this->sv->getErrors();
487 throw new Exception( "Cannot get '$name' property." );
491 * Backwards compatibility logic
493 * @param string $name
494 * @param mixed $value
496 function __set( $name, $value ) {
497 if ( $name === 'ok' ) {
498 $this->sv->setOK( $value );
499 } elseif ( !property_exists( $this, $name ) ) {
500 // Caller is using undeclared ad-hoc properties
501 $this->$name = $value;
502 } else {
503 throw new Exception( "Cannot set '$name' property." );
508 * @return string
510 public function __toString() {
511 return $this->sv->__toString();
515 * Don't save the callback when serializing, because Closures can't be
516 * serialized and we're going to clear it in __wakeup anyway.
518 function __sleep() {
519 $keys = array_keys( get_object_vars( $this ) );
520 return array_diff( $keys, [ 'cleanCallback' ] );
524 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
526 function __wakeup() {
527 $this->cleanCallback = false;