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