Merge "Ensure users are able to edit the page after changing the content model"
[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 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\MediaWikiServices;
23
24 /**
25 * Handler class for MWExceptions
26 * @ingroup Exception
27 */
28 class MWExceptionHandler {
29
30 /**
31 * @var string $reservedMemory
32 */
33 protected static $reservedMemory;
34 /**
35 * @var array $fatalErrorTypes
36 */
37 protected static $fatalErrorTypes = [
38 E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
39 /* HHVM's FATAL_ERROR level */ 16777217,
40 ];
41 /**
42 * @var bool $handledFatalCallback
43 */
44 protected static $handledFatalCallback = false;
45
46 /**
47 * Install handlers with PHP.
48 */
49 public static function installHandler() {
50 set_exception_handler( 'MWExceptionHandler::handleException' );
51 set_error_handler( 'MWExceptionHandler::handleError' );
52
53 // Reserve 16k of memory so we can report OOM fatals
54 self::$reservedMemory = str_repeat( ' ', 16384 );
55 register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
56 }
57
58 /**
59 * Report an exception to the user
60 * @param Exception|Throwable $e
61 */
62 protected static function report( $e ) {
63 try {
64 // Try and show the exception prettily, with the normal skin infrastructure
65 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY );
66 } catch ( Exception $e2 ) {
67 // Exception occurred from within exception handler
68 // Show a simpler message for the original exception,
69 // don't try to invoke report()
70 MWExceptionRenderer::output( $e, MWExceptionRenderer::AS_PRETTY, $e2 );
71 }
72 }
73
74 /**
75 * If there are any open database transactions, roll them back and log
76 * the stack trace of the exception that should have been caught so the
77 * transaction could be aborted properly.
78 *
79 * @since 1.23
80 * @param Exception|Throwable $e
81 */
82 public static function rollbackMasterChangesAndLog( $e ) {
83 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
84 if ( $lbFactory->hasMasterChanges() ) {
85 $logger = LoggerFactory::getInstance( 'Bug56269' );
86 $logger->warning(
87 'Exception thrown with an uncommited database transaction: ' .
88 self::getLogMessage( $e ),
89 self::getLogContext( $e )
90 );
91 }
92 $lbFactory->rollbackMasterChanges( __METHOD__ );
93 }
94
95 /**
96 * Exception handler which simulates the appropriate catch() handling:
97 *
98 * try {
99 * ...
100 * } catch ( Exception $e ) {
101 * $e->report();
102 * } catch ( Exception $e ) {
103 * echo $e->__toString();
104 * }
105 *
106 * @since 1.25
107 * @param Exception|Throwable $e
108 */
109 public static function handleException( $e ) {
110 try {
111 // Rollback DBs to avoid transaction notices. This may fail
112 // to rollback some DB due to connection issues or exceptions.
113 // However, any sane DB driver will rollback implicitly anyway.
114 self::rollbackMasterChangesAndLog( $e );
115 } catch ( DBError $e2 ) {
116 // If the DB is unreacheable, rollback() will throw an error
117 // and the error report() method might need messages from the DB,
118 // which would result in an exception loop. PHP may escalate such
119 // errors to "Exception thrown without a stack frame" fatals, but
120 // it's better to be explicit here.
121 self::logException( $e2 );
122 }
123
124 self::logException( $e );
125 self::report( $e );
126
127 // Exit value should be nonzero for the benefit of shell jobs
128 exit( 1 );
129 }
130
131 /**
132 * Handler for set_error_handler() callback notifications.
133 *
134 * Receive a callback from the interpreter for a raised error, create an
135 * ErrorException, and log the exception to the 'error' logging
136 * channel(s). If the raised error is a fatal error type (only under HHVM)
137 * delegate to handleFatalError() instead.
138 *
139 * @since 1.25
140 *
141 * @param int $level Error level raised
142 * @param string $message
143 * @param string $file
144 * @param int $line
145 * @return bool
146 *
147 * @see logError()
148 */
149 public static function handleError(
150 $level, $message, $file = null, $line = null
151 ) {
152 if ( in_array( $level, self::$fatalErrorTypes ) ) {
153 return call_user_func_array(
154 'MWExceptionHandler::handleFatalError', func_get_args()
155 );
156 }
157
158 // Map error constant to error name (reverse-engineer PHP error
159 // reporting)
160 switch ( $level ) {
161 case E_RECOVERABLE_ERROR:
162 $levelName = 'Error';
163 break;
164 case E_WARNING:
165 case E_CORE_WARNING:
166 case E_COMPILE_WARNING:
167 case E_USER_WARNING:
168 $levelName = 'Warning';
169 break;
170 case E_NOTICE:
171 case E_USER_NOTICE:
172 $levelName = 'Notice';
173 break;
174 case E_STRICT:
175 $levelName = 'Strict Standards';
176 break;
177 case E_DEPRECATED:
178 case E_USER_DEPRECATED:
179 $levelName = 'Deprecated';
180 break;
181 default:
182 $levelName = 'Unknown error';
183 break;
184 }
185
186 $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
187 self::logError( $e, 'error' );
188
189 // This handler is for logging only. Return false will instruct PHP
190 // to continue regular handling.
191 return false;
192 }
193
194 /**
195 * Dual purpose callback used as both a set_error_handler() callback and
196 * a registered shutdown function. Receive a callback from the interpreter
197 * for a raised error or system shutdown, check for a fatal error, and log
198 * to the 'fatal' logging channel.
199 *
200 * Special handling is included for missing class errors as they may
201 * indicate that the user needs to install 3rd-party libraries via
202 * Composer or other means.
203 *
204 * @since 1.25
205 *
206 * @param int $level Error level raised
207 * @param string $message Error message
208 * @param string $file File that error was raised in
209 * @param int $line Line number error was raised at
210 * @param array $context Active symbol table point of error
211 * @param array $trace Backtrace at point of error (undocumented HHVM
212 * feature)
213 * @return bool Always returns false
214 */
215 public static function handleFatalError(
216 $level = null, $message = null, $file = null, $line = null,
217 $context = null, $trace = null
218 ) {
219 // Free reserved memory so that we have space to process OOM
220 // errors
221 self::$reservedMemory = null;
222
223 if ( $level === null ) {
224 // Called as a shutdown handler, get data from error_get_last()
225 if ( static::$handledFatalCallback ) {
226 // Already called once (probably as an error handler callback
227 // under HHVM) so don't log again.
228 return false;
229 }
230
231 $lastError = error_get_last();
232 if ( $lastError !== null ) {
233 $level = $lastError['type'];
234 $message = $lastError['message'];
235 $file = $lastError['file'];
236 $line = $lastError['line'];
237 } else {
238 $level = 0;
239 $message = '';
240 }
241 }
242
243 if ( !in_array( $level, self::$fatalErrorTypes ) ) {
244 // Only interested in fatal errors, others should have been
245 // handled by MWExceptionHandler::handleError
246 return false;
247 }
248
249 $msg = "[{exception_id}] PHP Fatal Error: {$message}";
250
251 // Look at message to see if this is a class not found failure
252 // HHVM: Class undefined: foo
253 // PHP5: Class 'foo' not found
254 if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
255 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
256 $msg = <<<TXT
257 {$msg}
258
259 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.
260
261 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.
262 TXT;
263 // @codingStandardsIgnoreEnd
264 }
265
266 // We can't just create an exception and log it as it is likely that
267 // the interpreter has unwound the stack already. If that is true the
268 // stacktrace we would get would be functionally empty. If however we
269 // have been called as an error handler callback *and* HHVM is in use
270 // we will have been provided with a useful stacktrace that we can
271 // log.
272 $trace = $trace ?: debug_backtrace();
273 $logger = LoggerFactory::getInstance( 'fatal' );
274 $logger->error( $msg, [
275 'exception' => [
276 'class' => 'ErrorException',
277 'message' => "PHP Fatal Error: {$message}",
278 'code' => $level,
279 'file' => $file,
280 'line' => $line,
281 'trace' => static::redactTrace( $trace ),
282 ],
283 'exception_id' => wfRandomString( 8 ),
284 ] );
285
286 // Remember call so we don't double process via HHVM's fatal
287 // notifications and the shutdown hook behavior
288 static::$handledFatalCallback = true;
289 return false;
290 }
291
292 /**
293 * Generate a string representation of an exception's stack trace
294 *
295 * Like Exception::getTraceAsString, but replaces argument values with
296 * argument type or class name.
297 *
298 * @param Exception|Throwable $e
299 * @return string
300 * @see prettyPrintTrace()
301 */
302 public static function getRedactedTraceAsString( $e ) {
303 return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
304 }
305
306 /**
307 * Generate a string representation of a stacktrace.
308 *
309 * @param array $trace
310 * @param string $pad Constant padding to add to each line of trace
311 * @return string
312 * @since 1.26
313 */
314 public static function prettyPrintTrace( array $trace, $pad = '' ) {
315 $text = '';
316
317 $level = 0;
318 foreach ( $trace as $level => $frame ) {
319 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
320 $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
321 } else {
322 // 'file' and 'line' are unset for calls via call_user_func
323 // (bug 55634) This matches behaviour of
324 // Exception::getTraceAsString to instead display "[internal
325 // function]".
326 $text .= "{$pad}#{$level} [internal function]: ";
327 }
328
329 if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
330 $text .= $frame['class'] . $frame['type'] . $frame['function'];
331 } elseif ( isset( $frame['function'] ) ) {
332 $text .= $frame['function'];
333 } else {
334 $text .= 'NO_FUNCTION_GIVEN';
335 }
336
337 if ( isset( $frame['args'] ) ) {
338 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
339 } else {
340 $text .= "()\n";
341 }
342 }
343
344 $level = $level + 1;
345 $text .= "{$pad}#{$level} {main}";
346
347 return $text;
348 }
349
350 /**
351 * Return a copy of an exception's backtrace as an array.
352 *
353 * Like Exception::getTrace, but replaces each element in each frame's
354 * argument array with the name of its class (if the element is an object)
355 * or its type (if the element is a PHP primitive).
356 *
357 * @since 1.22
358 * @param Exception|Throwable $e
359 * @return array
360 */
361 public static function getRedactedTrace( $e ) {
362 return static::redactTrace( $e->getTrace() );
363 }
364
365 /**
366 * Redact a stacktrace generated by Exception::getTrace(),
367 * debug_backtrace() or similar means. Replaces each element in each
368 * frame's argument array with the name of its class (if the element is an
369 * object) or its type (if the element is a PHP primitive).
370 *
371 * @since 1.26
372 * @param array $trace Stacktrace
373 * @return array Stacktrace with arugment values converted to data types
374 */
375 public static function redactTrace( array $trace ) {
376 return array_map( function ( $frame ) {
377 if ( isset( $frame['args'] ) ) {
378 $frame['args'] = array_map( function ( $arg ) {
379 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
380 }, $frame['args'] );
381 }
382 return $frame;
383 }, $trace );
384 }
385
386 /**
387 * Get the ID for this exception.
388 *
389 * The ID is saved so that one can match the one output to the user (when
390 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
391 *
392 * @since 1.22
393 * @deprecated since 1.27: Exception IDs are synonymous with request IDs.
394 * @param Exception|Throwable $e
395 * @return string
396 */
397 public static function getLogId( $e ) {
398 wfDeprecated( __METHOD__, '1.27' );
399 return WebRequest::getRequestId();
400 }
401
402 /**
403 * If the exception occurred in the course of responding to a request,
404 * returns the requested URL. Otherwise, returns false.
405 *
406 * @since 1.23
407 * @return string|false
408 */
409 public static function getURL() {
410 global $wgRequest;
411 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
412 return false;
413 }
414 return $wgRequest->getRequestURL();
415 }
416
417 /**
418 * Get a message formatting the exception message and its origin.
419 *
420 * @since 1.22
421 * @param Exception|Throwable $e
422 * @return string
423 */
424 public static function getLogMessage( $e ) {
425 $id = WebRequest::getRequestId();
426 $type = get_class( $e );
427 $file = $e->getFile();
428 $line = $e->getLine();
429 $message = $e->getMessage();
430 $url = self::getURL() ?: '[no req]';
431
432 return "[$id] $url $type from line $line of $file: $message";
433 }
434
435 /**
436 * @param Exception|Throwable $e
437 * @return string
438 */
439 public static function getPublicLogMessage( $e ) {
440 $reqId = WebRequest::getRequestId();
441 $type = get_class( $e );
442 return '[' . $reqId . '] '
443 . gmdate( 'Y-m-d H:i:s' ) . ': '
444 . 'Fatal exception of type "' . $type . '"';
445 }
446
447 /**
448 * Get a PSR-3 log event context from an Exception.
449 *
450 * Creates a structured array containing information about the provided
451 * exception that can be used to augment a log message sent to a PSR-3
452 * logger.
453 *
454 * @param Exception|Throwable $e
455 * @return array
456 */
457 public static function getLogContext( $e ) {
458 return [
459 'exception' => $e,
460 'exception_id' => WebRequest::getRequestId(),
461 ];
462 }
463
464 /**
465 * Get a structured representation of an Exception.
466 *
467 * Returns an array of structured data (class, message, code, file,
468 * backtrace) derived from the given exception. The backtrace information
469 * will be redacted as per getRedactedTraceAsArray().
470 *
471 * @param Exception|Throwable $e
472 * @return array
473 * @since 1.26
474 */
475 public static function getStructuredExceptionData( $e ) {
476 global $wgLogExceptionBacktrace;
477 $data = [
478 'id' => WebRequest::getRequestId(),
479 'type' => get_class( $e ),
480 'file' => $e->getFile(),
481 'line' => $e->getLine(),
482 'message' => $e->getMessage(),
483 'code' => $e->getCode(),
484 'url' => self::getURL() ?: null,
485 ];
486
487 if ( $e instanceof ErrorException &&
488 ( error_reporting() & $e->getSeverity() ) === 0
489 ) {
490 // Flag surpressed errors
491 $data['suppressed'] = true;
492 }
493
494 if ( $wgLogExceptionBacktrace ) {
495 $data['backtrace'] = self::getRedactedTrace( $e );
496 }
497
498 $previous = $e->getPrevious();
499 if ( $previous !== null ) {
500 $data['previous'] = self::getStructuredExceptionData( $previous );
501 }
502
503 return $data;
504 }
505
506 /**
507 * Serialize an Exception object to JSON.
508 *
509 * The JSON object will have keys 'id', 'file', 'line', 'message', and
510 * 'url'. These keys map to string values, with the exception of 'line',
511 * which is a number, and 'url', which may be either a string URL or or
512 * null if the exception did not occur in the context of serving a web
513 * request.
514 *
515 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
516 * key, mapped to the array return value of Exception::getTrace, but with
517 * each element in each frame's "args" array (if set) replaced with the
518 * argument's class name (if the argument is an object) or type name (if
519 * the argument is a PHP primitive).
520 *
521 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
522 * @code
523 * {
524 * "id": "c41fb419",
525 * "type": "MWException",
526 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
527 * "line": 704,
528 * "message": "Non-string key given",
529 * "url": "/wiki/Main_Page"
530 * }
531 * @endcode
532 *
533 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
534 * @code
535 * {
536 * "id": "dc457938",
537 * "type": "MWException",
538 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
539 * "line": 704,
540 * "message": "Non-string key given",
541 * "url": "/wiki/Main_Page",
542 * "backtrace": [{
543 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
544 * "line": 80,
545 * "function": "get",
546 * "class": "MessageCache",
547 * "type": "->",
548 * "args": ["array"]
549 * }]
550 * }
551 * @endcode
552 *
553 * @since 1.23
554 * @param Exception|Throwable $e
555 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
556 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
557 * @return string|false JSON string if successful; false upon failure
558 */
559 public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
560 $data = self::getStructuredExceptionData( $e );
561 return FormatJson::encode( $data, $pretty, $escaping );
562 }
563
564 /**
565 * Log an exception to the exception log (if enabled).
566 *
567 * This method must not assume the exception is an MWException,
568 * it is also used to handle PHP exceptions or exceptions from other libraries.
569 *
570 * @since 1.22
571 * @param Exception|Throwable $e
572 */
573 public static function logException( $e ) {
574 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
575 $logger = LoggerFactory::getInstance( 'exception' );
576 $logger->error(
577 self::getLogMessage( $e ),
578 self::getLogContext( $e )
579 );
580
581 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
582 if ( $json !== false ) {
583 $logger = LoggerFactory::getInstance( 'exception-json' );
584 $logger->error( $json, [ 'private' => true ] );
585 }
586
587 Hooks::run( 'LogException', [ $e, false ] );
588 }
589 }
590
591 /**
592 * Log an exception that wasn't thrown but made to wrap an error.
593 *
594 * @since 1.25
595 * @param ErrorException $e
596 * @param string $channel
597 */
598 protected static function logError( ErrorException $e, $channel ) {
599 // The set_error_handler callback is independent from error_reporting.
600 // Filter out unwanted errors manually (e.g. when
601 // MediaWiki\suppressWarnings is active).
602 $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
603 if ( !$suppressed ) {
604 $logger = LoggerFactory::getInstance( $channel );
605 $logger->error(
606 self::getLogMessage( $e ),
607 self::getLogContext( $e )
608 );
609 }
610
611 // Include all errors in the json log (surpressed errors will be flagged)
612 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
613 if ( $json !== false ) {
614 $logger = LoggerFactory::getInstance( "{$channel}-json" );
615 $logger->error( $json, [ 'private' => true ] );
616 }
617
618 Hooks::run( 'LogException', [ $e, $suppressed ] );
619 }
620 }