d8c7b6aa877f6e6f5caed397da5be25f936c00e7
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'] );
45 * Whether to log this exception in the exception debug log.
50 function isLoggable() {
55 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
59 function useMessageCache() {
62 foreach ( $this->getTrace() as $frame ) {
63 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
68 return $wgLang instanceof Language
;
72 * Run hook to allow extensions to modify the text of the exception
74 * @param string $name class name of the exception
75 * @param array $args arguments to pass to the callback functions
76 * @return string|null string to output or null if any hook has been called
78 function runHooks( $name, $args = array() ) {
79 global $wgExceptionHooks;
81 if ( !isset( $wgExceptionHooks ) ||
!is_array( $wgExceptionHooks ) ) {
82 return null; // Just silently ignore
85 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
86 !is_array( $wgExceptionHooks[$name] )
91 $hooks = $wgExceptionHooks[$name];
92 $callargs = array_merge( array( $this ), $args );
94 foreach ( $hooks as $hook ) {
97 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
99 // 'function' or array( 'class', hook' )
100 $result = call_user_func_array( $hook, $callargs );
105 if ( is_string( $result ) ) {
113 * Get a message from i18n
115 * @param string $key message name
116 * @param string $fallback default message if the message cache can't be
117 * called by the exception
118 * The function also has other parameters that are arguments for the message
119 * @return string message with arguments replaced
121 function msg( $key, $fallback /*[, params...] */ ) {
122 $args = array_slice( func_get_args(), 2 );
124 if ( $this->useMessageCache() ) {
125 return wfMessage( $key, $args )->plain();
127 return wfMsgReplaceArgs( $fallback, $args );
132 * If $wgShowExceptionDetails is true, return a HTML message with a
133 * backtrace to the error, otherwise show a message to ask to set it to true
134 * to show that information.
136 * @return string html to output
139 global $wgShowExceptionDetails;
141 if ( $wgShowExceptionDetails ) {
142 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $this ) ) ) .
143 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $this ) ) ) .
146 return "<div class=\"errorbox\">" .
147 '[' . MWExceptionHandler
::getLogId( $this ) . '] ' .
148 gmdate( 'Y-m-d H:i:s' ) .
149 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
150 "<!-- Set \$wgShowExceptionDetails = true; " .
151 "at the bottom of LocalSettings.php to show detailed " .
152 "debugging information. -->";
157 * Get the text to display when reporting the error on the command line.
158 * If $wgShowExceptionDetails is true, return a text message with a
159 * backtrace to the error.
164 global $wgShowExceptionDetails;
166 if ( $wgShowExceptionDetails ) {
167 return MWExceptionHandler
::getLogMessage( $this ) .
168 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $this ) . "\n";
170 return "Set \$wgShowExceptionDetails = true; " .
171 "in LocalSettings.php to show detailed debugging information.\n";
176 * Return the title of the page when reporting this error in a HTTP response.
180 function getPageTitle() {
182 return $this->msg( 'pagetitle', "$1 - $wgSitename", $this->msg( 'internalerror', 'Internal error' ) );
186 * Get a the ID for this error.
189 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
192 function getLogId() {
193 wfDeprecated( __METHOD__
, '1.22' );
194 return MWExceptionHandler
::getLogId( $this );
198 * Return the requested URL and point to file and line number from which the
202 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
205 function getLogMessage() {
206 wfDeprecated( __METHOD__
, '1.22' );
207 return MWExceptionHandler
::getLogMessage( $this );
211 * Output the exception report using HTML.
213 function reportHTML() {
215 if ( $this->useOutputPage() ) {
216 $wgOut->prepareErrorPage( $this->getPageTitle() );
218 $hookResult = $this->runHooks( get_class( $this ) );
220 $wgOut->addHTML( $hookResult );
222 $wgOut->addHTML( $this->getHTML() );
227 header( 'Content-Type: text/html; charset=utf-8' );
228 echo "<!DOCTYPE html>\n" .
230 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
231 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
234 $hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
238 echo $this->getHTML();
241 echo "</body></html>\n";
246 * Output a report about the exception and takes care of formatting.
247 * It will be either HTML or plain text based on isCommandLine().
252 MWExceptionHandler
::logException( $this );
254 if ( defined( 'MW_API' ) ) {
255 // Unhandled API exception, we can't be sure that format printer is alive
256 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
257 wfHttpError( 500, 'Internal Server Error', $this->getText() );
258 } elseif ( self
::isCommandLine() ) {
259 MWExceptionHandler
::printError( $this->getText() );
261 header( 'HTTP/1.1 500 MediaWiki exception' );
262 header( 'Status: 500 MediaWiki exception', true );
263 header( "Content-Type: $wgMimeType; charset=utf-8", true );
270 * Check whether we are in command line mode or not to report the exception
271 * in the correct format.
275 static function isCommandLine() {
276 return !empty( $GLOBALS['wgCommandLineMode'] );
281 * Exception class which takes an HTML error message, and does not
282 * produce a backtrace. Replacement for OutputPage::fatalError().
287 class FatalError
extends MWException
{
293 return $this->getMessage();
300 return $this->getMessage();
305 * An error page which can definitely be safely rendered using the OutputPage.
310 class ErrorPageError
extends MWException
{
311 public $title, $msg, $params;
314 * Note: these arguments are keys into wfMessage(), not text!
316 * @param string|Message $title Message key (string) for page title, or a Message object
317 * @param string|Message $msg Message key (string) for error text, or a Message object
318 * @param array $params with parameters to wfMessage()
320 function __construct( $title, $msg, $params = array() ) {
321 $this->title
= $title;
323 $this->params
= $params;
325 // Bug 44111: Messages in the log files should be in English and not
326 // customized by the local wiki. So get the default English version for
327 // passing to the parent constructor. Our overridden report() below
328 // makes sure that the page shown to the user is not forced to English.
329 if ( $msg instanceof Message
) {
330 $enMsg = clone( $msg );
332 $enMsg = wfMessage( $msg, $params );
334 $enMsg->inLanguage( 'en' )->useDatabase( false );
335 parent
::__construct( $enMsg->text() );
341 $wgOut->showErrorPage( $this->title
, $this->msg
, $this->params
);
347 * Show an error page on a badtitle.
348 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
349 * browser it is not really a valid content.
354 class BadTitleError
extends ErrorPageError
{
356 * @param string|Message $msg A message key (default: 'badtitletext')
357 * @param array $params parameter to wfMessage()
359 function __construct( $msg = 'badtitletext', $params = array() ) {
360 parent
::__construct( 'badtitle', $msg, $params );
364 * Just like ErrorPageError::report() but additionally set
365 * a 400 HTTP status code (bug 33646).
370 // bug 33646: a badtitle error page need to return an error code
371 // to let mobile browser now that it is not a normal page.
372 $wgOut->setStatusCode( 400 );
379 * Show an error when a user tries to do something they do not have the necessary
385 class PermissionsError
extends ErrorPageError
{
386 public $permission, $errors;
388 function __construct( $permission, $errors = array() ) {
391 $this->permission
= $permission;
393 if ( !count( $errors ) ) {
395 array( 'User', 'makeGroupLinkWiki' ),
396 User
::getGroupsWithPermission( $this->permission
)
400 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
402 $errors[] = array( 'badaccess-group0' );
406 $this->errors
= $errors;
412 $wgOut->showPermissionsErrorPage( $this->errors
, $this->permission
);
418 * Show an error when the wiki is locked/read-only and the user tries to do
419 * something that requires write access.
424 class ReadOnlyError
extends ErrorPageError
{
425 public function __construct() {
429 wfReadOnlyReason() ?
: array()
435 * Show an error when the user hits a rate limit.
440 class ThrottledError
extends ErrorPageError
{
441 public function __construct() {
444 'actionthrottledtext'
448 public function report() {
450 $wgOut->setStatusCode( 503 );
456 * Show an error when the user tries to do something whilst blocked.
461 class UserBlockedError
extends ErrorPageError
{
462 public function __construct( Block
$block ) {
463 // @todo FIXME: Implement a more proper way to get context here.
464 $params = $block->getPermissionsError( RequestContext
::getMain() );
465 parent
::__construct( 'blockedtitle', array_shift( $params ), $params );
470 * Shows a generic "user is not logged in" error page.
472 * This is essentially an ErrorPageError exception which by default uses the
473 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
479 * if( $user->isAnon() ) {
480 * throw new UserNotLoggedIn();
484 * Note the parameter order differs from ErrorPageError, this allows you to
485 * simply specify a reason without overriding the default title.
489 * if( $user->isAnon() ) {
490 * throw new UserNotLoggedIn( 'action-require-loggedin' );
496 class UserNotLoggedIn
extends ErrorPageError
{
499 * @param string $reasonMsg A message key containing the reason for the error.
500 * Optional, default: 'exception-nologin-text'
501 * @param string $titleMsg A message key to set the page title.
502 * Optional, default: 'exception-nologin'
503 * @param array $params Parameters to wfMessage().
504 * Optional, default: array()
506 public function __construct(
507 $reasonMsg = 'exception-nologin-text',
508 $titleMsg = 'exception-nologin',
511 parent
::__construct( $titleMsg, $reasonMsg, $params );
516 * Show an error that looks like an HTTP server error.
517 * Replacement for wfHttpError().
522 class HttpError
extends MWException
{
523 private $httpCode, $header, $content;
528 * @param $httpCode Integer: HTTP status code to send to the client
529 * @param string|Message $content content of the message
530 * @param string|Message $header content of the header (\<title\> and \<h1\>)
532 public function __construct( $httpCode, $content, $header = null ) {
533 parent
::__construct( $content );
534 $this->httpCode
= (int)$httpCode;
535 $this->header
= $header;
536 $this->content
= $content;
540 * Returns the HTTP status code supplied to the constructor.
544 public function getStatusCode() {
545 return $this->httpCode
;
549 * Report the HTTP error.
550 * Sends the appropriate HTTP status code and outputs an
551 * HTML page with an error message.
553 public function report() {
554 $httpMessage = HttpStatus
::getMessage( $this->httpCode
);
556 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode
);
557 header( 'Content-type: text/html; charset=utf-8' );
559 print $this->getHTML();
563 * Returns HTML for reporting the HTTP error.
564 * This will be a minimal but complete HTML document.
566 * @return string HTML
568 public function getHTML() {
569 if ( $this->header
=== null ) {
570 $header = HttpStatus
::getMessage( $this->httpCode
);
571 } elseif ( $this->header
instanceof Message
) {
572 $header = $this->header
->escaped();
574 $header = htmlspecialchars( $this->header
);
577 if ( $this->content
instanceof Message
) {
578 $content = $this->content
->escaped();
580 $content = htmlspecialchars( $this->content
);
583 return "<!DOCTYPE html>\n" .
584 "<html><head><title>$header</title></head>\n" .
585 "<body><h1>$header</h1><p>$content</p></body></html>\n";
590 * Handler class for MWExceptions
593 class MWExceptionHandler
{
595 * Install an exception handler for MediaWiki exception types.
597 public static function installHandler() {
598 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
602 * Report an exception to the user
604 protected static function report( Exception
$e ) {
605 global $wgShowExceptionDetails;
607 $cmdLine = MWException
::isCommandLine();
609 if ( $e instanceof MWException
) {
611 // Try and show the exception prettily, with the normal skin infrastructure
613 } catch ( Exception
$e2 ) {
614 // Exception occurred from within exception handler
615 // Show a simpler error message for the original exception,
616 // don't try to invoke report()
617 $message = "MediaWiki internal error.\n\n";
619 if ( $wgShowExceptionDetails ) {
620 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
621 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
622 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
623 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
625 $message .= "Exception caught inside exception handler.\n\n" .
626 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
627 "to show detailed debugging information.";
633 self
::printError( $message );
635 echo nl2br( htmlspecialchars( $message ) ) . "\n";
639 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
640 get_class( $e ) . "\"";
642 if ( $wgShowExceptionDetails ) {
643 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
644 self
::getRedactedTraceAsString( $e ) . "\n";
648 self
::printError( $message );
650 echo nl2br( htmlspecialchars( $message ) ) . "\n";
656 * Print a message, if possible to STDERR.
657 * Use this in command line mode only (see isCommandLine)
659 * @param string $message Failure text
661 public static function printError( $message ) {
662 # NOTE: STDERR may not be available, especially if php-cgi is used from the
663 # command line (bug #15602). Try to produce meaningful output anyway. Using
664 # echo may corrupt output to STDOUT though.
665 if ( defined( 'STDERR' ) ) {
666 fwrite( STDERR
, $message );
673 * Exception handler which simulates the appropriate catch() handling:
677 * } catch ( MWException $e ) {
679 * } catch ( Exception $e ) {
680 * echo $e->__toString();
683 public static function handle( $e ) {
684 global $wgFullyInitialised;
689 if ( $wgFullyInitialised ) {
691 // uses $wgRequest, hence the $wgFullyInitialised condition
692 wfLogProfilingData();
693 } catch ( Exception
$e ) {
697 // Exit value should be nonzero for the benefit of shell jobs
702 * Generate a string representation of an exception's stack trace
704 * Like Exception::getTraceAsString, but replaces argument values with
705 * argument type or class name.
707 * @param Exception $e
710 public static function getRedactedTraceAsString( Exception
$e ) {
713 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
714 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
715 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
717 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
718 // This matches behaviour of Exception::getTraceAsString to instead
719 // display "[internal function]".
720 $text .= "#{$level} [internal function]: ";
723 if ( isset( $frame['class'] ) ) {
724 $text .= $frame['class'] . $frame['type'] . $frame['function'];
726 $text .= $frame['function'];
729 if ( isset( $frame['args'] ) ) {
730 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
737 $text .= "#{$level} {main}";
743 * Return a copy of an exception's backtrace as an array.
745 * Like Exception::getTrace, but replaces each element in each frame's
746 * argument array with the name of its class (if the element is an object)
747 * or its type (if the element is a PHP primitive).
750 * @param Exception $e
753 public static function getRedactedTrace( Exception
$e ) {
754 return array_map( function ( $frame ) {
755 if ( isset( $frame['args'] ) ) {
756 $frame['args'] = array_map( function ( $arg ) {
757 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
765 * Get the ID for this error.
767 * The ID is saved so that one can match the one output to the user (when
768 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
771 * @param Exception $e
774 public static function getLogId( Exception
$e ) {
775 if ( !isset( $e->_mwLogId
) ) {
776 $e->_mwLogId
= wfRandomString( 8 );
782 * If the exception occurred in the course of responding to a request,
783 * returns the requested URL. Otherwise, returns false.
786 * @return string|bool
788 public static function getURL() {
790 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
793 return $wgRequest->getRequestURL();
797 * Return the requested URL and point to file and line number from which the
798 * exception occurred.
801 * @param Exception $e
804 public static function getLogMessage( Exception
$e ) {
805 $id = self
::getLogId( $e );
806 $file = $e->getFile();
807 $line = $e->getLine();
808 $message = $e->getMessage();
809 $url = self
::getURL() ?
: '[no req]';
811 return "[$id] $url Exception from line $line of $file: $message";
815 * Serialize an Exception object to JSON.
817 * The JSON object will have keys 'id', 'file', 'line', 'message', and
818 * 'url'. These keys map to string values, with the exception of 'line',
819 * which is a number, and 'url', which may be either a string URL or or
820 * null if the exception did not occur in the context of serving a web
823 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
824 * key, mapped to the array return value of Exception::getTrace, but with
825 * each element in each frame's "args" array (if set) replaced with the
826 * argument's class name (if the argument is an object) or type name (if
827 * the argument is a PHP primitive).
829 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
833 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
835 * "message": "Non-string key given",
836 * "url": "/wiki/Main_Page"
840 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
844 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
846 * "message": "Non-string key given",
847 * "url": "/wiki/Main_Page",
849 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
852 * "class": "MessageCache",
860 * @param Exception $e
861 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
862 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
863 * @return string|bool: JSON string if successful; false upon failure
865 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
866 global $wgLogExceptionBacktrace;
868 $exceptionData = array(
869 'id' => self
::getLogId( $e ),
870 'file' => $e->getFile(),
871 'line' => $e->getLine(),
872 'message' => $e->getMessage(),
875 // Because MediaWiki is first and foremost a web application, we set a
876 // 'url' key unconditionally, but set it to null if the exception does
877 // not occur in the context of a web request, as a way of making that
878 // fact visible and explicit.
879 $exceptionData['url'] = self
::getURL() ?
: null;
881 if ( $wgLogExceptionBacktrace ) {
882 // Argument values may not be serializable, so redact them.
883 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
886 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
890 * Log an exception to the exception log (if enabled).
892 * This method must not assume the exception is an MWException,
893 * it is also used to handle PHP errors or errors from other libraries.
896 * @param Exception $e
898 public static function logException( Exception
$e ) {
899 global $wgLogExceptionBacktrace;
901 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
902 $log = self
::getLogMessage( $e );
903 if ( $wgLogExceptionBacktrace ) {
904 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() . "\n" );
906 wfDebugLog( 'exception', $log );
909 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
910 if ( $json !== false ) {
911 wfDebugLog( 'exception-json', $json, false );