Merge "Add hook to allow extensions to modify query used by Special:ShortPages"
[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
23 /**
24 * Handler class for MWExceptions
25 * @ingroup Exception
26 */
27 class MWExceptionHandler {
28
29 /**
30 * @var string $reservedMemory
31 */
32 protected static $reservedMemory;
33 /**
34 * @var array $fatalErrorTypes
35 */
36 protected static $fatalErrorTypes = array(
37 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
38 /* HHVM's FATAL_ERROR level */ 16777217,
39 );
40 /**
41 * @var bool $handledFatalCallback
42 */
43 protected static $handledFatalCallback = false;
44
45 /**
46 * Install handlers with PHP.
47 */
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
57 /**
58 * Report an exception to the user
59 * @param Exception|Throwable $e
60 */
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
112 /**
113 * Print a message, if possible to STDERR.
114 * Use this in command line mode only (see isCommandLine)
115 *
116 * @param string $message Failure text
117 */
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
129 /**
130 * If there are any open database transactions, roll them back and log
131 * the stack trace of the exception that should have been caught so the
132 * transaction could be aborted properly.
133 *
134 * @since 1.23
135 * @param Exception|Throwable $e
136 */
137 public static function rollbackMasterChangesAndLog( $e ) {
138 $factory = wfGetLBFactory();
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
150 /**
151 * Exception handler which simulates the appropriate catch() handling:
152 *
153 * try {
154 * ...
155 * } catch ( Exception $e ) {
156 * $e->report();
157 * } catch ( Exception $e ) {
158 * echo $e->__toString();
159 * }
160 *
161 * @since 1.25
162 * @param Exception|Throwable $e
163 */
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
186 /**
187 * Handler for set_error_handler() callback notifications.
188 *
189 * Receive a callback from the interpreter for a raised error, create an
190 * ErrorException, and log the exception to the 'error' logging
191 * channel(s). If the raised error is a fatal error type (only under HHVM)
192 * delegate to handleFatalError() instead.
193 *
194 * @since 1.25
195 *
196 * @param int $level Error level raised
197 * @param string $message
198 * @param string $file
199 * @param int $line
200 * @return bool
201 *
202 * @see logError()
203 */
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
249 /**
250 * Dual purpose callback used as both a set_error_handler() callback and
251 * a registered shutdown function. Receive a callback from the interpreter
252 * for a raised error or system shutdown, check for a fatal error, and log
253 * to the 'fatal' logging channel.
254 *
255 * Special handling is included for missing class errors as they may
256 * indicate that the user needs to install 3rd-party libraries via
257 * Composer or other means.
258 *
259 * @since 1.25
260 *
261 * @param int $level Error level raised
262 * @param string $message Error message
263 * @param string $file File that error was raised in
264 * @param int $line Line number error was raised at
265 * @param array $context Active symbol table point of error
266 * @param array $trace Backtrace at point of error (undocumented HHVM
267 * feature)
268 * @return bool Always returns false
269 */
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, array(
330 'exception' => array(
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
347 /**
348 * Generate a string representation of an exception's stack trace
349 *
350 * Like Exception::getTraceAsString, but replaces argument values with
351 * argument type or class name.
352 *
353 * @param Exception|Throwable $e
354 * @return string
355 * @see prettyPrintTrace()
356 */
357 public static function getRedactedTraceAsString( $e ) {
358 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
359 }
360
361 /**
362 * Generate a string representation of a stacktrace.
363 *
364 * @param array $trace
365 * @param string $pad Constant padding to add to each line of trace
366 * @return string
367 * @since 1.26
368 */
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
405 /**
406 * Return a copy of an exception's backtrace as an array.
407 *
408 * Like Exception::getTrace, but replaces each element in each frame's
409 * argument array with the name of its class (if the element is an object)
410 * or its type (if the element is a PHP primitive).
411 *
412 * @since 1.22
413 * @param Exception|Throwable $e
414 * @return array
415 */
416 public static function getRedactedTrace( $e ) {
417 return static::redactTrace( $e->getTrace() );
418 }
419
420 /**
421 * Redact a stacktrace generated by Exception::getTrace(),
422 * debug_backtrace() or similar means. Replaces each element in each
423 * frame's argument array with the name of its class (if the element is an
424 * object) or its type (if the element is a PHP primitive).
425 *
426 * @since 1.26
427 * @param array $trace Stacktrace
428 * @return array Stacktrace with arugment values converted to data types
429 */
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
441 /**
442 * Get the ID for this exception.
443 *
444 * The ID is saved so that one can match the one output to the user (when
445 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
446 *
447 * @since 1.22
448 * @param Exception|Throwable $e
449 * @return string
450 */
451 public static function getLogId( $e ) {
452 if ( !isset( $e->_mwLogId ) ) {
453 $e->_mwLogId = wfRandomString( 8 );
454 }
455 return $e->_mwLogId;
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 = self::getLogId( $e );
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 public static function getPublicLogMessage( Exception $e ) {
492 $logId = self::getLogId( $e );
493 $type = get_class( $e );
494 return '[' . $logId . '] '
495 . gmdate( 'Y-m-d H:i:s' ) . ': '
496 . 'Fatal exception of type ' . $type;
497 }
498
499 /**
500 * Get a PSR-3 log event context from an Exception.
501 *
502 * Creates a structured array containing information about the provided
503 * exception that can be used to augment a log message sent to a PSR-3
504 * logger.
505 *
506 * @param Exception|Throwable $e
507 * @return array
508 */
509 public static function getLogContext( $e ) {
510 return array(
511 'exception' => $e,
512 'exception_id' => static::getLogId( $e ),
513 );
514 }
515
516 /**
517 * Get a structured representation of an Exception.
518 *
519 * Returns an array of structured data (class, message, code, file,
520 * backtrace) derived from the given exception. The backtrace information
521 * will be redacted as per getRedactedTraceAsArray().
522 *
523 * @param Exception|Throwable $e
524 * @return array
525 * @since 1.26
526 */
527 public static function getStructuredExceptionData( $e ) {
528 global $wgLogExceptionBacktrace;
529 $data = array(
530 'id' => self::getLogId( $e ),
531 'type' => get_class( $e ),
532 'file' => $e->getFile(),
533 'line' => $e->getLine(),
534 'message' => $e->getMessage(),
535 'code' => $e->getCode(),
536 'url' => self::getURL() ?: null,
537 );
538
539 if ( $e instanceof ErrorException &&
540 ( error_reporting() & $e->getSeverity() ) === 0
541 ) {
542 // Flag surpressed errors
543 $data['suppressed'] = true;
544 }
545
546 if ( $wgLogExceptionBacktrace ) {
547 $data['backtrace'] = self::getRedactedTrace( $e );
548 }
549
550 $previous = $e->getPrevious();
551 if ( $previous !== null ) {
552 $data['previous'] = self::getStructuredExceptionData( $previous );
553 }
554
555 return $data;
556 }
557
558 /**
559 * Serialize an Exception object to JSON.
560 *
561 * The JSON object will have keys 'id', 'file', 'line', 'message', and
562 * 'url'. These keys map to string values, with the exception of 'line',
563 * which is a number, and 'url', which may be either a string URL or or
564 * null if the exception did not occur in the context of serving a web
565 * request.
566 *
567 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
568 * key, mapped to the array return value of Exception::getTrace, but with
569 * each element in each frame's "args" array (if set) replaced with the
570 * argument's class name (if the argument is an object) or type name (if
571 * the argument is a PHP primitive).
572 *
573 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
574 * @code
575 * {
576 * "id": "c41fb419",
577 * "type": "MWException",
578 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
579 * "line": 704,
580 * "message": "Non-string key given",
581 * "url": "/wiki/Main_Page"
582 * }
583 * @endcode
584 *
585 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
586 * @code
587 * {
588 * "id": "dc457938",
589 * "type": "MWException",
590 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
591 * "line": 704,
592 * "message": "Non-string key given",
593 * "url": "/wiki/Main_Page",
594 * "backtrace": [{
595 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
596 * "line": 80,
597 * "function": "get",
598 * "class": "MessageCache",
599 * "type": "->",
600 * "args": ["array"]
601 * }]
602 * }
603 * @endcode
604 *
605 * @since 1.23
606 * @param Exception|Throwable $e
607 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
608 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
609 * @return string|false JSON string if successful; false upon failure
610 */
611 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
612 $data = self::getStructuredExceptionData( $e );
613 return FormatJson::encode( $data, $pretty, $escaping );
614 }
615
616 /**
617 * Log an exception to the exception log (if enabled).
618 *
619 * This method must not assume the exception is an MWException,
620 * it is also used to handle PHP exceptions or exceptions from other libraries.
621 *
622 * @since 1.22
623 * @param Exception|Throwable $e
624 */
625 public static function logException( $e ) {
626 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
627 $logger = LoggerFactory::getInstance( 'exception' );
628 $logger->error(
629 self::getLogMessage( $e ),
630 self::getLogContext( $e )
631 );
632
633 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
634 if ( $json !== false ) {
635 $logger = LoggerFactory::getInstance( 'exception-json' );
636 $logger->error( $json, array( 'private' => true ) );
637 }
638
639 Hooks::run( 'LogException', array( $e, false ) );
640 }
641 }
642
643 /**
644 * Log an exception that wasn't thrown but made to wrap an error.
645 *
646 * @since 1.25
647 * @param ErrorException $e
648 * @param string $channel
649 */
650 protected static function logError( ErrorException $e, $channel ) {
651 // The set_error_handler callback is independent from error_reporting.
652 // Filter out unwanted errors manually (e.g. when
653 // MediaWiki\suppressWarnings is active).
654 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
655 if ( !$suppressed ) {
656 $logger = LoggerFactory::getInstance( $channel );
657 $logger->error(
658 self::getLogMessage( $e ),
659 self::getLogContext( $e )
660 );
661 }
662
663 // Include all errors in the json log (surpressed errors will be flagged)
664 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
665 if ( $json !== false ) {
666 $logger = LoggerFactory::getInstance( "{$channel}-json" );
667 $logger->error( $json, array( 'private' => true ) );
668 }
669
670 Hooks::run( 'LogException', array( $e, $suppressed ) );
671 }
672 }