diff --git a/public/astronomical_conversions.php b/public/astronomical_conversions.php index 43ee0c5..a904527 100644 --- a/public/astronomical_conversions.php +++ b/public/astronomical_conversions.php @@ -15,8 +15,99 @@ function h(?string $value): string { return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); } + +function runPythonApi(string $action, array $args): array +{ + $scriptPath = __DIR__ . '/py/api.py'; + $pythonCandidates = PHP_OS_FAMILY === 'Windows' + ? ['python', 'py'] + : ['/usr/bin/python3', '/usr/bin/python', 'python3', 'python']; + + $escapedArguments = array_map('escapeshellarg', array_merge([$scriptPath, $action], $args)); + $lastError = 'Python konnte nicht gestartet werden.'; + + foreach ($pythonCandidates as $pythonBinary) { + $command = $pythonBinary . ' ' . implode(' ', $escapedArguments) . ' 2>&1'; + $output = []; + $resultCode = 0; + exec($command, $output, $resultCode); + + $joined = trim(implode("\n", $output)); + $decoded = json_decode($joined, true); + + if (is_array($decoded)) { + return [ + 'ok' => (bool) ($decoded['ok'] ?? false), + 'data' => $decoded, + 'raw' => $joined, + 'command' => $command, + ]; + } + + if ($joined !== '') { + $lastError = $joined; + } elseif ($resultCode !== 0) { + $lastError = 'Fehlercode ' . $resultCode . ' bei ' . $pythonBinary; + } + } + + return [ + 'ok' => false, + 'error' => $lastError, + ]; +} + +if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['ajax'] ?? '') === '1') { + header('Content-Type: application/json; charset=utf-8'); + + $kind = trim((string) ($_POST['kind'] ?? '')); + if ($kind === 'distance') { + $pythonResult = runPythonApi('astronomical_conversions', [ + 'distance', + trim((string) ($_POST['sourceUnit'] ?? '')), + trim((string) ($_POST['sourceValue'] ?? '')), + ]); + } elseif ($kind === 'redshift') { + $pythonResult = runPythonApi('astronomical_conversions', [ + 'redshift', + trim((string) ($_POST['z'] ?? '')), + trim((string) ($_POST['restNm'] ?? '')), + ]); + } elseif ($kind === 'time') { + $pythonResult = runPythonApi('astronomical_conversions', [ + 'time', + trim((string) ($_POST['sourceUnit'] ?? '')), + trim((string) ($_POST['sourceValue'] ?? '')), + trim((string) ($_POST['longitude'] ?? '')), + ]); + } else { + echo json_encode([ + 'ok' => false, + 'error' => 'Unbekannter Umrechnungsbereich.', + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + if (!$pythonResult['ok']) { + echo json_encode([ + 'ok' => false, + 'error' => (string) ($pythonResult['error'] ?? 'Python-Fehler'), + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + echo json_encode($pythonResult['data'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; +} ?> + +