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