Translated using Weblate (Russian)
[phpmyadmin.git] / src / ErrorHandler.php
blob6c0d4c436893951901ee0bcf94423f8191992cbe
1 <?php
3 declare(strict_types=1);
5 namespace PhpMyAdmin;
7 use ErrorException;
8 use Fig\Http\Message\StatusCodeInterface;
9 use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
10 use PhpMyAdmin\Exceptions\ExitException;
11 use PhpMyAdmin\Http\Factory\ResponseFactory;
12 use Throwable;
14 use function __;
15 use function array_splice;
16 use function count;
17 use function defined;
18 use function error_reporting;
19 use function htmlspecialchars;
20 use function sprintf;
22 use const E_COMPILE_ERROR;
23 use const E_COMPILE_WARNING;
24 use const E_CORE_ERROR;
25 use const E_CORE_WARNING;
26 use const E_DEPRECATED;
27 use const E_ERROR;
28 use const E_NOTICE;
29 use const E_PARSE;
30 use const E_RECOVERABLE_ERROR;
31 use const E_STRICT;
32 use const E_USER_DEPRECATED;
33 use const E_USER_ERROR;
34 use const E_USER_NOTICE;
35 use const E_USER_WARNING;
36 use const E_WARNING;
38 /**
39 * handling errors
41 class ErrorHandler
43 public static self|null $instance = null;
45 /**
46 * holds errors to be displayed or reported later ...
48 * @var Error[]
50 protected array $errors = [];
52 /**
53 * Hide location of errors
55 protected bool $hideLocation = false;
57 /**
58 * Initial error reporting state
60 protected int $errorReporting = 0;
62 public function __construct()
64 if (! Util::isErrorReportingAvailable()) {
65 return;
68 $this->errorReporting = error_reporting();
71 public static function getInstance(): self
73 if (self::$instance === null) {
74 self::$instance = new self();
77 return self::$instance;
80 /**
81 * Destructor
83 * stores errors in session
85 public function __destruct()
87 if (! isset($_SESSION['errors'])) {
88 $_SESSION['errors'] = [];
91 // remember only not displayed errors
92 foreach ($this->errors as $key => $error) {
93 /**
94 * We don't want to store all errors here as it would
95 * explode user session.
97 if (count($_SESSION['errors']) >= 10) {
98 $error = new Error(
100 __('Too many error messages, some are not displayed.'),
101 __FILE__,
102 __LINE__,
104 $_SESSION['errors'][$error->getHash()] = $error;
105 break;
108 if ($error->isDisplayed()) {
109 continue;
112 $_SESSION['errors'][$key] = $error;
117 * Toggles location hiding
119 * @param bool $hide Whether to hide
121 public function setHideLocation(bool $hide): void
123 $this->hideLocation = $hide;
127 * returns array with all errors
129 * @param bool $check Whether to check for session errors
131 * @return Error[]
133 public function getErrors(bool $check = true): array
135 if ($check) {
136 $this->checkSavedErrors();
139 return $this->errors;
143 * returns the errors occurred in the current run only.
144 * Does not include the errors saved in the SESSION
146 * @return Error[]
148 public function getCurrentErrors(): array
150 return $this->errors;
154 * Pops recent errors from the storage
156 * @param int $count Old error count (amount of errors to splice)
158 * @return Error[] The non spliced elements (total-$count)
160 public function sliceErrors(int $count): array
162 // store the errors before any operation, example number of items: 10
163 $errors = $this->getErrors(false);
165 // before array_splice $this->errors has 10 elements
166 // cut out $count items out, let's say $count = 9
167 // $errors will now contain 10 - 9 = 1 elements
168 // $this->errors will contain the 9 elements left
169 $this->errors = array_splice($errors, 0, $count);
171 return $errors;
175 * Error handler - called when errors are triggered/occurred
177 * This calls the addError() function, escaping the error string
178 * Ignores the errors wherever Error Control Operator (@) is used.
180 * @param int $errno error number
181 * @param string $errstr error string
182 * @param string $errfile error file
183 * @param int $errline error line
185 * @return false
187 * @throws ErrorException
189 public function handleError(
190 int $errno,
191 string $errstr,
192 string $errfile,
193 int $errline,
194 ): bool {
195 if (Util::isErrorReportingAvailable()) {
197 * Check if Error Control Operator (@) was used, but still show
198 * user errors even in this case.
199 * See: https://github.com/phpmyadmin/phpmyadmin/issues/16729
201 $isSilenced = (error_reporting() & $errno) === 0;
203 $config = Config::getInstance();
204 if (
205 isset($config->settings['environment'])
206 && $config->settings['environment'] === 'development'
207 && ! $isSilenced
209 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
212 if (
213 $isSilenced &&
214 $this->errorReporting != 0 &&
215 ($errno & (E_USER_WARNING | E_USER_ERROR | E_USER_NOTICE | E_USER_DEPRECATED)) == 0
217 return false;
219 } elseif (($errno & (E_USER_WARNING | E_USER_ERROR | E_USER_NOTICE | E_USER_DEPRECATED)) == 0) {
220 return false;
223 $this->addError($errstr, $errno, $errfile, $errline);
225 return false;
229 * Hides exception if it's not in the development environment.
231 public function handleException(Throwable $exception): void
233 $this->hideLocation = Config::getInstance()->get('environment') !== 'development';
234 $this->addError(
235 $exception::class . ': ' . $exception->getMessage(),
236 (int) $exception->getCode(),
237 $exception->getFile(),
238 $exception->getLine(),
243 * Add an error; can also be called directly (with or without escaping)
245 * The following error types cannot be handled with a user defined function:
246 * E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR,
247 * E_COMPILE_WARNING,
248 * and most of E_STRICT raised in the file where set_error_handler() is called.
250 * Do not use the context parameter as we want to avoid storing the
251 * complete $GLOBALS inside $_SESSION['errors']
253 * @param string $errstr error string
254 * @param int $errno error number
255 * @param string $errfile error file
256 * @param int $errline error line
257 * @param bool $escape whether to escape the error string
259 public function addError(
260 string $errstr,
261 int $errno,
262 string $errfile,
263 int $errline,
264 bool $escape = true,
265 ): void {
266 if ($escape) {
267 $errstr = htmlspecialchars($errstr);
270 // create error object
271 $error = new Error($errno, $errstr, $errfile, $errline);
272 $error->setHideLocation($this->hideLocation);
274 // Deprecation errors will be shown in development environment, as they will have a different number.
275 if ($error->getErrorNumber() !== E_DEPRECATED) {
276 // do not repeat errors
277 $this->errors[$error->getHash()] = $error;
280 switch ($error->getErrorNumber()) {
281 case E_STRICT:
282 case E_DEPRECATED:
283 case E_NOTICE:
284 case E_WARNING:
285 case E_CORE_WARNING:
286 case E_COMPILE_WARNING:
287 case E_RECOVERABLE_ERROR:
288 /* Avoid rendering BB code in PHP errors */
289 $error->setBBCode(false);
290 break;
291 case E_USER_NOTICE:
292 case E_USER_WARNING:
293 case E_USER_ERROR:
294 case E_USER_DEPRECATED:
295 // just collect the error
296 // display is called from outside
297 break;
298 case E_ERROR:
299 case E_PARSE:
300 case E_CORE_ERROR:
301 case E_COMPILE_ERROR:
302 default:
303 // FATAL error, display it and exit
304 $this->dispFatalError($error);
309 * display fatal error and exit
311 * @param Error $error the error
313 protected function dispFatalError(Error $error): never
315 $response = ResponseFactory::create()->createResponse(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
316 $response->getBody()->write(sprintf(
317 "<!DOCTYPE html>\n<html lang=\"en\">\n<head><title>%s</title></head>\n<body>\n%s\n</body>\n</html>",
318 $error->getTitle(),
319 $error->getDisplay(),
322 (new SapiEmitter())->emit($response);
324 if (defined('TESTSUITE')) {
325 throw new ExitException();
328 exit;
332 * Displays user errors not displayed
334 public function dispUserErrors(): void
336 echo $this->getDispUserErrors();
340 * Renders user errors not displayed
342 public function getDispUserErrors(): string
344 $retval = '';
345 foreach ($this->getErrors() as $error) {
346 if (! $error->isUserError() || $error->isDisplayed()) {
347 continue;
350 $retval .= $error->getDisplay();
353 return $retval;
357 * renders errors not displayed
359 public function getDispErrors(): string
361 $retval = '';
362 // display errors if SendErrorReports is set to 'ask'.
363 $config = Config::getInstance();
364 if ($config->settings['SendErrorReports'] !== 'never') {
365 foreach ($this->getErrors() as $error) {
366 if ($error->isDisplayed()) {
367 continue;
370 $retval .= $error->getDisplay();
372 } else {
373 $retval .= $this->getDispUserErrors();
376 // if preference is not 'never' and
377 // there are 'actual' errors to be reported
378 if ($config->settings['SendErrorReports'] !== 'never' && $this->countErrors() !== $this->countUserErrors()) {
379 // add report button.
380 $retval .= '<form method="post" action="' . Url::getFromRoute('/error-report')
381 . '" id="pma_report_errors_form"';
382 if ($config->settings['SendErrorReports'] === 'always') {
383 // in case of 'always', generate 'invisible' form.
384 $retval .= ' class="hide"';
387 $retval .= '>';
388 $retval .= Url::getHiddenFields([
389 'exception_type' => 'php',
390 'send_error_report' => '1',
391 'server' => $GLOBALS['server'],
393 $retval .= '<input type="submit" value="'
394 . __('Report')
395 . '" id="pma_report_errors" class="btn btn-primary float-end">'
396 . '<input type="checkbox" name="always_send"'
397 . ' id="errorReportAlwaysSendCheckbox" value="true">'
398 . '<label for="errorReportAlwaysSendCheckbox">'
399 . __('Automatically send report next time')
400 . '</label>';
402 if ($config->settings['SendErrorReports'] === 'ask') {
403 // add ignore buttons
404 $retval .= '<input type="submit" value="'
405 . __('Ignore')
406 . '" id="pma_ignore_errors_bottom" class="btn btn-secondary float-end">';
409 $retval .= '<input type="submit" value="'
410 . __('Ignore All')
411 . '" id="pma_ignore_all_errors_bottom" class="btn btn-secondary float-end">';
412 $retval .= '</form>';
415 return $retval;
419 * look in session for saved errors
421 protected function checkSavedErrors(): void
423 if (! isset($_SESSION['errors'])) {
424 return;
427 // restore saved errors
428 foreach ($_SESSION['errors'] as $hash => $error) {
429 if (! ($error instanceof Error) || isset($this->errors[$hash])) {
430 continue;
433 $this->errors[$hash] = $error;
436 // delete stored errors
437 $_SESSION['errors'] = [];
438 unset($_SESSION['errors']);
442 * return count of errors
444 * @param bool $check Whether to check for session errors
446 * @return int number of errors occurred
448 public function countErrors(bool $check = true): int
450 return count($this->getErrors($check));
454 * return count of user errors
456 * @return int number of user errors occurred
458 public function countUserErrors(): int
460 $count = 0;
461 if ($this->countErrors() !== 0) {
462 foreach ($this->getErrors() as $error) {
463 if (! $error->isUserError()) {
464 continue;
467 $count++;
471 return $count;
475 * whether use errors occurred or not
477 public function hasUserErrors(): bool
479 return (bool) $this->countUserErrors();
483 * whether errors occurred or not
485 public function hasErrors(): bool
487 return (bool) $this->countErrors();
491 * number of errors to be displayed
493 * @return int number of errors to be displayed
495 public function countDisplayErrors(): int
497 if (Config::getInstance()->settings['SendErrorReports'] !== 'never') {
498 return $this->countErrors();
501 return $this->countUserErrors();
505 * whether there are errors to display or not
507 public function hasDisplayErrors(): bool
509 return (bool) $this->countDisplayErrors();
513 * Deletes previously stored errors in SESSION.
514 * Saves current errors in session as previous errors.
515 * Required to save current errors in case 'ask'
517 public function savePreviousErrors(): void
519 unset($_SESSION['prev_errors']);
520 $_SESSION['prev_errors'] = $this->getCurrentErrors();
524 * Function to check if there are any errors to be prompted.
525 * Needed because user warnings raised are
526 * also collected by global error handler.
527 * This distinguishes between the actual errors
528 * and user errors raised to warn user.
530 public function hasErrorsForPrompt(): bool
532 return Config::getInstance()->settings['SendErrorReports'] !== 'never'
533 && $this->countErrors() !== $this->countUserErrors();
537 * Function to report all the collected php errors.
538 * Must be called at the end of each script
539 * by the {@see getInstance()} only.
541 public function reportErrors(): void
543 // if there're no actual errors,
544 if (! $this->hasErrors() || $this->countErrors() === $this->countUserErrors()) {
545 // then simply return.
546 return;
549 // Delete all the prev_errors in session & store new prev_errors in session
550 $this->savePreviousErrors();
551 $response = ResponseRenderer::getInstance();
552 $jsCode = '';
553 $config = Config::getInstance();
554 if ($config->settings['SendErrorReports'] === 'always') {
555 if ($response->isAjax()) {
556 // set flag for automatic report submission.
557 $response->addJSON('sendErrorAlways', '1');
558 } else {
559 // send the error reports asynchronously & without asking user
560 $jsCode .= '$("#pma_report_errors_form").submit();'
561 . 'window.ajaxShowMessage(
562 window.Messages.phpErrorsBeingSubmitted, false
563 );';
564 // js code to appropriate focusing,
565 $jsCode .= '$("html, body").animate({
566 scrollTop:$(document).height()
567 }, "slow");';
569 } elseif ($config->settings['SendErrorReports'] === 'ask') {
570 //ask user whether to submit errors or not.
571 if (! $response->isAjax()) {
572 // js code to show appropriate msgs, event binding & focusing.
573 $jsCode = 'window.ajaxShowMessage(window.Messages.phpErrorsFound);'
574 . '$("#pma_ignore_errors_popup").on("click", function() {
575 window.ignorePhpErrors()
576 });'
577 . '$("#pma_ignore_all_errors_popup").on("click",
578 function() {
579 window.ignorePhpErrors(false)
580 });'
581 . '$("#pma_ignore_errors_bottom").on("click", function(e) {
582 e.preventDefault();
583 window.ignorePhpErrors()
584 });'
585 . '$("#pma_ignore_all_errors_bottom").on("click",
586 function(e) {
587 e.preventDefault();
588 window.ignorePhpErrors(false)
589 });'
590 . '$("html, body").animate({
591 scrollTop:$(document).height()
592 }, "slow");';
596 // The errors are already sent from the response.
597 // Just focus on errors division upon load event.
598 $response->getFooterScripts()->addCode($jsCode);