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