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