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