Merge "Convert Special:NewFiles to use OOUI."
[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 * @since 1.27
122 */
123 public function getStatusValue() {
124 return $this->sv;
125 }
126
127 /**
128 * Returns whether the operation completed and didn't have any error or
129 * warnings
130 *
131 * @return bool
132 */
133 public function isGood() {
134 return $this->sv->isGood();
135 }
136
137 /**
138 * Returns whether the operation completed
139 *
140 * @return bool
141 */
142 public function isOK() {
143 return $this->sv->isOK();
144 }
145
146 /**
147 * Add a new warning
148 *
149 * @param string|Message $message Message name or object
150 */
151 public function warning( $message /*, parameters... */ ) {
152 call_user_func_array( [ $this->sv, 'warning' ], func_get_args() );
153 }
154
155 /**
156 * Add an error, do not set fatal flag
157 * This can be used for non-fatal errors
158 *
159 * @param string|Message $message Message name or object
160 */
161 public function error( $message /*, parameters... */ ) {
162 call_user_func_array( [ $this->sv, 'error' ], func_get_args() );
163 }
164
165 /**
166 * Add an error and set OK to false, indicating that the operation
167 * as a whole was fatal
168 *
169 * @param string|Message $message Message name or object
170 */
171 public function fatal( $message /*, parameters... */ ) {
172 call_user_func_array( [ $this->sv, 'fatal' ], func_get_args() );
173 }
174
175 /**
176 * @param array $params
177 * @return array
178 */
179 protected function cleanParams( array $params ) {
180 if ( !$this->cleanCallback ) {
181 return $params;
182 }
183 $cleanParams = [];
184 foreach ( $params as $i => $param ) {
185 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
186 }
187 return $cleanParams;
188 }
189
190 /**
191 * @param string|Language|null $lang Language to use for processing
192 * messages, or null to default to the user language.
193 * @return Language
194 */
195 protected function languageFromParam( $lang ) {
196 global $wgLang;
197
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 );
205 }
206 }
207
208 /**
209 * Get the error list as a wikitext formatted list
210 *
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
216 */
217 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
218 $lang = $this->languageFromParam( $lang );
219
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" );
228 }
229 $rawErrors = $this->sv->getErrors(); // just added a fatal
230 }
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();
237 }
238 } else {
239 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
240 foreach ( $errors as &$error ) {
241 $error = $error->plain();
242 }
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();
248 }
249 }
250 return $s;
251 }
252
253 /**
254 * Get the error list as a Message object
255 *
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
262 */
263 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
264 $lang = $this->languageFromParam( $lang );
265
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" );
274 }
275 $rawErrors = $this->sv->getErrors(); // just added a fatal
276 }
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 );
285 }
286 } else {
287 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
288 $msgCount = count( $msgs );
289
290 if ( $shortContext ) {
291 $msgCount++;
292 }
293
294 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
295 $s->params( $msgs )->parse();
296
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 );
303 }
304 }
305
306 return $s;
307 }
308
309 /**
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
317 */
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 ) ) );
329 }
330 } else {
331 $msg = wfMessage( $error );
332 }
333
334 $msg->inLanguage( $this->languageFromParam( $lang ) );
335 return $msg;
336 }
337
338 /**
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
346 */
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;
352 }
353
354 /**
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[]
359 */
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 );
365 }
366
367 /**
368 * Merge another status object into this one
369 *
370 * @param Status $other Other Status object
371 * @param bool $overwriteValue Whether to override the "value" member
372 */
373 public function merge( $other, $overwriteValue = false ) {
374 $this->sv->merge( $other->sv, $overwriteValue );
375 }
376
377 /**
378 * Get the list of errors (but not warnings)
379 *
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
383 */
384 public function getErrorsArray() {
385 return $this->getStatusArray( 'error' );
386 }
387
388 /**
389 * Get the list of warnings (but not errors)
390 *
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
394 */
395 public function getWarningsArray() {
396 return $this->getStatusArray( 'warning' );
397 }
398
399 /**
400 * Returns a list of status messages of the given type (or all if false)
401 *
402 * @note: this handles RawMessage poorly
403 *
404 * @param string|bool $type
405 * @return array
406 */
407 protected function getStatusArray( $type = false ) {
408 $result = [];
409
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()
416 );
417 } elseif ( $error['params'] ) {
418 $result[] = array_merge( [ $error['message'] ], $error['params'] );
419 } else {
420 $result[] = [ $error['message'] ];
421 }
422 }
423 }
424
425 return $result;
426 }
427
428 /**
429 * Returns a list of status messages of the given type, with message and
430 * params left untouched, like a sane version of getStatusArray
431 *
432 * Each entry is a map of:
433 * - message: string message key or MessageSpecifier
434 * - params: array list of parameters
435 *
436 * @param string $type
437 * @return array
438 */
439 public function getErrorsByType( $type ) {
440 return $this->sv->getErrorsByType( $type );
441 }
442
443 /**
444 * Returns true if the specified message is present as a warning or error
445 *
446 * @param string|Message $message Message key or object to search for
447 *
448 * @return bool
449 */
450 public function hasMessage( $message ) {
451 return $this->sv->hasMessage( $message );
452 }
453
454 /**
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.
457 *
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.
460 *
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.
464 */
465 public function replaceMessage( $source, $dest ) {
466 return $this->sv->replaceMessage( $source, $dest );
467 }
468
469 /**
470 * @return mixed
471 */
472 public function getValue() {
473 return $this->sv->getValue();
474 }
475
476 /**
477 * Backwards compatibility logic
478 *
479 * @param string $name
480 */
481 function __get( $name ) {
482 if ( $name === 'ok' ) {
483 return $this->sv->isOK();
484 } elseif ( $name === 'errors' ) {
485 return $this->sv->getErrors();
486 }
487 throw new Exception( "Cannot get '$name' property." );
488 }
489
490 /**
491 * Backwards compatibility logic
492 *
493 * @param string $name
494 * @param mixed $value
495 */
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." );
504 }
505 }
506
507 /**
508 * @return string
509 */
510 public function __toString() {
511 return $this->sv->__toString();
512 }
513
514 /**
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.
517 */
518 function __sleep() {
519 $keys = array_keys( get_object_vars( $this ) );
520 return array_diff( $keys, [ 'cleanCallback' ] );
521 }
522
523 /**
524 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
525 */
526 function __wakeup() {
527 $this->cleanCallback = false;
528 }
529 }