Merge "Add MessagesBi.php"
[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 PHP error constant to a PSR-3 severity level.
180 // Avoid use of "DEBUG" or "INFO" levels, unless the
181 // error should evade error monitoring and alerts.
182 //
183 // To decide the log level, ask yourself: "Has the
184 // program's behaviour diverged from what the written
185 // code expected?"
186 //
187 // For example, use of a deprecated method or violating a strict standard
188 // has no impact on functional behaviour (Warning). On the other hand,
189 // accessing an undefined variable makes behaviour diverge from what the
190 // author intended/expected. PHP recovers from an undefined variables by
191 // yielding null and continuing execution, but it remains a change in
192 // behaviour given the null was not part of the code and is likely not
193 // accounted for.
194 switch ( $level ) {
195 case E_RECOVERABLE_ERROR:
196 $levelName = 'Error';
197 $severity = LogLevel::ERROR;
198 break;
199 case E_WARNING:
200 case E_CORE_WARNING:
201 case E_COMPILE_WARNING:
202 $levelName = 'Warning';
203 $severity = LogLevel::ERROR;
204 break;
205 case E_NOTICE:
206 $levelName = 'Notice';
207 $severity = LogLevel::ERROR;
208 break;
209 case E_USER_WARNING:
210 case E_USER_NOTICE:
211 // Used by wfWarn(), MWDebug::warning()
212 $levelName = 'Warning';
213 $severity = LogLevel::WARNING;
214 break;
215 case E_STRICT:
216 $levelName = 'Strict Standards';
217 $severity = LogLevel::WARNING;
218 break;
219 case E_DEPRECATED:
220 case E_USER_DEPRECATED:
221 $levelName = 'Deprecated';
222 $severity = LogLevel::WARNING;
223 break;
224 default:
225 $levelName = 'Unknown error';
226 $severity = LogLevel::ERROR;
227 break;
228 }
229
230 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
231 self::logError( $e, 'error', $severity );
232
233 // If $wgPropagateErrors is true return false so PHP shows/logs the error normally.
234 // Ignore $wgPropagateErrors if the error should break execution, or track_errors is set
235 // (which means someone is counting on regular PHP error handling behavior).
236 return !( $wgPropagateErrors || $level == E_RECOVERABLE_ERROR || ini_get( 'track_errors' ) );
237 }
238
239 /**
240 * Dual purpose callback used as both a set_error_handler() callback and
241 * a registered shutdown function. Receive a callback from the interpreter
242 * for a raised error or system shutdown, check for a fatal error, and log
243 * to the 'fatal' logging channel.
244 *
245 * Special handling is included for missing class errors as they may
246 * indicate that the user needs to install 3rd-party libraries via
247 * Composer or other means.
248 *
249 * @since 1.25
250 *
251 * @param int|null $level Error level raised
252 * @param string|null $message Error message
253 * @param string|null $file File that error was raised in
254 * @param int|null $line Line number error was raised at
255 * @param array|null $context Active symbol table point of error
256 * @param array|null $trace Backtrace at point of error (undocumented HHVM
257 * feature)
258 * @return bool Always returns false
259 */
260 public static function handleFatalError(
261 $level = null, $message = null, $file = null, $line = null,
262 $context = null, $trace = null
263 ) {
264 // Free reserved memory so that we have space to process OOM
265 // errors
266 self::$reservedMemory = null;
267
268 if ( $level === null ) {
269 // Called as a shutdown handler, get data from error_get_last()
270 if ( static::$handledFatalCallback ) {
271 // Already called once (probably as an error handler callback
272 // under HHVM) so don't log again.
273 return false;
274 }
275
276 $lastError = error_get_last();
277 if ( $lastError !== null ) {
278 $level = $lastError['type'];
279 $message = $lastError['message'];
280 $file = $lastError['file'];
281 $line = $lastError['line'];
282 } else {
283 $level = 0;
284 $message = '';
285 }
286 }
287
288 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
289 // Only interested in fatal errors, others should have been
290 // handled by MWExceptionHandler::handleError
291 return false;
292 }
293
294 $url = WebRequest::getGlobalRequestURL();
295 $msgParts = [
296 '[{exception_id}] {exception_url} PHP Fatal Error',
297 ( $line || $file ) ? ' from' : '',
298 $line ? " line $line" : '',
299 ( $line && $file ) ? ' of' : '',
300 $file ? " $file" : '',
301 ": $message",
302 ];
303 $msg = implode( '', $msgParts );
304
305 // Look at message to see if this is a class not found failure
306 // HHVM: Class undefined: foo
307 // PHP5: Class 'foo' not found
308 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $message ) ) {
309 // phpcs:disable Generic.Files.LineLength
310 $msg = <<<TXT
311 {$msg}
312
313 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.
314
315 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.
316 TXT;
317 // phpcs:enable
318 }
319
320 // We can't just create an exception and log it as it is likely that
321 // the interpreter has unwound the stack already. If that is true the
322 // stacktrace we would get would be functionally empty. If however we
323 // have been called as an error handler callback *and* HHVM is in use
324 // we will have been provided with a useful stacktrace that we can
325 // log.
326 $trace = $trace ?: debug_backtrace();
327 $logger = LoggerFactory::getInstance( 'fatal' );
328 $logger->error( $msg, [
329 'fatal_exception' => [
330 'class' => ErrorException::class,
331 'message' => "PHP Fatal Error: {$message}",
332 'code' => $level,
333 'file' => $file,
334 'line' => $line,
335 'trace' => self::prettyPrintTrace( self::redactTrace( $trace ) ),
336 ],
337 'exception_id' => WebRequest::getRequestId(),
338 'exception_url' => $url,
339 'caught_by' => self::CAUGHT_BY_HANDLER
340 ] );
341
342 // Remember call so we don't double process via HHVM's fatal
343 // notifications and the shutdown hook behavior
344 static::$handledFatalCallback = true;
345 return false;
346 }
347
348 /**
349 * Generate a string representation of an exception's stack trace
350 *
351 * Like Exception::getTraceAsString, but replaces argument values with
352 * argument type or class name.
353 *
354 * @param Exception|Throwable $e
355 * @return string
356 * @see prettyPrintTrace()
357 */
358 public static function getRedactedTraceAsString( $e ) {
359 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
360 }
361
362 /**
363 * Generate a string representation of a stacktrace.
364 *
365 * @param array $trace
366 * @param string $pad Constant padding to add to each line of trace
367 * @return string
368 * @since 1.26
369 */
370 public static function prettyPrintTrace( array $trace, $pad = '' ) {
371 $text = '';
372
373 $level = 0;
374 foreach ( $trace as $level => $frame ) {
375 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
376 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
377 } else {
378 // 'file' and 'line' are unset for calls via call_user_func
379 // (T57634) This matches behaviour of
380 // Exception::getTraceAsString to instead display "[internal
381 // function]".
382 $text .= "{$pad}#{$level} [internal function]: ";
383 }
384
385 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
386 $text .= $frame['class'] . $frame['type'] . $frame['function'];
387 } elseif ( isset( $frame['function'] ) ) {
388 $text .= $frame['function'];
389 } else {
390 $text .= 'NO_FUNCTION_GIVEN';
391 }
392
393 if ( isset( $frame['args'] ) ) {
394 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
395 } else {
396 $text .= "()\n";
397 }
398 }
399
400 $level = $level + 1;
401 $text .= "{$pad}#{$level} {main}";
402
403 return $text;
404 }
405
406 /**
407 * Return a copy of an exception's backtrace as an array.
408 *
409 * Like Exception::getTrace, but replaces each element in each frame's
410 * argument array with the name of its class (if the element is an object)
411 * or its type (if the element is a PHP primitive).
412 *
413 * @since 1.22
414 * @param Exception|Throwable $e
415 * @return array
416 */
417 public static function getRedactedTrace( $e ) {
418 return static::redactTrace( $e->getTrace() );
419 }
420
421 /**
422 * Redact a stacktrace generated by Exception::getTrace(),
423 * debug_backtrace() or similar means. Replaces each element in each
424 * frame's argument array with the name of its class (if the element is an
425 * object) or its type (if the element is a PHP primitive).
426 *
427 * @since 1.26
428 * @param array $trace Stacktrace
429 * @return array Stacktrace with arugment values converted to data types
430 */
431 public static function redactTrace( array $trace ) {
432 return array_map( function ( $frame ) {
433 if ( isset( $frame['args'] ) ) {
434 $frame['args'] = array_map( function ( $arg ) {
435 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
436 }, $frame['args'] );
437 }
438 return $frame;
439 }, $trace );
440 }
441
442 /**
443 * Get the ID for this exception.
444 *
445 * The ID is saved so that one can match the one output to the user (when
446 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
447 *
448 * @since 1.22
449 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
450 * @param Exception|Throwable $e
451 * @return string
452 */
453 public static function getLogId( $e ) {
454 wfDeprecated( __METHOD__, '1.27' );
455 return WebRequest::getRequestId();
456 }
457
458 /**
459 * If the exception occurred in the course of responding to a request,
460 * returns the requested URL. Otherwise, returns false.
461 *
462 * @since 1.23
463 * @return string|false
464 */
465 public static function getURL() {
466 global $wgRequest;
467 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
468 return false;
469 }
470 return $wgRequest->getRequestURL();
471 }
472
473 /**
474 * Get a message formatting the exception message and its origin.
475 *
476 * @since 1.22
477 * @param Exception|Throwable $e
478 * @return string
479 */
480 public static function getLogMessage( $e ) {
481 $id = WebRequest::getRequestId();
482 $type = get_class( $e );
483 $file = $e->getFile();
484 $line = $e->getLine();
485 $message = $e->getMessage();
486 $url = self::getURL() ?: '[no req]';
487
488 return "[$id] $url $type from line $line of $file: $message";
489 }
490
491 /**
492 * Get a normalised message for formatting with PSR-3 log event context.
493 *
494 * Must be used together with `getLogContext()` to be useful.
495 *
496 * @since 1.30
497 * @param Exception|Throwable $e
498 * @return string
499 */
500 public static function getLogNormalMessage( $e ) {
501 $type = get_class( $e );
502 $file = $e->getFile();
503 $line = $e->getLine();
504 $message = $e->getMessage();
505
506 return "[{exception_id}] {exception_url} $type from line $line of $file: $message";
507 }
508
509 /**
510 * @param Exception|Throwable $e
511 * @return string
512 */
513 public static function getPublicLogMessage( $e ) {
514 $reqId = WebRequest::getRequestId();
515 $type = get_class( $e );
516 return '[' . $reqId . '] '
517 . gmdate( 'Y-m-d H:i:s' ) . ': '
518 . 'Fatal exception of type "' . $type . '"';
519 }
520
521 /**
522 * Get a PSR-3 log event context from an Exception.
523 *
524 * Creates a structured array containing information about the provided
525 * exception that can be used to augment a log message sent to a PSR-3
526 * logger.
527 *
528 * @param Exception|Throwable $e
529 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
530 * @return array
531 */
532 public static function getLogContext( $e, $catcher = self::CAUGHT_BY_OTHER ) {
533 return [
534 'exception' => $e,
535 'exception_id' => WebRequest::getRequestId(),
536 'exception_url' => self::getURL() ?: '[no req]',
537 'caught_by' => $catcher
538 ];
539 }
540
541 /**
542 * Get a structured representation of an Exception.
543 *
544 * Returns an array of structured data (class, message, code, file,
545 * backtrace) derived from the given exception. The backtrace information
546 * will be redacted as per getRedactedTraceAsArray().
547 *
548 * @param Exception|Throwable $e
549 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
550 * @return array
551 * @since 1.26
552 */
553 public static function getStructuredExceptionData( $e, $catcher = self::CAUGHT_BY_OTHER ) {
554 global $wgLogExceptionBacktrace;
555
556 $data = [
557 'id' => WebRequest::getRequestId(),
558 'type' => get_class( $e ),
559 'file' => $e->getFile(),
560 'line' => $e->getLine(),
561 'message' => $e->getMessage(),
562 'code' => $e->getCode(),
563 'url' => self::getURL() ?: null,
564 'caught_by' => $catcher
565 ];
566
567 if ( $e instanceof ErrorException &&
568 ( error_reporting() & $e->getSeverity() ) === 0
569 ) {
570 // Flag surpressed errors
571 $data['suppressed'] = true;
572 }
573
574 if ( $wgLogExceptionBacktrace ) {
575 $data['backtrace'] = self::getRedactedTrace( $e );
576 }
577
578 $previous = $e->getPrevious();
579 if ( $previous !== null ) {
580 $data['previous'] = self::getStructuredExceptionData( $previous, $catcher );
581 }
582
583 return $data;
584 }
585
586 /**
587 * Serialize an Exception object to JSON.
588 *
589 * The JSON object will have keys 'id', 'file', 'line', 'message', and
590 * 'url'. These keys map to string values, with the exception of 'line',
591 * which is a number, and 'url', which may be either a string URL or or
592 * null if the exception did not occur in the context of serving a web
593 * request.
594 *
595 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
596 * key, mapped to the array return value of Exception::getTrace, but with
597 * each element in each frame's "args" array (if set) replaced with the
598 * argument's class name (if the argument is an object) or type name (if
599 * the argument is a PHP primitive).
600 *
601 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
602 * @code
603 * {
604 * "id": "c41fb419",
605 * "type": "MWException",
606 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
607 * "line": 704,
608 * "message": "Non-string key given",
609 * "url": "/wiki/Main_Page"
610 * }
611 * @endcode
612 *
613 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
614 * @code
615 * {
616 * "id": "dc457938",
617 * "type": "MWException",
618 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
619 * "line": 704,
620 * "message": "Non-string key given",
621 * "url": "/wiki/Main_Page",
622 * "backtrace": [{
623 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
624 * "line": 80,
625 * "function": "get",
626 * "class": "MessageCache",
627 * "type": "->",
628 * "args": ["array"]
629 * }]
630 * }
631 * @endcode
632 *
633 * @since 1.23
634 * @param Exception|Throwable $e
635 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
636 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
637 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
638 * @return string|false JSON string if successful; false upon failure
639 */
640 public static function jsonSerializeException(
641 $e, $pretty = false, $escaping = 0, $catcher = self::CAUGHT_BY_OTHER
642 ) {
643 return FormatJson::encode(
644 self::getStructuredExceptionData( $e, $catcher ),
645 $pretty,
646 $escaping
647 );
648 }
649
650 /**
651 * Log an exception to the exception log (if enabled).
652 *
653 * This method must not assume the exception is an MWException,
654 * it is also used to handle PHP exceptions or exceptions from other libraries.
655 *
656 * @since 1.22
657 * @param Exception|Throwable $e
658 * @param string $catcher CAUGHT_BY_* class constant indicating what caught the error
659 */
660 public static function logException( $e, $catcher = self::CAUGHT_BY_OTHER ) {
661 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
662 $logger = LoggerFactory::getInstance( 'exception' );
663 $logger->error(
664 self::getLogNormalMessage( $e ),
665 self::getLogContext( $e, $catcher )
666 );
667
668 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
669 if ( $json !== false ) {
670 $logger = LoggerFactory::getInstance( 'exception-json' );
671 $logger->error( $json, [ 'private' => true ] );
672 }
673
674 Hooks::run( 'LogException', [ $e, false ] );
675 }
676 }
677
678 /**
679 * Log an exception that wasn't thrown but made to wrap an error.
680 *
681 * @since 1.25
682 * @param ErrorException $e
683 * @param string $channel
684 * @param string $level
685 */
686 protected static function logError(
687 ErrorException $e, $channel, $level = LogLevel::ERROR
688 ) {
689 $catcher = self::CAUGHT_BY_HANDLER;
690 // The set_error_handler callback is independent from error_reporting.
691 // Filter out unwanted errors manually (e.g. when
692 // Wikimedia\suppressWarnings is active).
693 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
694 if ( !$suppressed ) {
695 $logger = LoggerFactory::getInstance( $channel );
696 $logger->log(
697 $level,
698 self::getLogNormalMessage( $e ),
699 self::getLogContext( $e, $catcher )
700 );
701 }
702
703 // Include all errors in the json log (surpressed errors will be flagged)
704 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK, $catcher );
705 if ( $json !== false ) {
706 $logger = LoggerFactory::getInstance( "{$channel}-json" );
707 $logger->log( $level, $json, [ 'private' => true ] );
708 }
709
710 Hooks::run( 'LogException', [ $e, $suppressed ] );
711 }
712 }