Don't output skinned errors in case of unhandled API exceptions
[mediawiki.git] / includes / Exception.php
blobe7700b51cf438a3a56a3356eff9a9f66ada780ab
1 <?php
2 /**
3 * Exception class and handler
5 * @file
6 */
8 /**
9 * @defgroup Exception Exception
12 /**
13 * MediaWiki exception
15 * @ingroup Exception
17 class MWException extends Exception {
18 /**
19 * Should the exception use $wgOut to output the error ?
20 * @return bool
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 !empty( $GLOBALS['wgOut'] ) &&
26 !empty( $GLOBALS['wgTitle'] );
29 /**
30 * Can the extension use wfMsg() to get i18n messages ?
31 * @return bool
33 function useMessageCache() {
34 global $wgLang;
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
38 return false;
42 return $wgLang instanceof Language;
45 /**
46 * Run hook to allow extensions to modify the text of the exception
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
52 function runHooks( $name, $args = array() ) {
53 global $wgExceptionHooks;
55 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
56 return; // Just silently ignore
59 if ( !array_key_exists( $name, $wgExceptionHooks ) || !is_array( $wgExceptionHooks[ $name ] ) ) {
60 return;
63 $hooks = $wgExceptionHooks[ $name ];
64 $callargs = array_merge( array( $this ), $args );
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;
73 if ( is_string( $result ) ) {
74 return $result;
79 /**
80 * Get a message from i18n
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
88 function msg( $key, $fallback /*[, params...] */ ) {
89 $args = array_slice( func_get_args(), 2 );
91 if ( $this->useMessageCache() ) {
92 return wfMsgNoTrans( $key, $args );
93 } else {
94 return wfMsgReplaceArgs( $fallback, $args );
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.
103 * @return String html to output
105 function getHTML() {
106 global $wgShowExceptionDetails;
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>";
120 * If $wgShowExceptionDetails is true, return a text message with a
121 * backtrace to the error.
122 * @return string
124 function getText() {
125 global $wgShowExceptionDetails;
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";
137 * Return titles of this error page
138 * @return String
140 function getPageTitle() {
141 return $this->msg( 'internalerror', "Internal error" );
145 * Return the requested URL and point to file and line number from which the
146 * exception occured
148 * @return String
150 function getLogMessage() {
151 global $wgRequest;
153 $file = $this->getFile();
154 $line = $this->getLine();
155 $message = $this->getMessage();
157 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest ) {
158 $url = $wgRequest->getRequestURL();
159 if ( !$url ) {
160 $url = '[no URL]';
162 } else {
163 $url = '[no req]';
166 return "$url Exception from line $line of $file: $message";
169 /** Output the exception report using HTML */
170 function reportHTML() {
171 global $wgOut;
172 if ( $this->useOutputPage() ) {
173 $wgOut->prepareErrorPage( $this->getPageTitle() );
175 $hookResult = $this->runHooks( get_class( $this ) );
176 if ( $hookResult ) {
177 $wgOut->addHTML( $hookResult );
178 } else {
179 $wgOut->addHTML( $this->getHTML() );
182 $wgOut->output();
183 } else {
184 header( "Content-Type: text/html; charset=utf-8" );
185 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
186 if ( $hookResult ) {
187 die( $hookResult );
190 echo $this->getHTML();
191 die(1);
196 * Output a report about the exception and takes care of formatting.
197 * It will be either HTML or plain text based on isCommandLine().
199 function report() {
200 $log = $this->getLogMessage();
202 if ( $log ) {
203 wfDebugLog( 'exception', $log );
206 if ( defined( 'MW_API' ) ) {
207 // Unhandled API exception, we can't be sure that format printer is alive
208 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
209 wfHttpError(500, 'Internal Server Error', $this->getText() );
210 } elseif ( self::isCommandLine() ) {
211 MWExceptionHandler::printError( $this->getText() );
212 } else {
213 $this->reportHTML();
218 * @static
219 * @return bool
221 static function isCommandLine() {
222 return !empty( $GLOBALS['wgCommandLineMode'] );
227 * Exception class which takes an HTML error message, and does not
228 * produce a backtrace. Replacement for OutputPage::fatalError().
229 * @ingroup Exception
231 class FatalError extends MWException {
234 * @return string
236 function getHTML() {
237 return $this->getMessage();
241 * @return string
243 function getText() {
244 return $this->getMessage();
249 * An error page which can definitely be safely rendered using the OutputPage
250 * @ingroup Exception
252 class ErrorPageError extends MWException {
253 public $title, $msg, $params;
256 * Note: these arguments are keys into wfMsg(), not text!
258 function __construct( $title, $msg, $params = null ) {
259 $this->title = $title;
260 $this->msg = $msg;
261 $this->params = $params;
263 if( $msg instanceof Message ){
264 parent::__construct( $msg );
265 } else {
266 parent::__construct( wfMsg( $msg ) );
270 function report() {
271 global $wgOut;
274 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
275 $wgOut->output();
280 * Show an error page on a badtitle.
281 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
282 * browser it is not really a valid content.
284 class BadTitleError extends ErrorPageError {
287 * @param $msg string A message key (default: 'badtitletext')
288 * @param $params Array parameter to wfMsg()
290 function __construct( $msg = 'badtitletext', $params = null ) {
291 parent::__construct( 'badtitle', $msg, $params );
295 * Just like ErrorPageError::report() but additionally set
296 * a 400 HTTP status code (bug 33646).
298 function report() {
299 global $wgOut;
301 // bug 33646: a badtitle error page need to return an error code
302 // to let mobile browser now that it is not a normal page.
303 $wgOut->setStatusCode( 400 );
304 parent::report();
310 * Show an error when a user tries to do something they do not have the necessary
311 * permissions for.
312 * @ingroup Exception
314 class PermissionsError extends ErrorPageError {
315 public $permission, $errors;
317 function __construct( $permission, $errors = array() ) {
318 global $wgLang;
320 $this->permission = $permission;
322 if ( !count( $errors ) ) {
323 $groups = array_map(
324 array( 'User', 'makeGroupLinkWiki' ),
325 User::getGroupsWithPermission( $this->permission )
328 if ( $groups ) {
329 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
330 } else {
331 $errors[] = array( 'badaccess-group0' );
335 $this->errors = $errors;
338 function report() {
339 global $wgOut;
341 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
342 $wgOut->output();
347 * Show an error when the wiki is locked/read-only and the user tries to do
348 * something that requires write access
349 * @ingroup Exception
351 class ReadOnlyError extends ErrorPageError {
352 public function __construct(){
353 parent::__construct(
354 'readonly',
355 'readonlytext',
356 wfReadOnlyReason()
362 * Show an error when the user hits a rate limit
363 * @ingroup Exception
365 class ThrottledError extends ErrorPageError {
366 public function __construct(){
367 parent::__construct(
368 'actionthrottled',
369 'actionthrottledtext'
373 public function report(){
374 global $wgOut;
375 $wgOut->setStatusCode( 503 );
376 return parent::report();
381 * Show an error when the user tries to do something whilst blocked
382 * @ingroup Exception
384 class UserBlockedError extends ErrorPageError {
385 public function __construct( Block $block ){
386 global $wgLang, $wgRequest;
388 $blocker = $block->getBlocker();
389 if ( $blocker instanceof User ) { // local user
390 $blockerUserpage = $block->getBlocker()->getUserPage();
391 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
392 } else { // foreign user
393 $link = $blocker;
396 $reason = $block->mReason;
397 if( $reason == '' ) {
398 $reason = wfMsg( 'blockednoreason' );
401 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
402 * This could be a username, an IP range, or a single IP. */
403 $intended = $block->getTarget();
405 parent::__construct(
406 'blockedtitle',
407 $block->mAuto ? 'autoblockedtext' : 'blockedtext',
408 array(
409 $link,
410 $reason,
411 $wgRequest->getIP(),
412 $block->getByName(),
413 $block->getId(),
414 $wgLang->formatExpiry( $block->mExpiry ),
415 $intended,
416 $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true )
423 * Show an error that looks like an HTTP server error.
424 * Replacement for wfHttpError().
426 * @ingroup Exception
428 class HttpError extends MWException {
429 private $httpCode, $header, $content;
432 * Constructor
434 * @param $httpCode Integer: HTTP status code to send to the client
435 * @param $content String|Message: content of the message
436 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
438 public function __construct( $httpCode, $content, $header = null ){
439 parent::__construct( $content );
440 $this->httpCode = (int)$httpCode;
441 $this->header = $header;
442 $this->content = $content;
445 public function reportHTML() {
446 $httpMessage = HttpStatus::getMessage( $this->httpCode );
448 header( "Status: {$this->httpCode} {$httpMessage}" );
449 header( 'Content-type: text/html; charset=utf-8' );
451 if ( $this->header === null ) {
452 $header = $httpMessage;
453 } elseif ( $this->header instanceof Message ) {
454 $header = $this->header->escaped();
455 } else {
456 $header = htmlspecialchars( $this->header );
459 if ( $this->content instanceof Message ) {
460 $content = $this->content->escaped();
461 } else {
462 $content = htmlspecialchars( $this->content );
465 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
466 "<html><head><title>$header</title></head>\n" .
467 "<body><h1>$header</h1><p>$content</p></body></html>\n";
472 * Handler class for MWExceptions
473 * @ingroup Exception
475 class MWExceptionHandler {
477 * Install an exception handler for MediaWiki exception types.
479 public static function installHandler() {
480 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
484 * Report an exception to the user
486 protected static function report( Exception $e ) {
487 global $wgShowExceptionDetails;
489 $cmdLine = MWException::isCommandLine();
491 if ( $e instanceof MWException ) {
492 try {
493 // Try and show the exception prettily, with the normal skin infrastructure
494 $e->report();
495 } catch ( Exception $e2 ) {
496 // Exception occurred from within exception handler
497 // Show a simpler error message for the original exception,
498 // don't try to invoke report()
499 $message = "MediaWiki internal error.\n\n";
501 if ( $wgShowExceptionDetails ) {
502 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
503 'Exception caught inside exception handler: ' . $e2->__toString();
504 } else {
505 $message .= "Exception caught inside exception handler.\n\n" .
506 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
507 "to show detailed debugging information.";
510 $message .= "\n";
512 if ( $cmdLine ) {
513 self::printError( $message );
514 } else {
515 self::escapeEchoAndDie( $message );
518 } else {
519 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
520 $e->__toString() . "\n";
522 if ( $wgShowExceptionDetails ) {
523 $message .= "\n" . $e->getTraceAsString() . "\n";
526 if ( $cmdLine ) {
527 self::printError( $message );
528 } else {
529 self::escapeEchoAndDie( $message );
535 * Print a message, if possible to STDERR.
536 * Use this in command line mode only (see isCommandLine)
537 * @param $message String Failure text
539 public static function printError( $message ) {
540 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
541 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
542 if ( defined( 'STDERR' ) ) {
543 fwrite( STDERR, $message );
544 } else {
545 echo( $message );
550 * Print a message after escaping it and converting newlines to <br>
551 * Use this for non-command line failures
552 * @param $message String Failure text
554 private static function escapeEchoAndDie( $message ) {
555 echo nl2br( htmlspecialchars( $message ) ) . "\n";
556 die(1);
560 * Exception handler which simulates the appropriate catch() handling:
562 * try {
563 * ...
564 * } catch ( MWException $e ) {
565 * $e->report();
566 * } catch ( Exception $e ) {
567 * echo $e->__toString();
570 public static function handle( $e ) {
571 global $wgFullyInitialised;
573 self::report( $e );
575 // Final cleanup
576 if ( $wgFullyInitialised ) {
577 try {
578 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
579 } catch ( Exception $e ) {}
582 // Exit value should be nonzero for the benefit of shell jobs
583 exit( 1 );