Add Status::getStatusValue()
[lhc/web/wiklou.git] / includes / Status.php
1 <?php
2 /**
3 * Generic operation result.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * Generic operation result class
25 * Has warning/error list, boolean status and arbitrary value
26 *
27 * "Good" means the operation was completed with no warnings or errors.
28 *
29 * "OK" means the operation was partially or wholly completed.
30 *
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.
34 *
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.
39 */
40 class Status {
41 /** @var StatusValue */
42 protected $sv;
43
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;
52
53 /** @var callable */
54 public $cleanCallback = false;
55
56 /**
57 * @param StatusValue $sv [optional]
58 */
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;
66 }
67
68 /**
69 * Succinct helper method to wrap a StatusValue
70 *
71 * This is is useful when formatting StatusValue objects:
72 * @code
73 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
74 * @endcode
75 *
76 * @param StatusValue|Status $sv
77 * @return Status
78 */
79 public static function wrap( $sv ) {
80 return $sv instanceof Status ? $sv : new self( $sv );
81 }
82
83 /**
84 * Factory function for fatal errors
85 *
86 * @param string|Message $message Message name or object
87 * @return Status
88 */
89 public static function newFatal( $message /*, parameters...*/ ) {
90 return new self( call_user_func_array(
91 [ 'StatusValue', 'newFatal' ], func_get_args()
92 ) );
93 }
94
95 /**
96 * Factory function for good results
97 *
98 * @param mixed $value
99 * @return Status
100 */
101 public static function newGood( $value = null ) {
102 $sv = new StatusValue();
103 $sv->value = $value;
104
105 return new self( $sv );
106 }
107
108 /**
109 * Change operation result
110 *
111 * @param bool $ok Whether the operation completed
112 * @param mixed $value
113 */
114 public function setResult( $ok, $value = null ) {
115 $this->sv->setResult( $ok, $value );
116 }
117
118 /**
119 * Returns the wrapped StatusValue object
120 * @return StatusValue
121 */
122 public function getStatusValue() {
123 return $this->sv;
124 }
125
126 /**
127 * Returns whether the operation completed and didn't have any error or
128 * warnings
129 *
130 * @return bool
131 */
132 public function isGood() {
133 return $this->sv->isGood();
134 }
135
136 /**
137 * Returns whether the operation completed
138 *
139 * @return bool
140 */
141 public function isOK() {
142 return $this->sv->isOK();
143 }
144
145 /**
146 * Add a new warning
147 *
148 * @param string|Message $message Message name or object
149 */
150 public function warning( $message /*, parameters... */ ) {
151 call_user_func_array( [ $this->sv, 'warning' ], func_get_args() );
152 }
153
154 /**
155 * Add an error, do not set fatal flag
156 * This can be used for non-fatal errors
157 *
158 * @param string|Message $message Message name or object
159 */
160 public function error( $message /*, parameters... */ ) {
161 call_user_func_array( [ $this->sv, 'error' ], func_get_args() );
162 }
163
164 /**
165 * Add an error and set OK to false, indicating that the operation
166 * as a whole was fatal
167 *
168 * @param string|Message $message Message name or object
169 */
170 public function fatal( $message /*, parameters... */ ) {
171 call_user_func_array( [ $this->sv, 'fatal' ], func_get_args() );
172 }
173
174 /**
175 * @param array $params
176 * @return array
177 */
178 protected function cleanParams( array $params ) {
179 if ( !$this->cleanCallback ) {
180 return $params;
181 }
182 $cleanParams = [];
183 foreach ( $params as $i => $param ) {
184 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
185 }
186 return $cleanParams;
187 }
188
189 /**
190 * @param string|Language|null $lang Language to use for processing
191 * messages, or null to default to the user language.
192 * @return Language
193 */
194 protected function languageFromParam( $lang ) {
195 global $wgLang;
196
197 if ( $lang === null ) {
198 // @todo: Use RequestContext::getMain()->getLanguage() instead
199 return $wgLang;
200 } elseif ( $lang instanceof Language || $lang instanceof StubUserLang ) {
201 return $lang;
202 } else {
203 return Language::factory( $lang );
204 }
205 }
206
207 /**
208 * Get the error list as a wikitext formatted list
209 *
210 * @param string|bool $shortContext A short enclosing context message name, to
211 * be used when there is a single error
212 * @param string|bool $longContext A long enclosing context message name, for a list
213 * @param string|Language $lang Language to use for processing messages
214 * @return string
215 */
216 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
217 $lang = $this->languageFromParam( $lang );
218
219 $rawErrors = $this->sv->getErrors();
220 if ( count( $rawErrors ) == 0 ) {
221 if ( $this->sv->isOK() ) {
222 $this->sv->fatal( 'internalerror_info',
223 __METHOD__ . " called for a good result, this is incorrect\n" );
224 } else {
225 $this->sv->fatal( 'internalerror_info',
226 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
227 }
228 $rawErrors = $this->sv->getErrors(); // just added a fatal
229 }
230 if ( count( $rawErrors ) == 1 ) {
231 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
232 if ( $shortContext ) {
233 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
234 } elseif ( $longContext ) {
235 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
236 }
237 } else {
238 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
239 foreach ( $errors as &$error ) {
240 $error = $error->plain();
241 }
242 $s = '* ' . implode( "\n* ", $errors ) . "\n";
243 if ( $longContext ) {
244 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
245 } elseif ( $shortContext ) {
246 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
247 }
248 }
249 return $s;
250 }
251
252 /**
253 * Get the error list as a Message object
254 *
255 * @param string|string[] $shortContext A short enclosing context message name (or an array of
256 * message names), to be used when there is a single error.
257 * @param string|string[] $longContext A long enclosing context message name (or an array of
258 * message names), for a list.
259 * @param string|Language $lang Language to use for processing messages
260 * @return Message
261 */
262 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
263 $lang = $this->languageFromParam( $lang );
264
265 $rawErrors = $this->sv->getErrors();
266 if ( count( $rawErrors ) == 0 ) {
267 if ( $this->sv->isOK() ) {
268 $this->sv->fatal( 'internalerror_info',
269 __METHOD__ . " called for a good result, this is incorrect\n" );
270 } else {
271 $this->sv->fatal( 'internalerror_info',
272 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
273 }
274 $rawErrors = $this->sv->getErrors(); // just added a fatal
275 }
276 if ( count( $rawErrors ) == 1 ) {
277 $s = $this->getErrorMessage( $rawErrors[0], $lang );
278 if ( $shortContext ) {
279 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
280 } elseif ( $longContext ) {
281 $wrapper = new RawMessage( "* \$1\n" );
282 $wrapper->params( $s )->parse();
283 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
284 }
285 } else {
286 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
287 $msgCount = count( $msgs );
288
289 if ( $shortContext ) {
290 $msgCount++;
291 }
292
293 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
294 $s->params( $msgs )->parse();
295
296 if ( $longContext ) {
297 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
298 } elseif ( $shortContext ) {
299 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
300 $wrapper->parse();
301 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
302 }
303 }
304
305 return $s;
306 }
307
308 /**
309 * Return the message for a single error.
310 * @param mixed $error With an array & two values keyed by
311 * 'message' and 'params', use those keys-value pairs.
312 * Otherwise, if its an array, just use the first value as the
313 * message and the remaining items as the params.
314 * @param string|Language $lang Language to use for processing messages
315 * @return Message
316 */
317 protected function getErrorMessage( $error, $lang = null ) {
318 if ( is_array( $error ) ) {
319 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
320 $msg = $error['message'];
321 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
322 $msg = wfMessage( $error['message'],
323 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
324 } else {
325 $msgName = array_shift( $error );
326 $msg = wfMessage( $msgName,
327 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
328 }
329 } else {
330 $msg = wfMessage( $error );
331 }
332
333 $msg->inLanguage( $this->languageFromParam( $lang ) );
334 return $msg;
335 }
336
337 /**
338 * Get the error message as HTML. This is done by parsing the wikitext error
339 * message.
340 * @param string $shortContext A short enclosing context message name, to
341 * be used when there is a single error
342 * @param string $longContext A long enclosing context message name, for a list
343 * @param string|Language $lang Language to use for processing messages
344 * @return string
345 */
346 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
347 $lang = $this->languageFromParam( $lang );
348 $text = $this->getWikiText( $shortContext, $longContext, $lang );
349 $out = MessageCache::singleton()->parse( $text, null, true, true, $lang );
350 return $out instanceof ParserOutput ? $out->getText() : $out;
351 }
352
353 /**
354 * Return an array with a Message object for each error.
355 * @param array $errors
356 * @param string|Language $lang Language to use for processing messages
357 * @return Message[]
358 */
359 protected function getErrorMessageArray( $errors, $lang = null ) {
360 $lang = $this->languageFromParam( $lang );
361 return array_map( function ( $e ) use ( $lang ) {
362 return $this->getErrorMessage( $e, $lang );
363 }, $errors );
364 }
365
366 /**
367 * Merge another status object into this one
368 *
369 * @param Status $other Other Status object
370 * @param bool $overwriteValue Whether to override the "value" member
371 */
372 public function merge( $other, $overwriteValue = false ) {
373 $this->sv->merge( $other->sv, $overwriteValue );
374 }
375
376 /**
377 * Get the list of errors (but not warnings)
378 *
379 * @return array A list in which each entry is an array with a message key as its first element.
380 * The remaining array elements are the message parameters.
381 * @deprecated 1.25
382 */
383 public function getErrorsArray() {
384 return $this->getStatusArray( 'error' );
385 }
386
387 /**
388 * Get the list of warnings (but not errors)
389 *
390 * @return array A list in which each entry is an array with a message key as its first element.
391 * The remaining array elements are the message parameters.
392 * @deprecated 1.25
393 */
394 public function getWarningsArray() {
395 return $this->getStatusArray( 'warning' );
396 }
397
398 /**
399 * Returns a list of status messages of the given type (or all if false)
400 *
401 * @note: this handles RawMessage poorly
402 *
403 * @param string|bool $type
404 * @return array
405 */
406 protected function getStatusArray( $type = false ) {
407 $result = [];
408
409 foreach ( $this->sv->getErrors() as $error ) {
410 if ( $type === false || $error['type'] === $type ) {
411 if ( $error['message'] instanceof MessageSpecifier ) {
412 $result[] = array_merge(
413 [ $error['message']->getKey() ],
414 $error['message']->getParams()
415 );
416 } elseif ( $error['params'] ) {
417 $result[] = array_merge( [ $error['message'] ], $error['params'] );
418 } else {
419 $result[] = [ $error['message'] ];
420 }
421 }
422 }
423
424 return $result;
425 }
426
427 /**
428 * Returns a list of status messages of the given type, with message and
429 * params left untouched, like a sane version of getStatusArray
430 *
431 * Each entry is a map of:
432 * - message: string message key or MessageSpecifier
433 * - params: array list of parameters
434 *
435 * @param string $type
436 * @return array
437 */
438 public function getErrorsByType( $type ) {
439 return $this->sv->getErrorsByType( $type );
440 }
441
442 /**
443 * Returns true if the specified message is present as a warning or error
444 *
445 * @param string|Message $message Message key or object to search for
446 *
447 * @return bool
448 */
449 public function hasMessage( $message ) {
450 return $this->sv->hasMessage( $message );
451 }
452
453 /**
454 * If the specified source message exists, replace it with the specified
455 * destination message, but keep the same parameters as in the original error.
456 *
457 * Note, due to the lack of tools for comparing Message objects, this
458 * function will not work when using a Message object as the search parameter.
459 *
460 * @param Message|string $source Message key or object to search for
461 * @param Message|string $dest Replacement message key or object
462 * @return bool Return true if the replacement was done, false otherwise.
463 */
464 public function replaceMessage( $source, $dest ) {
465 return $this->sv->replaceMessage( $source, $dest );
466 }
467
468 /**
469 * @return mixed
470 */
471 public function getValue() {
472 return $this->sv->getValue();
473 }
474
475 /**
476 * Backwards compatibility logic
477 *
478 * @param string $name
479 */
480 function __get( $name ) {
481 if ( $name === 'ok' ) {
482 return $this->sv->isOK();
483 } elseif ( $name === 'errors' ) {
484 return $this->sv->getErrors();
485 }
486 throw new Exception( "Cannot get '$name' property." );
487 }
488
489 /**
490 * Backwards compatibility logic
491 *
492 * @param string $name
493 * @param mixed $value
494 */
495 function __set( $name, $value ) {
496 if ( $name === 'ok' ) {
497 $this->sv->setOK( $value );
498 } elseif ( !property_exists( $this, $name ) ) {
499 // Caller is using undeclared ad-hoc properties
500 $this->$name = $value;
501 } else {
502 throw new Exception( "Cannot set '$name' property." );
503 }
504 }
505
506 /**
507 * @return string
508 */
509 public function __toString() {
510 return $this->sv->__toString();
511 }
512
513 /**
514 * Don't save the callback when serializing, because Closures can't be
515 * serialized and we're going to clear it in __wakeup anyway.
516 */
517 function __sleep() {
518 $keys = array_keys( get_object_vars( $this ) );
519 return array_diff( $keys, [ 'cleanCallback' ] );
520 }
521
522 /**
523 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
524 */
525 function __wakeup() {
526 $this->cleanCallback = false;
527 }
528 }