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