3 declare(strict_types
=1);
8 use Fig\Http\Message\StatusCodeInterface
;
9 use Laminas\HttpHandlerRunner\Emitter\SapiEmitter
;
10 use PhpMyAdmin\Exceptions\ExitException
;
11 use PhpMyAdmin\Http\Factory\ResponseFactory
;
15 use function array_splice
;
18 use function error_reporting
;
19 use function htmlspecialchars
;
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
;
30 use const E_RECOVERABLE_ERROR
;
32 use const E_USER_DEPRECATED
;
33 use const E_USER_ERROR
;
34 use const E_USER_NOTICE
;
35 use const E_USER_WARNING
;
43 public static self|
null $instance = null;
46 * holds errors to be displayed or reported later ...
50 protected array $errors = [];
53 * Hide location of errors
55 protected bool $hideLocation = false;
58 * Initial error reporting state
60 protected int $errorReporting = 0;
62 public function __construct()
64 if (! Util
::isErrorReportingAvailable()) {
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;
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) {
94 * We don't want to store all errors here as it would
95 * explode user session.
97 if (count($_SESSION['errors']) >= 10) {
100 __('Too many error messages, some are not displayed.'),
104 $_SESSION['errors'][$error->getHash()] = $error;
108 if ($error->isDisplayed()) {
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
133 public function getErrors(bool $check = true): array
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
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);
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
187 * @throws ErrorException
189 public function handleError(
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();
205 isset($config->settings
['environment'])
206 && $config->settings
['environment'] === 'development'
209 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
214 $this->errorReporting
!= 0 &&
215 ($errno & (E_USER_WARNING | E_USER_ERROR | E_USER_NOTICE | E_USER_DEPRECATED
)) == 0
219 } elseif (($errno & (E_USER_WARNING | E_USER_ERROR | E_USER_NOTICE | E_USER_DEPRECATED
)) == 0) {
223 $this->addError($errstr, $errno, $errfile, $errline);
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';
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,
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(
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()) {
286 case E_COMPILE_WARNING
:
287 case E_RECOVERABLE_ERROR
:
288 /* Avoid rendering BB code in PHP errors */
289 $error->setBBCode(false);
294 case E_USER_DEPRECATED
:
295 // just collect the error
296 // display is called from outside
301 case E_COMPILE_ERROR
:
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>",
319 $error->getDisplay(),
322 (new SapiEmitter())->emit($response);
324 if (defined('TESTSUITE')) {
325 throw new ExitException();
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
345 foreach ($this->getErrors() as $error) {
346 if (! $error->isUserError() ||
$error->isDisplayed()) {
350 $retval .= $error->getDisplay();
357 * renders errors not displayed
359 public function getDispErrors(): string
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()) {
370 $retval .= $error->getDisplay();
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"';
388 $retval .= Url
::getHiddenFields([
389 'exception_type' => 'php',
390 'send_error_report' => '1',
391 'server' => $GLOBALS['server'],
393 $retval .= '<input type="submit" value="'
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')
402 if ($config->settings
['SendErrorReports'] === 'ask') {
403 // add ignore buttons
404 $retval .= '<input type="submit" value="'
406 . '" id="pma_ignore_errors_bottom" class="btn btn-secondary float-end">';
409 $retval .= '<input type="submit" value="'
411 . '" id="pma_ignore_all_errors_bottom" class="btn btn-secondary float-end">';
412 $retval .= '</form>';
419 * look in session for saved errors
421 protected function checkSavedErrors(): void
423 if (! isset($_SESSION['errors'])) {
427 // restore saved errors
428 foreach ($_SESSION['errors'] as $hash => $error) {
429 if (! ($error instanceof Error
) ||
isset($this->errors
[$hash])) {
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
461 if ($this->countErrors() !== 0) {
462 foreach ($this->getErrors() as $error) {
463 if (! $error->isUserError()) {
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.
549 // Delete all the prev_errors in session & store new prev_errors in session
550 $this->savePreviousErrors();
551 $response = ResponseRenderer
::getInstance();
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');
559 // send the error reports asynchronously & without asking user
560 $jsCode .= '$("#pma_report_errors_form").submit();'
561 . 'window.ajaxShowMessage(
562 window.Messages.phpErrorsBeingSubmitted, false
564 // js code to appropriate focusing,
565 $jsCode .= '$("html, body").animate({
566 scrollTop:$(document).height()
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()
577 . '$("#pma_ignore_all_errors_popup").on("click",
579 window.ignorePhpErrors(false)
581 . '$("#pma_ignore_errors_bottom").on("click", function(e) {
583 window.ignorePhpErrors()
585 . '$("#pma_ignore_all_errors_bottom").on("click",
588 window.ignorePhpErrors(false)
590 . '$("html, body").animate({
591 scrollTop:$(document).height()
596 // The errors are already sent from the response.
597 // Just focus on errors division upon load event.
598 $response->getFooterScripts()->addCode($jsCode);