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 $html = $this->getHTML();
191 if ( defined( 'MEDIAWIKI_INSTALL' ) ) {
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'] ) && !defined( 'MEDIAWIKI_INSTALL' );
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 if ( $wgOut->getTitle() ) {
263 $wgOut->debug( 'Original title: ' . $wgOut->getTitle()->getPrefixedText() . "\n" );
265 $wgOut->setPageTitle( wfMsg( $this->title
) );
266 $wgOut->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
267 $wgOut->setRobotPolicy( 'noindex,nofollow' );
268 $wgOut->setArticleRelated( false );
269 $wgOut->enableClientCache( false );
270 $wgOut->mRedirect
= '';
273 if( $this->msg
instanceof Message
){
274 $wgOut->addHTML( $this->msg
->parse() );
276 $wgOut->addWikiMsgArray( $this->msg
, $this->params
);
279 $wgOut->returnToMain();
285 * Show an error when a user tries to do something they do not have the necessary
289 class PermissionsError
extends ErrorPageError
{
292 function __construct( $permission ) {
295 $this->permission
= $permission;
298 array( 'User', 'makeGroupLinkWiki' ),
299 User
::getGroupsWithPermission( $this->permission
)
307 $wgLang->commaList( $groups ),
321 * Show an error when the wiki is locked/read-only and the user tries to do
322 * something that requires write access
325 class ReadOnlyError
extends ErrorPageError
{
326 public function __construct(){
336 * Show an error when the user hits a rate limit
339 class ThrottledError
extends ErrorPageError
{
340 public function __construct(){
343 'actionthrottledtext'
346 public function report(){
348 $wgOut->setStatusCode( 503 );
349 return parent
::report();
354 * Show an error when the user tries to do something whilst blocked
357 class UserBlockedError
extends ErrorPageError
{
358 public function __construct( Block
$block ){
361 $blockerUserpage = $block->getBlocker()->getUserPage();
362 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
364 $reason = $block->mReason
;
365 if( $reason == '' ) {
366 $reason = wfMsg( 'blockednoreason' );
369 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
370 * This could be a username, an IP range, or a single IP. */
371 $intended = $block->getTarget();
375 $block->mAuto ?
'autoblocketext' : 'blockedtext',
380 $block->getBlocker()->getName(),
382 $wgLang->formatExpiry( $block->mExpiry
),
384 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
391 * Handler class for MWExceptions
394 class MWExceptionHandler
{
396 * Install an exception handler for MediaWiki exception types.
398 public static function installHandler() {
399 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
403 * Report an exception to the user
405 protected static function report( Exception
$e ) {
406 global $wgShowExceptionDetails;
408 $cmdLine = MWException
::isCommandLine();
410 if ( $e instanceof MWException
) {
412 // Try and show the exception prettily, with the normal skin infrastructure
414 } catch ( Exception
$e2 ) {
415 // Exception occurred from within exception handler
416 // Show a simpler error message for the original exception,
417 // don't try to invoke report()
418 $message = "MediaWiki internal error.\n\n";
420 if ( $wgShowExceptionDetails ) {
421 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
422 'Exception caught inside exception handler: ' . $e2->__toString();
424 $message .= "Exception caught inside exception handler.\n\n" .
425 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
426 "to show detailed debugging information.";
432 self
::printError( $message );
434 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
438 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
439 $e->__toString() . "\n";
441 if ( $wgShowExceptionDetails ) {
442 $message .= "\n" . $e->getTraceAsString() . "\n";
446 self
::printError( $message );
448 wfDie( nl2br( htmlspecialchars( $message ) ) ) . "\n";
454 * Print a message, if possible to STDERR.
455 * Use this in command line mode only (see isCommandLine)
457 public static function printError( $message ) {
458 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
459 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
460 if ( defined( 'STDERR' ) ) {
461 fwrite( STDERR
, $message );
468 * Exception handler which simulates the appropriate catch() handling:
472 * } catch ( MWException $e ) {
474 * } catch ( Exception $e ) {
475 * echo $e->__toString();
478 public static function handle( $e ) {
479 global $wgFullyInitialised;
484 if ( $wgFullyInitialised ) {
486 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
487 } catch ( Exception
$e ) {}
490 // Exit value should be nonzero for the benefit of shell jobs