Merge "Lower timeout of upload stash -> image scaler requests"
[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 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
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 // @codingStandardsIgnoreEnd
258 }
259 $e = new ErrorException( $msg, 0, $lastError['type'] );
260 self::logError( $e );
261 }
262 }
263
264 /**
265 * Generate a string representation of an exception's stack trace
266 *
267 * Like Exception::getTraceAsString, but replaces argument values with
268 * argument type or class name.
269 *
270 * @param Exception $e
271 * @return string
272 */
273 public static function getRedactedTraceAsString( Exception $e ) {
274 $text = '';
275
276 foreach ( self::getRedactedTrace( $e ) as $level => $frame ) {
277 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
278 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
279 } else {
280 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
281 // This matches behaviour of Exception::getTraceAsString to instead
282 // display "[internal function]".
283 $text .= "#{$level} [internal function]: ";
284 }
285
286 if ( isset( $frame['class'] ) ) {
287 $text .= $frame['class'] . $frame['type'] . $frame['function'];
288 } else {
289 $text .= $frame['function'];
290 }
291
292 if ( isset( $frame['args'] ) ) {
293 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
294 } else {
295 $text .= "()\n";
296 }
297 }
298
299 $level = $level + 1;
300 $text .= "#{$level} {main}";
301
302 return $text;
303 }
304
305 /**
306 * Return a copy of an exception's backtrace as an array.
307 *
308 * Like Exception::getTrace, but replaces each element in each frame's
309 * argument array with the name of its class (if the element is an object)
310 * or its type (if the element is a PHP primitive).
311 *
312 * @since 1.22
313 * @param Exception $e
314 * @return array
315 */
316 public static function getRedactedTrace( Exception $e ) {
317 return array_map( function ( $frame ) {
318 if ( isset( $frame['args'] ) ) {
319 $frame['args'] = array_map( function ( $arg ) {
320 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
321 }, $frame['args'] );
322 }
323 return $frame;
324 }, $e->getTrace() );
325 }
326
327 /**
328 * Get the ID for this exception.
329 *
330 * The ID is saved so that one can match the one output to the user (when
331 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
332 *
333 * @since 1.22
334 * @param Exception $e
335 * @return string
336 */
337 public static function getLogId( Exception $e ) {
338 if ( !isset( $e->_mwLogId ) ) {
339 $e->_mwLogId = wfRandomString( 8 );
340 }
341 return $e->_mwLogId;
342 }
343
344 /**
345 * If the exception occurred in the course of responding to a request,
346 * returns the requested URL. Otherwise, returns false.
347 *
348 * @since 1.23
349 * @return string|bool
350 */
351 public static function getURL() {
352 global $wgRequest;
353 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
354 return false;
355 }
356 return $wgRequest->getRequestURL();
357 }
358
359 /**
360 * Get a message formatting the exception message and its origin.
361 *
362 * @since 1.22
363 * @param Exception $e
364 * @return string
365 */
366 public static function getLogMessage( Exception $e ) {
367 $id = self::getLogId( $e );
368 $type = get_class( $e );
369 $file = $e->getFile();
370 $line = $e->getLine();
371 $message = $e->getMessage();
372 $url = self::getURL() ?: '[no req]';
373
374 return "[$id] $url $type from line $line of $file: $message";
375 }
376
377 /**
378 * Serialize an Exception object to JSON.
379 *
380 * The JSON object will have keys 'id', 'file', 'line', 'message', and
381 * 'url'. These keys map to string values, with the exception of 'line',
382 * which is a number, and 'url', which may be either a string URL or or
383 * null if the exception did not occur in the context of serving a web
384 * request.
385 *
386 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
387 * key, mapped to the array return value of Exception::getTrace, but with
388 * each element in each frame's "args" array (if set) replaced with the
389 * argument's class name (if the argument is an object) or type name (if
390 * the argument is a PHP primitive).
391 *
392 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
393 * @code
394 * {
395 * "id": "c41fb419",
396 * "type": "MWException",
397 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
398 * "line": 704,
399 * "message": "Non-string key given",
400 * "url": "/wiki/Main_Page"
401 * }
402 * @endcode
403 *
404 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
405 * @code
406 * {
407 * "id": "dc457938",
408 * "type": "MWException",
409 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
410 * "line": 704,
411 * "message": "Non-string key given",
412 * "url": "/wiki/Main_Page",
413 * "backtrace": [{
414 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
415 * "line": 80,
416 * "function": "get",
417 * "class": "MessageCache",
418 * "type": "->",
419 * "args": ["array"]
420 * }]
421 * }
422 * @endcode
423 *
424 * @since 1.23
425 * @param Exception $e
426 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
427 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
428 * @return string|bool JSON string if successful; false upon failure
429 */
430 public static function jsonSerializeException( Exception $e, $pretty = false, $escaping = 0 ) {
431 global $wgLogExceptionBacktrace;
432
433 $exceptionData = array(
434 'id' => self::getLogId( $e ),
435 'type' => get_class( $e ),
436 'file' => $e->getFile(),
437 'line' => $e->getLine(),
438 'message' => $e->getMessage(),
439 );
440
441 if ( $e instanceof ErrorException && ( error_reporting() & $e->getSeverity() ) === 0 ) {
442 // Flag surpressed errors
443 $exceptionData['suppressed'] = true;
444 }
445
446 // Because MediaWiki is first and foremost a web application, we set a
447 // 'url' key unconditionally, but set it to null if the exception does
448 // not occur in the context of a web request, as a way of making that
449 // fact visible and explicit.
450 $exceptionData['url'] = self::getURL() ?: null;
451
452 if ( $wgLogExceptionBacktrace ) {
453 // Argument values may not be serializable, so redact them.
454 $exceptionData['backtrace'] = self::getRedactedTrace( $e );
455 }
456
457 return FormatJson::encode( $exceptionData, $pretty, $escaping );
458 }
459
460 /**
461 * Log an exception to the exception log (if enabled).
462 *
463 * This method must not assume the exception is an MWException,
464 * it is also used to handle PHP exceptions or exceptions from other libraries.
465 *
466 * @since 1.22
467 * @param Exception $e
468 */
469 public static function logException( Exception $e ) {
470 global $wgLogExceptionBacktrace;
471
472 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
473 $log = self::getLogMessage( $e );
474 if ( $wgLogExceptionBacktrace ) {
475 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
476 } else {
477 wfDebugLog( 'exception', $log );
478 }
479
480 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
481 if ( $json !== false ) {
482 wfDebugLog( 'exception-json', $json, 'private' );
483 }
484 }
485 }
486
487 /**
488 * Log an exception that wasn't thrown but made to wrap an error.
489 *
490 * @since 1.25
491 * @param ErrorException $e
492 */
493 protected static function logError( ErrorException $e ) {
494 global $wgLogExceptionBacktrace;
495
496 // The set_error_handler callback is independent from error_reporting.
497 // Filter out unwanted errors manually (e.g. when wfSuppressWarnings is active).
498 if ( ( error_reporting() & $e->getSeverity() ) !== 0 ) {
499 $log = self::getLogMessage( $e );
500 if ( $wgLogExceptionBacktrace ) {
501 wfDebugLog( 'error', $log . "\n" . $e->getTraceAsString() );
502 } else {
503 wfDebugLog( 'error', $log );
504 }
505 }
506
507 // Include all errors in the json log (surpressed errors will be flagged)
508 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
509 if ( $json !== false ) {
510 wfDebugLog( 'error-json', $json, 'private' );
511 }
512 }
513 }