Merge "Remove redundant NS_MAIN from translations"
[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( $e ) {
154 global $wgFullyInitialised;
155
156 self::rollbackMasterChangesAndLog( $e );
157 self::logException( $e );
158 self::report( $e );
159
160 // Final cleanup
161 if ( $wgFullyInitialised ) {
162 try {
163 // uses $wgRequest, hence the $wgFullyInitialised condition
164 wfLogProfilingData();
165 } catch ( Exception $e ) {
166 }
167 }
168
169 // Exit value should be nonzero for the benefit of shell jobs
170 exit( 1 );
171 }
172
173 /**
174 * @since 1.25
175 * @param int $level Error level raised
176 * @param string $message
177 * @param string $file
178 * @param int $line
179 */
180 public static function handleError( $level, $message, $file = null, $line = null ) {
181 // Map error constant to error name (reverse-engineer PHP error reporting)
182 $channel = 'error';
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 $channel = 'fatal';
192 break;
193 case E_WARNING:
194 case E_CORE_WARNING:
195 case E_COMPILE_WARNING:
196 case E_USER_WARNING:
197 $levelName = 'Warning';
198 break;
199 case E_NOTICE:
200 case E_USER_NOTICE:
201 $levelName = 'Notice';
202 break;
203 case E_STRICT:
204 $levelName = 'Strict Standards';
205 break;
206 case E_DEPRECATED:
207 case E_USER_DEPRECATED:
208 $levelName = 'Deprecated';
209 break;
210 case /* HHVM's FATAL_ERROR */ 16777217:
211 $levelName = 'Fatal';
212 $channel = 'fatal';
213 break;
214 default:
215 $levelName = 'Unknown error';
216 break;
217 }
218
219 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
220 self::logError( $e, $channel );
221
222 // This handler is for logging only. Return false will instruct PHP
223 // to continue regular handling.
224 return false;
225 }
226
227
228 /**
229 * Look for a fatal error as the cause of the request termination and log
230 * as an exception.
231 *
232 * Special handling is included for missing class errors as they may
233 * indicate that the user needs to install 3rd-party libraries via
234 * Composer or other means.
235 *
236 * @since 1.25
237 */
238 public static function handleFatalError() {
239 self::$reservedMemory = null;
240 $lastError = error_get_last();
241
242 if ( $lastError &&
243 isset( $lastError['type'] ) &&
244 in_array( $lastError['type'], self::$fatalErrorTypes )
245 ) {
246 $msg = "Fatal Error: {$lastError['message']}";
247 // HHVM: Class undefined: foo
248 // PHP5: Class 'foo' not found
249 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/",
250 $lastError['message']
251 ) ) {
252 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
253 $msg = <<<TXT
254 {$msg}
255
256 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.
257
258 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.
259 TXT;
260 // @codingStandardsIgnoreEnd
261 }
262 $e = new ErrorException( $msg, 0, $lastError['type'] );
263 self::logError( $e, 'fatal' );
264 }
265 }
266
267 /**
268 * Generate a string representation of an exception's stack trace
269 *
270 * Like Exception::getTraceAsString, but replaces argument values with
271 * argument type or class name.
272 *
273 * @param Exception $e
274 * @return string
275 */
276 public static function getRedactedTraceAsString( Exception $e ) {
277 $text = '';
278
279 foreach ( self::getRedactedTrace( $e ) as $level => $frame ) {
280 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
281 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
282 } else {
283 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
284 // This matches behaviour of Exception::getTraceAsString to instead
285 // display "[internal function]".
286 $text .= "#{$level} [internal function]: ";
287 }
288
289 if ( isset( $frame['class'] ) ) {
290 $text .= $frame['class'] . $frame['type'] . $frame['function'];
291 } else {
292 $text .= $frame['function'];
293 }
294
295 if ( isset( $frame['args'] ) ) {
296 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
297 } else {
298 $text .= "()\n";
299 }
300 }
301
302 $level = $level + 1;
303 $text .= "#{$level} {main}";
304
305 return $text;
306 }
307
308 /**
309 * Return a copy of an exception's backtrace as an array.
310 *
311 * Like Exception::getTrace, but replaces each element in each frame's
312 * argument array with the name of its class (if the element is an object)
313 * or its type (if the element is a PHP primitive).
314 *
315 * @since 1.22
316 * @param Exception $e
317 * @return array
318 */
319 public static function getRedactedTrace( Exception $e ) {
320 return array_map( function ( $frame ) {
321 if ( isset( $frame['args'] ) ) {
322 $frame['args'] = array_map( function ( $arg ) {
323 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
324 }, $frame['args'] );
325 }
326 return $frame;
327 }, $e->getTrace() );
328 }
329
330 /**
331 * Get the ID for this exception.
332 *
333 * The ID is saved so that one can match the one output to the user (when
334 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
335 *
336 * @since 1.22
337 * @param Exception $e
338 * @return string
339 */
340 public static function getLogId( Exception $e ) {
341 if ( !isset( $e->_mwLogId ) ) {
342 $e->_mwLogId = wfRandomString( 8 );
343 }
344 return $e->_mwLogId;
345 }
346
347 /**
348 * If the exception occurred in the course of responding to a request,
349 * returns the requested URL. Otherwise, returns false.
350 *
351 * @since 1.23
352 * @return string|false
353 */
354 public static function getURL() {
355 global $wgRequest;
356 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
357 return false;
358 }
359 return $wgRequest->getRequestURL();
360 }
361
362 /**
363 * Get a message formatting the exception message and its origin.
364 *
365 * @since 1.22
366 * @param Exception $e
367 * @return string
368 */
369 public static function getLogMessage( Exception $e ) {
370 $id = self::getLogId( $e );
371 $type = get_class( $e );
372 $file = $e->getFile();
373 $line = $e->getLine();
374 $message = $e->getMessage();
375 $url = self::getURL() ?: '[no req]';
376
377 return "[$id] $url $type from line $line of $file: $message";
378 }
379
380 /**
381 * Serialize an Exception object to JSON.
382 *
383 * The JSON object will have keys 'id', 'file', 'line', 'message', and
384 * 'url'. These keys map to string values, with the exception of 'line',
385 * which is a number, and 'url', which may be either a string URL or or
386 * null if the exception did not occur in the context of serving a web
387 * request.
388 *
389 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
390 * key, mapped to the array return value of Exception::getTrace, but with
391 * each element in each frame's "args" array (if set) replaced with the
392 * argument's class name (if the argument is an object) or type name (if
393 * the argument is a PHP primitive).
394 *
395 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
396 * @code
397 * {
398 * "id": "c41fb419",
399 * "type": "MWException",
400 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
401 * "line": 704,
402 * "message": "Non-string key given",
403 * "url": "/wiki/Main_Page"
404 * }
405 * @endcode
406 *
407 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
408 * @code
409 * {
410 * "id": "dc457938",
411 * "type": "MWException",
412 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
413 * "line": 704,
414 * "message": "Non-string key given",
415 * "url": "/wiki/Main_Page",
416 * "backtrace": [{
417 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
418 * "line": 80,
419 * "function": "get",
420 * "class": "MessageCache",
421 * "type": "->",
422 * "args": ["array"]
423 * }]
424 * }
425 * @endcode
426 *
427 * @since 1.23
428 * @param Exception $e
429 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
430 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
431 * @return string|false JSON string if successful; false upon failure
432 */
433 public static function jsonSerializeException( Exception $e, $pretty = false, $escaping = 0 ) {
434 global $wgLogExceptionBacktrace;
435
436 $exceptionData = array(
437 'id' => self::getLogId( $e ),
438 'type' => get_class( $e ),
439 'file' => $e->getFile(),
440 'line' => $e->getLine(),
441 'message' => $e->getMessage(),
442 );
443
444 if ( $e instanceof ErrorException && ( error_reporting() & $e->getSeverity() ) === 0 ) {
445 // Flag surpressed errors
446 $exceptionData['suppressed'] = true;
447 }
448
449 // Because MediaWiki is first and foremost a web application, we set a
450 // 'url' key unconditionally, but set it to null if the exception does
451 // not occur in the context of a web request, as a way of making that
452 // fact visible and explicit.
453 $exceptionData['url'] = self::getURL() ?: null;
454
455 if ( $wgLogExceptionBacktrace ) {
456 // Argument values may not be serializable, so redact them.
457 $exceptionData['backtrace'] = self::getRedactedTrace( $e );
458 }
459
460 return FormatJson::encode( $exceptionData, $pretty, $escaping );
461 }
462
463 /**
464 * Log an exception to the exception log (if enabled).
465 *
466 * This method must not assume the exception is an MWException,
467 * it is also used to handle PHP exceptions or exceptions from other libraries.
468 *
469 * @since 1.22
470 * @param Exception $e
471 */
472 public static function logException( Exception $e ) {
473 global $wgLogExceptionBacktrace;
474
475 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
476 $log = self::getLogMessage( $e );
477 if ( $wgLogExceptionBacktrace ) {
478 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
479 } else {
480 wfDebugLog( 'exception', $log );
481 }
482
483 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
484 if ( $json !== false ) {
485 wfDebugLog( 'exception-json', $json, 'private' );
486 }
487 }
488 }
489
490 /**
491 * Log an exception that wasn't thrown but made to wrap an error.
492 *
493 * @since 1.25
494 * @param ErrorException $e
495 * @param string $channel
496 */
497 protected static function logError( ErrorException $e, $channel ) {
498 global $wgLogExceptionBacktrace;
499
500 // The set_error_handler callback is independent from error_reporting.
501 // Filter out unwanted errors manually (e.g. when wfSuppressWarnings is active).
502 if ( ( error_reporting() & $e->getSeverity() ) !== 0 ) {
503 $log = self::getLogMessage( $e );
504 if ( $wgLogExceptionBacktrace ) {
505 wfDebugLog( $channel, $log . "\n" . $e->getTraceAsString() );
506 } else {
507 wfDebugLog( $channel, $log );
508 }
509 }
510
511 // Include all errors in the json log (surpressed errors will be flagged)
512 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
513 if ( $json !== false ) {
514 wfDebugLog( "$channel-json", $json, 'private' );
515 }
516 }
517 }