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 * Whether to log this exception in the exception debug log.
52 function isLoggable() {
57 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
61 function useMessageCache() {
64 foreach ( $this->getTrace() as $frame ) {
65 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
70 return $wgLang instanceof Language
;
74 * Run hook to allow extensions to modify the text of the exception
76 * @param string $name class name of the exception
77 * @param array $args arguments to pass to the callback functions
78 * @return string|null string to output or null if any hook has been called
80 function runHooks( $name, $args = array() ) {
81 global $wgExceptionHooks;
83 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
84 return null; // Just silently ignore
87 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks[$name] ) ) {
91 $hooks = $wgExceptionHooks[$name];
92 $callargs = array_merge( array( $this ), $args );
94 foreach ( $hooks as $hook ) {
95 if ( is_string( $hook ) ||
( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) ) ) { // 'function' or array( 'class', hook' )
96 $result = call_user_func_array( $hook, $callargs );
101 if ( is_string( $result ) ) {
109 * Get a message from i18n
111 * @param string $key message name
112 * @param string $fallback default message if the message cache can't be
113 * called by the exception
114 * The function also has other parameters that are arguments for the message
115 * @return string message with arguments replaced
117 function msg( $key, $fallback /*[, params...] */ ) {
118 $args = array_slice( func_get_args(), 2 );
120 if ( $this->useMessageCache() ) {
121 return wfMessage( $key, $args )->plain();
123 return wfMsgReplaceArgs( $fallback, $args );
128 * If $wgShowExceptionDetails is true, return a HTML message with a
129 * backtrace to the error, otherwise show a message to ask to set it to true
130 * to show that information.
132 * @return string html to output
135 global $wgShowExceptionDetails;
137 if ( $wgShowExceptionDetails ) {
138 return '<p>' . nl2br( htmlspecialchars( $this->getMessage() ) ) .
139 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler
::formatRedactedTrace( $this ) ) ) .
142 return "<div class=\"errorbox\">" .
143 '[' . MWExceptionHandler
::getLogId( $this ) . '] ' .
144 gmdate( 'Y-m-d H:i:s' ) .
145 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
146 "<!-- Set \$wgShowExceptionDetails = true; " .
147 "at the bottom of LocalSettings.php to show detailed " .
148 "debugging information. -->";
153 * Get the text to display when reporting the error on the command line.
154 * If $wgShowExceptionDetails is true, return a text message with a
155 * backtrace to the error.
160 global $wgShowExceptionDetails;
162 if ( $wgShowExceptionDetails ) {
163 return $this->getMessage() .
164 "\nBacktrace:\n" . MWExceptionHandler
::formatRedactedTrace( $this ) . "\n";
166 return "Set \$wgShowExceptionDetails = true; " .
167 "in LocalSettings.php to show detailed debugging information.\n";
172 * Return the title of the page when reporting this error in a HTTP response.
176 function getPageTitle() {
178 return $this->msg( 'pagetitle', "$1 - $wgSitename", $this->msg( 'internalerror', 'Internal error' ) );
182 * Get a the ID for this error.
185 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
188 function getLogId() {
189 wfDeprecated( __METHOD__
, '1.22' );
190 return MWExceptionHandler
::getLogId( $this );
194 * Return the requested URL and point to file and line number from which the
198 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
201 function getLogMessage() {
202 wfDeprecated( __METHOD__
, '1.22' );
203 return MWExceptionHandler
::getLogMessage( $this );
207 * Output the exception report using HTML.
209 function reportHTML() {
211 if ( $this->useOutputPage() ) {
212 $wgOut->prepareErrorPage( $this->getPageTitle() );
214 $hookResult = $this->runHooks( get_class( $this ) );
216 $wgOut->addHTML( $hookResult );
218 $wgOut->addHTML( $this->getHTML() );
223 header( 'Content-Type: text/html; charset=utf-8' );
224 echo "<!DOCTYPE html>\n" .
226 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
227 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
230 $hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
234 echo $this->getHTML();
237 echo "</body></html>\n";
242 * Output a report about the exception and takes care of formatting.
243 * It will be either HTML or plain text based on isCommandLine().
248 MWExceptionHandler
::logException( $this );
250 if ( defined( 'MW_API' ) ) {
251 // Unhandled API exception, we can't be sure that format printer is alive
252 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
253 wfHttpError( 500, 'Internal Server Error', $this->getText() );
254 } elseif ( self
::isCommandLine() ) {
255 MWExceptionHandler
::printError( $this->getText() );
257 header( 'HTTP/1.1 500 MediaWiki exception' );
258 header( 'Status: 500 MediaWiki exception', true );
259 header( "Content-Type: $wgMimeType; charset=utf-8", true );
266 * Check whether we are in command line mode or not to report the exception
267 * in the correct format.
271 static function isCommandLine() {
272 return !empty( $GLOBALS['wgCommandLineMode'] );
277 * Exception class which takes an HTML error message, and does not
278 * produce a backtrace. Replacement for OutputPage::fatalError().
283 class FatalError
extends MWException
{
289 return $this->getMessage();
296 return $this->getMessage();
301 * An error page which can definitely be safely rendered using the OutputPage.
306 class ErrorPageError
extends MWException
{
307 public $title, $msg, $params;
310 * Note: these arguments are keys into wfMessage(), not text!
312 * @param string|Message $title Message key (string) for page title, or a Message object
313 * @param string|Message $msg Message key (string) for error text, or a Message object
314 * @param array $params with parameters to wfMessage()
316 function __construct( $title, $msg, $params = null ) {
317 $this->title
= $title;
319 $this->params
= $params;
321 // Bug 44111: Messages in the log files should be in English and not
322 // customized by the local wiki. So get the default English version for
323 // passing to the parent constructor. Our overridden report() below
324 // makes sure that the page shown to the user is not forced to English.
325 if ( $msg instanceof Message
) {
326 $enMsg = clone( $msg );
328 $enMsg = wfMessage( $msg, $params );
330 $enMsg->inLanguage( 'en' )->useDatabase( false );
331 parent
::__construct( $enMsg->text() );
337 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
343 * Show an error page on a badtitle.
344 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
345 * browser it is not really a valid content.
350 class BadTitleError
extends ErrorPageError
{
352 * @param string|Message $msg A message key (default: 'badtitletext')
353 * @param array $params parameter to wfMessage()
355 function __construct( $msg = 'badtitletext', $params = null ) {
356 parent
::__construct( 'badtitle', $msg, $params );
360 * Just like ErrorPageError::report() but additionally set
361 * a 400 HTTP status code (bug 33646).
366 // bug 33646: a badtitle error page need to return an error code
367 // to let mobile browser now that it is not a normal page.
368 $wgOut->setStatusCode( 400 );
375 * Show an error when a user tries to do something they do not have the necessary
381 class PermissionsError
extends ErrorPageError
{
382 public $permission, $errors;
384 function __construct( $permission, $errors = array() ) {
387 $this->permission
= $permission;
389 if ( !count( $errors ) ) {
391 array( 'User', 'makeGroupLinkWiki' ),
392 User
::getGroupsWithPermission( $this->permission
)
396 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
398 $errors[] = array( 'badaccess-group0' );
402 $this->errors
= $errors;
408 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
414 * Show an error when the wiki is locked/read-only and the user tries to do
415 * something that requires write access.
420 class ReadOnlyError
extends ErrorPageError
{
421 public function __construct() {
431 * Show an error when the user hits a rate limit.
436 class ThrottledError
extends ErrorPageError
{
437 public function __construct() {
440 'actionthrottledtext'
444 public function report() {
446 $wgOut->setStatusCode( 503 );
452 * Show an error when the user tries to do something whilst blocked.
457 class UserBlockedError
extends ErrorPageError
{
458 public function __construct( Block
$block ) {
459 // @todo FIXME: Implement a more proper way to get context here.
460 $params = $block->getPermissionsError( RequestContext
::getMain() );
461 parent
::__construct( 'blockedtitle', array_shift( $params ), $params );
466 * Shows a generic "user is not logged in" error page.
468 * This is essentially an ErrorPageError exception which by default uses the
469 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
475 * if( $user->isAnon() ) {
476 * throw new UserNotLoggedIn();
480 * Note the parameter order differs from ErrorPageError, this allows you to
481 * simply specify a reason without overriding the default title.
485 * if( $user->isAnon() ) {
486 * throw new UserNotLoggedIn( 'action-require-loggedin' );
492 class UserNotLoggedIn
extends ErrorPageError
{
495 * @param $reasonMsg A message key containing the reason for the error.
496 * Optional, default: 'exception-nologin-text'
497 * @param $titleMsg A message key to set the page title.
498 * Optional, default: 'exception-nologin'
499 * @param $params Parameters to wfMessage().
500 * Optional, default: null
502 public function __construct(
503 $reasonMsg = 'exception-nologin-text',
504 $titleMsg = 'exception-nologin',
507 parent
::__construct( $titleMsg, $reasonMsg, $params );
512 * Show an error that looks like an HTTP server error.
513 * Replacement for wfHttpError().
518 class HttpError
extends MWException
{
519 private $httpCode, $header, $content;
524 * @param $httpCode Integer: HTTP status code to send to the client
525 * @param string|Message $content content of the message
526 * @param string|Message $header content of the header (\<title\> and \<h1\>)
528 public function __construct( $httpCode, $content, $header = null ) {
529 parent
::__construct( $content );
530 $this->httpCode
= (int)$httpCode;
531 $this->header
= $header;
532 $this->content
= $content;
536 * Returns the HTTP status code supplied to the constructor.
540 public function getStatusCode() {
541 return $this->httpCode
;
545 * Report the HTTP error.
546 * Sends the appropriate HTTP status code and outputs an
547 * HTML page with an error message.
549 public function report() {
550 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
552 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
553 header( 'Content-type: text/html; charset=utf-8' );
555 print $this->getHTML();
559 * Returns HTML for reporting the HTTP error.
560 * This will be a minimal but complete HTML document.
562 * @return string HTML
564 public function getHTML() {
565 if ( $this->header
=== null ) {
566 $header = HttpStatus
::getMessage( $this->httpCode
);
567 } elseif ( $this->header
instanceof Message
) {
568 $header = $this->header
->escaped();
570 $header = htmlspecialchars( $this->header
);
573 if ( $this->content
instanceof Message
) {
574 $content = $this->content
->escaped();
576 $content = htmlspecialchars( $this->content
);
579 return "<!DOCTYPE html>\n" .
580 "<html><head><title>$header</title></head>\n" .
581 "<body><h1>$header</h1><p>$content</p></body></html>\n";
586 * Handler class for MWExceptions
589 class MWExceptionHandler
{
591 * Install an exception handler for MediaWiki exception types.
593 public static function installHandler() {
594 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
598 * Report an exception to the user
600 protected static function report( Exception
$e ) {
601 global $wgShowExceptionDetails;
603 $cmdLine = MWException
::isCommandLine();
605 if ( $e instanceof MWException
) {
607 // Try and show the exception prettily, with the normal skin infrastructure
609 } catch ( Exception
$e2 ) {
610 // Exception occurred from within exception handler
611 // Show a simpler error message for the original exception,
612 // don't try to invoke report()
613 $message = "MediaWiki internal error.\n\n";
615 if ( $wgShowExceptionDetails ) {
616 $message .= 'Original exception: ' . self
::formatRedactedTrace( $e ) . "\n\n" .
617 'Exception caught inside exception handler: ' . $e2->__toString();
619 $message .= "Exception caught inside exception handler.\n\n" .
620 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
621 "to show detailed debugging information.";
627 self
::printError( $message );
629 echo nl2br( htmlspecialchars( $message ) ) . "\n";
633 $message = "Unexpected non-MediaWiki exception encountered, of type \"" . get_class( $e ) . "\"";
635 if ( $wgShowExceptionDetails ) {
636 $message .= "\nexception '" . get_class( $e ) . "' in " . $e->getFile() . ":" . $e->getLine() . "\nStack trace:\n" . self
::formatRedactedTrace( $e ) . "\n";
640 self
::printError( $message );
642 echo nl2br( htmlspecialchars( $message ) ) . "\n";
648 * Print a message, if possible to STDERR.
649 * Use this in command line mode only (see isCommandLine)
651 * @param string $message Failure text
653 public static function printError( $message ) {
654 # NOTE: STDERR may not be available, especially if php-cgi is used from the command line (bug #15602).
655 # Try to produce meaningful output anyway. Using echo may corrupt output to STDOUT though.
656 if ( defined( 'STDERR' ) ) {
657 fwrite( STDERR
, $message );
664 * Exception handler which simulates the appropriate catch() handling:
668 * } catch ( MWException $e ) {
670 * } catch ( Exception $e ) {
671 * echo $e->__toString();
674 public static function handle( $e ) {
675 global $wgFullyInitialised;
680 if ( $wgFullyInitialised ) {
682 // uses $wgRequest, hence the $wgFullyInitialised condition
683 wfLogProfilingData();
684 } catch ( Exception
$e ) {
688 // Exit value should be nonzero for the benefit of shell jobs
693 * Get the stack trace from the exception as a string, redacting certain function arguments in the process
694 * @param Exception $e The exception
695 * @return string The stack trace as a string
697 public static function formatRedactedTrace( Exception
$e ) {
698 global $wgRedactedFunctionArguments;
699 $finalExceptionText = '';
701 // Unique value to indicate redacted parameters
702 $redacted = new stdClass();
704 foreach ( $e->getTrace() as $i => $call ) {
706 if ( isset( $call['class'] ) ) {
707 $checkFor[] = $call['class'] . '::' . $call['function'];
708 foreach ( class_parents( $call['class'] ) as $parent ) {
709 $checkFor[] = $parent . '::' . $call['function'];
712 $checkFor[] = $call['function'];
715 foreach ( $checkFor as $check ) {
716 if ( isset( $wgRedactedFunctionArguments[$check] ) ) {
717 foreach ( (array)$wgRedactedFunctionArguments[$check] as $argNo ) {
718 $call['args'][$argNo] = $redacted;
723 if ( isset( $call['file'] ) && isset( $call['line'] ) ) {
724 $finalExceptionText .= "#{$i} {$call['file']}({$call['line']}): ";
726 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
727 // This matches behaviour of Exception::getTraceAsString to instead
728 // display "[internal function]".
729 $finalExceptionText .= "#{$i} [internal function]: ";
732 if ( isset( $call['class'] ) ) {
733 $finalExceptionText .= $call['class'] . $call['type'] . $call['function'];
735 $finalExceptionText .= $call['function'];
738 if ( isset( $call['args'] ) ) {
739 foreach ( $call['args'] as $arg ) {
740 if ( $arg === $redacted ) {
741 $args[] = 'REDACTED';
742 } elseif ( is_object( $arg ) ) {
743 $args[] = 'Object(' . get_class( $arg ) . ')';
744 } elseif( is_array( $arg ) ) {
747 $args[] = var_export( $arg, true );
751 $finalExceptionText .= '(' . implode( ', ', $args ) . ")\n";
753 return $finalExceptionText . '#' . ( $i +
1 ) . ' {main}';
758 * Get the ID for this error.
760 * The ID is saved so that one can match the one output to the user (when
761 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
764 * @param Exception $e
767 public static function getLogId( Exception
$e ) {
768 if ( !isset( $e->_mwLogId
) ) {
769 $e->_mwLogId
= wfRandomString( 8 );
775 * Return the requested URL and point to file and line number from which the
776 * exception occurred.
779 * @param Exception $e
782 public static function getLogMessage( Exception
$e ) {
785 $id = self
::getLogId( $e );
786 $file = $e->getFile();
787 $line = $e->getLine();
788 $message = $e->getMessage();
790 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
791 $url = $wgRequest->getRequestURL();
799 return "[$id] $url Exception from line $line of $file: $message";
803 * Log an exception to the exception log (if enabled).
805 * This method must not assume the exception is an MWException,
806 * it is also used to handle PHP errors or errors from other libraries.
809 * @param Exception $e
811 public static function logException( Exception
$e ) {
812 global $wgLogExceptionBacktrace;
814 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
815 $log = self
::getLogMessage( $e );
816 if ( $wgLogExceptionBacktrace ) {
817 wfDebugLog( 'exception', $log . "\n" . self
::formatRedactedTrace( $e ) . "\n" );
819 wfDebugLog( 'exception', $log );