Merge "database: Rename LBFactoryMW to MWLBFactory"
[lhc/web/wiklou.git] / includes / exception / MWExceptionHandler.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
23
24 /**
25 * Handler class for MWExceptions
26 * @ingroup Exception
27 */
28 class MWExceptionHandler {
29
30 /**
31 * @var string $reservedMemory
32 */
33 protected static $reservedMemory;
34 /**
35 * @var array $fatalErrorTypes
36 */
37 protected static $fatalErrorTypes = [
38 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
39 /* HHVM's FATAL_ERROR level */ 16777217,
40 ];
41 /**
42 * @var bool $handledFatalCallback
43 */
44 protected static $handledFatalCallback = false;
45
46 /**
47 * Install handlers with PHP.
48 */
49 public static function installHandler() {
50 set_exception_handler( 'MWExceptionHandler::handleException' );
51 set_error_handler( 'MWExceptionHandler::handleError' );
52
53 // Reserve 16k of memory so we can report OOM fatals
54 self::$reservedMemory = str_repeat( ' ', 16384 );
55 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
56 }
57
58 /**
59 * Report an exception to the user
60 * @param Exception|Throwable $e
61 */
62 protected static function report( $e ) {
63 try {
64 // Try and show the exception prettily, with the normal skin infrastructure
65 if ( $e instanceof MWException ) {
66 // Delegate to MWException until all subclasses are handled by
67 // MWExceptionRenderer and MWException::report() has been
68 // removed.
69 $e->report();
70 } else {
71 MWExceptionRenderer::output(
72 $e, MWExceptionRenderer::AS_PRETTY );
73 }
74 } catch ( Exception $e2 ) {
75 // Exception occurred from within exception handler
76 // Show a simpler message for the original exception,
77 // don't try to invoke report()
78 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY, $e2 );
79 }
80 }
81
82 /**
83 * If there are any open database transactions, roll them back and log
84 * the stack trace of the exception that should have been caught so the
85 * transaction could be aborted properly.
86 *
87 * @since 1.23
88 * @param Exception|Throwable $e
89 */
90 public static function rollbackMasterChangesAndLog( $e ) {
91 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
92 if ( $lbFactory->hasMasterChanges() ) {
93 $logger = LoggerFactory::getInstance( 'Bug56269' );
94 $logger->warning(
95 'Exception thrown with an uncommited database transaction: ' .
96 self::getLogMessage( $e ),
97 self::getLogContext( $e )
98 );
99 }
100 $lbFactory->rollbackMasterChanges( __METHOD__ );
101 }
102
103 /**
104 * Exception handler which simulates the appropriate catch() handling:
105 *
106 * try {
107 * ...
108 * } catch ( Exception $e ) {
109 * $e->report();
110 * } catch ( Exception $e ) {
111 * echo $e->__toString();
112 * }
113 *
114 * @since 1.25
115 * @param Exception|Throwable $e
116 */
117 public static function handleException( $e ) {
118 try {
119 // Rollback DBs to avoid transaction notices. This may fail
120 // to rollback some DB due to connection issues or exceptions.
121 // However, any sane DB driver will rollback implicitly anyway.
122 self::rollbackMasterChangesAndLog( $e );
123 } catch ( DBError $e2 ) {
124 // If the DB is unreacheable, rollback() will throw an error
125 // and the error report() method might need messages from the DB,
126 // which would result in an exception loop. PHP may escalate such
127 // errors to "Exception thrown without a stack frame" fatals, but
128 // it's better to be explicit here.
129 self::logException( $e2 );
130 }
131
132 self::logException( $e );
133 self::report( $e );
134
135 // Exit value should be nonzero for the benefit of shell jobs
136 exit( 1 );
137 }
138
139 /**
140 * Handler for set_error_handler() callback notifications.
141 *
142 * Receive a callback from the interpreter for a raised error, create an
143 * ErrorException, and log the exception to the 'error' logging
144 * channel(s). If the raised error is a fatal error type (only under HHVM)
145 * delegate to handleFatalError() instead.
146 *
147 * @since 1.25
148 *
149 * @param int $level Error level raised
150 * @param string $message
151 * @param string $file
152 * @param int $line
153 * @return bool
154 *
155 * @see logError()
156 */
157 public static function handleError(
158 $level, $message, $file = null, $line = null
159 ) {
160 if ( in_array( $level, self::$fatalErrorTypes ) ) {
161 return call_user_func_array(
162 'MWExceptionHandler::handleFatalError', func_get_args()
163 );
164 }
165
166 // Map error constant to error name (reverse-engineer PHP error
167 // reporting)
168 switch ( $level ) {
169 case E_RECOVERABLE_ERROR:
170 $levelName = 'Error';
171 break;
172 case E_WARNING:
173 case E_CORE_WARNING:
174 case E_COMPILE_WARNING:
175 case E_USER_WARNING:
176 $levelName = 'Warning';
177 break;
178 case E_NOTICE:
179 case E_USER_NOTICE:
180 $levelName = 'Notice';
181 break;
182 case E_STRICT:
183 $levelName = 'Strict Standards';
184 break;
185 case E_DEPRECATED:
186 case E_USER_DEPRECATED:
187 $levelName = 'Deprecated';
188 break;
189 default:
190 $levelName = 'Unknown error';
191 break;
192 }
193
194 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
195 self::logError( $e, 'error' );
196
197 // This handler is for logging only. Return false will instruct PHP
198 // to continue regular handling.
199 return false;
200 }
201
202 /**
203 * Dual purpose callback used as both a set_error_handler() callback and
204 * a registered shutdown function. Receive a callback from the interpreter
205 * for a raised error or system shutdown, check for a fatal error, and log
206 * to the 'fatal' logging channel.
207 *
208 * Special handling is included for missing class errors as they may
209 * indicate that the user needs to install 3rd-party libraries via
210 * Composer or other means.
211 *
212 * @since 1.25
213 *
214 * @param int $level Error level raised
215 * @param string $message Error message
216 * @param string $file File that error was raised in
217 * @param int $line Line number error was raised at
218 * @param array $context Active symbol table point of error
219 * @param array $trace Backtrace at point of error (undocumented HHVM
220 * feature)
221 * @return bool Always returns false
222 */
223 public static function handleFatalError(
224 $level = null, $message = null, $file = null, $line = null,
225 $context = null, $trace = null
226 ) {
227 // Free reserved memory so that we have space to process OOM
228 // errors
229 self::$reservedMemory = null;
230
231 if ( $level === null ) {
232 // Called as a shutdown handler, get data from error_get_last()
233 if ( static::$handledFatalCallback ) {
234 // Already called once (probably as an error handler callback
235 // under HHVM) so don't log again.
236 return false;
237 }
238
239 $lastError = error_get_last();
240 if ( $lastError !== null ) {
241 $level = $lastError['type'];
242 $message = $lastError['message'];
243 $file = $lastError['file'];
244 $line = $lastError['line'];
245 } else {
246 $level = 0;
247 $message = '';
248 }
249 }
250
251 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
252 // Only interested in fatal errors, others should have been
253 // handled by MWExceptionHandler::handleError
254 return false;
255 }
256
257 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
258
259 // Look at message to see if this is a class not found failure
260 // HHVM: Class undefined: foo
261 // PHP5: Class 'foo' not found
262 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
263 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
264 $msg = <<<TXT
265 {$msg}
266
267 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.
268
269 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.
270 TXT;
271 // @codingStandardsIgnoreEnd
272 }
273
274 // We can't just create an exception and log it as it is likely that
275 // the interpreter has unwound the stack already. If that is true the
276 // stacktrace we would get would be functionally empty. If however we
277 // have been called as an error handler callback *and* HHVM is in use
278 // we will have been provided with a useful stacktrace that we can
279 // log.
280 $trace = $trace ?: debug_backtrace();
281 $logger = LoggerFactory::getInstance( 'fatal' );
282 $logger->error( $msg, [
283 'exception' => [
284 'class' => 'ErrorException',
285 'message' => "PHP Fatal Error: {$message}",
286 'code' => $level,
287 'file' => $file,
288 'line' => $line,
289 'trace' => static::redactTrace( $trace ),
290 ],
291 'exception_id' => wfRandomString( 8 ),
292 ] );
293
294 // Remember call so we don't double process via HHVM's fatal
295 // notifications and the shutdown hook behavior
296 static::$handledFatalCallback = true;
297 return false;
298 }
299
300 /**
301 * Generate a string representation of an exception's stack trace
302 *
303 * Like Exception::getTraceAsString, but replaces argument values with
304 * argument type or class name.
305 *
306 * @param Exception|Throwable $e
307 * @return string
308 * @see prettyPrintTrace()
309 */
310 public static function getRedactedTraceAsString( $e ) {
311 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
312 }
313
314 /**
315 * Generate a string representation of a stacktrace.
316 *
317 * @param array $trace
318 * @param string $pad Constant padding to add to each line of trace
319 * @return string
320 * @since 1.26
321 */
322 public static function prettyPrintTrace( array $trace, $pad = '' ) {
323 $text = '';
324
325 $level = 0;
326 foreach ( $trace as $level => $frame ) {
327 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
328 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
329 } else {
330 // 'file' and 'line' are unset for calls via call_user_func
331 // (bug 55634) This matches behaviour of
332 // Exception::getTraceAsString to instead display "[internal
333 // function]".
334 $text .= "{$pad}#{$level} [internal function]: ";
335 }
336
337 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
338 $text .= $frame['class'] . $frame['type'] . $frame['function'];
339 } elseif ( isset( $frame['function'] ) ) {
340 $text .= $frame['function'];
341 } else {
342 $text .= 'NO_FUNCTION_GIVEN';
343 }
344
345 if ( isset( $frame['args'] ) ) {
346 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
347 } else {
348 $text .= "()\n";
349 }
350 }
351
352 $level = $level + 1;
353 $text .= "{$pad}#{$level} {main}";
354
355 return $text;
356 }
357
358 /**
359 * Return a copy of an exception's backtrace as an array.
360 *
361 * Like Exception::getTrace, but replaces each element in each frame's
362 * argument array with the name of its class (if the element is an object)
363 * or its type (if the element is a PHP primitive).
364 *
365 * @since 1.22
366 * @param Exception|Throwable $e
367 * @return array
368 */
369 public static function getRedactedTrace( $e ) {
370 return static::redactTrace( $e->getTrace() );
371 }
372
373 /**
374 * Redact a stacktrace generated by Exception::getTrace(),
375 * debug_backtrace() or similar means. Replaces each element in each
376 * frame's argument array with the name of its class (if the element is an
377 * object) or its type (if the element is a PHP primitive).
378 *
379 * @since 1.26
380 * @param array $trace Stacktrace
381 * @return array Stacktrace with arugment values converted to data types
382 */
383 public static function redactTrace( array $trace ) {
384 return array_map( function ( $frame ) {
385 if ( isset( $frame['args'] ) ) {
386 $frame['args'] = array_map( function ( $arg ) {
387 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
388 }, $frame['args'] );
389 }
390 return $frame;
391 }, $trace );
392 }
393
394 /**
395 * Get the ID for this exception.
396 *
397 * The ID is saved so that one can match the one output to the user (when
398 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
399 *
400 * @since 1.22
401 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
402 * @param Exception|Throwable $e
403 * @return string
404 */
405 public static function getLogId( $e ) {
406 wfDeprecated( __METHOD__, '1.27' );
407 return WebRequest::getRequestId();
408 }
409
410 /**
411 * If the exception occurred in the course of responding to a request,
412 * returns the requested URL. Otherwise, returns false.
413 *
414 * @since 1.23
415 * @return string|false
416 */
417 public static function getURL() {
418 global $wgRequest;
419 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
420 return false;
421 }
422 return $wgRequest->getRequestURL();
423 }
424
425 /**
426 * Get a message formatting the exception message and its origin.
427 *
428 * @since 1.22
429 * @param Exception|Throwable $e
430 * @return string
431 */
432 public static function getLogMessage( $e ) {
433 $id = WebRequest::getRequestId();
434 $type = get_class( $e );
435 $file = $e->getFile();
436 $line = $e->getLine();
437 $message = $e->getMessage();
438 $url = self::getURL() ?: '[no req]';
439
440 return "[$id] $url $type from line $line of $file: $message";
441 }
442
443 /**
444 * @param Exception|Throwable $e
445 * @return string
446 */
447 public static function getPublicLogMessage( $e ) {
448 $reqId = WebRequest::getRequestId();
449 $type = get_class( $e );
450 return '[' . $reqId . '] '
451 . gmdate( 'Y-m-d H:i:s' ) . ': '
452 . 'Fatal exception of type "' . $type . '"';
453 }
454
455 /**
456 * Get a PSR-3 log event context from an Exception.
457 *
458 * Creates a structured array containing information about the provided
459 * exception that can be used to augment a log message sent to a PSR-3
460 * logger.
461 *
462 * @param Exception|Throwable $e
463 * @return array
464 */
465 public static function getLogContext( $e ) {
466 return [
467 'exception' => $e,
468 'exception_id' => WebRequest::getRequestId(),
469 ];
470 }
471
472 /**
473 * Get a structured representation of an Exception.
474 *
475 * Returns an array of structured data (class, message, code, file,
476 * backtrace) derived from the given exception. The backtrace information
477 * will be redacted as per getRedactedTraceAsArray().
478 *
479 * @param Exception|Throwable $e
480 * @return array
481 * @since 1.26
482 */
483 public static function getStructuredExceptionData( $e ) {
484 global $wgLogExceptionBacktrace;
485 $data = [
486 'id' => WebRequest::getRequestId(),
487 'type' => get_class( $e ),
488 'file' => $e->getFile(),
489 'line' => $e->getLine(),
490 'message' => $e->getMessage(),
491 'code' => $e->getCode(),
492 'url' => self::getURL() ?: null,
493 ];
494
495 if ( $e instanceof ErrorException &&
496 ( error_reporting() & $e->getSeverity() ) === 0
497 ) {
498 // Flag surpressed errors
499 $data['suppressed'] = true;
500 }
501
502 if ( $wgLogExceptionBacktrace ) {
503 $data['backtrace'] = self::getRedactedTrace( $e );
504 }
505
506 $previous = $e->getPrevious();
507 if ( $previous !== null ) {
508 $data['previous'] = self::getStructuredExceptionData( $previous );
509 }
510
511 return $data;
512 }
513
514 /**
515 * Serialize an Exception object to JSON.
516 *
517 * The JSON object will have keys 'id', 'file', 'line', 'message', and
518 * 'url'. These keys map to string values, with the exception of 'line',
519 * which is a number, and 'url', which may be either a string URL or or
520 * null if the exception did not occur in the context of serving a web
521 * request.
522 *
523 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
524 * key, mapped to the array return value of Exception::getTrace, but with
525 * each element in each frame's "args" array (if set) replaced with the
526 * argument's class name (if the argument is an object) or type name (if
527 * the argument is a PHP primitive).
528 *
529 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
530 * @code
531 * {
532 * "id": "c41fb419",
533 * "type": "MWException",
534 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
535 * "line": 704,
536 * "message": "Non-string key given",
537 * "url": "/wiki/Main_Page"
538 * }
539 * @endcode
540 *
541 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
542 * @code
543 * {
544 * "id": "dc457938",
545 * "type": "MWException",
546 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
547 * "line": 704,
548 * "message": "Non-string key given",
549 * "url": "/wiki/Main_Page",
550 * "backtrace": [{
551 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
552 * "line": 80,
553 * "function": "get",
554 * "class": "MessageCache",
555 * "type": "->",
556 * "args": ["array"]
557 * }]
558 * }
559 * @endcode
560 *
561 * @since 1.23
562 * @param Exception|Throwable $e
563 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
564 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
565 * @return string|false JSON string if successful; false upon failure
566 */
567 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
568 $data = self::getStructuredExceptionData( $e );
569 return FormatJson::encode( $data, $pretty, $escaping );
570 }
571
572 /**
573 * Log an exception to the exception log (if enabled).
574 *
575 * This method must not assume the exception is an MWException,
576 * it is also used to handle PHP exceptions or exceptions from other libraries.
577 *
578 * @since 1.22
579 * @param Exception|Throwable $e
580 */
581 public static function logException( $e ) {
582 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
583 $logger = LoggerFactory::getInstance( 'exception' );
584 $logger->error(
585 self::getLogMessage( $e ),
586 self::getLogContext( $e )
587 );
588
589 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
590 if ( $json !== false ) {
591 $logger = LoggerFactory::getInstance( 'exception-json' );
592 $logger->error( $json, [ 'private' => true ] );
593 }
594
595 Hooks::run( 'LogException', [ $e, false ] );
596 }
597 }
598
599 /**
600 * Log an exception that wasn't thrown but made to wrap an error.
601 *
602 * @since 1.25
603 * @param ErrorException $e
604 * @param string $channel
605 */
606 protected static function logError( ErrorException $e, $channel ) {
607 // The set_error_handler callback is independent from error_reporting.
608 // Filter out unwanted errors manually (e.g. when
609 // MediaWiki\suppressWarnings is active).
610 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
611 if ( !$suppressed ) {
612 $logger = LoggerFactory::getInstance( $channel );
613 $logger->error(
614 self::getLogMessage( $e ),
615 self::getLogContext( $e )
616 );
617 }
618
619 // Include all errors in the json log (surpressed errors will be flagged)
620 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
621 if ( $json !== false ) {
622 $logger = LoggerFactory::getInstance( "{$channel}-json" );
623 $logger->error( $json, [ 'private' => true ] );
624 }
625
626 Hooks::run( 'LogException', [ $e, $suppressed ] );
627 }
628 }