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.
124 global $wgShowExceptionDetails;
126 if ( $wgShowExceptionDetails ) {
127 return $this->getMessage() .
128 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
130 return "Set \$wgShowExceptionDetails = true; " .
131 "in LocalSettings.php to show detailed debugging information.\n";
136 * Return titles of this error page
139 function getPageTitle() {
141 return $this->msg( 'internalerror', "$wgSitename 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->setPageTitle( $this->getPageTitle() );
174 $wgOut->setRobotPolicy( "noindex,nofollow" );
175 $wgOut->setArticleRelated( false );
176 $wgOut->enableClientCache( false );
177 $wgOut->redirect( '' );
180 $hookResult = $this->runHooks( get_class( $this ) );
182 $wgOut->addHTML( $hookResult );
184 $wgOut->addHTML( $this->getHTML() );
189 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
194 echo $this->getHTML();
200 * Output a report about the exception and takes care of formatting.
201 * It will be either HTML or plain text based on isCommandLine().
204 $log = $this->getLogMessage();
207 wfDebugLog( 'exception', $log );
210 if ( self
::isCommandLine() ) {
211 MWExceptionHandler
::printError( $this->getText() );
217 static function isCommandLine() {
218 return !empty( $GLOBALS['wgCommandLineMode'] );
223 * Exception class which takes an HTML error message, and does not
224 * produce a backtrace. Replacement for OutputPage::fatalError().
227 class FatalError
extends MWException
{
229 return $this->getMessage();
233 return $this->getMessage();
238 * An error page which can definitely be safely rendered using the OutputPage
241 class ErrorPageError
extends MWException
{
242 public $title, $msg, $params;
245 * Note: these arguments are keys into wfMsg(), not text!
247 function __construct( $title, $msg, $params = null ) {
248 $this->title
= $title;
250 $this->params
= $params;
252 if( $msg instanceof Message
){
253 parent
::__construct( $msg );
255 parent
::__construct( wfMsg( $msg ) );
262 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
268 * Show an error when a user tries to do something they do not have the necessary
272 class PermissionsError
extends ErrorPageError
{
275 function __construct( $permission ) {
278 $this->permission
= $permission;
281 array( 'User', 'makeGroupLinkWiki' ),
282 User
::getGroupsWithPermission( $this->permission
)
290 $wgLang->commaList( $groups ),
304 * Show an error when the wiki is locked/read-only and the user tries to do
305 * something that requires write access
308 class ReadOnlyError
extends ErrorPageError
{
309 public function __construct(){
319 * Show an error when the user hits a rate limit
322 class ThrottledError
extends ErrorPageError
{
323 public function __construct(){
326 'actionthrottledtext'
329 public function report(){
331 $wgOut->setStatusCode( 503 );
332 return parent
::report();
337 * Show an error when the user tries to do something whilst blocked
340 class UserBlockedError
extends ErrorPageError
{
341 public function __construct( Block
$block ){
342 global $wgLang, $wgRequest;
344 $blockerUserpage = $block->getBlocker()->getUserPage();
345 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
347 $reason = $block->mReason
;
348 if( $reason == '' ) {
349 $reason = wfMsg( 'blockednoreason' );
352 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
353 * This could be a username, an IP range, or a single IP. */
354 $intended = $block->getTarget();
358 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
363 $block->getBlocker()->getName(),
365 $wgLang->formatExpiry( $block->mExpiry
),
367 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
374 * Show an error that looks like an HTTP server error.
375 * Replacement for wfHttpError().
379 class HttpError
extends MWException
{
380 private $httpCode, $header, $content;
385 * @param $httpCode Integer: HTTP status code to send to the client
386 * @param $content String|Message: content of the message
387 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
389 public function __construct( $httpCode, $content, $header = null ){
390 parent
::__construct( $content );
391 $this->httpCode
= (int)$httpCode;
392 $this->header
= $header;
393 $this->content
= $content;
396 public function reportHTML() {
397 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
399 header( "Status: {$this->httpCode} {$httpMessage}" );
400 header( 'Content-type: text/html; charset=utf-8' );
402 if ( $this->header
=== null ) {
403 $header = $httpMessage;
404 } elseif ( $this->header
instanceof Message
) {
405 $header = $this->header
->escaped();
407 $header = htmlspecialchars( $this->header
);
410 if ( $this->content
instanceof Message
) {
411 $content = $this->content
->escaped();
413 $content = htmlspecialchars( $this->content
);
416 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
417 "<html><head><title>$header</title></head>\n" .
418 "<body><h1>$header</h1><p>$content</p></body></html>\n";
423 * Handler class for MWExceptions
426 class MWExceptionHandler
{
428 * Install an exception handler for MediaWiki exception types.
430 public static function installHandler() {
431 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
435 * Report an exception to the user
437 protected static function report( Exception
$e ) {
438 global $wgShowExceptionDetails;
440 $cmdLine = MWException
::isCommandLine();
442 if ( $e instanceof MWException
) {
444 // Try and show the exception prettily, with the normal skin infrastructure
446 } catch ( Exception
$e2 ) {
447 // Exception occurred from within exception handler
448 // Show a simpler error message for the original exception,
449 // don't try to invoke report()
450 $message = "MediaWiki internal error.\n\n";
452 if ( $wgShowExceptionDetails ) {
453 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
454 'Exception caught inside exception handler: ' . $e2->__toString();
456 $message .= "Exception caught inside exception handler.\n\n" .
457 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
458 "to show detailed debugging information.";
464 self
::printError( $message );
466 self
::escapeEchoAndDie( $message );
470 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
471 $e->__toString() . "\n";
473 if ( $wgShowExceptionDetails ) {
474 $message .= "\n" . $e->getTraceAsString() . "\n";
478 self
::printError( $message );
480 self
::escapeEchoAndDie( $message );
486 * Print a message, if possible to STDERR.
487 * Use this in command line mode only (see isCommandLine)
488 * @param $message String Failure text
490 public static function printError( $message ) {
491 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
492 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
493 if ( defined( 'STDERR' ) ) {
494 fwrite( STDERR
, $message );
501 * Print a message after escaping it and converting newlines to <br>
502 * Use this for non-command line failures
503 * @param $message String Failure text
505 private static function escapeEchoAndDie( $message ) {
506 echo nl2br( htmlspecialchars( $message ) ) . "\n";
511 * Exception handler which simulates the appropriate catch() handling:
515 * } catch ( MWException $e ) {
517 * } catch ( Exception $e ) {
518 * echo $e->__toString();
521 public static function handle( $e ) {
522 global $wgFullyInitialised;
527 if ( $wgFullyInitialised ) {
529 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
530 } catch ( Exception
$e ) {}
533 // Exit value should be nonzero for the benefit of shell jobs