3 * Exception class and handler
9 * @defgroup Exception Exception
17 class MWException
extends Exception
{
21 * Should the exception use $wgOut to output the error ?
24 function useOutputPage() {
25 return $this->useMessageCache() &&
26 !empty( $GLOBALS['wgFullyInitialised'] ) &&
27 !empty( $GLOBALS['wgOut'] ) &&
28 !empty( $GLOBALS['wgTitle'] );
32 * Can the extension use wfMsg() to get i18n messages ?
35 function useMessageCache() {
38 foreach ( $this->getTrace() as $frame ) {
39 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
44 return $wgLang instanceof Language
;
48 * Run hook to allow extensions to modify the text of the exception
50 * @param $name String: class name of the exception
51 * @param $args Array: arguments to pass to the callback functions
52 * @return Mixed: string to output or null if any hook has been called
54 function runHooks( $name, $args = array() ) {
55 global $wgExceptionHooks;
57 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
58 return null; // Just silently ignore
61 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[ $name ] ) ) {
65 $hooks = $wgExceptionHooks[ $name ];
66 $callargs = array_merge( array( $this ), $args );
68 foreach ( $hooks as $hook ) {
69 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
70 $result = call_user_func_array( $hook, $callargs );
75 if ( is_string( $result ) ) {
83 * Get a message from i18n
85 * @param $key String: message name
86 * @param $fallback String: default message if the message cache can't be
87 * called by the exception
88 * The function also has other parameters that are arguments for the message
89 * @return String message with arguments replaced
91 function msg( $key, $fallback /*[, params...] */ ) {
92 $args = array_slice( func_get_args(), 2 );
94 if ( $this->useMessageCache() ) {
95 return wfMsgNoTrans( $key, $args );
97 return wfMsgReplaceArgs( $fallback, $args );
102 * If $wgShowExceptionDetails is true, return a HTML message with a
103 * backtrace to the error, otherwise show a message to ask to set it to true
104 * to show that information.
106 * @return String html to output
109 global $wgShowExceptionDetails;
111 if ( $wgShowExceptionDetails ) {
112 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
113 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
117 "<div class=\"errorbox\">" .
118 '[' . $this->getLogId() . '] ' .
119 gmdate( 'Y-m-d H:i:s' ) .
120 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
121 "<!-- Set \$wgShowExceptionDetails = true; " .
122 "at the bottom of LocalSettings.php to show detailed " .
123 "debugging information. -->";
128 * If $wgShowExceptionDetails is true, return a text message with a
129 * backtrace to the error.
133 global $wgShowExceptionDetails;
135 if ( $wgShowExceptionDetails ) {
136 return $this->getMessage() .
137 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
139 return "Set \$wgShowExceptionDetails = true; " .
140 "in LocalSettings.php to show detailed debugging information.\n";
145 * Return titles of this error page
148 function getPageTitle() {
149 return $this->msg( 'internalerror', "Internal error" );
152 function getLogId() {
153 if ( $this->logId
=== null ) {
154 $this->logId
= wfRandomString( 8 );
160 * Return the requested URL and point to file and line number from which the
165 function getLogMessage() {
168 $id = $this->getLogId();
169 $file = $this->getFile();
170 $line = $this->getLine();
171 $message = $this->getMessage();
173 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
174 $url = $wgRequest->getRequestURL();
182 return "[$id] $url Exception from line $line of $file: $message";
185 /** Output the exception report using HTML */
186 function reportHTML() {
188 if ( $this->useOutputPage() ) {
189 $wgOut->prepareErrorPage( $this->getPageTitle() );
191 $hookResult = $this->runHooks( get_class( $this ) );
193 $wgOut->addHTML( $hookResult );
195 $wgOut->addHTML( $this->getHTML() );
200 header( "Content-Type: text/html; charset=utf-8" );
201 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
206 echo $this->getHTML();
212 * Output a report about the exception and takes care of formatting.
213 * It will be either HTML or plain text based on isCommandLine().
216 global $wgLogExceptionBacktrace;
217 $log = $this->getLogMessage();
220 if ( $wgLogExceptionBacktrace ) {
221 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
223 wfDebugLog( 'exception', $log );
227 if ( defined( 'MW_API' ) ) {
228 // Unhandled API exception, we can't be sure that format printer is alive
229 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
230 wfHttpError(500, 'Internal Server Error', $this->getText() );
231 } elseif ( self
::isCommandLine() ) {
232 MWExceptionHandler
::printError( $this->getText() );
242 static function isCommandLine() {
243 return !empty( $GLOBALS['wgCommandLineMode'] );
248 * Exception class which takes an HTML error message, and does not
249 * produce a backtrace. Replacement for OutputPage::fatalError().
252 class FatalError
extends MWException
{
258 return $this->getMessage();
265 return $this->getMessage();
270 * An error page which can definitely be safely rendered using the OutputPage
273 class ErrorPageError
extends MWException
{
274 public $title, $msg, $params;
277 * Note: these arguments are keys into wfMsg(), not text!
279 function __construct( $title, $msg, $params = null ) {
280 $this->title
= $title;
282 $this->params
= $params;
284 if( $msg instanceof Message
){
285 parent
::__construct( $msg );
287 parent
::__construct( wfMsg( $msg ) );
294 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
300 * Show an error page on a badtitle.
301 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
302 * browser it is not really a valid content.
304 class BadTitleError
extends ErrorPageError
{
307 * @param $msg string A message key (default: 'badtitletext')
308 * @param $params Array parameter to wfMsg()
310 function __construct( $msg = 'badtitletext', $params = null ) {
311 parent
::__construct( 'badtitle', $msg, $params );
315 * Just like ErrorPageError::report() but additionally set
316 * a 400 HTTP status code (bug 33646).
321 // bug 33646: a badtitle error page need to return an error code
322 // to let mobile browser now that it is not a normal page.
323 $wgOut->setStatusCode( 400 );
330 * Show an error when a user tries to do something they do not have the necessary
334 class PermissionsError
extends ErrorPageError
{
335 public $permission, $errors;
337 function __construct( $permission, $errors = array() ) {
340 $this->permission
= $permission;
342 if ( !count( $errors ) ) {
344 array( 'User', 'makeGroupLinkWiki' ),
345 User
::getGroupsWithPermission( $this->permission
)
349 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
351 $errors[] = array( 'badaccess-group0' );
355 $this->errors
= $errors;
361 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
367 * Show an error when the wiki is locked/read-only and the user tries to do
368 * something that requires write access
371 class ReadOnlyError
extends ErrorPageError
{
372 public function __construct(){
382 * Show an error when the user hits a rate limit
385 class ThrottledError
extends ErrorPageError
{
386 public function __construct(){
389 'actionthrottledtext'
393 public function report(){
395 $wgOut->setStatusCode( 503 );
401 * Show an error when the user tries to do something whilst blocked
404 class UserBlockedError
extends ErrorPageError
{
405 public function __construct( Block
$block ){
406 global $wgLang, $wgRequest;
408 $blocker = $block->getBlocker();
409 if ( $blocker instanceof User
) { // local user
410 $blockerUserpage = $block->getBlocker()->getUserPage();
411 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
412 } else { // foreign user
416 $reason = $block->mReason
;
417 if( $reason == '' ) {
418 $reason = wfMsg( 'blockednoreason' );
421 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
422 * This could be a username, an IP range, or a single IP. */
423 $intended = $block->getTarget();
427 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
434 $wgLang->formatExpiry( $block->mExpiry
),
436 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
443 * Show an error that looks like an HTTP server error.
444 * Replacement for wfHttpError().
448 class HttpError
extends MWException
{
449 private $httpCode, $header, $content;
454 * @param $httpCode Integer: HTTP status code to send to the client
455 * @param $content String|Message: content of the message
456 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
458 public function __construct( $httpCode, $content, $header = null ){
459 parent
::__construct( $content );
460 $this->httpCode
= (int)$httpCode;
461 $this->header
= $header;
462 $this->content
= $content;
465 public function reportHTML() {
466 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
468 header( "Status: {$this->httpCode} {$httpMessage}" );
469 header( 'Content-type: text/html; charset=utf-8' );
471 if ( $this->header
=== null ) {
472 $header = $httpMessage;
473 } elseif ( $this->header
instanceof Message
) {
474 $header = $this->header
->escaped();
476 $header = htmlspecialchars( $this->header
);
479 if ( $this->content
instanceof Message
) {
480 $content = $this->content
->escaped();
482 $content = htmlspecialchars( $this->content
);
485 print "<!DOCTYPE html>\n".
486 "<html><head><title>$header</title></head>\n" .
487 "<body><h1>$header</h1><p>$content</p></body></html>\n";
492 * Handler class for MWExceptions
495 class MWExceptionHandler
{
497 * Install an exception handler for MediaWiki exception types.
499 public static function installHandler() {
500 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
504 * Report an exception to the user
506 protected static function report( Exception
$e ) {
507 global $wgShowExceptionDetails;
509 $cmdLine = MWException
::isCommandLine();
511 if ( $e instanceof MWException
) {
513 // Try and show the exception prettily, with the normal skin infrastructure
515 } catch ( Exception
$e2 ) {
516 // Exception occurred from within exception handler
517 // Show a simpler error message for the original exception,
518 // don't try to invoke report()
519 $message = "MediaWiki internal error.\n\n";
521 if ( $wgShowExceptionDetails ) {
522 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
523 'Exception caught inside exception handler: ' . $e2->__toString();
525 $message .= "Exception caught inside exception handler.\n\n" .
526 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
527 "to show detailed debugging information.";
533 self
::printError( $message );
535 self
::escapeEchoAndDie( $message );
539 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
540 $e->__toString() . "\n";
542 if ( $wgShowExceptionDetails ) {
543 $message .= "\n" . $e->getTraceAsString() . "\n";
547 self
::printError( $message );
549 self
::escapeEchoAndDie( $message );
555 * Print a message, if possible to STDERR.
556 * Use this in command line mode only (see isCommandLine)
557 * @param $message String Failure text
559 public static function printError( $message ) {
560 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
561 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
562 if ( defined( 'STDERR' ) ) {
563 fwrite( STDERR
, $message );
570 * Print a message after escaping it and converting newlines to <br>
571 * Use this for non-command line failures
572 * @param $message String Failure text
574 private static function escapeEchoAndDie( $message ) {
575 echo nl2br( htmlspecialchars( $message ) ) . "\n";
580 * Exception handler which simulates the appropriate catch() handling:
584 * } catch ( MWException $e ) {
586 * } catch ( Exception $e ) {
587 * echo $e->__toString();
590 public static function handle( $e ) {
591 global $wgFullyInitialised;
596 if ( $wgFullyInitialised ) {
598 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
599 } catch ( Exception
$e ) {}
602 // Exit value should be nonzero for the benefit of shell jobs