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
{
34 * Should the exception use $wgOut to output the error?
38 function useOutputPage() {
39 return $this->useMessageCache() &&
40 !empty( $GLOBALS['wgFullyInitialised'] ) &&
41 !empty( $GLOBALS['wgOut'] ) &&
42 !empty( $GLOBALS['wgTitle'] );
46 * Whether to log this exception in the exception debug log.
51 function isLoggable() {
56 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
60 function useMessageCache() {
63 foreach ( $this->getTrace() as $frame ) {
64 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
69 return $wgLang instanceof Language
;
73 * Run hook to allow extensions to modify the text of the exception
75 * @param string $name class name of the exception
76 * @param array $args arguments to pass to the callback functions
77 * @return string|null string to output or null if any hook has been called
79 function runHooks( $name, $args = array() ) {
80 global $wgExceptionHooks;
82 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
83 return null; // Just silently ignore
86 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
87 !is_array( $wgExceptionHooks[$name] )
92 $hooks = $wgExceptionHooks[$name];
93 $callargs = array_merge( array( $this ), $args );
95 foreach ( $hooks as $hook ) {
98 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
100 // 'function' or array( 'class', hook' )
101 $result = call_user_func_array( $hook, $callargs );
106 if ( is_string( $result ) ) {
114 * Get a message from i18n
116 * @param string $key message name
117 * @param string $fallback default message if the message cache can't be
118 * called by the exception
119 * The function also has other parameters that are arguments for the message
120 * @return string message with arguments replaced
122 function msg( $key, $fallback /*[, params...] */ ) {
123 $args = array_slice( func_get_args(), 2 );
125 if ( $this->useMessageCache() ) {
126 return wfMessage( $key, $args )->plain();
128 return wfMsgReplaceArgs( $fallback, $args );
133 * If $wgShowExceptionDetails is true, return a HTML message with a
134 * backtrace to the error, otherwise show a message to ask to set it to true
135 * to show that information.
137 * @return string html to output
140 global $wgShowExceptionDetails;
142 if ( $wgShowExceptionDetails ) {
143 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $this ) ) ) .
144 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $this ) ) ) .
147 return "<div class=\"errorbox\">" .
148 '[' . MWExceptionHandler
::getLogId( $this ) . '] ' .
149 gmdate( 'Y-m-d H:i:s' ) .
150 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
151 "<!-- Set \$wgShowExceptionDetails = true; " .
152 "at the bottom of LocalSettings.php to show detailed " .
153 "debugging information. -->";
158 * Get the text to display when reporting the error on the command line.
159 * If $wgShowExceptionDetails is true, return a text message with a
160 * backtrace to the error.
165 global $wgShowExceptionDetails;
167 if ( $wgShowExceptionDetails ) {
168 return MWExceptionHandler
::getLogMessage( $this ) .
169 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $this ) . "\n";
171 return "Set \$wgShowExceptionDetails = true; " .
172 "in LocalSettings.php to show detailed debugging information.\n";
177 * Return the title of the page when reporting this error in a HTTP response.
181 function getPageTitle() {
183 return $this->msg( 'pagetitle', "$1 - $wgSitename", $this->msg( 'internalerror', 'Internal error' ) );
187 * Get a the ID for this error.
190 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
193 function getLogId() {
194 wfDeprecated( __METHOD__
, '1.22' );
195 return MWExceptionHandler
::getLogId( $this );
199 * Return the requested URL and point to file and line number from which the
203 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
206 function getLogMessage() {
207 wfDeprecated( __METHOD__
, '1.22' );
208 return MWExceptionHandler
::getLogMessage( $this );
212 * Output the exception report using HTML.
214 function reportHTML() {
216 if ( $this->useOutputPage() ) {
217 $wgOut->prepareErrorPage( $this->getPageTitle() );
219 $hookResult = $this->runHooks( get_class( $this ) );
221 $wgOut->addHTML( $hookResult );
223 $wgOut->addHTML( $this->getHTML() );
228 header( 'Content-Type: text/html; charset=utf-8' );
229 echo "<!DOCTYPE html>\n" .
231 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
232 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
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().
253 MWExceptionHandler
::logException( $this );
255 if ( defined( 'MW_API' ) ) {
256 // Unhandled API exception, we can't be sure that format printer is alive
257 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
258 wfHttpError( 500, 'Internal Server Error', $this->getText() );
259 } elseif ( self
::isCommandLine() ) {
260 MWExceptionHandler
::printError( $this->getText() );
262 header( 'HTTP/1.1 500 MediaWiki exception' );
263 header( 'Status: 500 MediaWiki exception', true );
264 header( "Content-Type: $wgMimeType; charset=utf-8", true );
271 * Check whether we are in command line mode or not to report the exception
272 * in the correct format.
276 static function isCommandLine() {
277 return !empty( $GLOBALS['wgCommandLineMode'] );
282 * Exception class which takes an HTML error message, and does not
283 * produce a backtrace. Replacement for OutputPage::fatalError().
288 class FatalError
extends MWException
{
294 return $this->getMessage();
301 return $this->getMessage();
306 * An error page which can definitely be safely rendered using the OutputPage.
311 class ErrorPageError
extends MWException
{
312 public $title, $msg, $params;
315 * Note: these arguments are keys into wfMessage(), not text!
317 * @param string|Message $title Message key (string) for page title, or a Message object
318 * @param string|Message $msg Message key (string) for error text, or a Message object
319 * @param array $params with parameters to wfMessage()
321 function __construct( $title, $msg, $params = null ) {
322 $this->title
= $title;
324 $this->params
= $params;
326 // Bug 44111: Messages in the log files should be in English and not
327 // customized by the local wiki. So get the default English version for
328 // passing to the parent constructor. Our overridden report() below
329 // makes sure that the page shown to the user is not forced to English.
330 if ( $msg instanceof Message
) {
331 $enMsg = clone( $msg );
333 $enMsg = wfMessage( $msg, $params );
335 $enMsg->inLanguage( 'en' )->useDatabase( false );
336 parent
::__construct( $enMsg->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 string|Message $msg A message key (default: 'badtitletext')
358 * @param array $params 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 // @todo FIXME: Implement a more proper way to get context here.
465 $params = $block->getPermissionsError( RequestContext
::getMain() );
466 parent
::__construct( 'blockedtitle', array_shift( $params ), $params );
471 * Shows a generic "user is not logged in" error page.
473 * This is essentially an ErrorPageError exception which by default uses the
474 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
480 * if( $user->isAnon() ) {
481 * throw new UserNotLoggedIn();
485 * Note the parameter order differs from ErrorPageError, this allows you to
486 * simply specify a reason without overriding the default title.
490 * if( $user->isAnon() ) {
491 * throw new UserNotLoggedIn( 'action-require-loggedin' );
497 class UserNotLoggedIn
extends ErrorPageError
{
500 * @param string $reasonMsg A message key containing the reason for the error.
501 * Optional, default: 'exception-nologin-text'
502 * @param string $titleMsg A message key to set the page title.
503 * Optional, default: 'exception-nologin'
504 * @param array $params Parameters to wfMessage().
505 * Optional, default: null
507 public function __construct(
508 $reasonMsg = 'exception-nologin-text',
509 $titleMsg = 'exception-nologin',
512 parent
::__construct( $titleMsg, $reasonMsg, $params );
517 * Show an error that looks like an HTTP server error.
518 * Replacement for wfHttpError().
523 class HttpError
extends MWException
{
524 private $httpCode, $header, $content;
529 * @param $httpCode Integer: HTTP status code to send to the client
530 * @param string|Message $content content of the message
531 * @param string|Message $header content of the header (\<title\> and \<h1\>)
533 public function __construct( $httpCode, $content, $header = null ) {
534 parent
::__construct( $content );
535 $this->httpCode
= (int)$httpCode;
536 $this->header
= $header;
537 $this->content
= $content;
541 * Returns the HTTP status code supplied to the constructor.
545 public function getStatusCode() {
546 return $this->httpCode
;
550 * Report the HTTP error.
551 * Sends the appropriate HTTP status code and outputs an
552 * HTML page with an error message.
554 public function report() {
555 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
557 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
558 header( 'Content-type: text/html; charset=utf-8' );
560 print $this->getHTML();
564 * Returns HTML for reporting the HTTP error.
565 * This will be a minimal but complete HTML document.
567 * @return string HTML
569 public function getHTML() {
570 if ( $this->header
=== null ) {
571 $header = HttpStatus
::getMessage( $this->httpCode
);
572 } elseif ( $this->header
instanceof Message
) {
573 $header = $this->header
->escaped();
575 $header = htmlspecialchars( $this->header
);
578 if ( $this->content
instanceof Message
) {
579 $content = $this->content
->escaped();
581 $content = htmlspecialchars( $this->content
);
584 return "<!DOCTYPE html>\n" .
585 "<html><head><title>$header</title></head>\n" .
586 "<body><h1>$header</h1><p>$content</p></body></html>\n";
591 * Handler class for MWExceptions
594 class MWExceptionHandler
{
596 * Install an exception handler for MediaWiki exception types.
598 public static function installHandler() {
599 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
603 * Report an exception to the user
605 protected static function report( Exception
$e ) {
606 global $wgShowExceptionDetails;
608 $cmdLine = MWException
::isCommandLine();
610 if ( $e instanceof MWException
) {
612 // Try and show the exception prettily, with the normal skin infrastructure
614 } catch ( Exception
$e2 ) {
615 // Exception occurred from within exception handler
616 // Show a simpler error message for the original exception,
617 // don't try to invoke report()
618 $message = "MediaWiki internal error.\n\n";
620 if ( $wgShowExceptionDetails ) {
621 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
622 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
623 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
624 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
626 $message .= "Exception caught inside exception handler.\n\n" .
627 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
628 "to show detailed debugging information.";
634 self
::printError( $message );
636 echo nl2br( htmlspecialchars( $message ) ) . "\n";
640 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
641 get_class( $e ) . "\"";
643 if ( $wgShowExceptionDetails ) {
644 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
645 self
::getRedactedTraceAsString( $e ) . "\n";
649 self
::printError( $message );
651 echo nl2br( htmlspecialchars( $message ) ) . "\n";
657 * Print a message, if possible to STDERR.
658 * Use this in command line mode only (see isCommandLine)
660 * @param string $message Failure text
662 public static function printError( $message ) {
663 # NOTE: STDERR may not be available, especially if php-cgi is used from the
664 # command line (bug #15602). Try to produce meaningful output anyway. Using
665 # echo may corrupt output to STDOUT though.
666 if ( defined( 'STDERR' ) ) {
667 fwrite( STDERR
, $message );
674 * Exception handler which simulates the appropriate catch() handling:
678 * } catch ( MWException $e ) {
680 * } catch ( Exception $e ) {
681 * echo $e->__toString();
684 public static function handle( $e ) {
685 global $wgFullyInitialised;
690 if ( $wgFullyInitialised ) {
692 // uses $wgRequest, hence the $wgFullyInitialised condition
693 wfLogProfilingData();
694 } catch ( Exception
$e ) {
698 // Exit value should be nonzero for the benefit of shell jobs
703 * Generate a string representation of an exception's stack trace
705 * Like Exception::getTraceAsString, but replaces argument values with
706 * argument type or class name.
708 * @param Exception $e
711 public static function getRedactedTraceAsString( Exception
$e ) {
714 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
715 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
716 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
718 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
719 // This matches behaviour of Exception::getTraceAsString to instead
720 // display "[internal function]".
721 $text .= "#{$level} [internal function]: ";
724 if ( isset( $frame['class'] ) ) {
725 $text .= $frame['class'] . $frame['type'] . $frame['function'];
727 $text .= $frame['function'];
730 if ( isset( $frame['args'] ) ) {
731 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
738 $text .= "#{$level} {main}";
744 * Return a copy of an exception's backtrace as an array.
746 * Like Exception::getTrace, but replaces each element in each frame's
747 * argument array with the name of its class (if the element is an object)
748 * or its type (if the element is a PHP primitive).
751 * @param Exception $e
754 public static function getRedactedTrace( Exception
$e ) {
755 return array_map( function ( $frame ) {
756 if ( isset( $frame['args'] ) ) {
757 $frame['args'] = array_map( function ( $arg ) {
758 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
766 * Get the ID for this error.
768 * The ID is saved so that one can match the one output to the user (when
769 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
772 * @param Exception $e
775 public static function getLogId( Exception
$e ) {
776 if ( !isset( $e->_mwLogId
) ) {
777 $e->_mwLogId
= wfRandomString( 8 );
783 * Return the requested URL and point to file and line number from which the
784 * exception occurred.
787 * @param Exception $e
790 public static function getLogMessage( Exception
$e ) {
793 $id = self
::getLogId( $e );
794 $file = $e->getFile();
795 $line = $e->getLine();
796 $message = $e->getMessage();
798 if ( isset( $wgRequest ) && !$wgRequest instanceof FauxRequest
) {
799 $url = $wgRequest->getRequestURL();
807 return "[$id] $url Exception from line $line of $file: $message";
811 * Log an exception to the exception log (if enabled).
813 * This method must not assume the exception is an MWException,
814 * it is also used to handle PHP errors or errors from other libraries.
817 * @param Exception $e
819 public static function logException( Exception
$e ) {
820 global $wgLogExceptionBacktrace;
822 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
823 $log = self
::getLogMessage( $e );
824 if ( $wgLogExceptionBacktrace ) {
825 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() . "\n" );
827 wfDebugLog( 'exception', $log );