MediaWiki  1.27.2
MWExceptionHandler.php
Go to the documentation of this file.
1 <?php
22 
28 
32  protected static $reservedMemory;
36  protected static $fatalErrorTypes = [
37  E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
38  /* HHVM's FATAL_ERROR level */ 16777217,
39  ];
43  protected static $handledFatalCallback = false;
44 
48  public static function installHandler() {
49  set_exception_handler( 'MWExceptionHandler::handleException' );
50  set_error_handler( 'MWExceptionHandler::handleError' );
51 
52  // Reserve 16k of memory so we can report OOM fatals
53  self::$reservedMemory = str_repeat( ' ', 16384 );
54  register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
55  }
56 
61  protected static function report( $e ) {
62  global $wgShowExceptionDetails;
63 
64  $cmdLine = MWException::isCommandLine();
65 
66  if ( $e instanceof MWException ) {
67  try {
68  // Try and show the exception prettily, with the normal skin infrastructure
69  $e->report();
70  } catch ( Exception $e2 ) {
71  // Exception occurred from within exception handler
72  // Show a simpler message for the original exception,
73  // don't try to invoke report()
74  $message = "MediaWiki internal error.\n\n";
75 
76  if ( $wgShowExceptionDetails ) {
77  $message .= 'Original exception: ' . self::getLogMessage( $e ) .
78  "\nBacktrace:\n" . self::getRedactedTraceAsString( $e ) .
79  "\n\nException caught inside exception handler: " . self::getLogMessage( $e2 ) .
80  "\nBacktrace:\n" . self::getRedactedTraceAsString( $e2 );
81  } else {
82  $message .= "Exception caught inside exception handler.\n\n" .
83  "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
84  "to show detailed debugging information.";
85  }
86 
87  $message .= "\n";
88 
89  if ( $cmdLine ) {
90  self::printError( $message );
91  } else {
92  echo nl2br( htmlspecialchars( $message ) ) . "\n";
93  }
94  }
95  } else {
96  $message = "Exception encountered, of type \"" . get_class( $e ) . "\"";
97 
98  if ( $wgShowExceptionDetails ) {
99  $message .= "\n" . self::getLogMessage( $e ) . "\nBacktrace:\n" .
100  self::getRedactedTraceAsString( $e ) . "\n";
101  }
102 
103  if ( $cmdLine ) {
104  self::printError( $message );
105  } else {
106  echo nl2br( htmlspecialchars( $message ) ) . "\n";
107  }
108 
109  }
110  }
111 
118  public static function printError( $message ) {
119  # NOTE: STDERR may not be available, especially if php-cgi is used from the
120  # command line (bug #15602). Try to produce meaningful output anyway. Using
121  # echo may corrupt output to STDOUT though.
122  if ( defined( 'STDERR' ) ) {
123  fwrite( STDERR, $message );
124  } else {
125  echo $message;
126  }
127  }
128 
137  public static function rollbackMasterChangesAndLog( $e ) {
139  if ( $factory->hasMasterChanges() ) {
140  $logger = LoggerFactory::getInstance( 'Bug56269' );
141  $logger->warning(
142  'Exception thrown with an uncommited database transaction: ' .
143  self::getLogMessage( $e ),
144  self::getLogContext( $e )
145  );
146  $factory->rollbackMasterChanges( __METHOD__ );
147  }
148  }
149 
164  public static function handleException( $e ) {
165  try {
166  // Rollback DBs to avoid transaction notices. This may fail
167  // to rollback some DB due to connection issues or exceptions.
168  // However, any sane DB driver will rollback implicitly anyway.
169  self::rollbackMasterChangesAndLog( $e );
170  } catch ( DBError $e2 ) {
171  // If the DB is unreacheable, rollback() will throw an error
172  // and the error report() method might need messages from the DB,
173  // which would result in an exception loop. PHP may escalate such
174  // errors to "Exception thrown without a stack frame" fatals, but
175  // it's better to be explicit here.
176  self::logException( $e2 );
177  }
178 
179  self::logException( $e );
180  self::report( $e );
181 
182  // Exit value should be nonzero for the benefit of shell jobs
183  exit( 1 );
184  }
185 
204  public static function handleError(
205  $level, $message, $file = null, $line = null
206  ) {
207  if ( in_array( $level, self::$fatalErrorTypes ) ) {
208  return call_user_func_array(
209  'MWExceptionHandler::handleFatalError', func_get_args()
210  );
211  }
212 
213  // Map error constant to error name (reverse-engineer PHP error
214  // reporting)
215  switch ( $level ) {
216  case E_RECOVERABLE_ERROR:
217  $levelName = 'Error';
218  break;
219  case E_WARNING:
220  case E_CORE_WARNING:
221  case E_COMPILE_WARNING:
222  case E_USER_WARNING:
223  $levelName = 'Warning';
224  break;
225  case E_NOTICE:
226  case E_USER_NOTICE:
227  $levelName = 'Notice';
228  break;
229  case E_STRICT:
230  $levelName = 'Strict Standards';
231  break;
232  case E_DEPRECATED:
233  case E_USER_DEPRECATED:
234  $levelName = 'Deprecated';
235  break;
236  default:
237  $levelName = 'Unknown error';
238  break;
239  }
240 
241  $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
242  self::logError( $e, 'error' );
243 
244  // This handler is for logging only. Return false will instruct PHP
245  // to continue regular handling.
246  return false;
247  }
248 
270  public static function handleFatalError(
271  $level = null, $message = null, $file = null, $line = null,
272  $context = null, $trace = null
273  ) {
274  // Free reserved memory so that we have space to process OOM
275  // errors
276  self::$reservedMemory = null;
277 
278  if ( $level === null ) {
279  // Called as a shutdown handler, get data from error_get_last()
280  if ( static::$handledFatalCallback ) {
281  // Already called once (probably as an error handler callback
282  // under HHVM) so don't log again.
283  return false;
284  }
285 
286  $lastError = error_get_last();
287  if ( $lastError !== null ) {
288  $level = $lastError['type'];
289  $message = $lastError['message'];
290  $file = $lastError['file'];
291  $line = $lastError['line'];
292  } else {
293  $level = 0;
294  $message = '';
295  }
296  }
297 
298  if ( !in_array( $level, self::$fatalErrorTypes ) ) {
299  // Only interested in fatal errors, others should have been
300  // handled by MWExceptionHandler::handleError
301  return false;
302  }
303 
304  $msg = "[{exception_id}] PHP Fatal Error: {$message}";
305 
306  // Look at message to see if this is a class not found failure
307  // HHVM: Class undefined: foo
308  // PHP5: Class 'foo' not found
309  if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
310  // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
311  $msg = <<<TXT
312 {$msg}
313 
314 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.
315 
316 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.
317 TXT;
318  // @codingStandardsIgnoreEnd
319  }
320 
321  // We can't just create an exception and log it as it is likely that
322  // the interpreter has unwound the stack already. If that is true the
323  // stacktrace we would get would be functionally empty. If however we
324  // have been called as an error handler callback *and* HHVM is in use
325  // we will have been provided with a useful stacktrace that we can
326  // log.
327  $trace = $trace ?: debug_backtrace();
328  $logger = LoggerFactory::getInstance( 'fatal' );
329  $logger->error( $msg, [
330  'exception' => [
331  'class' => 'ErrorException',
332  'message' => "PHP Fatal Error: {$message}",
333  'code' => $level,
334  'file' => $file,
335  'line' => $line,
336  'trace' => static::redactTrace( $trace ),
337  ],
338  'exception_id' => wfRandomString( 8 ),
339  ] );
340 
341  // Remember call so we don't double process via HHVM's fatal
342  // notifications and the shutdown hook behavior
343  static::$handledFatalCallback = true;
344  return false;
345  }
346 
357  public static function getRedactedTraceAsString( $e ) {
358  return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
359  }
360 
369  public static function prettyPrintTrace( array $trace, $pad = '' ) {
370  $text = '';
371 
372  $level = 0;
373  foreach ( $trace as $level => $frame ) {
374  if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
375  $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
376  } else {
377  // 'file' and 'line' are unset for calls via call_user_func
378  // (bug 55634) This matches behaviour of
379  // Exception::getTraceAsString to instead display "[internal
380  // function]".
381  $text .= "{$pad}#{$level} [internal function]: ";
382  }
383 
384  if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
385  $text .= $frame['class'] . $frame['type'] . $frame['function'];
386  } elseif ( isset( $frame['function'] ) ) {
387  $text .= $frame['function'];
388  } else {
389  $text .= 'NO_FUNCTION_GIVEN';
390  }
391 
392  if ( isset( $frame['args'] ) ) {
393  $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
394  } else {
395  $text .= "()\n";
396  }
397  }
398 
399  $level = $level + 1;
400  $text .= "{$pad}#{$level} {main}";
401 
402  return $text;
403  }
404 
416  public static function getRedactedTrace( $e ) {
417  return static::redactTrace( $e->getTrace() );
418  }
419 
430  public static function redactTrace( array $trace ) {
431  return array_map( function ( $frame ) {
432  if ( isset( $frame['args'] ) ) {
433  $frame['args'] = array_map( function ( $arg ) {
434  return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
435  }, $frame['args'] );
436  }
437  return $frame;
438  }, $trace );
439  }
440 
452  public static function getLogId( $e ) {
453  wfDeprecated( __METHOD__, '1.27' );
454  return WebRequest::getRequestId();
455  }
456 
464  public static function getURL() {
466  if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
467  return false;
468  }
469  return $wgRequest->getRequestURL();
470  }
471 
479  public static function getLogMessage( $e ) {
480  $id = WebRequest::getRequestId();
481  $type = get_class( $e );
482  $file = $e->getFile();
483  $line = $e->getLine();
484  $message = $e->getMessage();
485  $url = self::getURL() ?: '[no req]';
486 
487  return "[$id] $url $type from line $line of $file: $message";
488  }
489 
490  public static function getPublicLogMessage( Exception $e ) {
491  $reqId = WebRequest::getRequestId();
492  $type = get_class( $e );
493  return '[' . $reqId . '] '
494  . gmdate( 'Y-m-d H:i:s' ) . ': '
495  . 'Fatal exception of type ' . $type;
496  }
497 
508  public static function getLogContext( $e ) {
509  return [
510  'exception' => $e,
511  'exception_id' => WebRequest::getRequestId(),
512  ];
513  }
514 
526  public static function getStructuredExceptionData( $e ) {
527  global $wgLogExceptionBacktrace;
528  $data = [
529  'id' => WebRequest::getRequestId(),
530  'type' => get_class( $e ),
531  'file' => $e->getFile(),
532  'line' => $e->getLine(),
533  'message' => $e->getMessage(),
534  'code' => $e->getCode(),
535  'url' => self::getURL() ?: null,
536  ];
537 
538  if ( $e instanceof ErrorException &&
539  ( error_reporting() & $e->getSeverity() ) === 0
540  ) {
541  // Flag surpressed errors
542  $data['suppressed'] = true;
543  }
544 
545  if ( $wgLogExceptionBacktrace ) {
546  $data['backtrace'] = self::getRedactedTrace( $e );
547  }
548 
549  $previous = $e->getPrevious();
550  if ( $previous !== null ) {
551  $data['previous'] = self::getStructuredExceptionData( $previous );
552  }
553 
554  return $data;
555  }
556 
610  public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
611  $data = self::getStructuredExceptionData( $e );
612  return FormatJson::encode( $data, $pretty, $escaping );
613  }
614 
624  public static function logException( $e ) {
625  if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
626  $logger = LoggerFactory::getInstance( 'exception' );
627  $logger->error(
628  self::getLogMessage( $e ),
629  self::getLogContext( $e )
630  );
631 
632  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
633  if ( $json !== false ) {
634  $logger = LoggerFactory::getInstance( 'exception-json' );
635  $logger->error( $json, [ 'private' => true ] );
636  }
637 
638  Hooks::run( 'LogException', [ $e, false ] );
639  }
640  }
641 
649  protected static function logError( ErrorException $e, $channel ) {
650  // The set_error_handler callback is independent from error_reporting.
651  // Filter out unwanted errors manually (e.g. when
652  // MediaWiki\suppressWarnings is active).
653  $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
654  if ( !$suppressed ) {
655  $logger = LoggerFactory::getInstance( $channel );
656  $logger->error(
657  self::getLogMessage( $e ),
658  self::getLogContext( $e )
659  );
660  }
661 
662  // Include all errors in the json log (surpressed errors will be flagged)
663  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
664  if ( $json !== false ) {
665  $logger = LoggerFactory::getInstance( "{$channel}-json" );
666  $logger->error( $json, [ 'private' => true ] );
667  }
668 
669  Hooks::run( 'LogException', [ $e, $suppressed ] );
670  }
671 }
static printError($message)
Print a message, if possible to STDERR.
static getStructuredExceptionData($e)
Get a structured representation of an Exception.
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...
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:265
static getLogMessage($e)
Get a message formatting the exception message and its origin.
$context
Definition: load.php:44
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
static handleError($level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
static handleException($e)
Exception handler which simulates the appropriate catch() handling:
A helper class for throttling authentication attempts.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfRandomString($length=32)
Get a random string containing a number of pseudo-random hex characters.
static logError(ErrorException $e, $channel)
Log an exception that wasn't thrown but made to wrap an error.
$factory
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL...
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static redactTrace(array $trace)
Redact a stacktrace generated by Exception::getTrace(), debug_backtrace() or similar means...
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
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 isCommandLine()
Check whether we are in command line mode or not to report the exception in the correct format...
static rollbackMasterChangesAndLog($e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
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
wfGetLBFactory()
Get the load balancer factory object.
static getPublicLogMessage(Exception $e)
static installHandler()
Install handlers with PHP.
static getLogContext($e)
Get a PSR-3 log event context from an Exception.
$line
Definition: cdb.php:59
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
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:86
static jsonSerializeException($e, $pretty=false, $escaping=0)
Serialize an Exception object to JSON.
static getRedactedTrace($e)
Return a copy of an exception's backtrace as an array.
static prettyPrintTrace(array $trace, $pad= '')
Generate a string representation of a stacktrace.
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:1932
static logException($e)
Log an exception to the exception log (if enabled).
static report($e)
Report an exception to the user.
static getLogId($e)
Get the ID for this exception.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:657
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338