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