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?
40 function useOutputPage() {
41 return $this->useMessageCache() &&
42 !empty( $GLOBALS['wgFullyInitialised'] ) &&
43 !empty( $GLOBALS['wgOut'] ) &&
44 !empty( $GLOBALS['wgTitle'] );
48 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
52 function useMessageCache() {
55 foreach ( $this->getTrace() as $frame ) {
56 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
61 return $wgLang instanceof Language
;
65 * Run hook to allow extensions to modify the text of the exception
67 * @param $name string: class name of the exception
68 * @param $args array: arguments to pass to the callback functions
69 * @return string|null string to output or null if any hook has been called
71 function runHooks( $name, $args = array() ) {
72 global $wgExceptionHooks;
74 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
75 return null; // Just silently ignore
78 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[ $name ] ) ) {
82 $hooks = $wgExceptionHooks[ $name ];
83 $callargs = array_merge( array( $this ), $args );
85 foreach ( $hooks as $hook ) {
86 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
87 $result = call_user_func_array( $hook, $callargs );
92 if ( is_string( $result ) ) {
100 * Get a message from i18n
102 * @param $key string: message name
103 * @param $fallback string: default message if the message cache can't be
104 * called by the exception
105 * The function also has other parameters that are arguments for the message
106 * @return string message with arguments replaced
108 function msg( $key, $fallback /*[, params...] */ ) {
109 $args = array_slice( func_get_args(), 2 );
111 if ( $this->useMessageCache() ) {
112 return wfMessage( $key, $args )->plain();
114 return wfMsgReplaceArgs( $fallback, $args );
119 * If $wgShowExceptionDetails is true, return a HTML message with a
120 * backtrace to the error, otherwise show a message to ask to set it to true
121 * to show that information.
123 * @return string html to output
126 global $wgShowExceptionDetails;
128 if ( $wgShowExceptionDetails ) {
129 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
130 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
134 "<div class=\"errorbox\">" .
135 '[' . $this->getLogId() . '] ' .
136 gmdate( 'Y-m-d H:i:s' ) .
137 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
138 "<!-- Set \$wgShowExceptionDetails = true; " .
139 "at the bottom of LocalSettings.php to show detailed " .
140 "debugging information. -->";
145 * Get the text to display when reporting the error on the command line.
146 * If $wgShowExceptionDetails is true, return a text message with a
147 * backtrace to the error.
152 global $wgShowExceptionDetails;
154 if ( $wgShowExceptionDetails ) {
155 return $this->getMessage() .
156 "\nBacktrace:\n" . $this->getTraceAsString() . "\n";
158 return "Set \$wgShowExceptionDetails = true; " .
159 "in LocalSettings.php to show detailed debugging information.\n";
164 * Return the title of the page when reporting this error in a HTTP response.
168 function getPageTitle() {
169 return $this->msg( 'internalerror', "Internal error" );
173 * Get a random ID for this error.
174 * This allows to link the exception to its correspoding log entry when
175 * $wgShowExceptionDetails is set to false.
179 function getLogId() {
180 if ( $this->logId
=== null ) {
181 $this->logId
= wfRandomString( 8 );
187 * Return the requested URL and point to file and line number from which the
192 function getLogMessage() {
195 $id = $this->getLogId();
196 $file = $this->getFile();
197 $line = $this->getLine();
198 $message = $this->getMessage();
200 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
201 $url = $wgRequest->getRequestURL();
209 return "[$id] $url Exception from line $line of $file: $message";
213 * Output the exception report using HTML.
215 function reportHTML() {
217 if ( $this->useOutputPage() ) {
218 $wgOut->prepareErrorPage( $this->getPageTitle() );
220 $hookResult = $this->runHooks( get_class( $this ) );
222 $wgOut->addHTML( $hookResult );
224 $wgOut->addHTML( $this->getHTML() );
229 header( "Content-Type: text/html; charset=utf-8" );
230 echo "<!doctype html>\n" .
232 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
235 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
239 echo $this->getHTML();
242 echo "</body></html>\n";
247 * Output a report about the exception and takes care of formatting.
248 * It will be either HTML or plain text based on isCommandLine().
251 global $wgLogExceptionBacktrace;
252 $log = $this->getLogMessage();
255 if ( $wgLogExceptionBacktrace ) {
256 wfDebugLog( 'exception', $log . "\n" . $this->getTraceAsString() . "\n" );
258 wfDebugLog( 'exception', $log );
262 if ( defined( 'MW_API' ) ) {
263 // Unhandled API exception, we can't be sure that format printer is alive
264 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
265 wfHttpError(500, 'Internal Server Error', $this->getText() );
266 } elseif ( self
::isCommandLine() ) {
267 MWExceptionHandler
::printError( $this->getText() );
269 header( "HTTP/1.1 500 MediaWiki exception" );
270 header( "Status: 500 MediaWiki exception", true );
277 * Check whether we are in command line mode or not to report the exception
278 * in the correct format.
282 static function isCommandLine() {
283 return !empty( $GLOBALS['wgCommandLineMode'] );
288 * Exception class which takes an HTML error message, and does not
289 * produce a backtrace. Replacement for OutputPage::fatalError().
294 class FatalError
extends MWException
{
300 return $this->getMessage();
307 return $this->getMessage();
312 * An error page which can definitely be safely rendered using the OutputPage.
317 class ErrorPageError
extends MWException
{
318 public $title, $msg, $params;
321 * Note: these arguments are keys into wfMessage(), not text!
323 * @param $title string|Message Message key (string) for page title, or a Message object
324 * @param $msg string|Message Message key (string) for error text, or a Message object
325 * @param $params array with parameters to wfMessage()
327 function __construct( $title, $msg, $params = null ) {
328 $this->title
= $title;
330 $this->params
= $params;
332 if( $msg instanceof Message
){
333 parent
::__construct( $msg );
335 parent
::__construct( wfMessage( $msg )->text() );
342 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
348 * Show an error page on a badtitle.
349 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
350 * browser it is not really a valid content.
355 class BadTitleError
extends ErrorPageError
{
357 * @param $msg string|Message A message key (default: 'badtitletext')
358 * @param $params Array parameter to wfMessage()
360 function __construct( $msg = 'badtitletext', $params = null ) {
361 parent
::__construct( 'badtitle', $msg, $params );
365 * Just like ErrorPageError::report() but additionally set
366 * a 400 HTTP status code (bug 33646).
371 // bug 33646: a badtitle error page need to return an error code
372 // to let mobile browser now that it is not a normal page.
373 $wgOut->setStatusCode( 400 );
380 * Show an error when a user tries to do something they do not have the necessary
386 class PermissionsError
extends ErrorPageError
{
387 public $permission, $errors;
389 function __construct( $permission, $errors = array() ) {
392 $this->permission
= $permission;
394 if ( !count( $errors ) ) {
396 array( 'User', 'makeGroupLinkWiki' ),
397 User
::getGroupsWithPermission( $this->permission
)
401 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
403 $errors[] = array( 'badaccess-group0' );
407 $this->errors
= $errors;
413 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
419 * Show an error when the wiki is locked/read-only and the user tries to do
420 * something that requires write access.
425 class ReadOnlyError
extends ErrorPageError
{
426 public function __construct(){
436 * Show an error when the user hits a rate limit.
441 class ThrottledError
extends ErrorPageError
{
442 public function __construct(){
445 'actionthrottledtext'
449 public function report(){
451 $wgOut->setStatusCode( 503 );
457 * Show an error when the user tries to do something whilst blocked.
462 class UserBlockedError
extends ErrorPageError
{
463 public function __construct( Block
$block ){
464 global $wgLang, $wgRequest;
466 $blocker = $block->getBlocker();
467 if ( $blocker instanceof User
) { // local user
468 $blockerUserpage = $block->getBlocker()->getUserPage();
469 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
470 } else { // foreign user
474 $reason = $block->mReason
;
475 if( $reason == '' ) {
476 $reason = wfMessage( 'blockednoreason' )->text();
479 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
480 * This could be a username, an IP range, or a single IP. */
481 $intended = $block->getTarget();
485 $block->mAuto ?
'autoblockedtext' : 'blockedtext',
492 $wgLang->formatExpiry( $block->mExpiry
),
494 $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true )
501 * Shows a generic "user is not logged in" error page.
503 * This is essentially an ErrorPageError exception which by default use the
504 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
510 * if( $user->isAnon ) {
511 * throw new UserNotLoggedIn();
515 * Please note the parameters are mixed up compared to ErrorPageError, this
516 * is done to be able to simply specify a reason whitout overriding the default
521 * if( $user->isAnon ) {
522 * throw new UserNotLoggedIn( 'action-require-loggedin' );
528 class UserNotLoggedIn
extends ErrorPageError
{
531 * @param $reasonMsg A message key containing the reason for the error.
532 * Optional, default: 'exception-nologin-text'
533 * @param $titleMsg A message key to set the page title.
534 * Optional, default: 'exception-nologin'
535 * @param $params Parameters to wfMessage().
536 * Optiona, default: null
538 public function __construct(
539 $reasonMsg = 'exception-nologin-text',
540 $titleMsg = 'exception-nologin',
543 parent
::__construct( $titleMsg, $reasonMsg, $params );
548 * Show an error that looks like an HTTP server error.
549 * Replacement for wfHttpError().
554 class HttpError
extends MWException
{
555 private $httpCode, $header, $content;
560 * @param $httpCode Integer: HTTP status code to send to the client
561 * @param $content String|Message: content of the message
562 * @param $header String|Message: content of the header (\<title\> and \<h1\>)
564 public function __construct( $httpCode, $content, $header = null ){
565 parent
::__construct( $content );
566 $this->httpCode
= (int)$httpCode;
567 $this->header
= $header;
568 $this->content
= $content;
571 public function report() {
572 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
574 header( "Status: {$this->httpCode} {$httpMessage}" );
575 header( 'Content-type: text/html; charset=utf-8' );
577 if ( $this->header
=== null ) {
578 $header = $httpMessage;
579 } elseif ( $this->header
instanceof Message
) {
580 $header = $this->header
->escaped();
582 $header = htmlspecialchars( $this->header
);
585 if ( $this->content
instanceof Message
) {
586 $content = $this->content
->escaped();
588 $content = htmlspecialchars( $this->content
);
591 print "<!DOCTYPE html>\n".
592 "<html><head><title>$header</title></head>\n" .
593 "<body><h1>$header</h1><p>$content</p></body></html>\n";
598 * Handler class for MWExceptions
601 class MWExceptionHandler
{
603 * Install an exception handler for MediaWiki exception types.
605 public static function installHandler() {
606 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
610 * Report an exception to the user
612 protected static function report( Exception
$e ) {
613 global $wgShowExceptionDetails;
615 $cmdLine = MWException
::isCommandLine();
617 if ( $e instanceof MWException
) {
619 // Try and show the exception prettily, with the normal skin infrastructure
621 } catch ( Exception
$e2 ) {
622 // Exception occurred from within exception handler
623 // Show a simpler error message for the original exception,
624 // don't try to invoke report()
625 $message = "MediaWiki internal error.\n\n";
627 if ( $wgShowExceptionDetails ) {
628 $message .= 'Original exception: ' . $e->__toString() . "\n\n" .
629 'Exception caught inside exception handler: ' . $e2->__toString();
631 $message .= "Exception caught inside exception handler.\n\n" .
632 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
633 "to show detailed debugging information.";
639 self
::printError( $message );
641 echo nl2br( htmlspecialchars( $message ) ) . "\n";
645 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"\n" .
646 $e->__toString() . "\n";
648 if ( $wgShowExceptionDetails ) {
649 $message .= "\n" . $e->getTraceAsString() . "\n";
653 self
::printError( $message );
655 echo nl2br( htmlspecialchars( $message ) ) . "\n";
661 * Print a message, if possible to STDERR.
662 * Use this in command line mode only (see isCommandLine)
664 * @param $message string Failure text
666 public static function printError( $message ) {
667 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
668 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
669 if ( defined( 'STDERR' ) ) {
670 fwrite( STDERR
, $message );
677 * Exception handler which simulates the appropriate catch() handling:
681 * } catch ( MWException $e ) {
683 * } catch ( Exception $e ) {
684 * echo $e->__toString();
687 public static function handle( $e ) {
688 global $wgFullyInitialised;
693 if ( $wgFullyInitialised ) {
695 wfLogProfilingData(); // uses $wgRequest, hence the $wgFullyInitialised condition
696 } catch ( Exception
$e ) {}
699 // Exit value should be nonzero for the benefit of shell jobs