From 07bcd18291af5d3dfed2c8d64c6319c175b58765 Mon Sep 17 00:00:00 2001 From: Lars Gebhardt-Kusche Date: Mon, 8 Dec 2025 01:37:28 +0100 Subject: [PATCH] up --- api/index.php | 13 ++ src/ApiKernel.php | 555 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 547 insertions(+), 21 deletions(-) create mode 100644 api/index.php diff --git a/api/index.php b/api/index.php new file mode 100644 index 0000000..ce3bed6 --- /dev/null +++ b/api/index.php @@ -0,0 +1,13 @@ +fail('Customer context missing', null, 500); $settings = $this->ensureSettingsTokens($customerId, $this->getCustomerSettings($customerId)); - $baseDir = dirname(__DIR__); + $content = $this->loadDownloadTemplate($type); if ($type === 'bridge') { - $path = $baseDir . '/download/emailtemplate_bridge.php'; - } elseif ($type === 'sender') { - $path = $baseDir . '/download/emailtemplate_sender.php'; + $content = $this->populateBridgeDownload($content, $settings); } else { - $this->fail('Unknown download type', $type, 404); - } - if (!is_file($path)) { - $this->fail('Datei nicht gefunden', basename($path), 404); - } - $content = (string)file_get_contents($path); - if ($type === 'bridge') { - $content = str_replace('REPLACE_WITH_SHARED_TOKEN', $settings['bridge_token'] ?? '', $content); - } else { - $apiBase = $this->defaultApiBase(); - $content = str_replace('REPLACE_WITH_SHARED_TOKEN', $settings['sender_token'] ?? '', $content); - $content = str_replace('REPLACE_WITH_TEMPLATE_API_TOKEN', $settings['external_api_token'] ?? '', $content); - if ($apiBase) { - $content = str_replace('https://api.emailtemplate.it/external/render', $apiBase, $content); - } + $content = $this->populateSenderDownload($content, $settings); } $this->respond([ 'ok' => true, - 'file_name' => basename($path), + 'file_name' => $type === 'bridge' ? 'emailtemplate_bridge.php' : 'emailtemplate_sender.php', 'content' => base64_encode($content), ]); } @@ -2292,6 +2276,535 @@ SQL; private function defaultApiBase(): string { $base = $this->conf['base_url'] ?? ''; - return $base ? rtrim($base, '/') . '/api.php' : '/api.php'; + if ($base === '' && !empty($_SERVER['HTTP_HOST'])) { + $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; + $base = $scheme . '://' . $_SERVER['HTTP_HOST']; + } + return $base ? rtrim($base, '/') : ''; + } + + private function loadDownloadTemplate(string $type): string + { + $map = [ + 'bridge' => 'emailtemplate_bridge.php', + 'sender' => 'emailtemplate_sender.php', + ]; + if (!isset($map[$type])) { + $this->fail('Unknown download type', $type, 404); + } + + $fileName = $map[$type]; + $candidates = [ + dirname(__DIR__) . '/download/' . $fileName, + __DIR__ . '/../download/' . $fileName, + dirname(__DIR__, 2) . '/download/' . $fileName, + ]; + foreach ($candidates as $candidate) { + if ($candidate && is_file($candidate)) { + $data = (string)file_get_contents($candidate); + if ($data !== '') { + return $data; + } + } + } + + return $this->defaultDownloadTemplate($type); + } + + private function defaultDownloadTemplate(string $type): string + { + if ($type === 'bridge') { + return $this->bridgeDownloadTemplate(); + } + if ($type === 'sender') { + return $this->senderDownloadTemplate(); + } + return ''; + } + + private function populateBridgeDownload(string $content, array $settings): string + { + $token = (string)($settings['bridge_token'] ?? ''); + $content = str_replace('REPLACE_WITH_SHARED_TOKEN', $token, $content); + + $tables = []; + if (!empty($settings['bridge_tables']) && is_array($settings['bridge_tables'])) { + $tables = array_values(array_filter(array_map('strval', $settings['bridge_tables']))); + } + $tablesExport = $this->exportPhpArray($tables); + $content = preg_replace( + "/'tables_allow'\\s*=>\\s*\\[\\s*\\],/", + "'tables_allow' => {$tablesExport},", + $content, + 1 + ); + + return $content; + } + + private function populateSenderDownload(string $content, array $settings): string + { + $content = str_replace('REPLACE_WITH_SHARED_TOKEN', (string)($settings['sender_token'] ?? ''), $content); + $content = str_replace('REPLACE_WITH_TEMPLATE_API_TOKEN', (string)($settings['external_api_token'] ?? ''), $content); + + $apiBase = $this->defaultApiBase(); + if ($apiBase !== '') { + $content = str_replace('https://api.emailtemplate.it/external/render', rtrim($apiBase, '/') . '/external/render', $content); + } + + return $content; + } + + private function exportPhpArray(array $values): string + { + if (empty($values)) { + return '[]'; + } + $escaped = array_map(function ($value) { + return "'" . str_replace(["\\", "'"], ["\\\\", "\\'"], $value) . "'"; + }, $values); + return '[' . implode(', ', $escaped) . ']'; + } + + private function bridgeDownloadTemplate(): string + { + return <<<'PHP' + getenv('EMAILTEMPLATE_BRIDGE_TOKEN') ?: 'REPLACE_WITH_SHARED_TOKEN', + 'db' => [ + 'dsn' => getenv('EMAILTEMPLATE_BRIDGE_DSN') ?: 'mysql:host=127.0.0.1;dbname=example;charset=utf8mb4', + 'user' => getenv('EMAILTEMPLATE_BRIDGE_DB_USER') ?: 'root', + 'pass' => getenv('EMAILTEMPLATE_BRIDGE_DB_PASS') ?: '', + 'options' => [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ], + ], + 'tables_allow' => [], // optional whitelist: ['customers', 'orders'] +]; + +$localOverride = __DIR__ . '/emailtemplate.bridge.conf.php'; +if (is_file($localOverride)) { + $override = include $localOverride; + if (is_array($override)) { + $bridgeConfig = array_replace_recursive($bridgeConfig, $override); + } +} + +function bridgeRespond($payload, int $status = 200): void +{ + http_response_code($status); + header('Content-Type: application/json; charset=utf-8'); + header('Cache-Control: no-store, max-age=0'); + echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; +} + +function bridgeRequireToken(array $config): void +{ + $expected = (string)($config['token'] ?? ''); + if ($expected === '') { + bridgeRespond(['ok' => false, 'error' => 'Bridge token not configured'], 500); + } + + $provided = null; + if (!empty($_SERVER['HTTP_AUTHORIZATION']) && stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0) { + $provided = trim(substr($_SERVER['HTTP_AUTHORIZATION'], 7)); + } elseif (!empty($_SERVER['HTTP_X_EMAILTEMPLATE_TOKEN'])) { + $provided = trim($_SERVER['HTTP_X_EMAILTEMPLATE_TOKEN']); + } elseif (isset($_GET['token'])) { + $provided = (string)$_GET['token']; + } elseif (isset($_POST['token'])) { + $provided = (string)$_POST['token']; + } + + if (!$provided || !hash_equals($expected, $provided)) { + bridgeRespond(['ok' => false, 'error' => 'Unauthorized'], 403); + } +} + +function bridgeDb(array $config): PDO +{ + static $pdo = null; + if ($pdo instanceof PDO) { + return $pdo; + } + + try { + $pdo = new PDO( + $config['db']['dsn'], + $config['db']['user'], + $config['db']['pass'], + $config['db']['options'] + ); + } catch (Throwable $e) { + bridgeRespond(['ok' => false, 'error' => 'DB connection failed', 'detail' => $e->getMessage()], 500); + } + + return $pdo; +} + +bridgeRequireToken($bridgeConfig); + +$action = strtolower((string)($_GET['action'] ?? $_POST['action'] ?? 'schema')); + +if ($action === 'ping') { + bridgeRespond(['ok' => true, 'time' => date(DATE_ATOM)]); +} + +if ($action !== 'schema') { + bridgeRespond(['ok' => false, 'error' => 'Unknown action'], 404); +} + +$pdo = bridgeDb($bridgeConfig); + +try { + $dbName = ''; + if (preg_match('/dbname=([^;]+)/i', $bridgeConfig['db']['dsn'], $m)) { + $dbName = $m[1]; + } + + $tablesStmt = $pdo->query('SHOW FULL TABLES'); + $tables = []; + $whitelist = []; + if (!empty($bridgeConfig['tables_allow']) && is_array($bridgeConfig['tables_allow'])) { + foreach ($bridgeConfig['tables_allow'] as $tbl) { + if (is_string($tbl) && $tbl !== '') { + $whitelist[strtolower($tbl)] = true; + } + } + } + while ($row = $tablesStmt->fetch(PDO::FETCH_NUM)) { + $tableName = $row[0]; + if ($tableName === null) { + continue; + } + if ($whitelist && empty($whitelist[strtolower($tableName)])) { + continue; + } + + $columnsStmt = $pdo->prepare( + 'SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table + ORDER BY ORDINAL_POSITION' + ); + $columnsStmt->execute([ + ':schema' => $dbName ?: $pdo->query('SELECT DATABASE()')->fetchColumn(), + ':table' => $tableName, + ]); + + $columns = []; + foreach ($columnsStmt as $col) { + $columns[] = [ + 'name' => $col['COLUMN_NAME'], + 'type' => $col['DATA_TYPE'], + 'nullable' => ($col['IS_NULLABLE'] === 'YES'), + 'default' => $col['COLUMN_DEFAULT'], + 'key' => $col['COLUMN_KEY'], + 'extra' => $col['EXTRA'], + 'placeholder'=> strtoupper($tableName) . '__' . strtoupper($col['COLUMN_NAME']), + ]; + } + + $tables[] = [ + 'name' => $tableName, + 'columns' => $columns, + ]; + } + + bridgeRespond([ + 'ok' => true, + 'tables' => $tables, + 'fetched' => date(DATE_ATOM), + ]); +} catch (Throwable $e) { + bridgeRespond(['ok' => false, 'error' => 'Schema fetch failed', 'detail' => $e->getMessage()], 500); +} +PHP; + } + + private function senderDownloadTemplate(): string + { + return <<<'PHP' + getenv('EMAILTEMPLATE_SENDER_TOKEN') ?: 'REPLACE_WITH_SHARED_TOKEN', + 'template_api' => [ + 'base_url' => getenv('EMAILTEMPLATE_API_BASE') ?: 'https://api.emailtemplate.it/external/render', + 'token' => getenv('EMAILTEMPLATE_API_TOKEN') ?: 'REPLACE_WITH_TEMPLATE_API_TOKEN', + 'timeout' => 15, + ], + 'db' => [ + 'dsn' => getenv('EMAILTEMPLATE_LOCAL_DSN') ?: 'mysql:host=127.0.0.1;dbname=example;charset=utf8mb4', + 'user' => getenv('EMAILTEMPLATE_LOCAL_DB_USER') ?: 'root', + 'pass' => getenv('EMAILTEMPLATE_LOCAL_DB_PASS') ?: '', + 'options' => [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ], + 'enabled' => true, + ], + 'mail' => [ + 'from_email' => 'no-reply@example.com', + 'from_name' => 'EmailTemplate Sender', + 'transport' => 'mail', // aktuell nur mail() + ], +]; + +$localSenderOverride = __DIR__ . '/emailtemplate.sender.conf.php'; +if (is_file($localSenderOverride)) { + $override = include $localSenderOverride; + if (is_array($override)) { + $senderConfig = array_replace_recursive($senderConfig, $override); + } +} + +function senderRespond($payload, int $status = 200): void +{ + http_response_code($status); + header('Content-Type: application/json; charset=utf-8'); + header('Cache-Control: no-store, max-age=0'); + echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; +} + +function senderRequireToken(array $config): void +{ + $expected = (string)($config['token'] ?? ''); + if ($expected === '') { + senderRespond(['ok' => false, 'error' => 'Sender token not configured'], 500); + } + + $provided = null; + if (!empty($_SERVER['HTTP_AUTHORIZATION']) && stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0) { + $provided = trim(substr($_SERVER['HTTP_AUTHORIZATION'], 7)); + } elseif (!empty($_SERVER['HTTP_X_EMAILTEMPLATE_TOKEN'])) { + $provided = trim($_SERVER['HTTP_X_EMAILTEMPLATE_TOKEN']); + } elseif (isset($_POST['token'])) { + $provided = (string)$_POST['token']; + } + + if (!$provided || !hash_equals($expected, $provided)) { + senderRespond(['ok' => false, 'error' => 'Unauthorized'], 403); + } +} + +function senderInput(): array +{ + $raw = file_get_contents('php://input'); + if ($raw !== false && trim($raw) !== '') { + $decoded = json_decode($raw, true); + if (is_array($decoded)) { + return $decoded; + } + } + + if (!empty($_POST)) { + return $_POST; + } + + return []; +} + +function senderDb(array $config): ?PDO +{ + if (empty($config['db']['enabled'])) { + return null; + } + + static $pdo = null; + if ($pdo instanceof PDO) { + return $pdo; + } + + try { + $pdo = new PDO( + $config['db']['dsn'], + $config['db']['user'], + $config['db']['pass'], + $config['db']['options'] + ); + } catch (Throwable $e) { + senderRespond(['ok' => false, 'error' => 'DB connection failed', 'detail' => $e->getMessage()], 500); + } + + return $pdo; +} + +function resolvePlaceholderValue($definition, ?PDO $pdo) +{ + if (is_scalar($definition)) { + return $definition; + } + if (!is_array($definition)) { + return null; + } + + if (array_key_exists('value', $definition)) { + return $definition['value']; + } + + if (($definition['source'] ?? '') === 'db') { + if (!$pdo) { + throw new RuntimeException('Database access disabled'); + } + $table = $definition['table'] ?? null; + $column = $definition['column'] ?? null; + $where = $definition['where'] ?? []; + if (!$table || !$column || !is_array($where) || !$where) { + throw new InvalidArgumentException('Invalid DB placeholder definition'); + } + $conditions = []; + $params = []; + foreach ($where as $key => $value) { + $param = ':w_' . preg_replace('/[^a-z0-9_]/i', '_', $key); + $conditions[] = sprintf('`%s` = %s', str_replace('`', '', $key), $param); + $params[$param] = $value; + } + $sql = sprintf( + 'SELECT `%s` FROM `%s` WHERE %s LIMIT 1', + str_replace('`', '', $column), + str_replace('`', '', $table), + implode(' AND ', $conditions) + ); + $stmt = $pdo->prepare($sql); + foreach ($params as $param => $value) { + $stmt->bindValue($param, $value); + } + $stmt->execute(); + return $stmt->fetchColumn(); + } + + return null; +} + +function fetchTemplateHtml(array $config, array $payload): array +{ + $apiUrl = $config['template_api']['base_url']; + $apiToken = $config['template_api']['token']; + if (!$apiUrl || !$apiToken) { + senderRespond(['ok' => false, 'error' => 'Template API not configured'], 500); + } + + $body = $payload; + $body['token'] = $apiToken; + + $context = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'header' => "Content-Type: application/json\r\n", + 'timeout' => (int)($config['template_api']['timeout'] ?? 15), + 'content' => json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + ], + ]); + + $response = @file_get_contents($apiUrl, false, $context); + if ($response === false) { + senderRespond(['ok' => false, 'error' => 'Template API unreachable'], 502); + } + + $decoded = json_decode($response, true); + if (!is_array($decoded) || !empty($decoded['ok']) === false) { + senderRespond(['ok' => false, 'error' => 'Template API error', 'detail' => $decoded], 502); + } + + return $decoded; +} + +function sendMail(array $config, string $html, string $subject, array $payload): void +{ + $headers = []; + if (!empty($config['mail']['from_email'])) { + $fromName = $config['mail']['from_name'] ?? ''; + if ($fromName !== '') { + $headers[] = 'From: ' . sprintf('"%s" <%s>', addslashes($fromName), $config['mail']['from_email']); + } else { + $headers[] = 'From: ' . $config['mail']['from_email']; + } + } + $headers[] = 'Content-Type: text/html; charset=utf-8'; + + $to = $payload['to'] ?? ''; + if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) { + senderRespond(['ok' => false, 'error' => 'Invalid recipient'], 422); + } + + if (!mail($to, $subject, $html, implode("\r\n", $headers))) { + senderRespond(['ok' => false, 'error' => 'mail() transport failed'], 500); + } +} + +senderRequireToken($senderConfig); +$input = senderInput(); +$pdo = senderDb($senderConfig); + +try { + $placeholders = $input['placeholders'] ?? []; + if (!is_array($placeholders)) { + senderRespond(['ok' => false, 'error' => 'Invalid placeholders'], 422); + } + $resolved = []; + foreach ($placeholders as $key => $definition) { + $resolved[$key] = resolvePlaceholderValue($definition, $pdo); + } + $input['placeholders'] = $resolved; + + $template = fetchTemplateHtml($senderConfig, $input); + if (empty($template['ok']) || empty($template['html'])) { + senderRespond(['ok' => false, 'error' => 'Template API returned no HTML'], 502); + } + + $subject = $input['subject'] ?? ($template['subject'] ?? 'EmailTemplate'); + sendMail($senderConfig, $template['html'], $subject, $input); + + senderRespond(['ok' => true]); +} catch (Throwable $e) { + senderRespond(['ok' => false, 'error' => 'Sender failure', 'detail' => $e->getMessage()], 500); +} +PHP; } }