MediaWiki  master
MWExceptionHandler.php
Go to the documentation of this file.
1 <?php
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 ) {
194  self::rollbackMasterChangesAndLog( $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  // PHP5: 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 
690  public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER ) {
691  if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
692  $logger = LoggerFactory::getInstance( 'exception' );
693  $logger->error(
694  self::getLogNormalMessage( $e ),
695  self::getLogContext( $e, $catcher )
696  );
697 
698  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
699  if ( $json !== false ) {
700  $logger = LoggerFactory::getInstance( 'exception-json' );
701  $logger->error( $json, [ 'private' => true ] );
702  }
703 
704  Hooks::run( 'LogException', [ $e, false ] );
705  }
706  }
707 
716  protected static function logError(
717  ErrorException $e, $channel, $level = LogLevel::ERROR
718  ) {
719  $catcher = self::CAUGHT_BY_HANDLER;
720  // The set_error_handler callback is independent from error_reporting.
721  // Filter out unwanted errors manually (e.g. when
722  // Wikimedia\suppressWarnings is active).
723  $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
724  if ( !$suppressed ) {
725  $logger = LoggerFactory::getInstance( $channel );
726  $logger->log(
727  $level,
728  self::getLogNormalMessage( $e ),
729  self::getLogContext( $e, $catcher )
730  );
731  }
732 
733  // Include all errors in the json log (surpressed errors will be flagged)
734  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
735  if ( $json !== false ) {
736  $logger = LoggerFactory::getInstance( "{$channel}-json" );
737  $logger->log( $level, $json, [ 'private' => true ] );
738  }
739 
740  Hooks::run( 'LogException', [ $e, $suppressed ] );
741  }
742 }
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
static getLogMessage( $e)
Get a message formatting the exception message and its origin.
static jsonSerializeException( $e, $pretty=false, $escaping=0, $catcher=self::CAUGHT_BY_OTHER)
Serialize an Exception object to JSON.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:275
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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...
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
static getRedactedTrace( $e)
Return a copy of an exception&#39;s backtrace as an array.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
A helper class for throttling authentication attempts.
static getRedactedTraceAsString( $e)
Generate a string representation of an exception&#39;s stack trace.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2217
static handleError( $level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
static logException( $e, $catcher=self::CAUGHT_BY_OTHER)
Log an exception to the exception log (if enabled).
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
wfIsCLI()
Check if we are running from the commandline.
static redactTrace(array $trace)
Redact a stacktrace generated by Exception::getTrace(), debug_backtrace() or similar means...
static logError(ErrorException $e, $channel, $level=LogLevel::ERROR)
Log an exception that wasn&#39;t thrown but made to wrap an error.
static handleException( $e)
Exception handler which simulates the appropriate catch() handling:
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static report( $e)
Report an exception to the user.
static output( $e, $mode, $eNew=null)
static getGlobalRequestURL()
Return the path and query string portion of the main request URI.
Definition: WebRequest.php:806
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static installHandler()
Install handlers with PHP.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$line
Definition: cdb.php:59
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2633
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:77
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
static handleUncaughtException( $e)
Callback to use with PHP&#39;s set_exception_handler.
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:783
static getLogNormalMessage( $e)
Get a normalised message for formatting with PSR-3 log event context.
$wgPropagateErrors
If true, the MediaWiki error handler passes errors/warnings to the default error handler after loggin...
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging a wrapping ErrorException $suppressed
Definition: hooks.txt:2159
static getStructuredExceptionData( $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of an Exception.
static $fatalErrorTypes
Error types that, if unhandled, are fatal to the request.
static getPublicLogMessage( $e)
Database error base class.
Definition: DBError.php:30
static getLogContext( $e, $catcher=self::CAUGHT_BY_OTHER)
Get a PSR-3 log event context from an Exception.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200