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 = "Unexpected non-MediaWiki exception encountered, of type \"" .
87 get_class( $e ) . "\"";
89 if ( $wgShowExceptionDetails ) {
90 $message .= "\n" . MWExceptionHandler
::getLogMessage( $e ) . "\nBacktrace:\n" .
91 self
::getRedactedTraceAsString( $e ) . "\n";
95 self
::printError( $message );
97 echo nl2br( htmlspecialchars( $message ) ) . "\n";
104 * Print a message, if possible to STDERR.
105 * Use this in command line mode only (see isCommandLine)
107 * @param string $message Failure text
109 public static function printError( $message ) {
110 # NOTE: STDERR may not be available, especially if php-cgi is used from the
111 # command line (bug #15602). Try to produce meaningful output anyway. Using
112 # echo may corrupt output to STDOUT though.
113 if ( defined( 'STDERR' ) ) {
114 fwrite( STDERR
, $message );
121 * If there are any open database transactions, roll them back and log
122 * the stack trace of the exception that should have been caught so the
123 * transaction could be aborted properly.
126 * @param Exception $e
128 public static function rollbackMasterChangesAndLog( Exception
$e ) {
129 $factory = wfGetLBFactory();
130 if ( $factory->hasMasterChanges() ) {
131 wfDebugLog( 'Bug56269',
132 'Exception thrown with an uncommited database transaction: ' .
133 MWExceptionHandler
::getLogMessage( $e ) . "\n" .
134 $e->getTraceAsString()
136 $factory->rollbackMasterChanges();
141 * Exception handler which simulates the appropriate catch() handling:
145 * } catch ( MWException $e ) {
147 * } catch ( Exception $e ) {
148 * echo $e->__toString();
152 * @param Exception $e
154 public static function handleException( $e ) {
155 global $wgFullyInitialised;
157 self
::rollbackMasterChangesAndLog( $e );
158 self
::logException( $e );
162 if ( $wgFullyInitialised ) {
164 // uses $wgRequest, hence the $wgFullyInitialised condition
165 wfLogProfilingData();
166 } catch ( Exception
$e ) {
170 // Exit value should be nonzero for the benefit of shell jobs
176 * @param int $level Error level raised
177 * @param string $message
178 * @param string $file
181 public static function handleError( $level, $message, $file = null, $line = null ) {
182 // Map error constant to error name (reverse-engineer PHP error reporting)
186 case E_COMPILE_ERROR
:
188 case E_RECOVERABLE_ERROR
:
190 $levelName = 'Error';
194 case E_COMPILE_WARNING
:
196 $levelName = 'Warning';
200 $levelName = 'Notice';
203 $levelName = 'Strict Standards';
206 case E_USER_DEPRECATED
:
207 $levelName = 'Deprecated';
209 case /* HHVM's FATAL_ERROR */ 16777217:
210 $levelName = 'Fatal';
213 $levelName = 'Unknown error';
217 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
218 self
::logError( $e );
220 // This handler is for logging only. Return false will instruct PHP
221 // to continue regular handling.
227 * Look for a fatal error as the cause of the request termination and log
230 * Special handling is included for missing class errors as they may
231 * indicate that the user needs to install 3rd-party libraries via
232 * Composer or other means.
236 public static function handleFatalError() {
237 self
::$reservedMemory = null;
238 $lastError = error_get_last();
241 isset( $lastError['type'] ) &&
242 in_array( $lastError['type'], self
::$fatalErrorTypes )
244 $msg = "Fatal Error: {$lastError['message']}";
245 // HHVM: Class undefined: foo
246 // PHP5: Class 'foo' not found
247 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/",
248 $lastError['message']
253 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.
255 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.
258 $e = new ErrorException( $msg, 0, $lastError['type'] );
259 self
::logError( $e );
264 * Generate a string representation of an exception's stack trace
266 * Like Exception::getTraceAsString, but replaces argument values with
267 * argument type or class name.
269 * @param Exception $e
272 public static function getRedactedTraceAsString( Exception
$e ) {
275 foreach ( self
::getRedactedTrace( $e ) as $level => $frame ) {
276 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
277 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
279 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
280 // This matches behaviour of Exception::getTraceAsString to instead
281 // display "[internal function]".
282 $text .= "#{$level} [internal function]: ";
285 if ( isset( $frame['class'] ) ) {
286 $text .= $frame['class'] . $frame['type'] . $frame['function'];
288 $text .= $frame['function'];
291 if ( isset( $frame['args'] ) ) {
292 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
299 $text .= "#{$level} {main}";
305 * Return a copy of an exception's backtrace as an array.
307 * Like Exception::getTrace, but replaces each element in each frame's
308 * argument array with the name of its class (if the element is an object)
309 * or its type (if the element is a PHP primitive).
312 * @param Exception $e
315 public static function getRedactedTrace( Exception
$e ) {
316 return array_map( function ( $frame ) {
317 if ( isset( $frame['args'] ) ) {
318 $frame['args'] = array_map( function ( $arg ) {
319 return is_object( $arg ) ?
get_class( $arg ) : gettype( $arg );
327 * Get the ID for this exception.
329 * The ID is saved so that one can match the one output to the user (when
330 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
333 * @param Exception $e
336 public static function getLogId( Exception
$e ) {
337 if ( !isset( $e->_mwLogId
) ) {
338 $e->_mwLogId
= wfRandomString( 8 );
344 * If the exception occurred in the course of responding to a request,
345 * returns the requested URL. Otherwise, returns false.
348 * @return string|bool
350 public static function getURL() {
352 if ( !isset( $wgRequest ) ||
$wgRequest instanceof FauxRequest
) {
355 return $wgRequest->getRequestURL();
359 * Get a message formatting the exception message and its origin.
362 * @param Exception $e
365 public static function getLogMessage( Exception
$e ) {
366 $id = self
::getLogId( $e );
367 $type = get_class( $e );
368 $file = $e->getFile();
369 $line = $e->getLine();
370 $message = $e->getMessage();
371 $url = self
::getURL() ?
: '[no req]';
373 return "[$id] $url $type from line $line of $file: $message";
377 * Serialize an Exception object to JSON.
379 * The JSON object will have keys 'id', 'file', 'line', 'message', and
380 * 'url'. These keys map to string values, with the exception of 'line',
381 * which is a number, and 'url', which may be either a string URL or or
382 * null if the exception did not occur in the context of serving a web
385 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
386 * key, mapped to the array return value of Exception::getTrace, but with
387 * each element in each frame's "args" array (if set) replaced with the
388 * argument's class name (if the argument is an object) or type name (if
389 * the argument is a PHP primitive).
391 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
395 * "type": "MWException",
396 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
398 * "message": "Non-string key given",
399 * "url": "/wiki/Main_Page"
403 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
407 * "type": "MWException",
408 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
410 * "message": "Non-string key given",
411 * "url": "/wiki/Main_Page",
413 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
416 * "class": "MessageCache",
424 * @param Exception $e
425 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
426 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
427 * @return string|bool JSON string if successful; false upon failure
429 public static function jsonSerializeException( Exception
$e, $pretty = false, $escaping = 0 ) {
430 global $wgLogExceptionBacktrace;
432 $exceptionData = array(
433 'id' => self
::getLogId( $e ),
434 'type' => get_class( $e ),
435 'file' => $e->getFile(),
436 'line' => $e->getLine(),
437 'message' => $e->getMessage(),
440 // Because MediaWiki is first and foremost a web application, we set a
441 // 'url' key unconditionally, but set it to null if the exception does
442 // not occur in the context of a web request, as a way of making that
443 // fact visible and explicit.
444 $exceptionData['url'] = self
::getURL() ?
: null;
446 if ( $wgLogExceptionBacktrace ) {
447 // Argument values may not be serializable, so redact them.
448 $exceptionData['backtrace'] = self
::getRedactedTrace( $e );
451 return FormatJson
::encode( $exceptionData, $pretty, $escaping );
455 * Log an exception to the exception log (if enabled).
457 * This method must not assume the exception is an MWException,
458 * it is also used to handle PHP exceptions or exceptions from other libraries.
461 * @param Exception $e
463 public static function logException( Exception
$e ) {
464 global $wgLogExceptionBacktrace;
466 if ( !( $e instanceof MWException
) ||
$e->isLoggable() ) {
467 $log = self
::getLogMessage( $e );
468 if ( $wgLogExceptionBacktrace ) {
469 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
471 wfDebugLog( 'exception', $log );
474 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
475 if ( $json !== false ) {
476 wfDebugLog( 'exception-json', $json, 'private' );
482 * Log an exception that wasn't thrown but made to wrap an error.
485 * @param Exception $e
487 protected static function logError( Exception
$e ) {
488 global $wgLogExceptionBacktrace;
490 $log = self
::getLogMessage( $e );
491 if ( $wgLogExceptionBacktrace ) {
492 wfDebugLog( 'error', $log . "\n" . $e->getTraceAsString() );
494 wfDebugLog( 'error', $log );
497 $json = self
::jsonSerializeException( $e, false, FormatJson
::ALL_OK
);
498 if ( $json !== false ) {
499 wfDebugLog( 'error-json', $json, 'private' );