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
{
35 * 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 the Message class/wfMessage to get i18n-ed messages?
51 function useMessageCache() {
54 foreach ( $this->getTrace() as $frame ) {
55 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
60 return $wgLang instanceof Language
;
64 * Run hook to allow extensions to modify the text of the exception
66 * @param string $name class name of the exception
67 * @param array $args arguments to pass to the callback functions
68 * @return string|null string to output or null if any hook has been called
70 function runHooks( $name, $args = array() ) {
71 global $wgExceptionHooks;
73 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
74 return null; // Just silently ignore
77 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[$name] ) ) {
81 $hooks = $wgExceptionHooks[$name];
82 $callargs = array_merge( array( $this ), $args );
84 foreach ( $hooks as $hook ) {
85 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
86 $result = call_user_func_array( $hook, $callargs );
91 if ( is_string( $result ) ) {
99 * Get a message from i18n
101 * @param string $key message name
102 * @param string $fallback default message if the message cache can't be
103 * called by the exception
104 * The function also has other parameters that are arguments for the message
105 * @return string message with arguments replaced
107 function msg( $key, $fallback /*[, params...] */ ) {
108 $args = array_slice( func_get_args(), 2 );
110 if ( $this->useMessageCache() ) {
111 return wfMessage( $key, $args )->plain();
113 return wfMsgReplaceArgs( $fallback, $args );
118 * If $wgShowExceptionDetails is true, return a HTML message with a
119 * backtrace to the error, otherwise show a message to ask to set it to true
120 * to show that information.
122 * @return string html to output
125 global $wgShowExceptionDetails;
127 if ( $wgShowExceptionDetails ) {
128 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
129 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler
::formatRedactedTrace( $this ) ) ) .
132 return "<div class=\"errorbox\">" .
133 '[' . MWExceptionHandler
::getLogId( $this ) . '] ' .
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 * Get the text to display when reporting the error on the command line.
144 * If $wgShowExceptionDetails is true, return a text message with a
145 * backtrace to the error.
150 global $wgShowExceptionDetails;
152 if ( $wgShowExceptionDetails ) {
153 return $this->getMessage() .
154 "\nBacktrace:\n" . MWExceptionHandler
::formatRedactedTrace( $this ) . "\n";
156 return "Set \$wgShowExceptionDetails = true; " .
157 "in LocalSettings.php to show detailed debugging information.\n";
162 * Return the title of the page when reporting this error in a HTTP response.
166 function getPageTitle() {
167 return $this->msg( 'internalerror', "Internal error" );
171 * Get a the ID for this error.
174 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
177 function getLogId() {
178 wfDeprecated( __METHOD__
, '1.22' );
179 return MWExceptionHandler
::getLogId( $this );
183 * Return the requested URL and point to file and line number from which the
187 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
190 function getLogMessage() {
191 wfDeprecated( __METHOD__
, '1.22' );
192 return MWExceptionHandler
::getLogMessage( $this );
196 * Output the exception report using HTML.
198 function reportHTML() {
200 if ( $this->useOutputPage() ) {
201 $wgOut->prepareErrorPage( $this->getPageTitle() );
203 $hookResult = $this->runHooks( get_class( $this ) );
205 $wgOut->addHTML( $hookResult );
207 $wgOut->addHTML( $this->getHTML() );
212 header( "Content-Type: text/html; charset=utf-8" );
213 echo "<!doctype html>\n" .
215 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
218 $hookResult = $this->runHooks( get_class( $this ) . "Raw" );
222 echo $this->getHTML();
225 echo "</body></html>\n";
230 * Output a report about the exception and takes care of formatting.
231 * It will be either HTML or plain text based on isCommandLine().
236 MWExceptionHandler
::logException( $this );
238 if ( defined( 'MW_API' ) ) {
239 // Unhandled API exception, we can't be sure that format printer is alive
240 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
241 wfHttpError( 500, 'Internal Server Error', $this->getText() );
242 } elseif ( self
::isCommandLine() ) {
243 MWExceptionHandler
::printError( $this->getText() );
245 header( "HTTP/1.1 500 MediaWiki exception" );
246 header( "Status: 500 MediaWiki exception", true );
247 header( "Content-Type: $wgMimeType; charset=utf-8", true );
254 * Check whether we are in command line mode or not to report the exception
255 * in the correct format.
259 static function isCommandLine() {
260 return !empty( $GLOBALS['wgCommandLineMode'] );
265 * Exception class which takes an HTML error message, and does not
266 * produce a backtrace. Replacement for OutputPage::fatalError().
271 class FatalError
extends MWException
{
277 return $this->getMessage();
284 return $this->getMessage();
289 * An error page which can definitely be safely rendered using the OutputPage.
294 class ErrorPageError
extends MWException
{
295 public $title, $msg, $params;
298 * Note: these arguments are keys into wfMessage(), not text!
300 * @param string|Message $title Message key (string) for page title, or a Message object
301 * @param string|Message $msg Message key (string) for error text, or a Message object
302 * @param array $params with parameters to wfMessage()
304 function __construct( $title, $msg, $params = null ) {
305 $this->title
= $title;
307 $this->params
= $params;
309 // Bug 44111: Messages in the log files should be in English and not
310 // customized by the local wiki. So get the default English version for
311 // passing to the parent constructor. Our overridden report() below
312 // makes sure that the page shown to the user is not forced to English.
313 if ( $msg instanceof Message
) {
314 $enMsg = clone( $msg );
316 $enMsg = wfMessage( $msg, $params );
318 $enMsg->inLanguage( 'en' )->useDatabase( false );
319 parent
::__construct( $enMsg->text() );
325 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
331 * Show an error page on a badtitle.
332 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
333 * browser it is not really a valid content.
338 class BadTitleError
extends ErrorPageError
{
340 * @param string|Message $msg A message key (default: 'badtitletext')
341 * @param array $params parameter to wfMessage()
343 function __construct( $msg = 'badtitletext', $params = null ) {
344 parent
::__construct( 'badtitle', $msg, $params );
348 * Just like ErrorPageError::report() but additionally set
349 * a 400 HTTP status code (bug 33646).
354 // bug 33646: a badtitle error page need to return an error code
355 // to let mobile browser now that it is not a normal page.
356 $wgOut->setStatusCode( 400 );
363 * Show an error when a user tries to do something they do not have the necessary
369 class PermissionsError
extends ErrorPageError
{
370 public $permission, $errors;
372 function __construct( $permission, $errors = array() ) {
375 $this->permission
= $permission;
377 if ( !count( $errors ) ) {
379 array( 'User', 'makeGroupLinkWiki' ),
380 User
::getGroupsWithPermission( $this->permission
)
384 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
386 $errors[] = array( 'badaccess-group0' );
390 $this->errors
= $errors;
396 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
402 * Show an error when the wiki is locked/read-only and the user tries to do
403 * something that requires write access.
408 class ReadOnlyError
extends ErrorPageError
{
409 public function __construct() {
419 * Show an error when the user hits a rate limit.
424 class ThrottledError
extends ErrorPageError
{
425 public function __construct() {
428 'actionthrottledtext'
432 public function report() {
434 $wgOut->setStatusCode( 503 );
440 * Show an error when the user tries to do something whilst blocked.
445 class UserBlockedError
extends ErrorPageError
{
446 public function __construct( Block
$block ) {
447 // @todo FIXME: Implement a more proper way to get context here.
448 $params = $block->getPermissionsError( RequestContext
::getMain() );
449 parent
::__construct( 'blockedtitle', array_shift( $params ), $params );
454 * Shows a generic "user is not logged in" error page.
456 * This is essentially an ErrorPageError exception which by default uses the
457 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
463 * if( $user->isAnon() ) {
464 * throw new UserNotLoggedIn();
468 * Note the parameter order differs from ErrorPageError, this allows you to
469 * simply specify a reason without overriding the default title.
473 * if( $user->isAnon() ) {
474 * throw new UserNotLoggedIn( 'action-require-loggedin' );
480 class UserNotLoggedIn
extends ErrorPageError
{
483 * @param $reasonMsg A message key containing the reason for the error.
484 * Optional, default: 'exception-nologin-text'
485 * @param $titleMsg A message key to set the page title.
486 * Optional, default: 'exception-nologin'
487 * @param $params Parameters to wfMessage().
488 * Optional, default: null
490 public function __construct(
491 $reasonMsg = 'exception-nologin-text',
492 $titleMsg = 'exception-nologin',
495 parent
::__construct( $titleMsg, $reasonMsg, $params );
500 * Show an error that looks like an HTTP server error.
501 * Replacement for wfHttpError().
506 class HttpError
extends MWException
{
507 private $httpCode, $header, $content;
512 * @param $httpCode Integer: HTTP status code to send to the client
513 * @param string|Message $content content of the message
514 * @param string|Message $header content of the header (\<title\> and \<h1\>)
516 public function __construct( $httpCode, $content, $header = null ) {
517 parent
::__construct( $content );
518 $this->httpCode
= (int)$httpCode;
519 $this->header
= $header;
520 $this->content
= $content;
524 * Returns the HTTP status code supplied to the constructor.
528 public function getStatusCode() {
529 return $this->httpCode
;
533 * Report the HTTP error.
534 * Sends the appropriate HTTP status code and outputs an
535 * HTML page with an error message.
537 public function report() {
538 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
540 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
541 header( 'Content-type: text/html; charset=utf-8' );
543 print $this->getHTML();
547 * Returns HTML for reporting the HTTP error.
548 * This will be a minimal but complete HTML document.
550 * @return string HTML
552 public function getHTML() {
553 if ( $this->header
=== null ) {
554 $header = HttpStatus
::getMessage( $this->httpCode
);
555 } elseif ( $this->header
instanceof Message
) {
556 $header = $this->header
->escaped();
558 $header = htmlspecialchars( $this->header
);
561 if ( $this->content
instanceof Message
) {
562 $content = $this->content
->escaped();
564 $content = htmlspecialchars( $this->content
);
567 return "<!DOCTYPE html>\n" .
568 "<html><head><title>$header</title></head>\n" .
569 "<body><h1>$header</h1><p>$content</p></body></html>\n";
574 * Handler class for MWExceptions
577 class MWExceptionHandler
{
579 * Install an exception handler for MediaWiki exception types.
581 public static function installHandler() {
582 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
586 * Report an exception to the user
588 protected static function report( Exception
$e ) {
589 global $wgShowExceptionDetails;
591 $cmdLine = MWException
::isCommandLine();
593 if ( $e instanceof MWException
) {
595 // Try and show the exception prettily, with the normal skin infrastructure
597 } catch ( Exception
$e2 ) {
598 // Exception occurred from within exception handler
599 // Show a simpler error message for the original exception,
600 // don't try to invoke report()
601 $message = "MediaWiki internal error.\n\n";
603 if ( $wgShowExceptionDetails ) {
604 $message .= 'Original exception: ' . self
::formatRedactedTrace( $e ) . "\n\n" .
605 'Exception caught inside exception handler: ' . $e2->__toString();
607 $message .= "Exception caught inside exception handler.\n\n" .
608 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
609 "to show detailed debugging information.";
615 self
::printError( $message );
617 echo nl2br( htmlspecialchars( $message ) ) . "\n";
621 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"";
623 if ( $wgShowExceptionDetails ) {
624 $message .= "\nexception '" . get_class( $e ) . "' in " . $e->getFile() . ":" . $e->getLine() . "\nStack trace:\n" . self
::formatRedactedTrace( $e ) . "\n";
628 self
::printError( $message );
630 echo nl2br( htmlspecialchars( $message ) ) . "\n";
636 * Print a message, if possible to STDERR.
637 * Use this in command line mode only (see isCommandLine)
639 * @param string $message Failure text
641 public static function printError( $message ) {
642 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
643 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
644 if ( defined( 'STDERR' ) ) {
645 fwrite( STDERR
, $message );
652 * Exception handler which simulates the appropriate catch() handling:
656 * } catch ( MWException $e ) {
658 * } catch ( Exception $e ) {
659 * echo $e->__toString();
662 public static function handle( $e ) {
663 global $wgFullyInitialised;
668 if ( $wgFullyInitialised ) {
670 // uses $wgRequest, hence the $wgFullyInitialised condition
671 wfLogProfilingData();
672 } catch ( Exception
$e ) {
676 // Exit value should be nonzero for the benefit of shell jobs
681 * Get the stack trace from the exception as a string, redacting certain function arguments in the process
682 * @param Exception $e The exception
683 * @return string The stack trace as a string
685 public static function formatRedactedTrace( Exception
$e ) {
686 global $wgRedactedFunctionArguments;
687 $finalExceptionText = '';
689 // Unique value to indicate redacted parameters
690 $redacted = new stdClass();
692 foreach ( $e->getTrace() as $i => $call ) {
694 if ( isset( $call['class'] ) ) {
695 $checkFor[] = $call['class'] . '::' . $call['function'];
696 foreach ( class_parents( $call['class'] ) as $parent ) {
697 $checkFor[] = $parent . '::' . $call['function'];
700 $checkFor[] = $call['function'];
703 foreach ( $checkFor as $check ) {
704 if ( isset( $wgRedactedFunctionArguments[$check] ) ) {
705 foreach ( (array)$wgRedactedFunctionArguments[$check] as $argNo ) {
706 $call['args'][$argNo] = $redacted;
711 if ( isset( $call['file'] ) && isset( $call['line'] ) ) {
712 $finalExceptionText .= "#{$i} {$call['file']}({$call['line']}): ";
714 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
715 // This matches behaviour of Exception::getTraceAsString to instead
716 // display "[internal function]".
717 $finalExceptionText .= "#{$i} [internal function]: ";
720 if ( isset( $call['class'] ) ) {
721 $finalExceptionText .= $call['class'] . $call['type'] . $call['function'];
723 $finalExceptionText .= $call['function'];
726 if ( isset( $call['args'] ) ) {
727 foreach ( $call['args'] as $arg ) {
728 if ( $arg === $redacted ) {
729 $args[] = 'REDACTED';
730 } elseif ( is_object( $arg ) ) {
731 $args[] = 'Object(' . get_class( $arg ) . ')';
732 } elseif( is_array( $arg ) ) {
735 $args[] = var_export( $arg, true );
739 $finalExceptionText .= '(' . implode( ', ', $args ) . ")\n";
741 return $finalExceptionText . '#' . ( $i +
1 ) . ' {main}';
746 * Get the ID for this error.
748 * The ID is saved so that one can match the one output to the user (when
749 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
752 * @param Exception $e
755 public static function getLogId( Exception
$e ) {
756 if ( !isset( $e->_mwLogId
) ) {
757 $e->_mwLogId
= wfRandomString( 8 );
763 * Return the requested URL and point to file and line number from which the
764 * exception occurred.
767 * @param Exception $e
770 public static function getLogMessage( Exception
$e ) {
773 $id = self
::getLogId( $e );
774 $file = $e->getFile();
775 $line = $e->getLine();
776 $message = $e->getMessage();
778 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
779 $url = $wgRequest->getRequestURL();
787 return "[$id] $url Exception from line $line of $file: $message";
791 * Log an exception to the exception log (if enabled).
793 * This method must not assume the exception is an MWException,
794 * it is also used to handle PHP errors or errors from other libraries.
797 * @param Exception $e
799 public static function logException( Exception
$e ) {
800 global $wgLogExceptionBacktrace;
802 $log = self
::getLogMessage( $e );
804 if ( $wgLogExceptionBacktrace ) {
805 wfDebugLog( 'exception', $log . "\n" . self
::formatRedactedTrace( $e ) . "\n" );
807 wfDebugLog( 'exception', $log );