From 72d14770de505c1470ab18ce860be1714e5370f3 Mon Sep 17 00:00:00 2001 From: Michael Kaufmann Date: Fri, 22 Jul 2022 08:37:19 +0200 Subject: [PATCH] catch php errors to return valid JSON when invoking API, refs #1047 Signed-off-by: Michael Kaufmann --- api.php | 6 ++++++ lib/Froxlor/Api/Api.php | 14 ++++++++++++++ lib/Froxlor/Cli/RunApiCommand.php | 6 ++++++ 3 files changed, 26 insertions(+) diff --git a/api.php b/api.php index c4b02611..afa8a710 100644 --- a/api.php +++ b/api.php @@ -30,6 +30,12 @@ require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/lib/functions.php'; require __DIR__ . '/lib/tables.inc.php'; +// set error-handler +@set_error_handler([ + '\\Froxlor\\Api\\Api', + 'phpErrHandler' +]); + // Return response try { echo (new Api)->formatMiddleware(@file_get_contents('php://input'))->handle(); diff --git a/lib/Froxlor/Api/Api.php b/lib/Froxlor/Api/Api.php index e04affa1..404ef735 100644 --- a/lib/Froxlor/Api/Api.php +++ b/lib/Froxlor/Api/Api.php @@ -101,6 +101,20 @@ class Api return $apiObj->$method(); } + /** + * API PHP error handler to always return a valid JSON response + * + * @param mixed $errno + * @param mixed $errstr + * @param mixed $errfile + * @param mixed $errline + * @return never + */ + public static function phpErrHandler($errno, $errstr, $errfile, $errline) + { + throw new Exception('Internal PHP error: #' . $errno . ' ' . $errstr /* . ' in ' . $errfile . ':' . $errline */, 500); + } + private function stripcslashesDeep($value) { return is_array($value) ? array_map([$this, 'stripcslashesDeep'], $value) : stripcslashes($value); diff --git a/lib/Froxlor/Cli/RunApiCommand.php b/lib/Froxlor/Cli/RunApiCommand.php index d9afce69..8ed316fc 100644 --- a/lib/Froxlor/Cli/RunApiCommand.php +++ b/lib/Froxlor/Cli/RunApiCommand.php @@ -56,6 +56,12 @@ final class RunApiCommand extends CliCommand require Froxlor::getInstallDir() . '/lib/functions.php'; + // set error-handler + @set_error_handler([ + '\\Froxlor\\Api\\Api', + 'phpErrHandler' + ]); + if ($result == self::SUCCESS) { try { $loginname = $input->getArgument('user');