MediaWiki  REL1_34
MWExceptionHandler.php
Go to the documentation of this file.
1 <?php
23 use Psr\Log\LogLevel;
25 
31  const CAUGHT_BY_HANDLER = 'mwe_handler'; // error reported by this exception handler
32  const CAUGHT_BY_OTHER = 'other'; // error reported by direct logException() call
33 
37  protected static $reservedMemory;
38 
55  protected static $fatalErrorTypes = [
56  E_ERROR,
57  E_PARSE,
58  E_CORE_ERROR,
59  E_COMPILE_ERROR,
60  E_USER_ERROR,
61 
62  // E.g. "Catchable fatal error: Argument X must be Y, null given"
63  E_RECOVERABLE_ERROR,
64 
65  // HHVM's FATAL_ERROR constant
66  16777217,
67  ];
71  protected static $handledFatalCallback = false;
72 
76  public static function installHandler() {
77  // This catches:
78  // * Exception objects that were explicitly thrown but not
79  // caught anywhere in the application. This is rare given those
80  // would normally be caught at a high-level like MediaWiki::run (index.php),
81  // api.php, or ResourceLoader::respond (load.php). These high-level
82  // catch clauses would then call MWExceptionHandler::logException
83  // or MWExceptionHandler::handleException.
84  // If they are not caught, then they are handled here.
85  // * Error objects (on PHP 7+), for issues that would historically
86  // cause fatal errors but may now be caught as Throwable (not Exception).
87  // Same as previous case, but more common to bubble to here instead of
88  // caught locally because they tend to not be safe to recover from.
89  // (e.g. argument TypeErorr, devision by zero, etc.)
90  set_exception_handler( 'MWExceptionHandler::handleUncaughtException' );
91 
92  // This catches:
93  // * Non-fatal errors (e.g. PHP Notice, PHP Warning, PHP Error) that do not
94  // interrupt execution in any way. We log these in the background and then
95  // continue execution.
96  // * Fatal errors (on HHVM in PHP5 mode) where PHP 7 would throw Throwable.
97  set_error_handler( 'MWExceptionHandler::handleError' );
98 
99  // This catches:
100  // * Fatal error for which no Throwable is thrown (PHP 7), and no Error emitted (HHVM).
101  // This includes Out-Of-Memory and Timeout fatals.
102  //
103  // Reserve 16k of memory so we can report OOM fatals
104  self::$reservedMemory = str_repeat( ' ', 16384 );
105  register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
106  }
107 
112  protected static function report( $e ) {
113  try {
114  // Try and show the exception prettily, with the normal skin infrastructure
115  if ( $e instanceof MWException ) {
116  // Delegate to MWException until all subclasses are handled by
117  // MWExceptionRenderer and MWException::report() has been
118  // removed.
119  $e->report();
120  } else {
122  }
123  } catch ( Exception $e2 ) {
124  // Exception occurred from within exception handler
125  // Show a simpler message for the original exception,
126  // don't try to invoke report()
128  }
129  }
130 
139  public static function rollbackMasterChangesAndLog( $e ) {
140  $services = MediaWikiServices::getInstance();
141  if ( !$services->isServiceDisabled( 'DBLoadBalancerFactory' ) ) {
142  // Rollback DBs to avoid transaction notices. This might fail
143  // to rollback some databases due to connection issues or exceptions.
144  // However, any sane DB driver will rollback implicitly anyway.
145  try {
146  $services->getDBLoadBalancerFactory()->rollbackMasterChanges( __METHOD__ );
147  } catch ( DBError $e2 ) {
148  // If the DB is unreacheable, rollback() will throw an error
149  // and the error report() method might need messages from the DB,
150  // which would result in an exception loop. PHP may escalate such
151  // errors to "Exception thrown without a stack frame" fatals, but
152  // it's better to be explicit here.
153  self::logException( $e2, self::CAUGHT_BY_HANDLER );
154  }
155  }
156 
157  self::logException( $e, self::CAUGHT_BY_HANDLER );
158  }
159 
166  public static function handleUncaughtException( $e ) {
167  self::handleException( $e );
168 
169  // Make sure we don't claim success on exit for CLI scripts (T177414)
170  if ( wfIsCLI() ) {
171  register_shutdown_function(
172  function () {
173  exit( 255 );
174  }
175  );
176  }
177  }
178 
193  public static function handleException( $e ) {
195  self::report( $e );
196  }
197 
216  public static function handleError(
217  $level, $message, $file = null, $line = null
218  ) {
219  global $wgPropagateErrors;
220 
221  if ( in_array( $level, self::$fatalErrorTypes ) ) {
222  return self::handleFatalError( ...func_get_args() );
223  }
224 
225  // Map PHP error constant to a PSR-3 severity level.
226  // Avoid use of "DEBUG" or "INFO" levels, unless the
227  // error should evade error monitoring and alerts.
228  //
229  // To decide the log level, ask yourself: "Has the
230  // program's behaviour diverged from what the written
231  // code expected?"
232  //
233  // For example, use of a deprecated method or violating a strict standard
234  // has no impact on functional behaviour (Warning). On the other hand,
235  // accessing an undefined variable makes behaviour diverge from what the
236  // author intended/expected. PHP recovers from an undefined variables by
237  // yielding null and continuing execution, but it remains a change in
238  // behaviour given the null was not part of the code and is likely not
239  // accounted for.
240  switch ( $level ) {
241  case E_WARNING:
242  case E_CORE_WARNING:
243  case E_COMPILE_WARNING:
244  $levelName = 'Warning';
245  $severity = LogLevel::ERROR;
246  break;
247  case E_NOTICE:
248  $levelName = 'Notice';
249  $severity = LogLevel::ERROR;
250  break;
251  case E_USER_NOTICE:
252  // Used by wfWarn(), MWDebug::warning()
253  $levelName = 'Notice';
254  $severity = LogLevel::WARNING;
255  break;
256  case E_USER_WARNING:
257  // Used by wfWarn(), MWDebug::warning()
258  $levelName = 'Warning';
259  $severity = LogLevel::WARNING;
260  break;
261  case E_STRICT:
262  $levelName = 'Strict Standards';
263  $severity = LogLevel::WARNING;
264  break;
265  case E_DEPRECATED:
266  case E_USER_DEPRECATED:
267  $levelName = 'Deprecated';
268  $severity = LogLevel::WARNING;
269  break;
270  default:
271  $levelName = 'Unknown error';
272  $severity = LogLevel::ERROR;
273  break;
274  }
275 
276  $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
277  self::logError( $e, 'error', $severity );
278 
279  // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
280  // Ignore $wgPropagateErrors if track_errors is set
281  // (which means someone is counting on regular PHP error handling behavior).
282  return !( $wgPropagateErrors || ini_get( 'track_errors' ) );
283  }
284 
306  public static function handleFatalError(
307  $level = null, $message = null, $file = null, $line = null,
308  $context = null, $trace = null
309  ) {
310  // Free reserved memory so that we have space to process OOM
311  // errors
312  self::$reservedMemory = null;
313 
314  if ( $level === null ) {
315  // Called as a shutdown handler, get data from error_get_last()
316  if ( static::$handledFatalCallback ) {
317  // Already called once (probably as an error handler callback
318  // under HHVM) so don't log again.
319  return false;
320  }
321 
322  $lastError = error_get_last();
323  if ( $lastError !== null ) {
324  $level = $lastError['type'];
325  $message = $lastError['message'];
326  $file = $lastError['file'];
327  $line = $lastError['line'];
328  } else {
329  $level = 0;
330  $message = '';
331  }
332  }
333 
334  if ( !in_array( $level, self::$fatalErrorTypes ) ) {
335  // Only interested in fatal errors, others should have been
336  // handled by MWExceptionHandler::handleError
337  return false;
338  }
339 
341  $msgParts = [
342  '[{exception_id}] {exception_url} PHP Fatal Error',
343  ( $line || $file ) ? ' from' : '',
344  $line ? " line $line" : '',
345  ( $line && $file ) ? ' of' : '',
346  $file ? " $file" : '',
347  ": $message",
348  ];
349  $msg = implode( '', $msgParts );
350 
351  // Look at message to see if this is a class not found failure
352  // HHVM: Class undefined: foo
353  // PHP7: Class 'foo' not found
354  if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
355  // phpcs:disable Generic.Files.LineLength
356  $msg = <<<TXT
357 {$msg}
358 
359 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.
360 
361 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.
362 TXT;
363  // phpcs:enable
364  }
365 
366  // We can't just create an exception and log it as it is likely that
367  // the interpreter has unwound the stack already. If that is true the
368  // stacktrace we would get would be functionally empty. If however we
369  // have been called as an error handler callback *and* HHVM is in use
370  // we will have been provided with a useful stacktrace that we can
371  // log.
372  $trace = $trace ?: debug_backtrace();
373  $logger = LoggerFactory::getInstance( 'fatal' );
374  $logger->error( $msg, [
375  'fatal_exception' => [
376  'class' => ErrorException::class,
377  'message' => "PHP Fatal Error: {$message}",
378  'code' => $level,
379  'file' => $file,
380  'line' => $line,
381  'trace' => self::prettyPrintTrace( self::redactTrace( $trace ) ),
382  ],
383  'exception_id' => WebRequest::getRequestId(),
384  'exception_url' => $url,
385  'caught_by' => self::CAUGHT_BY_HANDLER
386  ] );
387 
388  // Remember call so we don't double process via HHVM's fatal
389  // notifications and the shutdown hook behavior
390  static::$handledFatalCallback = true;
391  return false;
392  }
393 
404  public static function getRedactedTraceAsString( $e ) {
405  return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
406  }
407 
416  public static function prettyPrintTrace( array $trace, $pad = '' ) {
417  $text = '';
418 
419  $level = 0;
420  foreach ( $trace as $level => $frame ) {
421  if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
422  $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
423  } else {
424  // 'file' and 'line' are unset for calls via call_user_func
425  // (T57634) This matches behaviour of
426  // Exception::getTraceAsString to instead display "[internal
427  // function]".
428  $text .= "{$pad}#{$level} [internal function]: ";
429  }
430 
431  if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
432  $text .= $frame['class'] . $frame['type'] . $frame['function'];
433  } elseif ( isset( $frame['function'] ) ) {
434  $text .= $frame['function'];
435  } else {
436  $text .= 'NO_FUNCTION_GIVEN';
437  }
438 
439  if ( isset( $frame['args'] ) ) {
440  $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
441  } else {
442  $text .= "()\n";
443  }
444  }
445 
446  $level = $level + 1;
447  $text .= "{$pad}#{$level} {main}";
448 
449  return $text;
450  }
451 
463  public static function getRedactedTrace( $e ) {
464  return static::redactTrace( $e->getTrace() );
465  }
466 
477  public static function redactTrace( array $trace ) {
478  return array_map( function ( $frame ) {
479  if ( isset( $frame['args'] ) ) {
480  $frame['args'] = array_map( function ( $arg ) {
481  return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
482  }, $frame['args'] );
483  }
484  return $frame;
485  }, $trace );
486  }
487 
495  public static function getURL() {
496  global $wgRequest;
497  if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
498  return false;
499  }
500  return $wgRequest->getRequestURL();
501  }
502 
510  public static function getLogMessage( $e ) {
511  $id = WebRequest::getRequestId();
512  $type = get_class( $e );
513  $file = $e->getFile();
514  $line = $e->getLine();
515  $message = $e->getMessage();
516  $url = self::getURL() ?: '[no req]';
517 
518  return "[$id] $url $type from line $line of $file: $message";
519  }
520 
530  public static function getLogNormalMessage( $e ) {
531  $type = get_class( $e );
532  $file = $e->getFile();
533  $line = $e->getLine();
534  $message = $e->getMessage();
535 
536  return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
537  }
538 
543  public static function getPublicLogMessage( $e ) {
544  $reqId = WebRequest::getRequestId();
545  $type = get_class( $e );
546  return '[' . $reqId . '] '
547  . gmdate( 'Y-m-d H:i:s' ) . ': '
548  . 'Fatal exception of type "' . $type . '"';
549  }
550 
562  public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
563  return [
564  'exception' => $e,
565  'exception_id' => WebRequest::getRequestId(),
566  'exception_url' => self::getURL() ?: '[no req]',
567  'caught_by' => $catcher
568  ];
569  }
570 
583  public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
585 
586  $data = [
587  'id' => WebRequest::getRequestId(),
588  'type' => get_class( $e ),
589  'file' => $e->getFile(),
590  'line' => $e->getLine(),
591  'message' => $e->getMessage(),
592  'code' => $e->getCode(),
593  'url' => self::getURL() ?: null,
594  'caught_by' => $catcher
595  ];
596 
597  if ( $e instanceof ErrorException &&
598  ( error_reporting() & $e->getSeverity() ) === 0
599  ) {
600  // Flag surpressed errors
601  $data['suppressed'] = true;
602  }
603 
604  if ( $wgLogExceptionBacktrace ) {
605  $data['backtrace'] = self::getRedactedTrace( $e );
606  }
607 
608  $previous = $e->getPrevious();
609  if ( $previous !== null ) {
610  $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
611  }
612 
613  return $data;
614  }
615 
670  public static function jsonSerializeException(
671  $e, $pretty = false, $escaping = 0, $catcher = self::CAUGHT_BY_OTHER
672  ) {
673  return FormatJson::encode(
674  self::getStructuredExceptionData( $e, $catcher ),
675  $pretty,
676  $escaping
677  );
678  }
679 
691  public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER, $extraData = [] ) {
692  if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
693  $logger = LoggerFactory::getInstance( 'exception' );
694  $context = self::getLogContext( $e, $catcher );
695  if ( $extraData ) {
696  $context['extraData'] = $extraData;
697  }
698  $logger->error(
699  self::getLogNormalMessage( $e ),
700  $context
701  );
702 
703  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
704  if ( $json !== false ) {
705  $logger = LoggerFactory::getInstance( 'exception-json' );
706  $logger->error( $json, [ 'private' => true ] );
707  }
708 
709  Hooks::run( 'LogException', [ $e, false ] );
710  }
711  }
712 
721  protected static function logError(
722  ErrorException $e, $channel, $level = LogLevel::ERROR
723  ) {
724  $catcher = self::CAUGHT_BY_HANDLER;
725  // The set_error_handler callback is independent from error_reporting.
726  // Filter out unwanted errors manually (e.g. when
727  // Wikimedia\suppressWarnings is active).
728  $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
729  if ( !$suppressed ) {
730  $logger = LoggerFactory::getInstance( $channel );
731  $logger->log(
732  $level,
733  self::getLogNormalMessage( $e ),
734  self::getLogContext( $e, $catcher )
735  );
736  }
737 
738  // Include all errors in the json log (surpressed errors will be flagged)
739  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
740  if ( $json !== false ) {
741  $logger = LoggerFactory::getInstance( "{$channel}-json" );
742  $logger->log( $level, $json, [ 'private' => true ] );
743  }
744 
745  Hooks::run( 'LogException', [ $e, $suppressed ] );
746  }
747 }
MWExceptionHandler\logError
static logError(ErrorException $e, $channel, $level=LogLevel::ERROR)
Log an exception that wasn't thrown but made to wrap an error.
Definition: MWExceptionHandler.php:721
MWExceptionHandler\$handledFatalCallback
static $handledFatalCallback
Definition: MWExceptionHandler.php:71
MWExceptionHandler\getRedactedTrace
static getRedactedTrace( $e)
Return a copy of an exception's backtrace as an array.
Definition: MWExceptionHandler.php:463
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
MWExceptionHandler\getLogNormalMessage
static getLogNormalMessage( $e)
Get a normalised message for formatting with PSR-3 log event context.
Definition: MWExceptionHandler.php:530
MWExceptionHandler\getStructuredExceptionData
static getStructuredExceptionData( $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of an Exception.
Definition: MWExceptionHandler.php:583
MWExceptionHandler
Handler class for MWExceptions.
Definition: MWExceptionHandler.php:30
MWExceptionHandler\CAUGHT_BY_HANDLER
const CAUGHT_BY_HANDLER
Definition: MWExceptionHandler.php:31
MWExceptionHandler\redactTrace
static redactTrace(array $trace)
Redact a stacktrace generated by Exception::getTrace(), debug_backtrace() or similar means.
Definition: MWExceptionHandler.php:477
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
MWExceptionHandler\installHandler
static installHandler()
Install handlers with PHP.
Definition: MWExceptionHandler.php:76
MWExceptionHandler\handleUncaughtException
static handleUncaughtException( $e)
Callback to use with PHP's set_exception_handler.
Definition: MWExceptionHandler.php:166
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
$wgPropagateErrors
$wgPropagateErrors
If true, the MediaWiki error handler passes errors/warnings to the default error handler after loggin...
Definition: DefaultSettings.php:6387
MWExceptionHandler\getPublicLogMessage
static getPublicLogMessage( $e)
Definition: MWExceptionHandler.php:543
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
MWExceptionHandler\CAUGHT_BY_OTHER
const CAUGHT_BY_OTHER
Definition: MWExceptionHandler.php:32
MWExceptionHandler\handleFatalError
static handleFatalError( $level=null, $message=null, $file=null, $line=null, $context=null, $trace=null)
Dual purpose callback used as both a set_error_handler() callback and a registered shutdown function.
Definition: MWExceptionHandler.php:306
MWException
MediaWiki exception.
Definition: MWException.php:26
MWExceptionHandler\getLogContext
static getLogContext( $e, $catcher=self::CAUGHT_BY_OTHER)
Get a PSR-3 log event context from an Exception.
Definition: MWExceptionHandler.php:562
MWExceptionHandler\prettyPrintTrace
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
Definition: MWExceptionHandler.php:416
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
MWExceptionHandler\getURL
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL.
Definition: MWExceptionHandler.php:495
MWExceptionHandler\handleException
static handleException( $e)
Exception handler which simulates the appropriate catch() handling:
Definition: MWExceptionHandler.php:193
MWExceptionHandler\getLogMessage
static getLogMessage( $e)
Get a message formatting the exception message and its origin.
Definition: MWExceptionHandler.php:510
MWExceptionHandler\$fatalErrorTypes
static $fatalErrorTypes
Error types that, if unhandled, are fatal to the request.
Definition: MWExceptionHandler.php:55
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
Definition: MWExceptionHandler.php:139
MediaWiki
A helper class for throttling authentication attempts.
$wgLogExceptionBacktrace
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
Definition: DefaultSettings.php:6381
MWExceptionHandler\$reservedMemory
static $reservedMemory
Definition: MWExceptionHandler.php:37
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:31
$line
$line
Definition: cdb.php:59
wfIsCLI
wfIsCLI()
Check if we are running from the commandline.
Definition: GlobalFunctions.php:1912
$context
$context
Definition: load.php:45
MWExceptionRenderer\output
static output( $e, $mode, $eNew=null)
Definition: MWExceptionRenderer.php:38
MWExceptionHandler\report
static report( $e)
Report an exception to the user.
Definition: MWExceptionHandler.php:112
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:303
WebRequest\getGlobalRequestURL
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
Definition: WebRequest.php:887
MWExceptionHandler\jsonSerializeException
static jsonSerializeException( $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize an Exception object to JSON.
Definition: MWExceptionHandler.php:670
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:751
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MWExceptionHandler\handleError
static handleError( $level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
Definition: MWExceptionHandler.php:216
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:404
MWExceptionRenderer\AS_RAW
const AS_RAW
Definition: MWExceptionRenderer.php:30
$type
$type
Definition: testCompression.php:48
MWExceptionHandler\logException
static logException( $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log an exception to the exception log (if enabled).
Definition: MWExceptionHandler.php:691