3 * Exception class and handler
9 * @defgroup Exception Exception
17 class MWException
extends Exception
{
19 * Should the exception use $wgOut to output the error ?
22 function useOutputPage() {
23 return $this->useMessageCache() &&
24 !empty( $GLOBALS['wgFullyInitialised'] ) &&
25 !empty( $GLOBALS['wgOut'] ) &&
26 !empty( $GLOBALS['wgTitle'] );
30 * Can the extension use wfMsg() to get i18n messages ?
33 function useMessageCache() {
36 foreach ( $this->getTrace() as $frame ) {
37 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
42 return $wgLang instanceof Language
;
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 ] ) ) {
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 );
73 if ( is_string( $result ) ) {
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 );
94 return wfMsgReplaceArgs( $fallback, $args );
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
106 global $wgShowExceptionDetails;
108 if ( $wgShowExceptionDetails ) {
109 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
110 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
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.
125 global $wgShowExceptionDetails;
127 if ( $wgShowExceptionDetails ) {
128 return $this->getMessage() .
129 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
131 return "Set \$wgShowExceptionDetails = true; " .
132 "in LocalSettings.php to show detailed debugging information.\n";
137 * Return titles of this error page
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
150 function getLogMessage() {
153 $file = $this->getFile();
154 $line = $this->getLine();
155 $message = $this->getMessage();
157 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
158 $url = $wgRequest->getRequestURL();
166 return "$url Exception from line $line of $file: $message";
169 /** Output the exception report using HTML */
170 function reportHTML() {
172 if ( $this->useOutputPage() ) {
173 $wgOut->prepareErrorPage( $this->getPageTitle() );
175 $hookResult = $this->runHooks( get_class( $this ) );
177 $wgOut->addHTML( $hookResult );
179 $wgOut->addHTML( $this->getHTML() );
184 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
189 echo $this->getHTML();
195 * Output a report about the exception and takes care of formatting.
196 * It will be either HTML or plain text based on isCommandLine().
199 $log = $this->getLogMessage();
202 wfDebugLog( 'exception', $log );
205 if ( self
::isCommandLine() ) {
206 MWExceptionHandler
::printError( $this->getText() );
216 static function isCommandLine() {
217 return !empty( $GLOBALS['wgCommandLineMode'] );
222 * Exception class which takes an HTML error message, and does not
223 * produce a backtrace. Replacement for OutputPage::fatalError().
226 class FatalError
extends MWException
{
232 return $this->getMessage();
239 return $this->getMessage();
244 * An error page which can definitely be safely rendered using the OutputPage
247 class ErrorPageError
extends MWException
{
248 public $title, $msg, $params;
251 * Note: these arguments are keys into wfMsg(), not text!
253 function __construct( $title, $msg, $params = null ) {
254 $this->title
= $title;
256 $this->params
= $params;
258 if( $msg instanceof Message
){
259 parent
::__construct( $msg );
261 parent
::__construct( wfMsg( $msg ) );
268 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
274 * Show an error when a user tries to do something they do not have the necessary
278 class PermissionsError
extends ErrorPageError
{
281 function __construct( $permission ) {
284 $this->permission
= $permission;
287 array( 'User', 'makeGroupLinkWiki' ),
288 User
::getGroupsWithPermission( $this->permission
)
296 $wgLang->commaList( $groups ),
310 * Show an error when the wiki is locked/read-only and the user tries to do
311 * something that requires write access
314 class ReadOnlyError
extends ErrorPageError
{
315 public function __construct(){
325 * Show an error when the user hits a rate limit
328 class ThrottledError
extends ErrorPageError
{
329 public function __construct(){
332 'actionthrottledtext'
336 public function report(){
338 $wgOut->setStatusCode( 503 );
339 return parent
::report();
344 * Show an error when the user tries to do something whilst blocked
347 class UserBlockedError
extends ErrorPageError
{
348 public function __construct( Block
$block ){
349 global $wgLang, $wgRequest;
351 $blocker = $block->getBlocker();
352 if ( $blocker instanceof User
) { // local user
353 $blockerUserpage = $block->getBlocker()->getUserPage();
354 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
355 } else { // foreign user
359 $reason = $block->mReason
;
360 if( $reason == '' ) {
361 $reason = wfMsg( 'blockednoreason' );
364 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
365 * This could be a username, an IP range, or a single IP. */
366 $intended = $block->getTarget();
370 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
375 $block->getBlocker()->getName(),
377 $wgLang->formatExpiry( $block->mExpiry
),
379 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
386 * Show an error that looks like an HTTP server error.
387 * Replacement for wfHttpError().
391 class HttpError
extends MWException
{
392 private $httpCode, $header, $content;
397 * @param $httpCode Integer: HTTP status code to send to the client
398 * @param $content String|Message: content of the message
399 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
401 public function __construct( $httpCode, $content, $header = null ){
402 parent
::__construct( $content );
403 $this->httpCode
= (int)$httpCode;
404 $this->header
= $header;
405 $this->content
= $content;
408 public function reportHTML() {
409 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
411 header( "Status: {$this->httpCode} {$httpMessage}" );
412 header( 'Content-type: text/html; charset=utf-8' );
414 if ( $this->header
=== null ) {
415 $header = $httpMessage;
416 } elseif ( $this->header
instanceof Message
) {
417 $header = $this->header
->escaped();
419 $header = htmlspecialchars( $this->header
);
422 if ( $this->content
instanceof Message
) {
423 $content = $this->content
->escaped();
425 $content = htmlspecialchars( $this->content
);
428 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
429 "<html><head><title>$header</title></head>\n" .
430 "<body><h1>$header</h1><p>$content</p></body></html>\n";
435 * Handler class for MWExceptions
438 class MWExceptionHandler
{
440 * Install an exception handler for MediaWiki exception types.
442 public static function installHandler() {
443 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
447 * Report an exception to the user
449 protected static function report( Exception
$e ) {
450 global $wgShowExceptionDetails;
452 $cmdLine = MWException
::isCommandLine();
454 if ( $e instanceof MWException
) {
456 // Try and show the exception prettily, with the normal skin infrastructure
458 } catch ( Exception
$e2 ) {
459 // Exception occurred from within exception handler
460 // Show a simpler error message for the original exception,
461 // don't try to invoke report()
462 $message = "MediaWiki internal error.\n\n";
464 if ( $wgShowExceptionDetails ) {
465 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
466 'Exception caught inside exception handler: ' . $e2->__toString();
468 $message .= "Exception caught inside exception handler.\n\n" .
469 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
470 "to show detailed debugging information.";
476 self
::printError( $message );
478 self
::escapeEchoAndDie( $message );
482 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
483 $e->__toString() . "\n";
485 if ( $wgShowExceptionDetails ) {
486 $message .= "\n" . $e->getTraceAsString() . "\n";
490 self
::printError( $message );
492 self
::escapeEchoAndDie( $message );
498 * Print a message, if possible to STDERR.
499 * Use this in command line mode only (see isCommandLine)
500 * @param $message String Failure text
502 public static function printError( $message ) {
503 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
504 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
505 if ( defined( 'STDERR' ) ) {
506 fwrite( STDERR
, $message );
513 * Print a message after escaping it and converting newlines to <br>
514 * Use this for non-command line failures
515 * @param $message String Failure text
517 private static function escapeEchoAndDie( $message ) {
518 echo nl2br( htmlspecialchars( $message ) ) . "\n";
523 * Exception handler which simulates the appropriate catch() handling:
527 * } catch ( MWException $e ) {
529 * } catch ( Exception $e ) {
530 * echo $e->__toString();
533 public static function handle( $e ) {
534 global $wgFullyInitialised;
539 if ( $wgFullyInitialised ) {
541 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
542 } catch ( Exception
$e ) {}
545 // Exit value should be nonzero for the benefit of shell jobs