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