3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 * Handler class for MWExceptions
25 class MWExceptionHandler
{
27 protected static $reservedMemory;
28 protected static $fatalErrorTypes = array(
29 E_ERROR
, E_PARSE
, E_CORE_ERROR
, E_COMPILE_ERROR
, E_USER_ERROR
,
30 /* HHVM's FATAL_ERROR level */ 16777217,
34 * Install handlers with PHP.
36 public static function installHandler() {
37 set_exception_handler( array( 'MWExceptionHandler', 'handleException' ) );
38 set_error_handler( array( 'MWExceptionHandler', 'handleError' ) );
40 // Reserve 16k of memory so we can report OOM fatals
41 self
::$reservedMemory = str_repeat( ' ', 16384 );
42 register_shutdown_function(
43 array( 'MWExceptionHandler', 'handleFatalError' )
48 * Report an exception to the user
51 protected static function report( Exception
$e ) {
52 global $wgShowExceptionDetails;
54 $cmdLine = MWException
::isCommandLine();
56 if ( $e instanceof MWException
) {
58 // Try and show the exception prettily, with the normal skin infrastructure
60 } catch ( Exception
$e2 ) {
61 // Exception occurred from within exception handler
62 // Show a simpler message for the original exception,
63 // don't try to invoke report()
64 $message = "MediaWiki internal error.\n\n";
66 if ( $wgShowExceptionDetails ) {
67 $message .= 'Original exception: ' . self
::getLogMessage( $e ) .
68 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e ) .
69 "\n\nException caught inside exception handler: " . self
::getLogMessage( $e2 ) .
70 "\nBacktrace:\n" . self
::getRedactedTraceAsString( $e2 );
72 $message .= "Exception caught inside exception handler.\n\n" .
73 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
74 "to show detailed debugging information.";
80 self
::printError( $message );
82 echo nl2br( htmlspecialchars( $message ) ) . "\n";
86 $message = "Exception encountered, of type \"" . get_class( $e ) . "\"";
88 if ( $wgShowExceptionDetails ) {
89 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
90 self
::getRedactedTraceAsString( $e ) . "\n";
94 self
::printError( $message );
96 echo nl2br( htmlspecialchars( $message ) ) . "\n";
103 * Print a message, if possible to STDERR.
104 * Use this in command line mode only (see isCommandLine)
106 * @param string $message Failure text
108 public static function printError( $message ) {
109 # NOTE: STDERR may not be available, especially if php-cgi is used from the
110 # command line (bug #15602). Try to produce meaningful output anyway. Using
111 # echo may corrupt output to STDOUT though.
112 if ( defined( 'STDERR' ) ) {
113 fwrite( STDERR
, $message );
120 * If there are any open database transactions, roll them back and log
121 * the stack trace of the exception that should have been caught so the
122 * transaction could be aborted properly.
125 * @param Exception $e
127 public static function rollbackMasterChangesAndLog( Exception
$e ) {
128 $factory = wfGetLBFactory();
129 if ( $factory->hasMasterChanges() ) {
130 wfDebugLog( 'Bug56269',
131 'Exception thrown with an uncommited database transaction: ' .
132 MWExceptionHandler
::getLogMessage( $e ) . "\n" .
133 $e->getTraceAsString()
135 $factory->rollbackMasterChanges();
140 * Exception handler which simulates the appropriate catch() handling:
144 * } catch ( Exception $e ) {
146 * } catch ( Exception $e ) {
147 * echo $e->__toString();
151 * @param Exception $e
153 public static function handleException( $e ) {
154 global $wgFullyInitialised;
156 self
::rollbackMasterChangesAndLog( $e );
157 self
::logException( $e );
161 if ( $wgFullyInitialised ) {
163 // uses $wgRequest, hence the $wgFullyInitialised condition
164 wfLogProfilingData();
165 } catch ( Exception
$e ) {
169 // Exit value should be nonzero for the benefit of shell jobs
175 * @param int $level Error level raised
176 * @param string $message
177 * @param string $file
180 public static function handleError( $level, $message, $file = null, $line = null ) {
181 // Map error constant to error name (reverse-engineer PHP error reporting)
186 case E_COMPILE_ERROR
:
188 case E_RECOVERABLE_ERROR
:
190 $levelName = 'Error';
195 case E_COMPILE_WARNING
:
197 $levelName = 'Warning';
201 $levelName = 'Notice';
204 $levelName = 'Strict Standards';
207 case E_USER_DEPRECATED
:
208 $levelName = 'Deprecated';
210 case /* HHVM's FATAL_ERROR */ 16777217:
211 $levelName = 'Fatal';
215 $levelName = 'Unknown error';
219 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
220 self
::logError( $e, $channel );
222 // This handler is for logging only. Return false will instruct PHP
223 // to continue regular handling.
229 * Look for a fatal error as the cause of the request termination and log
232 * Special handling is included for missing class errors as they may
233 * indicate that the user needs to install 3rd-party libraries via
234 * Composer or other means.
238 public static function handleFatalError() {
239 self
::$reservedMemory = null;
240 $lastError = error_get_last();
243 isset( $lastError['type'] ) &&
244 in_array( $lastError['type'], self
::$fatalErrorTypes )
246 $msg = "Fatal Error: {$lastError['message']}";
247 // HHVM: Class undefined: foo
248 // PHP5: Class 'foo' not found
249 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/",
250 $lastError['message']
252 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
256 MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
258 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
260 // @codingStandardsIgnoreEnd
262 $e = new ErrorException( $msg, 0, $lastError['type'] );
263 self
::logError( $e, 'fatal' );
268 * Generate a string representation of an exception's stack trace
270 * Like Exception::getTraceAsString, but replaces argument values with
271 * argument type or class name.
273 * @param Exception $e
276 public static function getRedactedTraceAsString( Exception
$e ) {
279 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
280 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
281 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
283 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
284 // This matches behaviour of Exception::getTraceAsString to instead
285 // display "[internal function]".
286 $text .= "#{$level} [internal function]: ";
289 if ( isset( $frame['class'] ) ) {
290 $text .= $frame['class'] . $frame['type'] . $frame['function'];
292 $text .= $frame['function'];
295 if ( isset( $frame['args'] ) ) {
296 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
303 $text .= "#{$level} {main}";
309 * Return a copy of an exception's backtrace as an array.
311 * Like Exception::getTrace, but replaces each element in each frame's
312 * argument array with the name of its class (if the element is an object)
313 * or its type (if the element is a PHP primitive).
316 * @param Exception $e
319 public static function getRedactedTrace( Exception
$e ) {
320 return array_map( function ( $frame ) {
321 if ( isset( $frame['args'] ) ) {
322 $frame['args'] = array_map( function ( $arg ) {
323 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
331 * Get the ID for this exception.
333 * The ID is saved so that one can match the one output to the user (when
334 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
337 * @param Exception $e
340 public static function getLogId( Exception
$e ) {
341 if ( !isset( $e->_mwLogId
) ) {
342 $e->_mwLogId
= wfRandomString( 8 );
348 * If the exception occurred in the course of responding to a request,
349 * returns the requested URL. Otherwise, returns false.
352 * @return string|false
354 public static function getURL() {
356 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
359 return $wgRequest->getRequestURL();
363 * Get a message formatting the exception message and its origin.
366 * @param Exception $e
369 public static function getLogMessage( Exception
$e ) {
370 $id = self
::getLogId( $e );
371 $type = get_class( $e );
372 $file = $e->getFile();
373 $line = $e->getLine();
374 $message = $e->getMessage();
375 $url = self
::getURL() ?
: '[no req]';
377 return "[$id] $url $type from line $line of $file: $message";
381 * Serialize an Exception object to JSON.
383 * The JSON object will have keys 'id', 'file', 'line', 'message', and
384 * 'url'. These keys map to string values, with the exception of 'line',
385 * which is a number, and 'url', which may be either a string URL or or
386 * null if the exception did not occur in the context of serving a web
389 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
390 * key, mapped to the array return value of Exception::getTrace, but with
391 * each element in each frame's "args" array (if set) replaced with the
392 * argument's class name (if the argument is an object) or type name (if
393 * the argument is a PHP primitive).
395 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
399 * "type": "MWException",
400 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
402 * "message": "Non-string key given",
403 * "url": "/wiki/Main_Page"
407 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
411 * "type": "MWException",
412 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
414 * "message": "Non-string key given",
415 * "url": "/wiki/Main_Page",
417 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
420 * "class": "MessageCache",
428 * @param Exception $e
429 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
430 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
431 * @return string|false JSON string if successful; false upon failure
433 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
434 global $wgLogExceptionBacktrace;
436 $exceptionData = array(
437 'id' => self
::getLogId( $e ),
438 'type' => get_class( $e ),
439 'file' => $e->getFile(),
440 'line' => $e->getLine(),
441 'message' => $e->getMessage(),
444 if ( $e instanceof ErrorException
&& ( error_reporting() & $e->getSeverity() ) === 0 ) {
445 // Flag surpressed errors
446 $exceptionData['suppressed'] = true;
449 // Because MediaWiki is first and foremost a web application, we set a
450 // 'url' key unconditionally, but set it to null if the exception does
451 // not occur in the context of a web request, as a way of making that
452 // fact visible and explicit.
453 $exceptionData['url'] = self
::getURL() ?
: null;
455 if ( $wgLogExceptionBacktrace ) {
456 // Argument values may not be serializable, so redact them.
457 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
460 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
464 * Log an exception to the exception log (if enabled).
466 * This method must not assume the exception is an MWException,
467 * it is also used to handle PHP exceptions or exceptions from other libraries.
470 * @param Exception $e
472 public static function logException( Exception
$e ) {
473 global $wgLogExceptionBacktrace;
475 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
476 $log = self
::getLogMessage( $e );
477 if ( $wgLogExceptionBacktrace ) {
478 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
480 wfDebugLog( 'exception', $log );
483 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
484 if ( $json !== false ) {
485 wfDebugLog( 'exception-json', $json, 'private' );
491 * Log an exception that wasn't thrown but made to wrap an error.
494 * @param ErrorException $e
495 * @param string $channel
497 protected static function logError( ErrorException
$e, $channel ) {
498 global $wgLogExceptionBacktrace;
500 // The set_error_handler callback is independent from error_reporting.
501 // Filter out unwanted errors manually (e.g. when wfSuppressWarnings is active).
502 if ( ( error_reporting() & $e->getSeverity() ) !== 0 ) {
503 $log = self
::getLogMessage( $e );
504 if ( $wgLogExceptionBacktrace ) {
505 wfDebugLog( $channel, $log . "\n" . $e->getTraceAsString() );
507 wfDebugLog( $channel, $log );
511 // Include all errors in the json log (surpressed errors will be flagged)
512 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
513 if ( $json !== false ) {
514 wfDebugLog( "$channel-json", $json, 'private' );