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";
134 /* Return titles of this error page */
135 function getPageTitle() {
137 return $this->msg( 'internalerror', "$wgSitename error" );
141 * Return the requested URL and point to file and line number from which the
146 function getLogMessage() {
149 $file = $this->getFile();
150 $line = $this->getLine();
151 $message = $this->getMessage();
153 if ( isset( $wgRequest ) ) {
154 $url = $wgRequest->getRequestURL();
162 return "$url Exception from line $line of $file: $message";
165 /** Output the exception report using HTML */
166 function reportHTML() {
168 if ( $this->useOutputPage() ) {
169 $wgOut->setPageTitle( $this->getPageTitle() );
170 $wgOut->setRobotPolicy( "noindex,nofollow" );
171 $wgOut->setArticleRelated( false );
172 $wgOut->enableClientCache( false );
173 $wgOut->redirect( '' );
176 $hookResult = $this->runHooks( get_class( $this ) );
178 $wgOut->addHTML( $hookResult );
180 $wgOut->addHTML( $this->getHTML() );
185 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
190 echo $this->getHTML();
196 * Output a report about the exception and takes care of formatting.
197 * It will be either HTML or plain text based on isCommandLine().
200 $log = $this->getLogMessage();
203 wfDebugLog( 'exception', $log );
206 if ( self
::isCommandLine() ) {
207 MWExceptionHandler
::printError( $this->getText() );
213 static function isCommandLine() {
214 return !empty( $GLOBALS['wgCommandLineMode'] );
219 * Exception class which takes an HTML error message, and does not
220 * produce a backtrace. Replacement for OutputPage::fatalError().
223 class FatalError
extends MWException
{
225 return $this->getMessage();
229 return $this->getMessage();
234 * An error page which can definitely be safely rendered using the OutputPage
237 class ErrorPageError
extends MWException
{
238 public $title, $msg, $params;
241 * Note: these arguments are keys into wfMsg(), not text!
243 function __construct( $title, $msg, $params = null ) {
244 $this->title
= $title;
246 $this->params
= $params;
248 if( $msg instanceof Message
){
249 parent
::__construct( $msg );
251 parent
::__construct( wfMsg( $msg ) );
258 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
264 * Show an error when a user tries to do something they do not have the necessary
268 class PermissionsError
extends ErrorPageError
{
271 function __construct( $permission ) {
274 $this->permission
= $permission;
277 array( 'User', 'makeGroupLinkWiki' ),
278 User
::getGroupsWithPermission( $this->permission
)
286 $wgLang->commaList( $groups ),
300 * Show an error when the wiki is locked/read-only and the user tries to do
301 * something that requires write access
304 class ReadOnlyError
extends ErrorPageError
{
305 public function __construct(){
315 * Show an error when the user hits a rate limit
318 class ThrottledError
extends ErrorPageError
{
319 public function __construct(){
322 'actionthrottledtext'
325 public function report(){
327 $wgOut->setStatusCode( 503 );
328 return parent
::report();
333 * Show an error when the user tries to do something whilst blocked
336 class UserBlockedError
extends ErrorPageError
{
337 public function __construct( Block
$block ){
338 global $wgLang, $wgRequest;
340 $blockerUserpage = $block->getBlocker()->getUserPage();
341 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
343 $reason = $block->mReason
;
344 if( $reason == '' ) {
345 $reason = wfMsg( 'blockednoreason' );
348 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
349 * This could be a username, an IP range, or a single IP. */
350 $intended = $block->getTarget();
354 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
359 $block->getBlocker()->getName(),
361 $wgLang->formatExpiry( $block->mExpiry
),
363 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
370 * Handler class for MWExceptions
373 class MWExceptionHandler
{
375 * Install an exception handler for MediaWiki exception types.
377 public static function installHandler() {
378 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
382 * Report an exception to the user
384 protected static function report( Exception
$e ) {
385 global $wgShowExceptionDetails;
387 $cmdLine = MWException
::isCommandLine();
389 if ( $e instanceof MWException
) {
391 // Try and show the exception prettily, with the normal skin infrastructure
393 } catch ( Exception
$e2 ) {
394 // Exception occurred from within exception handler
395 // Show a simpler error message for the original exception,
396 // don't try to invoke report()
397 $message = "MediaWiki internal error.\n\n";
399 if ( $wgShowExceptionDetails ) {
400 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
401 'Exception caught inside exception handler: ' . $e2->__toString();
403 $message .= "Exception caught inside exception handler.\n\n" .
404 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
405 "to show detailed debugging information.";
411 self
::printError( $message );
413 self
::escapeEchoAndDie( $message );
417 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
418 $e->__toString() . "\n";
420 if ( $wgShowExceptionDetails ) {
421 $message .= "\n" . $e->getTraceAsString() . "\n";
425 self
::printError( $message );
427 self
::escapeEchoAndDie( $message );
433 * Print a message, if possible to STDERR.
434 * Use this in command line mode only (see isCommandLine)
435 * @param $message String Failure text
437 public static function printError( $message ) {
438 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
439 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
440 if ( defined( 'STDERR' ) ) {
441 fwrite( STDERR
, $message );
448 * Print a message after escaping it and converting newlines to <br>
449 * Use this for non-command line failures
450 * @param $message String Failure text
452 private static function escapeEchoAndDie( $message ) {
453 echo nl2br( htmlspecialchars( $message ) ) . "\n";
458 * Exception handler which simulates the appropriate catch() handling:
462 * } catch ( MWException $e ) {
464 * } catch ( Exception $e ) {
465 * echo $e->__toString();
468 public static function handle( $e ) {
469 global $wgFullyInitialised;
474 if ( $wgFullyInitialised ) {
476 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
477 } catch ( Exception
$e ) {}
480 // Exit value should be nonzero for the benefit of shell jobs