432b768af26befcf3dc4971a27f070d6603382c0
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 ) && !$wgRequest instanceof FauxRequest
) {
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 * Show an error that looks like an HTTP server error.
371 * Replacement for wfHttpError().
375 class HttpError
extends MWException
{
376 private $httpCode, $header, $content;
381 * @param $httpCode Integer: HTTP status code to send to the client
382 * @param $content String|Message: content of the message
383 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
385 public function __construct( $httpCode, $content, $header = null ){
386 parent
::__construct( $content );
387 $this->httpCode
= (int)$httpCode;
388 $this->header
= $header;
389 $this->content
= $content;
392 public function reportHTML() {
393 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
395 header( "Status: {$this->httpCode} {$httpMessage}" );
396 header( 'Content-type: text/html; charset=utf-8' );
398 if ( $this->header
=== null ) {
399 $header = $httpMessage;
400 } elseif ( $this->header
instanceof Message
) {
401 $header = $this->header
->escaped();
403 $header = htmlspecialchars( $this->header
);
406 if ( $this->content
instanceof Message
) {
407 $content = $this->content
->escaped();
409 $content = htmlspecialchars( $this->content
);
412 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n".
413 "<html><head><title>$header</title></head>\n" .
414 "<body><h1>$header</h1><p>$content</p></body></html>\n";
419 * Handler class for MWExceptions
422 class MWExceptionHandler
{
424 * Install an exception handler for MediaWiki exception types.
426 public static function installHandler() {
427 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
431 * Report an exception to the user
433 protected static function report( Exception
$e ) {
434 global $wgShowExceptionDetails;
436 $cmdLine = MWException
::isCommandLine();
438 if ( $e instanceof MWException
) {
440 // Try and show the exception prettily, with the normal skin infrastructure
442 } catch ( Exception
$e2 ) {
443 // Exception occurred from within exception handler
444 // Show a simpler error message for the original exception,
445 // don't try to invoke report()
446 $message = "MediaWiki internal error.\n\n";
448 if ( $wgShowExceptionDetails ) {
449 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
450 'Exception caught inside exception handler: ' . $e2->__toString();
452 $message .= "Exception caught inside exception handler.\n\n" .
453 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
454 "to show detailed debugging information.";
460 self
::printError( $message );
462 self
::escapeEchoAndDie( $message );
466 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
467 $e->__toString() . "\n";
469 if ( $wgShowExceptionDetails ) {
470 $message .= "\n" . $e->getTraceAsString() . "\n";
474 self
::printError( $message );
476 self
::escapeEchoAndDie( $message );
482 * Print a message, if possible to STDERR.
483 * Use this in command line mode only (see isCommandLine)
484 * @param $message String Failure text
486 public static function printError( $message ) {
487 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
488 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
489 if ( defined( 'STDERR' ) ) {
490 fwrite( STDERR
, $message );
497 * Print a message after escaping it and converting newlines to <br>
498 * Use this for non-command line failures
499 * @param $message String Failure text
501 private static function escapeEchoAndDie( $message ) {
502 echo nl2br( htmlspecialchars( $message ) ) . "\n";
507 * Exception handler which simulates the appropriate catch() handling:
511 * } catch ( MWException $e ) {
513 * } catch ( Exception $e ) {
514 * echo $e->__toString();
517 public static function handle( $e ) {
518 global $wgFullyInitialised;
523 if ( $wgFullyInitialised ) {
525 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
526 } catch ( Exception
$e ) {}
529 // Exit value should be nonzero for the benefit of shell jobs