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