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