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 ) )
79 * Get a message from i18n
81 * @param $key String: message name
82 * @param $fallback String: default message if the message cache can't be
83 * called by the exception
84 * The function also has other parameters that are arguments for the message
85 * @return String message with arguments replaced
87 function msg( $key, $fallback /*[, params...] */ ) {
88 $args = array_slice( func_get_args(), 2 );
90 if ( $this->useMessageCache() ) {
91 return wfMsgNoTrans( $key, $args );
93 return wfMsgReplaceArgs( $fallback, $args );
98 * If $wgShowExceptionDetails is true, return a HTML message with a
99 * backtrace to the error, otherwise show a message to ask to set it to true
100 * to show that information.
102 * @return String html to output
105 global $wgShowExceptionDetails;
107 if ( $wgShowExceptionDetails ) {
108 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
109 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
112 return "<p>Set <b><tt>\$wgShowExceptionDetails = true;</tt></b> " .
113 "at the bottom of LocalSettings.php to show detailed " .
114 "debugging information.</p>";
119 * If $wgShowExceptionDetails is true, return a text message with a
120 * backtrace to the error.
123 global $wgShowExceptionDetails;
125 if ( $wgShowExceptionDetails ) {
126 return $this->getMessage() .
127 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
129 return "Set \$wgShowExceptionDetails = true; " .
130 "in LocalSettings.php to show detailed debugging information.\n";
135 * Return titles of this error page
138 function getPageTitle() {
140 return $this->msg( 'internalerror', "$wgSitename error" );
144 * Return the requested URL and point to file and line number from which the
149 function getLogMessage() {
152 $file = $this->getFile();
153 $line = $this->getLine();
154 $message = $this->getMessage();
156 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
157 $url = $wgRequest->getRequestURL();
165 return "$url Exception from line $line of $file: $message";
168 /** Output the exception report using HTML */
169 function reportHTML() {
171 if ( $this->useOutputPage() ) {
172 $wgOut->setPageTitle( $this->getPageTitle() );
173 $wgOut->setRobotPolicy( "noindex,nofollow" );
174 $wgOut->setArticleRelated( false );
175 $wgOut->enableClientCache( false );
176 $wgOut->redirect( '' );
179 $hookResult = $this->runHooks( get_class( $this ) );
181 $wgOut->addHTML( $hookResult );
183 $wgOut->addHTML( $this->getHTML() );
188 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
193 echo $this->getHTML();
199 * Output a report about the exception and takes care of formatting.
200 * It will be either HTML or plain text based on isCommandLine().
203 $log = $this->getLogMessage();
206 wfDebugLog( 'exception', $log );
209 if ( self
::isCommandLine() ) {
210 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
{
228 return $this->getMessage();
232 return $this->getMessage();
237 * An error page which can definitely be safely rendered using the OutputPage
240 class ErrorPageError
extends MWException
{
241 public $title, $msg, $params;
244 * Note: these arguments are keys into wfMsg(), not text!
246 function __construct( $title, $msg, $params = null ) {
247 $this->title
= $title;
249 $this->params
= $params;
251 if( $msg instanceof Message
){
252 parent
::__construct( $msg );
254 parent
::__construct( wfMsg( $msg ) );
261 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
267 * Show an error when a user tries to do something they do not have the necessary
271 class PermissionsError
extends ErrorPageError
{
274 function __construct( $permission ) {
277 $this->permission
= $permission;
280 array( 'User', 'makeGroupLinkWiki' ),
281 User
::getGroupsWithPermission( $this->permission
)
289 $wgLang->commaList( $groups ),
303 * Show an error when the wiki is locked/read-only and the user tries to do
304 * something that requires write access
307 class ReadOnlyError
extends ErrorPageError
{
308 public function __construct(){
318 * Show an error when the user hits a rate limit
321 class ThrottledError
extends ErrorPageError
{
322 public function __construct(){
325 'actionthrottledtext'
328 public function report(){
330 $wgOut->setStatusCode( 503 );
331 return parent
::report();
336 * Show an error when the user tries to do something whilst blocked
339 class UserBlockedError
extends ErrorPageError
{
340 public function __construct( Block
$block ){
341 global $wgLang, $wgRequest;
343 $blockerUserpage = $block->getBlocker()->getUserPage();
344 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
346 $reason = $block->mReason
;
347 if( $reason == '' ) {
348 $reason = wfMsg( 'blockednoreason' );
351 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
352 * This could be a username, an IP range, or a single IP. */
353 $intended = $block->getTarget();
357 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
362 $block->getBlocker()->getName(),
364 $wgLang->formatExpiry( $block->mExpiry
),
366 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
373 * Show an error that looks like an HTTP server error.
374 * Replacement for wfHttpError().
378 class HttpError
extends MWException
{
379 private $httpCode, $header, $content;
384 * @param $httpCode Integer: HTTP status code to send to the client
385 * @param $content String|Message: content of the message
386 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
388 public function __construct( $httpCode, $content, $header = null ){
389 parent
::__construct( $content );
390 $this->httpCode
= (int)$httpCode;
391 $this->header
= $header;
392 $this->content
= $content;
395 public function reportHTML() {
396 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
398 header( "Status: {$this->httpCode} {$httpMessage}" );
399 header( 'Content-type: text/html; charset=utf-8' );
401 if ( $this->header
=== null ) {
402 $header = $httpMessage;
403 } elseif ( $this->header
instanceof Message
) {
404 $header = $this->header
->escaped();
406 $header = htmlspecialchars( $this->header
);
409 if ( $this->content
instanceof Message
) {
410 $content = $this->content
->escaped();
412 $content = htmlspecialchars( $this->content
);
415 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
416 "<html><head><title>$header</title></head>\n" .
417 "<body><h1>$header</h1><p>$content</p></body></html>\n";
422 * Handler class for MWExceptions
425 class MWExceptionHandler
{
427 * Install an exception handler for MediaWiki exception types.
429 public static function installHandler() {
430 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
434 * Report an exception to the user
436 protected static function report( Exception
$e ) {
437 global $wgShowExceptionDetails;
439 $cmdLine = MWException
::isCommandLine();
441 if ( $e instanceof MWException
) {
443 // Try and show the exception prettily, with the normal skin infrastructure
445 } catch ( Exception
$e2 ) {
446 // Exception occurred from within exception handler
447 // Show a simpler error message for the original exception,
448 // don't try to invoke report()
449 $message = "MediaWiki internal error.\n\n";
451 if ( $wgShowExceptionDetails ) {
452 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
453 'Exception caught inside exception handler: ' . $e2->__toString();
455 $message .= "Exception caught inside exception handler.\n\n" .
456 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
457 "to show detailed debugging information.";
463 self
::printError( $message );
465 self
::escapeEchoAndDie( $message );
469 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
470 $e->__toString() . "\n";
472 if ( $wgShowExceptionDetails ) {
473 $message .= "\n" . $e->getTraceAsString() . "\n";
477 self
::printError( $message );
479 self
::escapeEchoAndDie( $message );
485 * Print a message, if possible to STDERR.
486 * Use this in command line mode only (see isCommandLine)
487 * @param $message String Failure text
489 public static function printError( $message ) {
490 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
491 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
492 if ( defined( 'STDERR' ) ) {
493 fwrite( STDERR
, $message );
500 * Print a message after escaping it and converting newlines to <br>
501 * Use this for non-command line failures
502 * @param $message String Failure text
504 private static function escapeEchoAndDie( $message ) {
505 echo nl2br( htmlspecialchars( $message ) ) . "\n";
510 * Exception handler which simulates the appropriate catch() handling:
514 * } catch ( MWException $e ) {
516 * } catch ( Exception $e ) {
517 * echo $e->__toString();
520 public static function handle( $e ) {
521 global $wgFullyInitialised;
526 if ( $wgFullyInitialised ) {
528 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
529 } catch ( Exception
$e ) {}
532 // Exit value should be nonzero for the benefit of shell jobs