3 * Exception class and handler.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * @defgroup Exception Exception
32 class MWException
extends Exception
{
36 * Should the exception use $wgOut to output the error ?
39 function useOutputPage() {
40 return $this->useMessageCache() &&
41 !empty( $GLOBALS['wgFullyInitialised'] ) &&
42 !empty( $GLOBALS['wgOut'] ) &&
43 !empty( $GLOBALS['wgTitle'] );
47 * Can the extension use wfMsg() to get i18n messages ?
50 function useMessageCache() {
53 foreach ( $this->getTrace() as $frame ) {
54 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
59 return $wgLang instanceof Language
;
63 * Run hook to allow extensions to modify the text of the exception
65 * @param $name String: class name of the exception
66 * @param $args Array: arguments to pass to the callback functions
67 * @return Mixed: string to output or null if any hook has been called
69 function runHooks( $name, $args = array() ) {
70 global $wgExceptionHooks;
72 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
73 return null; // Just silently ignore
76 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[ $name ] ) ) {
80 $hooks = $wgExceptionHooks[ $name ];
81 $callargs = array_merge( array( $this ), $args );
83 foreach ( $hooks as $hook ) {
84 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
85 $result = call_user_func_array( $hook, $callargs );
90 if ( is_string( $result ) ) {
98 * Get a message from i18n
100 * @param $key String: message name
101 * @param $fallback String: default message if the message cache can't be
102 * called by the exception
103 * The function also has other parameters that are arguments for the message
104 * @return String message with arguments replaced
106 function msg( $key, $fallback /*[, params...] */ ) {
107 $args = array_slice( func_get_args(), 2 );
109 if ( $this->useMessageCache() ) {
110 return wfMsgNoTrans( $key, $args );
112 return wfMsgReplaceArgs( $fallback, $args );
117 * If $wgShowExceptionDetails is true, return a HTML message with a
118 * backtrace to the error, otherwise show a message to ask to set it to true
119 * to show that information.
121 * @return String html to output
124 global $wgShowExceptionDetails;
126 if ( $wgShowExceptionDetails ) {
127 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
128 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
132 "<div class=\"errorbox\">" .
133 '[' . $this->getLogId() . '] ' .
134 gmdate( 'Y-m-d H:i:s' ) .
135 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
136 "<!-- Set \$wgShowExceptionDetails = true; " .
137 "at the bottom of LocalSettings.php to show detailed " .
138 "debugging information. -->";
143 * If $wgShowExceptionDetails is true, return a text message with a
144 * backtrace to the error.
148 global $wgShowExceptionDetails;
150 if ( $wgShowExceptionDetails ) {
151 return $this->getMessage() .
152 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
154 return "Set \$wgShowExceptionDetails = true; " .
155 "in LocalSettings.php to show detailed debugging information.\n";
160 * Return titles of this error page
163 function getPageTitle() {
164 return $this->msg( 'internalerror', "Internal error" );
167 function getLogId() {
168 if ( $this->logId
=== null ) {
169 $this->logId
= wfRandomString( 8 );
175 * Return the requested URL and point to file and line number from which the
180 function getLogMessage() {
183 $id = $this->getLogId();
184 $file = $this->getFile();
185 $line = $this->getLine();
186 $message = $this->getMessage();
188 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
189 $url = $wgRequest->getRequestURL();
197 return "[$id] $url Exception from line $line of $file: $message";
200 /** Output the exception report using HTML */
201 function reportHTML() {
203 if ( $this->useOutputPage() ) {
204 $wgOut->prepareErrorPage( $this->getPageTitle() );
206 $hookResult = $this->runHooks( get_class( $this ) );
208 $wgOut->addHTML( $hookResult );
210 $wgOut->addHTML( $this->getHTML() );
215 header( "Content-Type: text/html; charset=utf-8" );
216 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
221 echo $this->getHTML();
227 * Output a report about the exception and takes care of formatting.
228 * It will be either HTML or plain text based on isCommandLine().
231 global $wgLogExceptionBacktrace;
232 $log = $this->getLogMessage();
235 if ( $wgLogExceptionBacktrace ) {
236 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
238 wfDebugLog( 'exception', $log );
242 if ( defined( 'MW_API' ) ) {
243 // Unhandled API exception, we can't be sure that format printer is alive
244 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
245 wfHttpError(500, 'Internal Server Error', $this->getText() );
246 } elseif ( self
::isCommandLine() ) {
247 MWExceptionHandler
::printError( $this->getText() );
257 static function isCommandLine() {
258 return !empty( $GLOBALS['wgCommandLineMode'] );
263 * Exception class which takes an HTML error message, and does not
264 * produce a backtrace. Replacement for OutputPage::fatalError().
267 class FatalError
extends MWException
{
273 return $this->getMessage();
280 return $this->getMessage();
285 * An error page which can definitely be safely rendered using the OutputPage
288 class ErrorPageError
extends MWException
{
289 public $title, $msg, $params;
292 * Note: these arguments are keys into wfMsg(), not text!
294 function __construct( $title, $msg, $params = null ) {
295 $this->title
= $title;
297 $this->params
= $params;
299 if( $msg instanceof Message
){
300 parent
::__construct( $msg );
302 parent
::__construct( wfMsg( $msg ) );
309 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
315 * Show an error page on a badtitle.
316 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
317 * browser it is not really a valid content.
319 class BadTitleError
extends ErrorPageError
{
322 * @param $msg string A message key (default: 'badtitletext')
323 * @param $params Array parameter to wfMsg()
325 function __construct( $msg = 'badtitletext', $params = null ) {
326 parent
::__construct( 'badtitle', $msg, $params );
330 * Just like ErrorPageError::report() but additionally set
331 * a 400 HTTP status code (bug 33646).
336 // bug 33646: a badtitle error page need to return an error code
337 // to let mobile browser now that it is not a normal page.
338 $wgOut->setStatusCode( 400 );
345 * Show an error when a user tries to do something they do not have the necessary
349 class PermissionsError
extends ErrorPageError
{
350 public $permission, $errors;
352 function __construct( $permission, $errors = array() ) {
355 $this->permission
= $permission;
357 if ( !count( $errors ) ) {
359 array( 'User', 'makeGroupLinkWiki' ),
360 User
::getGroupsWithPermission( $this->permission
)
364 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
366 $errors[] = array( 'badaccess-group0' );
370 $this->errors
= $errors;
376 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
382 * Show an error when the wiki is locked/read-only and the user tries to do
383 * something that requires write access
386 class ReadOnlyError
extends ErrorPageError
{
387 public function __construct(){
397 * Show an error when the user hits a rate limit
400 class ThrottledError
extends ErrorPageError
{
401 public function __construct(){
404 'actionthrottledtext'
408 public function report(){
410 $wgOut->setStatusCode( 503 );
416 * Show an error when the user tries to do something whilst blocked
419 class UserBlockedError
extends ErrorPageError
{
420 public function __construct( Block
$block ){
421 global $wgLang, $wgRequest;
423 $blocker = $block->getBlocker();
424 if ( $blocker instanceof User
) { // local user
425 $blockerUserpage = $block->getBlocker()->getUserPage();
426 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
427 } else { // foreign user
431 $reason = $block->mReason
;
432 if( $reason == '' ) {
433 $reason = wfMsg( 'blockednoreason' );
436 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
437 * This could be a username, an IP range, or a single IP. */
438 $intended = $block->getTarget();
442 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
449 $wgLang->formatExpiry( $block->mExpiry
),
451 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
458 * Show an error that looks like an HTTP server error.
459 * Replacement for wfHttpError().
463 class HttpError
extends MWException
{
464 private $httpCode, $header, $content;
469 * @param $httpCode Integer: HTTP status code to send to the client
470 * @param $content String|Message: content of the message
471 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
473 public function __construct( $httpCode, $content, $header = null ){
474 parent
::__construct( $content );
475 $this->httpCode
= (int)$httpCode;
476 $this->header
= $header;
477 $this->content
= $content;
480 public function report() {
481 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
483 header( "Status: {$this->httpCode} {$httpMessage}" );
484 header( 'Content-type: text/html; charset=utf-8' );
486 if ( $this->header
=== null ) {
487 $header = $httpMessage;
488 } elseif ( $this->header
instanceof Message
) {
489 $header = $this->header
->escaped();
491 $header = htmlspecialchars( $this->header
);
494 if ( $this->content
instanceof Message
) {
495 $content = $this->content
->escaped();
497 $content = htmlspecialchars( $this->content
);
500 print "<!DOCTYPE html>\n".
501 "<html><head><title>$header</title></head>\n" .
502 "<body><h1>$header</h1><p>$content</p></body></html>\n";
507 * Handler class for MWExceptions
510 class MWExceptionHandler
{
512 * Install an exception handler for MediaWiki exception types.
514 public static function installHandler() {
515 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
519 * Report an exception to the user
521 protected static function report( Exception
$e ) {
522 global $wgShowExceptionDetails;
524 $cmdLine = MWException
::isCommandLine();
526 if ( $e instanceof MWException
) {
528 // Try and show the exception prettily, with the normal skin infrastructure
530 } catch ( Exception
$e2 ) {
531 // Exception occurred from within exception handler
532 // Show a simpler error message for the original exception,
533 // don't try to invoke report()
534 $message = "MediaWiki internal error.\n\n";
536 if ( $wgShowExceptionDetails ) {
537 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
538 'Exception caught inside exception handler: ' . $e2->__toString();
540 $message .= "Exception caught inside exception handler.\n\n" .
541 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
542 "to show detailed debugging information.";
548 self
::printError( $message );
550 self
::escapeEchoAndDie( $message );
554 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
555 $e->__toString() . "\n";
557 if ( $wgShowExceptionDetails ) {
558 $message .= "\n" . $e->getTraceAsString() . "\n";
562 self
::printError( $message );
564 self
::escapeEchoAndDie( $message );
570 * Print a message, if possible to STDERR.
571 * Use this in command line mode only (see isCommandLine)
572 * @param $message String Failure text
574 public static function printError( $message ) {
575 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
576 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
577 if ( defined( 'STDERR' ) ) {
578 fwrite( STDERR
, $message );
585 * Print a message after escaping it and converting newlines to <br>
586 * Use this for non-command line failures
587 * @param $message String Failure text
589 private static function escapeEchoAndDie( $message ) {
590 echo nl2br( htmlspecialchars( $message ) ) . "\n";
595 * Exception handler which simulates the appropriate catch() handling:
599 * } catch ( MWException $e ) {
601 * } catch ( Exception $e ) {
602 * echo $e->__toString();
605 public static function handle( $e ) {
606 global $wgFullyInitialised;
611 if ( $wgFullyInitialised ) {
613 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
614 } catch ( Exception
$e ) {}
617 // Exit value should be nonzero for the benefit of shell jobs