Fix Bug #30383 for Pg
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * Exception class and handler
4 *
5 * @file
6 */
7
8 /**
9 * @defgroup Exception Exception
10 */
11
12 /**
13 * MediaWiki exception
14 *
15 * @ingroup Exception
16 */
17 class MWException extends Exception {
18 /**
19 * Should the exception use $wgOut to output the error ?
20 * @return bool
21 */
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 !empty( $GLOBALS['wgOut'] ) &&
26 !empty( $GLOBALS['wgTitle'] );
27 }
28
29 /**
30 * Can the extension use wfMsg() to get i18n messages ?
31 * @return bool
32 */
33 function useMessageCache() {
34 global $wgLang;
35
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
38 return false;
39 }
40 }
41
42 return $wgLang instanceof Language;
43 }
44
45 /**
46 * Run hook to allow extensions to modify the text of the exception
47 *
48 * @param $name String: class name of the exception
49 * @param $args Array: arguments to pass to the callback functions
50 * @return Mixed: string to output or null if any hook has been called
51 */
52 function runHooks( $name, $args = array() ) {
53 global $wgExceptionHooks;
54
55 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
56 return; // Just silently ignore
57 }
58
59 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
60 return;
61 }
62
63 $hooks = $wgExceptionHooks[ $name ];
64 $callargs = array_merge( array( $this ), $args );
65
66 foreach ( $hooks as $hook ) {
67 if ( is_string( $hook ) || ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
68 $result = call_user_func_array( $hook, $callargs );
69 } else {
70 $result = null;
71 }
72
73 if ( is_string( $result ) ) {
74 return $result;
75 }
76 }
77 }
78
79 /**
80 * Get a message from i18n
81 *
82 * @param $key String: message name
83 * @param $fallback String: default message if the message cache can't be
84 * called by the exception
85 * The function also has other parameters that are arguments for the message
86 * @return String message with arguments replaced
87 */
88 function msg( $key, $fallback /*[, params...] */ ) {
89 $args = array_slice( func_get_args(), 2 );
90
91 if ( $this->useMessageCache() ) {
92 return wfMsgNoTrans( $key, $args );
93 } else {
94 return wfMsgReplaceArgs( $fallback, $args );
95 }
96 }
97
98 /**
99 * If $wgShowExceptionDetails is true, return a HTML message with a
100 * backtrace to the error, otherwise show a message to ask to set it to true
101 * to show that information.
102 *
103 * @return String html to output
104 */
105 function getHTML() {
106 global $wgShowExceptionDetails;
107
108 if ( $wgShowExceptionDetails ) {
109 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
110 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
111 "</p>\n";
112 } else {
113 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
114 "at the bottom of LocalSettings.php to show detailed " .
115 "debugging information.</p>";
116 }
117 }
118
119 /**
120 * If $wgShowExceptionDetails is true, return a text message with a
121 * backtrace to the error.
122 * @return string
123 */
124 function getText() {
125 global $wgShowExceptionDetails;
126
127 if ( $wgShowExceptionDetails ) {
128 return $this->getMessage() .
129 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
130 } else {
131 return "Set \$wgShowExceptionDetails = true; " .
132 "in LocalSettings.php to show detailed debugging information.\n";
133 }
134 }
135
136 /**
137 * Return titles of this error page
138 * @return String
139 */
140 function getPageTitle() {
141 return $this->msg( 'internalerror', "Internal error" );
142 }
143
144 /**
145 * Return the requested URL and point to file and line number from which the
146 * exception occured
147 *
148 * @return String
149 */
150 function getLogMessage() {
151 global $wgRequest;
152
153 $file = $this->getFile();
154 $line = $this->getLine();
155 $message = $this->getMessage();
156
157 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
158 $url = $wgRequest->getRequestURL();
159 if ( !$url ) {
160 $url = '[no URL]';
161 }
162 } else {
163 $url = '[no req]';
164 }
165
166 return "$url Exception from line $line of $file: $message";
167 }
168
169 /** Output the exception report using HTML */
170 function reportHTML() {
171 global $wgOut;
172 if ( $this->useOutputPage() ) {
173 $wgOut->prepareErrorPage( $this->getPageTitle() );
174
175 $hookResult = $this->runHooks( get_class( $this ) );
176 if ( $hookResult ) {
177 $wgOut->addHTML( $hookResult );
178 } else {
179 $wgOut->addHTML( $this->getHTML() );
180 }
181
182 $wgOut->output();
183 } else {
184 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
185 if ( $hookResult ) {
186 die( $hookResult );
187 }
188
189 echo $this->getHTML();
190 die(1);
191 }
192 }
193
194 /**
195 * Output a report about the exception and takes care of formatting.
196 * It will be either HTML or plain text based on isCommandLine().
197 */
198 function report() {
199 $log = $this->getLogMessage();
200
201 if ( $log ) {
202 wfDebugLog( 'exception', $log );
203 }
204
205 if ( self::isCommandLine() ) {
206 MWExceptionHandler::printError( $this->getText() );
207 } else {
208 $this->reportHTML();
209 }
210 }
211
212 /**
213 * @static
214 * @return bool
215 */
216 static function isCommandLine() {
217 return !empty( $GLOBALS['wgCommandLineMode'] );
218 }
219 }
220
221 /**
222 * Exception class which takes an HTML error message, and does not
223 * produce a backtrace. Replacement for OutputPage::fatalError().
224 * @ingroup Exception
225 */
226 class FatalError extends MWException {
227
228 /**
229 * @return string
230 */
231 function getHTML() {
232 return $this->getMessage();
233 }
234
235 /**
236 * @return string
237 */
238 function getText() {
239 return $this->getMessage();
240 }
241 }
242
243 /**
244 * An error page which can definitely be safely rendered using the OutputPage
245 * @ingroup Exception
246 */
247 class ErrorPageError extends MWException {
248 public $title, $msg, $params;
249
250 /**
251 * Note: these arguments are keys into wfMsg(), not text!
252 */
253 function __construct( $title, $msg, $params = null ) {
254 $this->title = $title;
255 $this->msg = $msg;
256 $this->params = $params;
257
258 if( $msg instanceof Message ){
259 parent::__construct( $msg );
260 } else {
261 parent::__construct( wfMsg( $msg ) );
262 }
263 }
264
265 function report() {
266 global $wgOut;
267
268 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
269 $wgOut->output();
270 }
271 }
272
273 /**
274 * Show an error when a user tries to do something they do not have the necessary
275 * permissions for.
276 * @ingroup Exception
277 */
278 class PermissionsError extends ErrorPageError {
279 public $permission;
280
281 function __construct( $permission ) {
282 global $wgLang;
283
284 $this->permission = $permission;
285
286 $groups = array_map(
287 array( 'User', 'makeGroupLinkWiki' ),
288 User::getGroupsWithPermission( $this->permission )
289 );
290
291 if( $groups ) {
292 parent::__construct(
293 'badaccess',
294 'badaccess-groups',
295 array(
296 $wgLang->commaList( $groups ),
297 count( $groups )
298 )
299 );
300 } else {
301 parent::__construct(
302 'badaccess',
303 'badaccess-group0'
304 );
305 }
306 }
307 }
308
309 /**
310 * Show an error when the wiki is locked/read-only and the user tries to do
311 * something that requires write access
312 * @ingroup Exception
313 */
314 class ReadOnlyError extends ErrorPageError {
315 public function __construct(){
316 parent::__construct(
317 'readonly',
318 'readonlytext',
319 wfReadOnlyReason()
320 );
321 }
322 }
323
324 /**
325 * Show an error when the user hits a rate limit
326 * @ingroup Exception
327 */
328 class ThrottledError extends ErrorPageError {
329 public function __construct(){
330 parent::__construct(
331 'actionthrottled',
332 'actionthrottledtext'
333 );
334 }
335
336 public function report(){
337 global $wgOut;
338 $wgOut->setStatusCode( 503 );
339 return parent::report();
340 }
341 }
342
343 /**
344 * Show an error when the user tries to do something whilst blocked
345 * @ingroup Exception
346 */
347 class UserBlockedError extends ErrorPageError {
348 public function __construct( Block $block ){
349 global $wgLang, $wgRequest;
350
351 $blockerUserpage = $block->getBlocker()->getUserPage();
352 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
353
354 $reason = $block->mReason;
355 if( $reason == '' ) {
356 $reason = wfMsg( 'blockednoreason' );
357 }
358
359 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
360 * This could be a username, an IP range, or a single IP. */
361 $intended = $block->getTarget();
362
363 parent::__construct(
364 'blockedtitle',
365 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
366 array(
367 $link,
368 $reason,
369 $wgRequest->getIP(),
370 $block->getBlocker()->getName(),
371 $block->getId(),
372 $wgLang->formatExpiry( $block->mExpiry ),
373 $intended,
374 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
375 )
376 );
377 }
378 }
379
380 /**
381 * Show an error that looks like an HTTP server error.
382 * Replacement for wfHttpError().
383 *
384 * @ingroup Exception
385 */
386 class HttpError extends MWException {
387 private $httpCode, $header, $content;
388
389 /**
390 * Constructor
391 *
392 * @param $httpCode Integer: HTTP status code to send to the client
393 * @param $content String|Message: content of the message
394 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
395 */
396 public function __construct( $httpCode, $content, $header = null ){
397 parent::__construct( $content );
398 $this->httpCode = (int)$httpCode;
399 $this->header = $header;
400 $this->content = $content;
401 }
402
403 public function reportHTML() {
404 $httpMessage = HttpStatus::getMessage( $this->httpCode );
405
406 header( "Status: {$this->httpCode} {$httpMessage}" );
407 header( 'Content-type: text/html; charset=utf-8' );
408
409 if ( $this->header === null ) {
410 $header = $httpMessage;
411 } elseif ( $this->header instanceof Message ) {
412 $header = $this->header->escaped();
413 } else {
414 $header = htmlspecialchars( $this->header );
415 }
416
417 if ( $this->content instanceof Message ) {
418 $content = $this->content->escaped();
419 } else {
420 $content = htmlspecialchars( $this->content );
421 }
422
423 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
424 "<html><head><title>$header</title></head>\n" .
425 "<body><h1>$header</h1><p>$content</p></body></html>\n";
426 }
427 }
428
429 /**
430 * Handler class for MWExceptions
431 * @ingroup Exception
432 */
433 class MWExceptionHandler {
434 /**
435 * Install an exception handler for MediaWiki exception types.
436 */
437 public static function installHandler() {
438 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
439 }
440
441 /**
442 * Report an exception to the user
443 */
444 protected static function report( Exception $e ) {
445 global $wgShowExceptionDetails;
446
447 $cmdLine = MWException::isCommandLine();
448
449 if ( $e instanceof MWException ) {
450 try {
451 // Try and show the exception prettily, with the normal skin infrastructure
452 $e->report();
453 } catch ( Exception $e2 ) {
454 // Exception occurred from within exception handler
455 // Show a simpler error message for the original exception,
456 // don't try to invoke report()
457 $message = "MediaWiki internal error.\n\n";
458
459 if ( $wgShowExceptionDetails ) {
460 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
461 'Exception caught inside exception handler: ' . $e2->__toString();
462 } else {
463 $message .= "Exception caught inside exception handler.\n\n" .
464 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
465 "to show detailed debugging information.";
466 }
467
468 $message .= "\n";
469
470 if ( $cmdLine ) {
471 self::printError( $message );
472 } else {
473 self::escapeEchoAndDie( $message );
474 }
475 }
476 } else {
477 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
478 $e->__toString() . "\n";
479
480 if ( $wgShowExceptionDetails ) {
481 $message .= "\n" . $e->getTraceAsString() . "\n";
482 }
483
484 if ( $cmdLine ) {
485 self::printError( $message );
486 } else {
487 self::escapeEchoAndDie( $message );
488 }
489 }
490 }
491
492 /**
493 * Print a message, if possible to STDERR.
494 * Use this in command line mode only (see isCommandLine)
495 * @param $message String Failure text
496 */
497 public static function printError( $message ) {
498 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
499 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
500 if ( defined( 'STDERR' ) ) {
501 fwrite( STDERR, $message );
502 } else {
503 echo( $message );
504 }
505 }
506
507 /**
508 * Print a message after escaping it and converting newlines to <br>
509 * Use this for non-command line failures
510 * @param $message String Failure text
511 */
512 private static function escapeEchoAndDie( $message ) {
513 echo nl2br( htmlspecialchars( $message ) ) . "\n";
514 die(1);
515 }
516
517 /**
518 * Exception handler which simulates the appropriate catch() handling:
519 *
520 * try {
521 * ...
522 * } catch ( MWException $e ) {
523 * $e->report();
524 * } catch ( Exception $e ) {
525 * echo $e->__toString();
526 * }
527 */
528 public static function handle( $e ) {
529 global $wgFullyInitialised;
530
531 self::report( $e );
532
533 // Final cleanup
534 if ( $wgFullyInitialised ) {
535 try {
536 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
537 } catch ( Exception $e ) {}
538 }
539
540 // Exit value should be nonzero for the benefit of shell jobs
541 exit( 1 );
542 }
543 }