diff --git a/README.md b/README.md index 77c7951..9ca00f3 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,45 @@ -# emailtemplate +# Mailadmin – Email Template System (R17 modular) +Stand: 2025-08-31 +## Struktur +mailadmin/ + inc/ + config.example.php # Deine echte config.php kommt hierhin (NICHT in public/) + public/ + index.php # Admin UI (helles Design) + api.php # JSON API (Dual-DB + Prefix) + tools/ + config-doctor.php # Prüft inc/config.php + db-doctor.php # Prüft DB-Verbindung + assets/ + css/toast.css + js/ + toast.js + app.js # entry (type=module) + api.js # API wrapper + ui-tabs.js # Tabs + ui-list.js # Liste + Vorschau + Löschen + Editor öffnen + ui-create.js # „Neu …“ dialog + ui-editor.js # Editor-Dialog + Handshake + editor/ + editor-core.php # LÄDT NUR LOKAL (kein CDN) + bridge-core.js + config.js # Bibliothek in Block-Leiste +## Vendor (lokal bereitstellen) +Lege die GrapesJS-Dateien lokal ab (kein CDN): +- mailadmin/public/vendor/grapesjs/grapes.min.css +- mailadmin/public/vendor/grapesjs/grapes.min.js +- mailadmin/public/vendor/grapesjs-preset-newsletter/grapesjs-preset-newsletter.min.js -## Getting started +## Datenbank +Nutze `schema.sql` (inkl. *NULL‑fähiger* Fremdschlüssel & ON DELETE SET NULL). +Prefix standardmäßig: `emailtemplate_`. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## Schnellstart +1) `mailadmin/inc/config.php` anlegen (siehe `config.example.php`). +2) `schema.sql` in deiner Templates-Datenbank ausführen. +3) Vendor-Dateien in `public/vendor/...` kopieren. +4) `public/tools/config-doctor.php` & `public/api.php?action=health` prüfen. +5) `public/index.php` öffnen → „Neu …“, „Vorschau“, „Im E‑Mail‑Editor öffnen“ etc. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.int.kusche.berlin/emailtemplate/emailtemplate.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.int.kusche.berlin/emailtemplate/emailtemplate/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..6aba98d --- /dev/null +++ b/README.txt @@ -0,0 +1 @@ +This archive contains the R17 modular Email Template System. Fill inc/config.php and vendor libs. \ No newline at end of file diff --git a/STATE.yaml b/STATE.yaml new file mode 100644 index 0000000..5333cb6 --- /dev/null +++ b/STATE.yaml @@ -0,0 +1,47 @@ +state_version: 1 +project: emailtemplate-suite +snapshot_label: "stand-2025-09-04" +editor: + bridge_core: "bridge-core.js" + grapesjs: "local vendor, no CDN" + blocks: + categories: ["Bausteine","Bibliothek","Bibliothek: Sections","Bibliothek: Blöcke","Default(last, closed)"] + features: + - "Snippets by value (HTML)" + - "Blocks/Sections als Referenzen (data-ref-*)" + - "Quelltext-Button (custom) aktiv" + - "Reload-Bibliothek-Button (Snippets) aktiv" + - "Light UI" +api: + file: "public/api.php" + features: + - "CRUD: templates, sections, blocks, snippets" + - "Items: template_items, section_items (sync)" + - "render: template|section ({{children}})" + - "health, debug=db" + db_profiles: + templates: true + project: optional + table_prefix: "emailtemplate_" +db: + schema_file: "schema.sql" + tables: + - emailtemplate_templates + - emailtemplate_sections + - emailtemplate_blocks + - emailtemplate_snippets + - emailtemplate_template_items + - emailtemplate_section_items +ui: + files: ["public/index.php","public/app.js","public/ui-list.js","public/ui-create.js","public/ui-editor.js"] + vendor: ["public/vendor/grapesjs/","public/vendor/grapesjs-preset-newsletter/"] +tools: + doctor: "public/tools/db-doctor.php" +compat_signature: + api: "ETS-API-2025-09-04" + bridge_core: "ETS-BRIDGE-2025-09-04" +notes: + - "DocumentRoot zeigt auf /public" + - "inc/config.php liegt außerhalb des Webroots" + - "kein Tailwind-CDN in Prod" + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..82f3e80 --- /dev/null +++ b/composer.json @@ -0,0 +1,6 @@ +{ + "name": "ssh-w020abd8/staging", + "require": { + "tijsverkoyen/css-to-inline-styles": "^2.3" + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..7564226 --- /dev/null +++ b/composer.lock @@ -0,0 +1,139 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "ce66bd5061d136b6edd6dea47ae9354d", + "packages": [ + { + "name": "symfony/css-selector", + "version": "v7.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/css-selector.git", + "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/601a5ce9aaad7bf10797e3663faefce9e26c24e2", + "reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\CssSelector\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Jean-François Simon", + "email": "jeanfrancois.simon@sensiolabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Converts CSS selectors to XPath expressions", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/css-selector/tree/v7.3.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:21:43+00:00" + }, + { + "name": "tijsverkoyen/css-to-inline-styles", + "version": "v2.3.0", + "source": { + "type": "git", + "url": "https://github.com/tijsverkoyen/CssToInlineStyles.git", + "reference": "0d72ac1c00084279c1816675284073c5a337c20d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/tijsverkoyen/CssToInlineStyles/zipball/0d72ac1c00084279c1816675284073c5a337c20d", + "reference": "0d72ac1c00084279c1816675284073c5a337c20d", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "php": "^7.4 || ^8.0", + "symfony/css-selector": "^5.4 || ^6.0 || ^7.0" + }, + "require-dev": { + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpunit/phpunit": "^8.5.21 || ^9.5.10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "TijsVerkoyen\\CssToInlineStyles\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Tijs Verkoyen", + "email": "css_to_inline_styles@verkoyen.eu", + "role": "Developer" + } + ], + "description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.", + "homepage": "https://github.com/tijsverkoyen/CssToInlineStyles", + "support": { + "issues": "https://github.com/tijsverkoyen/CssToInlineStyles/issues", + "source": "https://github.com/tijsverkoyen/CssToInlineStyles/tree/v2.3.0" + }, + "time": "2024-12-21T16:25:41+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +} diff --git a/config/domaindata.php b/config/domaindata.php new file mode 100644 index 0000000..fe8f705 --- /dev/null +++ b/config/domaindata.php @@ -0,0 +1,4 @@ + 0, + 'path' => '/', + 'domain' => APP_COOKIE_DOMAIN ?: '', + 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'), + 'httponly' => true, + 'samesite' => 'Lax', + ]); + + session_start(); + } +} + + +// ----------------------------------------------------------- +// 2) Persistente Client-ID (für Tracking über Besuche hinweg) +// ----------------------------------------------------------- +if (php_sapi_name() !== 'cli') { + $clientId = $_COOKIE[$clientCookieName] ?? null; + + // Erwartet wird: 64 Hex-Zeichen (32 Bytes) + if ( + !is_string($clientId) || + $clientId === '' || + !preg_match('/^[a-f0-9]{64}$/', $clientId) + ) { + // neue ID erzeugen + try { + $clientId = bin2hex(random_bytes(32)); // 32 bytes → 64 hex + } catch (Throwable $e) { + $clientId = bin2hex(openssl_random_pseudo_bytes(32)); + } + + $cookieOpts = [ + 'expires' => time() + APP_CLIENT_COOKIE_LIFETIME, + 'path' => '/', + 'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'), + 'httponly' => false, // JS darf es lesen, wenn erwünscht + 'samesite' => 'Lax', + ]; + + if (!empty(APP_COOKIE_DOMAIN)) { + $cookieOpts['domain'] = APP_COOKIE_DOMAIN; + } + + setcookie($clientCookieName, $clientId, $cookieOpts); + $_COOKIE[$clientCookieName] = $clientId; + } + + // global verfügbar machen (NEUER NAME!) + $GLOBALS['cookie_client_id'] = $clientId; +} + + +// ----------------------------------------------------------- +// 3) Sprachlogik laden (bleibt sinnvoll zentral) +// ----------------------------------------------------------- +require_once __DIR__ . '/i18n.php'; + + +// ----------------------------------------------------------- +// 4) Rest des Systems laden (DB, Funktionen, Hilfs-Libs) +// ----------------------------------------------------------- +require_once __DIR__ . "/db.php"; +require_once __DIR__ . '/../src/functions.php'; diff --git a/config/i18n.php b/config/i18n.php new file mode 100644 index 0000000..2621bc8 --- /dev/null +++ b/config/i18n.php @@ -0,0 +1,397 @@ + 2) { + $code = substr($code, 0, 2); + } + + if ($code === '') { + return null; + } + + $label = isset($meta['label']) && $meta['label'] !== '' + ? (string)$meta['label'] + : strtoupper($code); + + $flag = isset($meta['flag']) ? (string)$meta['flag'] : ''; + + return [ + 'code' => $code, + 'label' => $label, + 'flag' => $flag, + ]; +} + +/** + * Alle verfügbaren Sprachen aus /public/assets/i18n/*.json ermitteln. + * Verfügbar = JSON mit meta.enabled === true. + * EN wird garantiert hinzugefügt (Fallback), falls nicht gefunden. + */ +function app_i18n_detect_available_languages(): array +{ + $baseDir = realpath(__DIR__ . '/../public/assets/i18n'); + if ($baseDir === false) { + // Wenn gar kein Verzeichnis da ist: minimaler EN-Fallback + return [ + 'en' => [ + 'code' => 'en', + 'label' => 'English', + 'flag' => '', + ], + ]; + } + + $files = glob($baseDir . '/*.json') ?: []; + $langs = []; + + foreach ($files as $file) { + $meta = app_i18n_load_language_meta_from_file($file); + if ($meta === null) { + continue; + } + + $code = $meta['code']; + + // Erste gültige Definition pro Code gewinnt + if (!isset($langs[$code])) { + $langs[$code] = $meta; + } + } + + // EN muss immer vorhanden sein (laut deiner Vorgabe) + if (!isset($langs['en'])) { + // Versuch: gibt es eine en.json, auch wenn enabled=false? + foreach ($files as $file) { + $base = strtolower(basename($file, '.json')); + if ($base === 'en') { + $json = @file_get_contents($file); + $data = json_decode($json, true); + $meta = is_array($data['meta'] ?? null) ? $data['meta'] : []; + + $label = isset($meta['label']) && $meta['label'] !== '' + ? (string)$meta['label'] + : 'English'; + $flag = isset($meta['flag']) ? (string)$meta['flag'] : ''; + + $langs['en'] = [ + 'code' => 'en', + 'label' => $label, + 'flag' => $flag, + ]; + break; + } + } + } + + // Wenn immer noch kein EN → minimaler Stub + if (!isset($langs['en'])) { + $langs['en'] = [ + 'code' => 'en', + 'label' => 'English', + 'flag' => '', + ]; + } + + ksort($langs); + + return $langs; +} + +/** + * Browsersprache aus HTTP_ACCEPT_LANGUAGE extrahieren (2-Buchstaben), + * aber nur, wenn sie in $available existiert. + */ +function app_i18n_detect_browser_lang(array $available): ?string +{ + $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''; + if ($header === '') { + return null; + } + + $parts = explode(',', $header); + foreach ($parts as $part) { + $part = trim($part); + if ($part === '') { + continue; + } + + $code = strtolower(substr($part, 0, 2)); // "de-DE" → "de" + if (isset($available[$code])) { + return $code; + } + } + + return null; +} + +/** + * Aktuelle Sprache bestimmen: + * 1) ?lang=xx (wenn in $available) + * 2) Browsersprache (wenn in $available) + * 3) Fallback "en" + */ +function app_i18n_resolve_current_lang(array $available): string +{ + // 1) URL-Parameter ?lang=xx + if (!empty($_GET['lang'])) { + $param = strtolower(substr($_GET['lang'], 0, 2)); + if (isset($available[$param])) { + return $param; + } + } + + // 2) Browsersprache + $browser = app_i18n_detect_browser_lang($available); + if ($browser !== null) { + return $browser; + } + + // 3) Standard EN + if (isset($available['en'])) { + return 'en'; + } + + // Sicherheitsfallback: erste verfügbare Sprache + $keys = array_keys($available); + return $keys[0] ?? 'en'; +} + +// ----------------------------------------------------- +// Bootstrap ausführen +// ----------------------------------------------------- + +$availableLangs = app_i18n_detect_available_languages(); +$currentLang = app_i18n_resolve_current_lang($availableLangs); + +// Global bereitstellen +$GLOBALS['availableLangs'] = $availableLangs; +$GLOBALS['lang'] = $currentLang; + +// Optional in Session merken (muss nicht, schadet aber auch nicht) +$_SESSION['lang'] = $currentLang; + +/** + * Frontend-Config für JS (usbConfig.i18n) + * → benutzt direkt die Meta-Daten aus den JSONs (code, label, flag) + */ +function app_i18n_get_frontend_config(): array +{ + return [ + 'current' => $GLOBALS['lang'] ?? 'en', + 'available' => $GLOBALS['availableLangs'] ?? [], + ]; +} + +/** + * Komplette JSON-Struktur für eine Sprache laden. + * Nutzt einfachen Request-Cache, damit pro Sprache nur einmal von Platte gelesen wird. + */ +function app_i18n_load_lang_json(string $lang): array +{ + static $cache = []; + + $lang = strtolower(substr($lang, 0, 5)); + + if (isset($cache[$lang])) { + return $cache[$lang]; + } + + $baseDir = realpath(__DIR__ . '/../public/assets/i18n'); + if ($baseDir === false) { + $cache[$lang] = []; + return $cache[$lang]; + } + + $path = $baseDir . '/' . $lang . '.json'; + if (!is_file($path)) { + // Fallback: en.json, falls vorhanden + $fallback = $baseDir . '/en.json'; + if (is_file($fallback)) { + $json = @file_get_contents($fallback); + $data = json_decode($json, true); + $cache[$lang] = is_array($data) ? $data : []; + return $cache[$lang]; + } + + $cache[$lang] = []; + return $cache[$lang]; + } + + $json = @file_get_contents($path); + $data = json_decode($json, true); + $cache[$lang] = is_array($data) ? $data : []; + + return $cache[$lang]; +} + +/** + * Aus einem Label einen stabilen i18n-Key für Nav-Anker bauen. + * Beispiel: "So funktioniert USBCheck!" -> "nav_so_funktioniert_usbcheck" + */ +function app_i18n_make_anchor_key(string $label): string +{ + // HTML-Entities entfernen (z. B. &) + $decoded = html_entity_decode($label, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + // Kleinbuchstaben + $decoded = mb_strtolower($decoded, 'UTF-8'); + + // Alles, was kein a-z oder 0-9 ist, durch Unterstrich ersetzen + $key = preg_replace('/[^a-z0-9]+/u', '_', $decoded); + + // Mehrfache Unterstriche trimmen + $key = trim($key, '_'); + + if ($key === '') { + $key = 'item'; + } + + // Prefix, damit klar ist, dass es Navigationskeys sind + return 'nav_' . $key; +} + +/** + * Nav-Anker für eine Seite aus der Sprachdatei holen. + * + * Haupt-Variante im JSON: + * + * "pages": { + * "landing": { + * "anchors": { + * "how": "So funktioniert USBCheck", + * "problem": "Warum gefälschte USB-Sticks gefährlich sind", + * "features": "Funktionen", + * "security": "Sicherheit", + * "faq": "FAQ" + * } + * } + * } + * + * Optional explizit: + * "anchors": { + * "how": { "label": "So funktioniert USBCheck", "i18n": "nav_how" }, + * "faq": { "i18n": "nav_faq" } + * } + * + * Rückgabe-Format: + * [ + * [ 'href' => '#how', 'label' => 'So funktioniert USBCheck', 'i18n' => 'nav_so_funktioniert_usbcheck' ], + * [ 'href' => '#faq', 'label' => '', 'i18n' => 'nav_faq' ], + * ] + */ +function app_get_nav_anchors(string $pageKey): array +{ + $lang = $GLOBALS['lang'] ?? 'en'; + $data = app_i18n_load_lang_json($lang); + + $cfg = $data['pages'][$pageKey]['anchors'] ?? null; + if (!is_array($cfg)) { + return []; + } + + $anchors = []; + + foreach ($cfg as $id => $value) { + $id = trim((string)$id); + if ($id === '') { + continue; + } + + $href = '#' . $id; + $label = ''; + $i18n = ''; + + if (is_string($value)) { + // String IMMER als Label übernehmen + $labelTrim = trim($value); + if ($labelTrim === '') { + continue; + } + + $label = $labelTrim; + // i18n-Key automatisch aus dem Label ableiten + $i18n = app_i18n_make_anchor_key($labelTrim); + + } elseif (is_array($value)) { + // Explizite Variante: + // "how": { "label": "...", "i18n": "nav_how" } + if (!empty($value['label'])) { + $label = trim((string)$value['label']); + } + if (!empty($value['i18n'])) { + $i18n = trim((string)$value['i18n']); + } + + if ($label === '' && $i18n === '') { + continue; + } + + // Wenn Label gesetzt, aber kein i18n: automatisch generieren + if ($label !== '' && $i18n === '') { + $i18n = app_i18n_make_anchor_key($label); + } + } else { + // Weder String noch Array → ignorieren + continue; + } + + $anchors[] = [ + 'href' => $href, + 'label' => $label, + 'i18n' => $i18n, + ]; + } + + return $anchors; +} diff --git a/config/prod/config.php b/config/prod/config.php new file mode 100644 index 0000000..b11bace --- /dev/null +++ b/config/prod/config.php @@ -0,0 +1,34 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; + +try { + $pdo = new PDO( + "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4", + $DB_USER, + $DB_PASS, + $options + ); +} catch (PDOException $e) { + // In Produktion Logging, keine Details ausgeben + http_response_code(500); + echo 'Database connection error.'; + exit; +} diff --git a/config/staging/config.php b/config/staging/config.php new file mode 100644 index 0000000..e2ea33f --- /dev/null +++ b/config/staging/config.php @@ -0,0 +1,36 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, +]; + +try { + $pdo = new PDO( + "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4", + $DB_USER, + $DB_PASS, + $options + ); +} catch (PDOException $e) { + // In Produktion Logging, keine Details ausgeben + http_response_code(500); + echo 'Database connection error.'; + exit; +} diff --git a/inc/ApiKernel (Kopie).php b/inc/ApiKernel (Kopie).php new file mode 100644 index 0000000..79538fd --- /dev/null +++ b/inc/ApiKernel (Kopie).php @@ -0,0 +1,636 @@ +conf = $this->loadConfig(); + $this->cors(); + $this->setInput(); + $this->pdo = $this->getPdoTemplates(); + $this->resolveAction(); + $this->resolveTableMap(); + $this->authService = new AuthService($this->conf, $this->pdo); + } catch (Throwable $e) { + $this->fail('Initialization error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } + + // --- Core Responder-Methoden (Unverändert) --- + + public function respond($data, int $code = 200): void + { + http_response_code($code); + echo is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + public function fail(string $msg, $detail = null, int $code = 400): void + { + $this->respond(['ok' => false, 'error' => $msg, 'detail' => $detail], $code); + } + + // --- Private Initialisierungs- & Utility-Methoden (Unverändert) --- + + private function loadConfig(): array { /* ... Logik bleibt unverändert ... */ + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + $this->fail('Invalid config.php', 'config.php not found or not returning array', 500); + } + private function cors(): void { /* ... Logik bleibt unverändert ... */ + $cors = $this->conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') $this->respond(['ok' => true]); + + if (!empty($this->conf['auth']['cookie'])) { + $c = $this->conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + } + private function setInput(): void { /* ... Logik bleibt unverändert ... */ + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k => $v) $data[$k] = $v; + foreach ($_GET as $k => $v) if (!array_key_exists($k, $data)) $data[$k] = $v; + $this->in = $data; + } + private function getPdoTemplates(): PDO { /* ... Logik bleibt unverändert ... */ + if (!isset($this->conf['templates']) || !is_array($this->conf['templates'])) { + $this->fail('Missing templates DB config', null, 500); + } + $c = $this->conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); + } + private function resolveAction(): void { /* ... Logik bleibt unverändert ... */ + $action = $this->val($this->in, 'action', ''); + $resource = $this->val($this->in, 'resource', null); + $allowedResources = ['templates', 'sections', 'blocks', 'snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list', 'get', 'create', 'update', 'delete'], true)) $action = $resource . '.' . $verb; + } + $this->action = $action; + } + private function resolveTableMap(): void { /* ... Logik bleibt unverändert ... */ + $tables = $this->conf['tables'] ?? []; + $this->tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + } + + private function val(array $in, $keys, $default = null) { /* ... Logik bleibt unverändert ... */ + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k, $in)) return $in[$k]; + return $default; + } + private function firstExisting(array $columns, array $candidates): ?string { /* ... Logik bleibt unverändert ... */ + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; + } + private function tableColumns(string $table): array { /* ... Logik bleibt unverändert ... */ + $cols = []; + $stmt = $this->pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; + } + private function primaryKey(string $table): ?string { /* ... Logik bleibt unverändert ... */ + $stmt = $this->pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; + } + private function requireAuth(): array { /* ... Logik bleibt unverändert ... */ + return $this->authService->requireAuth(); + } + private function pullId(array $src) { /* ... Logik bleibt unverändert ... */ + $aliases = ['id', 'item_id', 'template_id', 'tpl_id', 'section_id', 'sec_id', 'block_id', 'blk_id', 'snippet_id', 'snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + } + private function tenantWhere(array $session): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val === null || $val === '') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant' => $val]]; + } + private function tenantAssign(array $session, array $columns): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val === null || $val === '') ? [] : [$tenantCol => $val]; + } + private function resolveIdCol(string $kind): array { /* ... Logik bleibt unverändert ... */ + $t = $this->tableMap[$kind]; + $cfg = $this->conf['columns'][$kind] ?? []; + $cols = $this->tableColumns($t); + $idCol = $cfg['id'] ?? ($this->firstExisting($cols, ['id']) ?: $this->primaryKey($t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; + } + private function parseHtmlToGjsComponents(string $html): array { /* ... Logik bleibt unverändert ... */ + if (trim($html) === '') return []; + + return [ + [ + 'type' => 'html', + 'content' => $html, + 'removable' => true, + 'draggable' => true, + 'droppable' => true, + 'copyable' => true, + 'selectable' => true, + 'editable' => false, + 'traits' => [], + ] + ]; + } + + // 💡 KORREKTUR: Bereinigungsmethode (von vorheriger Version übernommen) + private function cleanReferenceComponents(array $components): array { + foreach ($components as &$component) { + if (is_array($component) && isset($component['type'])) { + + if ($component['type'] === 'library-reference') { + if (isset($component['content'])) { + $component['content'] = ''; + } + if (isset($component['components'])) { + $component['components'] = []; + } + } + if (isset($component['components']) && is_array($component['components'])) { + $component['components'] = $this->cleanReferenceComponents($component['components']); + } + } + } + return $components; + } + + + // ================================================================= + // 🚀 NEUE CRUD HANDLER METHODEN (Logik aus run() extrahiert) + // ================================================================= + + /** + * Allgemeine Methode zur Handhabung von LIST-Anfragen. + */ + private function handleList(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $q = trim((string)$this->val($this->in, 'q', '')); + $limit = max(1, (int)$this->val($this->in, 'limit', 500)); + $offset = max(0, (int)$this->val($this->in, 'offset', 0)); + + $where = ' WHERE 1=1 '; + $params = []; + // Suchlogik (q) + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (" . implode(' OR ', $parts) . ") "; + $params[':q'] = '%' . $q . '%'; + } + + // Filterlogik (parentFilters) + $parentFilters = [ + 'template_id' => $this->val($this->in, ['template_id', 'tpl_id'], null), + 'section_id' => $this->val($this->in, ['section_id', 'sec_id'], null), + 'block_id' => $this->val($this->in, ['block_id', 'blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Tenant-Filter + [$tw, $tp] = $this->tenantWhere($auth); + $where .= $tw; + foreach ($tp as $k => $v) $params[$k] = $v; + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $this->pdo->prepare($sql); + + // Bind parameters + foreach ($params as $k => $v) $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR); + $stmt->bindValue(':off', $offset, PDO::PARAM_INT); + $stmt->bindValue(':lim', $limit, PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + if ($htmlCol && isset($r[$htmlCol])) $item['html'] = (string)$r[$htmlCol]; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + if ($jsonCol && isset($r[$jsonCol])) $item['content'] = $r[$jsonCol]; + + $out[] = $item; + } + $this->respond(['ok' => true, 'kind' => $kind, 'items' => $out, 'data' => $out, 'count' => count($out), 'offset' => $offset, 'limit' => $limit]); + } + + /** + * Allgemeine Methode zur Handhabung von GET-Anfragen. + */ + private function handleGet(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) $this->fail('Not found', ['kind' => $kind, 'id' => $id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + $gjsComponents = []; + + if ($topContent !== null) { + $decodedContent = json_decode($topContent, true); + if (is_array($decodedContent)) { + $gjsComponents = $decodedContent; + } + } + + if (empty($gjsComponents) && $topHtml !== null) { + $gjsComponents = $this->parseHtmlToGjsComponents($topHtml); + } + + $this->respond([ + 'ok' => true, + 'kind' => $kind, + 'id' => $rowOut['id'], + 'item' => $rowOut, + 'data' => $rowOut, + 'html' => $topHtml, + 'content' => $topContent, + 'gjs_components' => $gjsComponents + ]); + } + + /** + * Allgemeine Methode zur Handhabung von CREATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleCreate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + + $name = trim((string)$this->val($this->in, ['name', 'title'], '')); + if ($name === '') $this->fail('name required', null, 422); + + $desc = (string)$this->val($this->in, ['description', 'desc'], null); + $cat = (string)$this->val($this->in, ['category', 'cat'], null); + $html = (string)$this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + $templateId = $this->val($this->in, ['template_id', 'tpl_id'], null); + $sectionId = $this->val($this->in, ['section_id', 'sec_id'], null); + $blockId = $this->val($this->in, ['block_id', 'blk_id'], null); + + $data = [$nameCol => $name]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + } + + // 2. HTML-Content speichern + if ($htmlDbCol && $html !== null) { + $data[$htmlDbCol] = $html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($c && $settings !== null) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + if ($templateId !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $templateId; + if ($sectionId !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sectionId; + if ($blockId !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blockId; + + $data = $data + $this->tenantAssign($_SESSION['auth'] ?? [], $allCols); + + $now = date('Y-m-d H:i:s'); + $createdCol = $this->firstExisting($allCols, ['created_at', 'created', 'createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + + $fields = array_keys($data); + $place = array_map(fn($c) => ":$c", $fields); + $sql = "INSERT INTO `$t` (" . implode(',', array_map(fn($c) => "`$c`", $fields)) . ") VALUES (" . implode(',', $place) . ")"; + $stmt = $this->pdo->prepare($sql); + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $this->pdo->lastInsertId(); + + $out = ['id' => $newId, 'name' => $name]; + if ($desc !== null) $out['desc'] = $desc; + if ($cat !== null) $out['category'] = $cat; + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $newId, 'item' => $out, 'data' => $out]); + } + + /** + * Allgemeine Methode zur Handhabung von UPDATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleUpdate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + $data = []; + $name = $this->val($this->in, ['name', 'title'], null); + $desc = $this->val($this->in, ['description', 'desc'], null); + $cat = $this->val($this->in, ['category', 'cat'], null); + $html = $this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + // Wenn JSON-Spalte existiert, JSON verarbeiten und speichern + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + + // 2. Den zugehörigen HTML-Output speichern (wird vom Editor immer mitgesendet, wenn JSON da ist) + if ($html !== null && $htmlDbCol) { + $data[$htmlDbCol] = (string)$html; + } + } elseif ($html !== null && $htmlDbCol) { + // Wenn NUR HTML gesendet wird (für minimale Änderungen), speichern wir nur HTML. + $data[$htmlDbCol] = (string)$html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($settings !== null && $c) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + $tpl = $this->val($this->in, ['template_id', 'tpl_id'], null); + if ($tpl !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $tpl; + $sec = $this->val($this->in, ['section_id', 'sec_id'], null); + if ($sec !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sec; + $blk = $this->val($this->in, ['block_id', 'blk_id'], null); + if ($blk !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blk; + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) $this->fail('nothing to update', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $set = []; + foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET " . implode(',', $set) . " WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'updated' => array_keys($data)]); + } + + /** + * Allgemeine Methode zur Handhabung von DELETE-Anfragen. + */ + private function handleDelete(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'deleted' => true]); + } + + // ================================================================= + // 💡 Öffentliche run()-Methode (DEUTLICH VEREINFACHT) + // ================================================================= + + public function run(): void + { + header('Content-Type: application/json; charset=utf-8'); + + try { + // Extrahiere den Ressourcen-Typ und die Operation (z.B. 'templates' und 'list') + [$kind, $operation] = explode('.', $this->action, 2) + [1 => '']; + + switch ($this->action) { + case 'health': + $this->respond(['ok' => true, 'time' => date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': + $result = $this->authService->login($this->in); + $this->respond(['ok' => true] + $result); + break; + case 'auth.me': + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + $this->respond(['ok' => true, 'user' => $_SESSION['auth']]); + break; + case 'auth.logout': + $this->authService->logout(); + $this->respond(['ok' => true]); + break; + + /* ---------- CRUD HANDLER ---------- */ + default: + if (in_array($kind, ['templates', 'sections', 'blocks', 'snippets'])) { + switch ($operation) { + case 'list': + $this->handleList($kind); + break; + case 'get': + $this->handleGet($kind); + break; + case 'create': + $this->handleCreate($kind); + break; + case 'update': + $this->handleUpdate($kind); + break; + case 'delete': + $this->handleDelete($kind); + break; + default: + $this->fail('Unknown operation for resource: ' . $this->action, null, 404); + break; + } + } else { + $this->fail('Unknown action', $this->action ?: 'missing', 404); + } + break; + } + } catch (Throwable $e) { + $this->fail('Server error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } +} diff --git a/inc/ApiKernel.php b/inc/ApiKernel.php new file mode 100644 index 0000000..26cc516 --- /dev/null +++ b/inc/ApiKernel.php @@ -0,0 +1,657 @@ +conf = $this->loadConfig(); + $this->cors(); + $this->setInput(); + $this->pdo = $this->getPdoTemplates(); + $this->resolveAction(); + $this->resolveTableMap(); + $this->authService = new AuthService($this->conf, $this->pdo); + } catch (Throwable $e) { + // Im Fehlerfall ruft fail() die respond() Methode auf, die den Header setzt und den Buffer leert. + $this->fail('Initialization error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } + + // --- Core Responder-Methoden (KORRIGIERT) --- + + public function respond($data, int $code = 200): void + { + // 1. Output-Puffer leeren, um jeglichen unbeabsichtigten Output zu verwerfen (z.B. PHP Notices). + if (ob_get_level() > 0) { + ob_clean(); + } + + // 2. 💡 KRITISCHE KORREKTUR: Content-Type Header setzen. + // Dies ist der entscheidende Schritt, der dem Browser sagt: "Dies ist JSON!" + if (!headers_sent() && !isset($this->conf['no_content_type'])) { + header('Content-Type: application/json; charset=utf-8'); + } + + http_response_code($code); + echo is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } + + public function fail(string $msg, $detail = null, int $code = 400): void + { + $this->respond(['ok' => false, 'error' => $msg, 'detail' => $detail], $code); + } + + // --- Private Initialisierungs- & Utility-Methoden (Unverändert) --- + + private function loadConfig(): array { /* ... Logik bleibt unverändert ... */ + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + $this->fail('Invalid config.php', 'config.php not found or not returning array', 500); + } + private function cors(): void { /* ... Logik bleibt unverändert ... */ + $cors = $this->conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') $this->respond(['ok' => true]); + + if (!empty($this->conf['auth']['cookie'])) { + $c = $this->conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + } + private function setInput(): void { /* ... Logik bleibt unverändert ... */ + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k => $v) $data[$k] = $v; + foreach ($_GET as $k => $v) if (!array_key_exists($k, $data)) $data[$k] = $v; + $this->in = $data; + } + private function getPdoTemplates(): PDO { /* ... Logik bleibt unverändert ... */ + if (!isset($this->conf['templates']) || !is_array($this->conf['templates'])) { + $this->fail('Missing templates DB config', null, 500); + } + $c = $this->conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); + } + private function resolveAction(): void { /* ... Logik bleibt unverändert ... */ + $action = $this->val($this->in, 'action', ''); + $resource = $this->val($this->in, 'resource', null); + $allowedResources = ['templates', 'sections', 'blocks', 'snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list', 'get', 'create', 'update', 'delete'], true)) $action = $resource . '.' . $verb; + } + $this->action = $action; + } + private function resolveTableMap(): void { /* ... Logik bleibt unverändert ... */ + $tables = $this->conf['tables'] ?? []; + $this->tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + } + + private function val(array $in, $keys, $default = null) { /* ... Logik bleibt unverändert ... */ + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k, $in)) return $in[$k]; + return $default; + } + private function firstExisting(array $columns, array $candidates): ?string { /* ... Logik bleibt unverändert ... */ + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; + } + private function tableColumns(string $table): array { /* ... Logik bleibt unverändert ... */ + $cols = []; + $stmt = $this->pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; + } + private function primaryKey(string $table): ?string { /* ... Logik bleibt unverändert ... */ + $stmt = $this->pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; + } + private function requireAuth(): array { /* ... Logik bleibt unverändert ... */ + return $this->authService->requireAuth(); + } + private function pullId(array $src) { /* ... Logik bleibt unverändert ... */ + $aliases = ['id', 'item_id', 'template_id', 'tpl_id', 'section_id', 'sec_id', 'block_id', 'blk_id', 'snippet_id', 'snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + } + private function tenantWhere(array $session): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val === null || $val === '') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant' => $val]]; + } + private function tenantAssign(array $session, array $columns): array { /* ... Logik bleibt unverändert ... */ + $multi = $this->conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val === null || $val === '') ? [] : [$tenantCol => $val]; + } + private function resolveIdCol(string $kind): array { /* ... Logik bleibt unverändert ... */ + $t = $this->tableMap[$kind]; + $cfg = $this->conf['columns'][$kind] ?? []; + $cols = $this->tableColumns($t); + $idCol = $cfg['id'] ?? ($this->firstExisting($cols, ['id']) ?: $this->primaryKey($t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; + } + private function parseHtmlToGjsComponents(string $html): array { /* ... Logik bleibt unverändert ... */ + if (trim($html) === '') return []; + + return [ + [ + 'type' => 'html', + 'content' => $html, + 'removable' => true, + 'draggable' => true, + 'droppable' => true, + 'copyable' => true, + 'selectable' => true, + 'editable' => false, + 'traits' => [], + ] + ]; + } + + // 💡 Bereinigungsmethode + private function cleanReferenceComponents(array $components): array { + foreach ($components as &$component) { + if (is_array($component) && isset($component['type'])) { + + if ($component['type'] === 'library-reference') { + if (isset($component['content'])) { + $component['content'] = ''; + } + if (isset($component['components'])) { + $component['components'] = []; + } + } + if (isset($component['components']) && is_array($component['components'])) { + $component['components'] = $this->cleanReferenceComponents($component['components']); + } + } + } + return $components; + } + + + // ================================================================= + // 🚀 CRUD HANDLER METHODEN + // ================================================================= + + /** + * Allgemeine Methode zur Handhabung von LIST-Anfragen. + */ + private function handleList(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $q = trim((string)$this->val($this->in, 'q', '')); + $limit = max(1, (int)$this->val($this->in, 'limit', 500)); + $offset = max(0, (int)$this->val($this->in, 'offset', 0)); + + $where = ' WHERE 1=1 '; + $params = []; + // Suchlogik (q) + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (" . implode(' OR ', $parts) . ") "; + $params[':q'] = '%' . $q . '%'; + } + + // Filterlogik (parentFilters) + $parentFilters = [ + 'template_id' => $this->val($this->in, ['template_id', 'tpl_id'], null), + 'section_id' => $this->val($this->in, ['section_id', 'sec_id'], null), + 'block_id' => $this->val($this->in, ['block_id', 'blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Tenant-Filter + [$tw, $tp] = $this->tenantWhere($auth); + $where .= $tw; + foreach ($tp as $k => $v) $params[$k] = $v; + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $this->pdo->prepare($sql); + + // Bind parameters + foreach ($params as $k => $v) $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR); + $stmt->bindValue(':off', $offset, PDO::PARAM_INT); + $stmt->bindValue(':lim', $limit, PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + if ($htmlCol && isset($r[$htmlCol])) $item['html'] = (string)$r[$htmlCol]; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + if ($jsonCol && isset($r[$jsonCol])) $item['content'] = $r[$jsonCol]; + + $out[] = $item; + } + $this->respond(['ok' => true, 'kind' => $kind, 'items' => $out, 'data' => $out, 'count' => count($out), 'offset' => $offset, 'limit' => $limit]); + } + + /** + * Allgemeine Methode zur Handhabung von GET-Anfragen. + */ + private function handleGet(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) $this->fail('Not found', ['kind' => $kind, 'id' => $id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // Lade HTML und JSON aus den korrekten Spalten + $htmlCol = $this->firstExisting($allCols, ['html', 'body', 'markup', 'content']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $jsonCol = $this->firstExisting($allCols, ['json_content']); + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + $gjsComponents = []; + + if ($topContent !== null) { + $decodedContent = json_decode($topContent, true); + if (is_array($decodedContent)) { + $gjsComponents = $decodedContent; + } + } + + if (empty($gjsComponents) && $topHtml !== null) { + $gjsComponents = $this->parseHtmlToGjsComponents($topHtml); + } + + $this->respond([ + 'ok' => true, + 'kind' => $kind, + 'id' => $rowOut['id'], + 'item' => $rowOut, + 'data' => $rowOut, + 'html' => $topHtml, + 'content' => $topContent, + 'gjs_components' => $gjsComponents + ]); + } + + /** + * Allgemeine Methode zur Handhabung von CREATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleCreate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + + $name = trim((string)$this->val($this->in, ['name', 'title'], '')); + if ($name === '') $this->fail('name required', null, 422); + + $desc = (string)$this->val($this->in, ['description', 'desc'], null); + $cat = (string)$this->val($this->in, ['category', 'cat'], null); + $html = (string)$this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + $templateId = $this->val($this->in, ['template_id', 'tpl_id'], null); + $sectionId = $this->val($this->in, ['section_id', 'sec_id'], null); + $blockId = $this->val($this->in, ['block_id', 'blk_id'], null); + + $data = [$nameCol => $name]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + } + + // 2. HTML-Content speichern + if ($htmlDbCol && $html !== null) { + $data[$htmlDbCol] = $html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($c && $settings !== null) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + if ($templateId !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $templateId; + if ($sectionId !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sectionId; + if ($blockId !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blockId; + + $data = $data + $this->tenantAssign($_SESSION['auth'] ?? [], $allCols); + + $now = date('Y-m-d H:i:s'); + $createdCol = $this->firstExisting($allCols, ['created_at', 'created', 'createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + + $fields = array_keys($data); + $place = array_map(fn($c) => ":$c", $fields); + $sql = "INSERT INTO `$t` (" . implode(',', array_map(fn($c) => "`$c`", $fields)) . ") VALUES (" . implode(',', $place) . ")"; + $stmt = $this->pdo->prepare($sql); + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $this->pdo->lastInsertId(); + + $out = ['id' => $newId, 'name' => $name]; + if ($desc !== null) $out['desc'] = $desc; + if ($cat !== null) $out['category'] = $cat; + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $newId, 'item' => $out, 'data' => $out]); + } + + /** + * Allgemeine Methode zur Handhabung von UPDATE-Anfragen (inkl. JSON-Bereinigung). + */ + private function handleUpdate(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $cfg = $this->conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? ($this->firstExisting($allCols, ['name']) ?: $idCol); + $descCol = $cfg['desc'] ?? $this->firstExisting($allCols, ['description', 'desc', 'descr']); + $catCol = $cfg['cat'] ?? $this->firstExisting($allCols, ['category', 'cat']); + $updCol = $cfg['upd'] ?? $this->firstExisting($allCols, ['updated_at', 'updated', 'updatedAt']); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + $data = []; + $name = $this->val($this->in, ['name', 'title'], null); + $desc = $this->val($this->in, ['description', 'desc'], null); + $cat = $this->val($this->in, ['category', 'cat'], null); + $html = $this->val($this->in, ['html', 'body', 'markup'], null); + $json = $this->val($this->in, ['content_json', 'json', 'content', 'structure_json'], null); + $settings = $this->val($this->in, ['settings_json', 'settings'], null); + + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $htmlDbCol = $this->firstExisting($allCols, ($kind === 'snippets' ? ['content'] : ['html', 'body', 'markup'])); + $jsonDbCol = $this->firstExisting($allCols, ['json_content']); + + // --- LOGIK mit ERWEITERTER PRÜFUNG START --- + + // 1. JSON-Content behandeln + if ($json !== null) { + if ($jsonDbCol) { + // Wenn JSON-Spalte existiert, JSON verarbeiten und speichern + $components = is_string($json) ? json_decode($json, true) : $json; + if (is_array($components)) { + $components = $this->cleanReferenceComponents($components); // BEREINIGUNG + $data[$jsonDbCol] = json_encode($components, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } else { + $data[$jsonDbCol] = is_string($json) ? $json : ''; + } + } else { + // FALLBACK: Wenn JSON gesendet wurde, aber keine json_content Spalte existiert, FEHLER ausgeben + $this->fail( + 'JSON content provided but no `json_content` column found', + ['table' => $t, 'available_cols' => $allCols], + 422 + ); + } + + // 2. Den zugehörigen HTML-Output speichern (wird vom Editor immer mitgesendet, wenn JSON da ist) + if ($html !== null && $htmlDbCol) { + $data[$htmlDbCol] = (string)$html; + } + } elseif ($html !== null && $htmlDbCol) { + // Wenn NUR HTML gesendet wird (für minimale Änderungen), speichern wir nur HTML. + $data[$htmlDbCol] = (string)$html; + } + // --- LOGIK mit ERWEITERTER PRÜFUNG ENDE --- + + $c = $this->firstExisting($allCols, ['settings_json', 'settings']); + if ($settings !== null && $c) $data[$c] = is_string($settings) ? $settings : json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + $tpl = $this->val($this->in, ['template_id', 'tpl_id'], null); + if ($tpl !== null && in_array('template_id', $allCols, true)) $data['template_id'] = $tpl; + $sec = $this->val($this->in, ['section_id', 'sec_id'], null); + if ($sec !== null && in_array('section_id', $allCols, true)) $data['section_id'] = $sec; + $blk = $this->val($this->in, ['block_id', 'blk_id'], null); + if ($blk !== null && in_array('block_id', $allCols, true)) $data['block_id'] = $blk; + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) $this->fail('nothing to update', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $set = []; + foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET " . implode(',', $set) . " WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + + foreach ($data as $k => $v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'updated' => array_keys($data)]); + } + + /** + * Allgemeine Methode zur Handhabung von DELETE-Anfragen. + */ + private function handleDelete(string $kind): void + { + $auth = $this->requireAuth(); + $t = $this->tableMap[$kind]; + [$idCol, $allCols] = $this->resolveIdCol($kind); + $id = $this->pullId($this->in); + if ($id === null || $id === '') $this->fail('id required', null, 422); + + [$tw, $tp] = $this->tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id" . $tw . " LIMIT 1"; + $stmt = $this->pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k => $v) $stmt->bindValue($k, $v); + $stmt->execute(); + $this->respond(['ok' => true, 'kind' => $kind, 'id' => $id, 'deleted' => true]); + } + + // ================================================================= + // 💡 Öffentliche run()-Methode (KORRIGIERT) + // ================================================================= + + public function run(): void + { + // 💡 KORREKTUR: Der Content-Type Header wird hier entfernt, da er jetzt in respond() + // zentralisiert wurde, um sicherzustellen, dass er auch bei Fehlern im Konstruktor oder + // im try-Block korrekt gesetzt wird. + // header('Content-Type: application/json; charset=utf-8'); // DIESE ZEILE ENTFERNT + + try { + // Extrahiere den Ressourcen-Typ und die Operation (z.B. 'templates' und 'list') + [$kind, $operation] = explode('.', $this->action, 2) + [1 => '']; + + switch ($this->action) { + case 'health': + $this->respond(['ok' => true, 'time' => date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': + $result = $this->authService->login($this->in); + $this->respond(['ok' => true] + $result); + break; + case 'auth.me': + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + $this->respond(['ok' => true, 'user' => $_SESSION['auth']]); + break; + case 'auth.logout': + $this->authService->logout(); + $this->respond(['ok' => true]); + break; + + /* ---------- CRUD HANDLER ---------- */ + default: + if (in_array($kind, ['templates', 'sections', 'blocks', 'snippets'])) { + switch ($operation) { + case 'list': + $this->handleList($kind); + break; + case 'get': + $this->handleGet($kind); + break; + case 'create': + $this->handleCreate($kind); + break; + case 'update': + $this->handleUpdate($kind); + break; + case 'delete': + $this->handleDelete($kind); + break; + default: + $this->fail('Unknown operation for resource: ' . $this->action, null, 404); + break; + } + } else { + $this->fail('Unknown action', $this->action ?: 'missing', 404); + } + break; + } + } catch (Throwable $e) { + $this->fail('Server error', get_class($e) . ': ' . $e->getMessage(), 500); + } + } +} diff --git a/inc/AuthService.php b/inc/AuthService.php new file mode 100644 index 0000000..f0112d4 --- /dev/null +++ b/inc/AuthService.php @@ -0,0 +1,105 @@ +conf = $conf; + $this->pdo = $pdo; + } + + // --- Private Utility Methoden --- + + private function fail(string $msg, $detail = null, int $code = 400): void + { + // Wir müssen hier direkt antworten, da wir das Fail-Verhalten des Kernels benötigen. + // Im ApiKernel werden wir die respond/fail-Methoden als public lassen, + // um sie hier injizieren zu können, oder wir lassen sie hier im Global Scope + // (WENN Sie die ursprünglichen globalen Funktionen respond/fail wieder zulassen). + // Für eine saubere Kapselung injizieren wir die Respond-Logik. + // HIER verwenden wir eine einfache JSON-Antwort, da die fail-Methode + // normalerweise den gesamten Kernel stoppt. Wir nutzen exit. + + http_response_code($code); + echo json_encode(['ok'=>false,'error'=>$msg,'detail'=>$detail], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; + } + + private function verifyPassword(string $input, string $stored, array $authDbConf): bool + { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); + } + + // --- Public Service Methoden --- + + public function requireAuth(): array + { + if (empty($_SESSION['auth'])) $this->fail('Not authenticated', null, 401); + return $_SESSION['auth']; + } + + public function logout(): bool + { + $_SESSION = []; + if (session_id() !== '') session_destroy(); + return true; + } + + public function login(array $in): array + { + $authDb = $this->conf['auth']['db'] ?? []; + $colUser = $authDb['col_user'] ?? 'email'; + $colPass = $authDb['col_pass'] ?? 'password'; + $colName = $authDb['col_name'] ?? 'name'; + $colId = $authDb['col_id'] ?? 'id'; + $colStatus = $authDb['col_status']?? null; + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + $table = $authDb['table'] ?? 'emailtemplate_users'; + + $identifier = trim((string)($in['username'] ?? $in['user'] ?? $in['email'] ?? $in['login'] ?? '')); + $password = (string)($in['password'] ?? $in['pass'] ?? $in['pwd'] ?? ''); + + if ($identifier === '' || $password === '') $this->fail('username/password required', null, 422); + + $stmt = $this->pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + $stmt->execute([':u'=>$identifier]); + $row = $stmt->fetch(); + + if (!$row) $this->fail('Invalid credentials', null, 401); + + if ($colStatus && isset($row[$colStatus])) { + if (!in_array($row[$colStatus], $activeValues, true)) { + $this->fail('Account inactive', null, 403); + } + } + + $stored = (string)($row[$colPass] ?? ''); + if ($stored === '' || !$this->verifyPassword($password, $stored, $authDb)) { + $this->fail('Invalid credentials', null, 401); + } + + $_SESSION['auth'] = [ + 'id' => $row[$colId] ?? null, + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + 'email' => $row[$colUser] ?? $identifier, + 'at' => time(), + ]; + + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + return ['user'=>$_SESSION['auth'], 'token'=>$token]; + } +} diff --git a/inc/OUTDATED auth_helpers.php b/inc/OUTDATED auth_helpers.php new file mode 100644 index 0000000..6ad3f69 --- /dev/null +++ b/inc/OUTDATED auth_helpers.php @@ -0,0 +1,138 @@ + 0, + 'path' => $cookiePath, + 'domain' => $cookieDomain, + 'secure' => $cookieSecure, + 'httponly' => $cookieHttpOnly, + 'samesite' => $cookieSameSite, + ]); + session_start(); + } +} + +/** ===== Auth Core ===== */ +function auth_login(PDO $pdoCustomers, array $cfg, string $email, string $password): array { + auth_start_session($cfg); + + $sql = "SELECT cu.id, cu.customer_id, cu.email, cu.password_hash, cu.role, + c.slug AS customer_slug, c.plan, c.status + FROM customer_users cu + JOIN customers c ON c.id = cu.customer_id + WHERE cu.email = :email AND cu.is_active = 1 + LIMIT 1"; + $st = $pdoCustomers->prepare($sql); + $st->execute([':email' => $email]); + $u = $st->fetch(PDO::FETCH_ASSOC); + + if (!$u || !password_verify($password, $u['password_hash'])) { + return ['ok' => false, 'error' => 'invalid_credentials']; + } + if (($u['status'] ?? 'active') !== 'active') { + return ['ok' => false, 'error' => 'customer_inactive']; + } + + // neue Session-ID, alte wird invalidiert + session_regenerate_id(true); + + $_SESSION['user'] = [ + 'id' => (int)$u['id'], + 'email' => $u['email'], + 'role' => $u['role'], + 'customer_id' => (int)$u['customer_id'], + 'customer_slug' => $u['customer_slug'], + 'plan' => $u['plan'], + ]; + return ['ok' => true, 'user' => $_SESSION['user']]; +} + +function auth_logout(array $cfg): void { + auth_start_session($cfg); + + // Sessiondaten löschen + $_SESSION = []; + + // Cookie-Parameter aus der aktiven Session + $params = session_get_cookie_params(); + $name = session_name(); + + // Kandidaten für Domain/Path, um "falsch" gesetzte Cookies sicher zu treffen + $host = $_SERVER['HTTP_HOST'] ?? ''; + $cfgDomain = $cfg['auth']['cookie_domain'] ?? ''; + $paths = array_values(array_unique([$params['path'] ?? '/', '/', ''])); + $domains = array_values(array_unique([ + $params['domain'] ?? '', + $cfgDomain, + $host, + ltrim($host, '.'), + (strpos($host, '.') !== false ? '.' . ltrim($host, '.') : $host), + ])); + + // Alle Varianten invalidieren (secure/httponly wie gesetzt) + foreach ($paths as $p) { + foreach ($domains as $d) { + if ($d === null) continue; + setcookie($name, '', time() - 3600, $p, $d, $params['secure'] ?? true, $params['httponly'] ?? true); + } + // zusätzlich: ohne Domain (trifft Host-spezifische Cookies) + setcookie($name, '', time() - 3600, $p, '', $params['secure'] ?? true, $params['httponly'] ?? true); + } + + // Session beenden + session_destroy(); + session_write_close(); + + // In Staging aggressiv: Browser bitten, Cookies zu löschen (nicht jeder Browser respektiert das sofort) + if (($cfg['env'] ?? 'prod') === 'staging') { + header('Clear-Site-Data: "cookies"', false); + } +} + +function auth_require(array $cfg): void { + auth_start_session($cfg); + if (empty($_SESSION['user'])) { + http_response_code(401); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['ok' => false, 'error' => 'unauthorized']); + exit; + } +} + +function require_role(array $cfg, array $roles): void { + auth_start_session($cfg); + $r = $_SESSION['user']['role'] ?? null; + if (!$r || !in_array($r, $roles, true)) { + http_response_code(403); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode(['ok' => false, 'error' => 'forbidden']); + exit; + } +} + +function current_user(array $cfg): ?array { + auth_start_session($cfg); + return $_SESSION['user'] ?? null; +} + +function current_customer_id(array $cfg): ?int { + $u = current_user($cfg); + return $u['customer_id'] ?? null; +} + diff --git a/inc/OUTDATED bootstrap.php b/inc/OUTDATED bootstrap.php new file mode 100644 index 0000000..6a6c05c --- /dev/null +++ b/inc/OUTDATED bootstrap.php @@ -0,0 +1,232 @@ +false,'error'=>$msg,'detail'=>$detail], $code); +} + +// RESTLICHE HELFER (MÜSSEN KEINE GLOBALS VERWENDEN) +function load_config(): array { + $paths = [ + __DIR__ . '/config.php', + __DIR__ . '/../config.php', + __DIR__ . '/../../config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + fail('Invalid config.php', 'config.php not found or not returning array', 500); +} + +function cors(array $conf): void { + $cors = $conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); +} + +function get_input(): array { + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k=>$v) $data[$k]=$v; + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + return $data; +} + +function val(array $in, $keys, $default=null) { + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + return $default; +} + +function first_existing(array $columns, array $candidates): ?string { + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; +} + +function pdo_templates(array $conf): PDO { + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + fail('Missing templates DB config', null, 500); + } + $c = $conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); +} + +function table_columns(PDO $pdo, string $table): array { + $cols = []; + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; +} + +function primary_key(PDO $pdo, string $table): ?string { + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; +} + + +// --- Neue, reguläre Funktionen (ersetzen Closures) --- + +function requireAuth(): array { + // Muss auf globale $_SESSION zugreifen + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + return $_SESSION['auth']; +} + +function pullId(array $src) { + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; +} + +function tenantWhere(array $session): array { + // Muss auf globale $conf zugreifen, um $tenantCol und $mapSess zu erhalten + global $conf; + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val===null || $val==='') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; +} + +function tenantAssign(array $session, array $columns): array { + // Muss auf globale $conf zugreifen + global $conf; + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; +} + +function resolveIdCol(string $kind): array { + // Muss auf globale $conf, $pdo, und $tableMap zugreifen + global $conf, $pdo, $tableMap; + + $t = $tableMap[$kind]; + $cfg = $conf['columns'][$kind] ?? []; + $cols = table_columns($pdo, $t); + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + if (!$idCol) $idCol = 'id'; + return [$idCol, $cols]; +} + +// --- Haupt-Setup-Logik (Setzt die globalen Variablen) --- + +try { + // Deklariere alle Variablen, die im Router von api.php benötigt werden, als global + global $conf, $pdo, $in, $action, $tableMap; + + // 1. Globale Konfiguration und CORS + $conf = load_config(); + cors($conf); + + // 2. Cookie-Parameter setzen + if (!empty($conf['auth']['cookie'])) { + $c = $conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + + // 3. Input-Daten abrufen + $in = get_input(); + + // 4. Datenbankverbindung herstellen + $pdo = pdo_templates($conf); + + // 5. Action / Resource auflösen + $action = val($in, 'action', ''); + $resource = val($in, 'resource', null); + $allowedResources = ['templates','sections','blocks','snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + } + + // 6. Tabellenzuweisungen + $tables = $conf['tables'] ?? []; + $tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + +} catch (Throwable $e) { + // Fehler während der Initialisierung abfangen + fail('Initialization error', get_class($e).': '.$e->getMessage(), 500); +} diff --git a/inc/OUTDATED config.example.php b/inc/OUTDATED config.example.php new file mode 100644 index 0000000..a990df8 --- /dev/null +++ b/inc/OUTDATED config.example.php @@ -0,0 +1,36 @@ + [ + 'db_host' => '127.0.0.1', + 'db_port' => 3306, + 'db_name' => 'YOUR_DB_NAME', + 'db_user' => 'YOUR_DB_USER', + 'db_pass' => 'YOUR_DB_PASS', + 'db_charset' => 'utf8mb4', + 'prefix' => 'emailtemplate_', + ], + 'project' => [ + 'db_host' => '127.0.0.1', + 'db_port' => 3306, + 'db_name' => 'YOUR_PROJECT_DB', + 'db_user' => 'YOUR_PROJECT_USER', + 'db_pass' => 'YOUR_PROJECT_PASS', + 'db_charset' => 'utf8mb4', + ], + + // SMTP / Testversand + 'smtp' => [ + 'host' => getenv('SMTP_HOST') ?: '', + 'port' => getenv('SMTP_PORT') ?: 587, + 'user' => getenv('SMTP_USER') ?: '', + 'pass' => getenv('SMTP_PASS') ?: '', + 'secure' => getenv('SMTP_SECURE') ?: 'tls', + 'from_email' => getenv('SMTP_FROM_EMAIL') ?: 'no-reply@example.com', + 'from_name' => getenv('SMTP_FROM_NAME') ?: 'EmailTemplate', + ], + + // Export-API: statische API-Keys + 'export' => [ + 'api_keys' => explode(',', getenv('EXPORT_API_KEYS') ?: 'dev-key-123'), + ], +]; diff --git a/inc/api_kernel_log.txt b/inc/api_kernel_log.txt new file mode 100644 index 0000000..21abd13 --- /dev/null +++ b/inc/api_kernel_log.txt @@ -0,0 +1,259 @@ + + + +[2025-10-31 01:21:54] --- Get::blocks - Raw JSON from DB --- +Array +( + [topContent] => {"dataSources":[],"assets":[],"styles":[{"selectors":[],"selectorsAdd":"*","style":{"box-sizing":"border-box"}},{"selectors":[],"selectorsAdd":"body","style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"}}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"components":[{"type":"library-reference","content":"Alles Neu macht der Mai","lib-kind":"snippets","lib-id":1}],"head":{"type":"head"},"docEl":{"tagName":"html"}},"id":"P4uy9DBKbT5yTO4c"}],"type":"main","id":"dJ5hyxgFUxsCWgbi"}],"symbols":[]} +) + + +[2025-10-31 01:21:54] --- Get::blocks - Decoded JSON --- +Array +( + [decodedContent] => Array + ( + [dataSources] => Array + ( + ) + + [assets] => Array + ( + ) + + [styles] => Array + ( + [0] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => * + [style] => Array + ( + [box-sizing] => border-box + ) + + ) + + [1] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => body + [style] => Array + ( + [margin-top] => 0px + [margin-right] => 0px + [margin-bottom] => 0px + [margin-left] => 0px + ) + + ) + + ) + + [pages] => Array + ( + [0] => Array + ( + [frames] => Array + ( + [0] => Array + ( + [component] => Array + ( + [type] => wrapper + [stylable] => Array + ( + [0] => background + [1] => background-color + [2] => background-image + [3] => background-repeat + [4] => background-attachment + [5] => background-position + [6] => background-size + ) + + [components] => Array + ( + [0] => Array + ( + [type] => library-reference + [content] => Alles Neu macht der Mai + [lib-kind] => snippets + [lib-id] => 1 + ) + + ) + + [head] => Array + ( + [type] => head + ) + + [docEl] => Array + ( + [tagName] => html + ) + + ) + + [id] => P4uy9DBKbT5yTO4c + ) + + ) + + [type] => main + [id] => dJ5hyxgFUxsCWgbi + ) + + ) + + [symbols] => Array + ( + ) + + ) + +) + + +[2025-10-31 01:21:54] --- Get::blocks - Final Gjs Components --- +Array +( + [count] => 5 + [first_component] => N/A +) + + +[2025-10-31 01:21:54] --- Get::blocks - Raw JSON from DB --- +Array +( + [topContent] => {"dataSources":[],"assets":[],"styles":[{"selectors":[],"selectorsAdd":"*","style":{"box-sizing":"border-box"}},{"selectors":[],"selectorsAdd":"body","style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"}}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"components":[{"type":"library-reference","content":"Alles Neu macht der Mai","lib-kind":"snippets","lib-id":1}],"head":{"type":"head"},"docEl":{"tagName":"html"}},"id":"P4uy9DBKbT5yTO4c"}],"type":"main","id":"dJ5hyxgFUxsCWgbi"}],"symbols":[]} +) + + +[2025-10-31 01:21:54] --- Get::blocks - Decoded JSON --- +Array +( + [decodedContent] => Array + ( + [dataSources] => Array + ( + ) + + [assets] => Array + ( + ) + + [styles] => Array + ( + [0] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => * + [style] => Array + ( + [box-sizing] => border-box + ) + + ) + + [1] => Array + ( + [selectors] => Array + ( + ) + + [selectorsAdd] => body + [style] => Array + ( + [margin-top] => 0px + [margin-right] => 0px + [margin-bottom] => 0px + [margin-left] => 0px + ) + + ) + + ) + + [pages] => Array + ( + [0] => Array + ( + [frames] => Array + ( + [0] => Array + ( + [component] => Array + ( + [type] => wrapper + [stylable] => Array + ( + [0] => background + [1] => background-color + [2] => background-image + [3] => background-repeat + [4] => background-attachment + [5] => background-position + [6] => background-size + ) + + [components] => Array + ( + [0] => Array + ( + [type] => library-reference + [content] => Alles Neu macht der Mai + [lib-kind] => snippets + [lib-id] => 1 + ) + + ) + + [head] => Array + ( + [type] => head + ) + + [docEl] => Array + ( + [tagName] => html + ) + + ) + + [id] => P4uy9DBKbT5yTO4c + ) + + ) + + [type] => main + [id] => dJ5hyxgFUxsCWgbi + ) + + ) + + [symbols] => Array + ( + ) + + ) + +) + + +[2025-10-31 01:21:54] --- Get::blocks - Final Gjs Components --- +Array +( + [count] => 5 + [first_component] => N/A +) diff --git a/inc/config.php b/inc/config.php new file mode 100644 index 0000000..3f2ed05 --- /dev/null +++ b/inc/config.php @@ -0,0 +1,76 @@ + [ + 'db_host' => getenv('DB_TPL_HOST') ?: 'localhost', + 'db_name' => getenv('DB_TPL_NAME') ?: 'd044ae9e', + 'db_user' => getenv('DB_TPL_USER') ?: 'd044ae9e', + 'db_pass' => getenv('DB_TPL_PASS') ?: '9BVUn)Töcü@ÖVÜfgO8!J', + 'db_charset' => 'utf8', + 'prefix' => getenv('DB_TPL_PREFIX') ?: 'emailtemplate_', + + ], + 'project' => [ + 'db_host' => getenv('DB_TPL_HOST') ?: 'w0207fd0.kasserver.com', + 'db_name' => getenv('DB_TPL_NAME') ?: 'd0444c25', + 'db_user' => getenv('DB_TPL_USER') ?: 'd0444c25', + 'db_pass' => getenv('DB_TPL_PASS') ?: '/7ü9+§ÄfkiQvGPr§2Op7', + 'db_charset' => 'utf8', + ], + 'cors' => getenv('CORS_ORIGIN') ?: '*', + 'env' => 'staging', + 'base_url' => 'https://staging.emailtemplate.it', + 'auth' => [ + 'session_name' => 'et_session', + 'cookie_domain' => 'staging.emailtemplate.it', + 'cookie_secure' => true, + 'cookie_httponly'=> true, + 'cookie_samesite'=> 'Lax', + 'db' => [ + 'table' => 'customer_users', + 'col_user' => 'email', // alternativ: 'username' + 'col_pass' => 'password_hash', + 'col_name' => 'name', // optional + 'col_id' => 'id', // optional + 'col_status' => 'is_active', // optional + 'active_values'=> ['active','1',1], // optional + 'legacy' => 'md5' // optional: 'md5' | 'sha1' | 'plain' (sonst bcrypt/argon2) + ], + + ], +'smtp' => [ + 'host' => 'smtp.example.com', + 'port' => 587, + 'user' => 'smtp-user', + 'pass' => 'smtp-pass', + 'secure' => 'tls', // oder 'ssl' + 'from_email' => 'no-reply@example.com', + 'from_name' => 'EmailTemplate', +], +'export' => [ + 'api_keys' => ['dev-key-123', 'noch-ein-key'], // füge hier deine Keys ein +], + 'multi' => [ + // Spalte in ALLEN Content-Tabellen, die dem Besitzer/Mandanten entspricht: + 'tenant_col' => 'customer_id', // <— falls es bei dir z. B. 'owner_id' heißt: entsprechend anpassen. + // Welche Session-Info darauf gemappt wird: + 'map_session_to' => 'id', // 'id' (Default) | 'email' | 'name' + ], + + // optional: abweichende Tabellennamen/Spalten: + 'tables' => [ + 'templates' => 'emailtemplate_templates', + 'sections' => 'emailtemplate_sections', + 'blocks' => 'emailtemplate_blocks', + 'snippets' => 'emailtemplate_snippets', + ], + 'columns' => [ + // Nur anpassen, wenn deine Spaltennamen abweichen + 'templates' => ['id'=>'id','name'=>'name','desc'=>null,'cat'=>null,'upd'=>'updated_at'], + 'sections' => ['id'=>'id','name'=>'name','cat'=>null,'upd'=>'updated_at'], + 'blocks' => ['id'=>'id','name'=>'name','cat'=>'category','upd'=>'updated_at'], + 'snippets' => ['id'=>'id','name'=>'name','cat'=>'category','upd'=>'updated_at'], + ], +]; + diff --git a/public/api (Kopie).php b/public/api (Kopie).php new file mode 100644 index 0000000..60e81b1 --- /dev/null +++ b/public/api (Kopie).php @@ -0,0 +1,525 @@ +false,'error'=>$msg,'detail'=>$detail], $code); +} + +function load_config(): array { + $paths = [ + __DIR__ . '/../inc/config.php', + __DIR__ . '/inc/config.php', + __DIR__ . '/config.php', + ]; + + foreach ($paths as $p) { + if (is_file($p)) { + $conf = @include $p; + if (is_array($conf)) return $conf; + } + } + fail('Invalid config.php', 'config.php not found or not returning array', 500); +} + +function cors(array $conf): void { + $cors = $conf['cors'] ?? '*'; + if ($cors) { + header('Access-Control-Allow-Origin: ' . $cors); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + header('Access-Control-Allow-Credentials: true'); + } + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); +} + +function get_input(): array { + $data = []; + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + if (stripos($ct, 'application/json') !== false) { + $raw = file_get_contents('php://input'); + if ($raw !== false && $raw !== '') { + $js = json_decode($raw, true); + if (is_array($js)) $data = $js; + } + } + foreach ($_POST as $k=>$v) $data[$k]=$v; + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + return $data; +} + +function val(array $in, $keys, $default=null) { + if (!is_array($keys)) $keys = [$keys]; + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + return $default; +} + +/** + * Inline-Styling für E-Mail-Templates (nutzt TijsVerkoyen/CssToInlineStyles) + * + * Diese Funktion steht nur bereit, wird aber noch nicht verwendet. + * @param string $html + * @param string|null $css + * @return string + */ +function inline_css(string $html, ?string $css = null): string { + // 1. Klasse existiert nicht + if (!class_exists('\TijsVerkoyen\CssToInlineStyles\CssToInlineStyles')) { + return $html; + } + + // 2. Direkte Instanziierung und Aufruf in einer einzigen Zeile + $result = (new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($html, $css))->convert(); + + return $result; +} + +/* ===================== DB helpers ===================== */ +function pdo_templates(array $conf): PDO { + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + fail('Missing templates DB config', null, 500); + } + $c = $conf['templates']; + $host = $c['db_host'] ?? 'localhost'; + $db = $c['db_name'] ?? ($c['database'] ?? ''); + $user = $c['db_user'] ?? ($c['username'] ?? ''); + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + $charset = $c['db_charset'] ?? 'utf8mb4'; + $port = $c['db_port'] ?? 3306; + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + $opt = [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]; + return new PDO($dsn, $user, $pass, $opt); +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + $legacy = strtolower($authDbConf['legacy'] ?? ''); + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + if ($legacy === 'plain')return hash_equals($stored, $input); + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + return hash_equals($stored, $input); +} + +/* ============ schema helpers ============ */ +function table_columns(PDO $pdo, string $table): array { + $cols = []; + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + return $cols; +} + +function primary_key(PDO $pdo, string $table): ?string { + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['Column_name'] ?? null; +} + +function first_existing(array $columns, array $candidates): ?string { + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + return null; +} + +/* ===================== Boot ===================== */ +try { + $conf = load_config(); + cors($conf); + // if (session_status() === PHP_SESSION_NONE) session_start(); + if (!empty($conf['auth']['cookie'])) { + $c = $conf['auth']['cookie']; + $params = session_get_cookie_params(); + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + $params['path'] = $c['path'] ?? $params['path']; + $params['domain'] = $c['domain'] ?? $params['domain']; + $params['secure'] = $c['secure'] ?? $params['secure']; + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + session_set_cookie_params($params); + } + + $in = get_input(); + + /* ---- Compat: ?resource=blocks&action=list -> blocks.list ---- */ + $action = val($in, 'action', ''); + $resource = val($in, 'resource', null); + $allowedResources = ['templates','sections','blocks','snippets']; + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + $verb = strtolower((string)$action); + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + } + + /* ---- Multi-tenant ---- */ + $multi = $conf['multi'] ?? []; + $tenantCol = $multi['tenant_col'] ?? null; + $mapSess = $multi['map_session_to'] ?? 'id'; // 'id'|'email'|'name' + + $tenantWhere = function(array $session) use ($tenantCol, $mapSess) { + if (!$tenantCol) return ['', []]; + if (!$session) return [' AND 1=0 ', []]; + $val = $session[$mapSess] ?? null; + if ($val===null || $val==='') return [' AND 1=0 ', []]; + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; + }; + + $tenantAssign = function(array $session, array $columns) use ($tenantCol, $mapSess) { + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + $val = $session[$mapSess] ?? null; + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; + }; + + $requireAuth = function() { + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + return $_SESSION['auth']; + }; + + /* ---- config tables/columns ---- */ + $tables = $conf['tables'] ?? []; + $tableMap = [ + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + ]; + + $colsDefault = [ + 'id' => 'id', + 'name' => 'name', + 'desc' => 'description', + 'cat' => 'category', + 'upd' => 'updated_at', + ]; + + $pdo = pdo_templates($conf); + + /* helper: resolve id column for a table */ + $resolveIdCol = function(string $kind) use ($conf, $colsDefault, $tableMap, $pdo) { + $t = $tableMap[$kind]; + $cfg = $conf['columns'][$kind] ?? []; + $cols = table_columns($pdo, $t); + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + if (!$idCol) $idCol = 'id'; // fallback + return [$idCol, $cols]; + }; + + /* helper: accept many id aliases */ + $pullId = function(array $src) { + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + return null; + }; + + /* ===================== Router ===================== */ + switch ($action) { + case 'health': + respond(['ok'=>true,'time'=>date('c')]); + + /* ---------- AUTH ---------- */ + case 'auth.login': { + $identifier = trim((string)val($in, ['username','user','email','login'], '')); + $password = (string)val($in, ['password','pass','pwd'], ''); + if ($identifier === '' || $password === '') fail('username/password required', null, 422); + $authDb = $conf['auth']['db'] ?? []; + $table = $authDb['table'] ?? 'emailtemplate_users'; + $colUser = $authDb['col_user'] ?? 'email'; + $colPass = $authDb['col_pass'] ?? 'password'; + $colName = $authDb['col_name'] ?? 'name'; + $colId = $authDb['col_id'] ?? 'id'; + $colStatus = $authDb['col_status']?? null; + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + + $stmt = $pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + + $stmt->execute([':u'=>$identifier]); + $row = $stmt->fetch(); + if (!$row) fail('Invalid credentials', null, 401); + if ($colStatus && isset($row[$colStatus])) { + if (!in_array($row[$colStatus], $activeValues, true)) { + fail('Account inactive', null, 403); + } + } + + $stored = (string)($row[$colPass] ?? ''); + if ($stored === '' || !verify_password($password, $stored, $authDb)) { + fail('Invalid credentials', null, 401); + } + + $_SESSION['auth'] = [ + 'id' => $row[$colId] ?? null, + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + 'email' => $row[$colUser] ?? $identifier, + 'at' => time(), + ]; + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + respond(['ok'=>true,'user'=>$_SESSION['auth'],'token'=>$token]); + } + + case 'auth.me': + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + respond(['ok'=>true,'user'=>$_SESSION['auth']]); + case 'auth.logout': + $_SESSION = []; + if (session_id() !== '') session_destroy(); + + respond(['ok'=>true]); + + /* ---------- LIST (mit Parent-Filtern) ---------- */ + case 'templates.list': + case 'sections.list': + case 'blocks.list': + case 'snippets.list': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $q = trim((string)val($in,'q','')); + $limit = max(1, (int)val($in,'limit', 500)); + $offset = max(0, (int)val($in,'offset',0)); + $where = ' WHERE 1=1 '; + $params = []; + if ($q !== '') { + $parts = ["`$nameCol` LIKE :q"]; + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + $where .= " AND (".implode(' OR ', $parts).") "; + $params[':q'] = '%'.$q.'%'; + } + + // Parent-Filtern (falls Spalten existieren) + $parentFilters = [ + 'template_id' => val($in, ['template_id','tpl_id'], null), + 'section_id' => val($in, ['section_id','sec_id'], null), + 'block_id' => val($in, ['block_id','blk_id'], null), + ]; + foreach ($parentFilters as $col => $v) { + if ($v === null || $v === '') continue; + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + } + + // Mandant + [$tw,$tp] = $tenantWhere($auth); + $where .= $tw; foreach ($tp as $k=>$v) $params[$k]=$v; + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + $stmt = $pdo->prepare($sql); + foreach ($params as $k=>$v) $stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR); + $stmt->bindValue(':off',$offset,PDO::PARAM_INT); + $stmt->bindValue(':lim',$limit,PDO::PARAM_INT); + $stmt->execute(); + $rows = $stmt->fetchAll(); + + $out = []; + foreach ($rows as $r) { + $item = [ + 'id' => $r[$idCol] ?? null, + 'name' => $r[$nameCol] ?? null, + ]; + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + $out[] = $item; + } + respond(['ok'=>true,'kind'=>$kind,'items'=>$out,'data'=>$out,'count'=>count($out),'offset'=>$offset,'limit'=>$limit]); + } + + /* ---------- GET (JETZT mit top-level html/content) ---------- */ + case 'templates.get': + case 'sections.get': + case 'blocks.get': + case 'snippets.get': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + $stmt->bindValue(':id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + $row = $stmt->fetch(); + if (!$row) fail('Not found', ['kind'=>$kind,'id'=>$id], 404); + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + // NEU: Spalten für HTML/JSON erkennen und top-level ausgeben + $htmlCol = first_existing($allCols, ['html','body','markup']); + $jsonCol = first_existing($allCols, ['content_json','json','content','structure_json']); + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + respond([ + 'ok'=>true, + 'kind'=>$kind, + 'id'=>$rowOut['id'], + 'item'=>$rowOut, + 'data'=>$rowOut, + 'html'=>$topHtml, // <— wichtig für Vorschau + 'content'=>$topContent // optional (z. B. GrapesJS JSON) + ]); + } + + /* ---------- CREATE ---------- */ + case 'templates.create': + case 'sections.create': + case 'blocks.create': + case 'snippets.create': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $name = trim((string)val($in, ['name','title'], '')); + if ($name === '') fail('name required', null, 422); + $desc = (string)val($in, ['description','desc'], null); + $cat = (string)val($in, ['category','cat'], null); + $html = (string)val($in, ['html','body','markup'], null); + $json = val($in, ['content_json','json','content','structure_json'], null); + $settings = val($in, ['settings_json','settings'], null); + $templateId = val($in, ['template_id','tpl_id'], null); + $sectionId = val($in, ['section_id','sec_id'], null); + $blockId = val($in, ['block_id','blk_id'], null); + $data = [ $nameCol => $name ]; + if ($desc !== null && $descCol) $data[$descCol] = $desc; + if ($cat !== null && $catCol) $data[$catCol] = $cat; + $c = first_existing($allCols, ['html','body','markup']); if ($c && $html !== null) $data[$c]=$html; + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($c && $json !== null) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $c = first_existing($allCols, ['settings_json','settings']); if ($c && $settings !== null) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + if ($templateId !== null && in_array('template_id',$allCols,true)) $data['template_id']=$templateId; + if ($sectionId !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sectionId; + if ($blockId !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blockId; + $data = $data + $tenantAssign($_SESSION['auth'] ?? [], $allCols); + $now = date('Y-m-d H:i:s'); + $createdCol = first_existing($allCols, ['created_at','created','createdAt']); + if ($createdCol) $data[$createdCol] = $now; + if ($updCol) $data[$updCol] = $now; + $fields = array_keys($data); + $place = array_map(fn($c)=>":$c", $fields); + $sql = "INSERT INTO `$t` (".implode(',', array_map(fn($c)=>"`$c`",$fields)).") VALUES (".implode(',', $place).")"; + $stmt = $pdo->prepare($sql); + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + $stmt->execute(); + $newId = $pdo->lastInsertId(); + $out = ['id'=>$newId,'name'=>$name]; + if ($desc !== null) $out['desc']=$desc; + if ($cat !== null) $out['category']=$cat; + respond(['ok'=>true,'kind'=>$kind,'id'=>$newId,'item'=>$out,'data'=>$out]); + } + + /* ---------- UPDATE ---------- */ + case 'templates.update': + case 'sections.update': + case 'blocks.update': + case 'snippets.update': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $cfg = $conf['columns'][$kind] ?? []; + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + $data = []; + $name = val($in, ['name','title'], null); + $desc = val($in, ['description','desc'], null); + $cat = val($in, ['category','cat'], null); + $html = val($in, ['html','body','markup'], null); + $json = val($in, ['content_json','json','content','structure_json'], null); + $settings = val($in, ['settings_json','settings'], null); + if ($name !== null) $data[$nameCol] = (string)$name; + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + $c = first_existing($allCols, ['html','body','markup']); if ($html !== null && $c) $data[$c]=(string)$html; + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($json !== null && $c) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $c = first_existing($allCols, ['settings_json','settings']); if ($settings !== null && $c) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + $tpl = val($in, ['template_id','tpl_id'], null); if ($tpl !== null && in_array('template_id',$allCols,true)) $data['template_id']=$tpl; + $sec = val($in, ['section_id','sec_id'], null); if ($sec !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sec; + $blk = val($in, ['block_id','blk_id'], null); if ($blk !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blk; + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + if (!$data) fail('nothing to update', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $set = []; foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + $sql = "UPDATE `$t` SET ".implode(',',$set)." WHERE `$idCol` = :__id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'updated'=>array_keys($data)]); + } + + /* ---------- DELETE ---------- */ + case 'templates.delete': + case 'sections.delete': + case 'blocks.delete': + case 'snippets.delete': { + $auth = $requireAuth(); + $kind = explode('.', $action)[0]; + $t = $tableMap[$kind]; + [$idCol, $allCols] = $resolveIdCol($kind); + $id = $pullId($in); + if ($id === null || $id === '') fail('id required', null, 422); + [$tw,$tp] = $tenantWhere($auth); + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id".$tw." LIMIT 1"; + $stmt = $pdo->prepare($sql); + $stmt->bindValue(':__id', $id); + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + $stmt->execute(); + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'deleted'=>true]); + } + + /* ---------- Platzhalter für kommende Features ---------- */ + case 'render.preview': + fail('Not implemented', 'Preview wird im Feature-Patch geliefert', 501); + case 'templates.test_send': + fail('Not implemented', 'Testversand wird im Feature-Patch geliefert', 501); + case 'export.render': + fail('Not implemented', 'Export-API wird im Feature-Patch geliefert', 501); + default: + fail('Unknown action', $action ?: 'missing', 404); + } +} catch (Throwable $e) { + fail('Server error', get_class($e).': '.$e->getMessage(), 500); +} diff --git a/public/api-original.php b/public/api-original.php new file mode 100644 index 0000000..cfb6653 --- /dev/null +++ b/public/api-original.php @@ -0,0 +1,1017 @@ +false,'error'=>$msg,'detail'=>$detail], $code); + +} + +function load_config(): array { + + $paths = [ + + __DIR__ . '/../inc/config.php', + + __DIR__ . '/inc/config.php', + + __DIR__ . '/config.php', + + ]; + + foreach ($paths as $p) { + + if (is_file($p)) { + + $conf = @include $p; + + if (is_array($conf)) return $conf; + + } + + } + + fail('Invalid config.php', 'config.php not found or not returning array', 500); + +} + +function cors(array $conf): void { + + $cors = $conf['cors'] ?? '*'; + + if ($cors) { + + header('Access-Control-Allow-Origin: ' . $cors); + + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + + header('Access-Control-Allow-Headers: Content-Type, Authorization'); + + header('Access-Control-Allow-Credentials: true'); + + } + + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') respond(['ok'=>true]); + +} + +function get_input(): array { + + $data = []; + + $ct = $_SERVER['CONTENT_TYPE'] ?? ''; + + if (stripos($ct, 'application/json') !== false) { + + $raw = file_get_contents('php://input'); + + if ($raw !== false && $raw !== '') { + + $js = json_decode($raw, true); + + if (is_array($js)) $data = $js; + + } + + } + + foreach ($_POST as $k=>$v) $data[$k]=$v; + + foreach ($_GET as $k=>$v) if (!array_key_exists($k,$data)) $data[$k]=$v; + + return $data; + +} + +function val(array $in, $keys, $default=null) { + + if (!is_array($keys)) $keys = [$keys]; + + foreach ($keys as $k) if (array_key_exists($k,$in)) return $in[$k]; + + return $default; + +} + + + +/* ===================== DB helpers ===================== */ + +function pdo_templates(array $conf): PDO { + + if (!isset($conf['templates']) || !is_array($conf['templates'])) { + + fail('Missing templates DB config', null, 500); + + } + + $c = $conf['templates']; + + $host = $c['db_host'] ?? 'localhost'; + + $db = $c['db_name'] ?? ($c['database'] ?? ''); + + $user = $c['db_user'] ?? ($c['username'] ?? ''); + + $pass = $c['db_pass'] ?? ($c['password'] ?? ''); + + $charset = $c['db_charset'] ?? 'utf8mb4'; + + $port = $c['db_port'] ?? 3306; + + $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; + + $opt = [ + + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + + ]; + + return new PDO($dsn, $user, $pass, $opt); + +} + +function verify_password(string $input, string $stored, array $authDbConf): bool { + + if (preg_match('~^\$2[aby]\$~', $stored) || strpos($stored, '$argon2') === 0) return password_verify($input, $stored); + + $legacy = strtolower($authDbConf['legacy'] ?? ''); + + if ($legacy === 'md5') return hash_equals($stored, md5($input)); + + if ($legacy === 'sha1') return hash_equals($stored, sha1($input)); + + if ($legacy === 'plain')return hash_equals($stored, $input); + + if (password_get_info($stored)['algo'] !== 0) return password_verify($input, $stored); + + return hash_equals($stored, $input); + +} + + + +/* ============ schema helpers ============ */ + +function table_columns(PDO $pdo, string $table): array { + + $cols = []; + + $stmt = $pdo->query("SHOW COLUMNS FROM `$table`"); + + foreach ($stmt->fetchAll() as $r) $cols[] = $r['Field']; + + return $cols; + +} + +function primary_key(PDO $pdo, string $table): ?string { + + $stmt = $pdo->prepare("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'"); + + $stmt->execute(); + + $row = $stmt->fetch(); + + return $row['Column_name'] ?? null; + +} + +function first_existing(array $columns, array $candidates): ?string { + + foreach ($candidates as $c) if (in_array($c, $columns, true)) return $c; + + return null; + +} + + + +/* ===================== Boot ===================== */ + +try { + + $conf = load_config(); + + cors($conf); + + if (session_status() === PHP_SESSION_NONE) session_start(); + + if (!empty($conf['auth']['cookie'])) { + + $c = $conf['auth']['cookie']; + + $params = session_get_cookie_params(); + + $params['lifetime'] = $c['lifetime'] ?? $params['lifetime']; + + $params['path'] = $c['path'] ?? $params['path']; + + $params['domain'] = $c['domain'] ?? $params['domain']; + + $params['secure'] = $c['secure'] ?? $params['secure']; + + $params['httponly'] = $c['httponly'] ?? $params['httponly']; + + if (isset($c['samesite'])) $params['samesite'] = $c['samesite']; + + session_set_cookie_params($params); + + } + + + + $in = get_input(); + + + + /* ---- Compat: ?resource=blocks&action=list -> blocks.list ---- */ + + $action = val($in, 'action', ''); + + $resource = val($in, 'resource', null); + + $allowedResources = ['templates','sections','blocks','snippets']; + + if ($resource && in_array($resource, $allowedResources, true) && strpos((string)$action, '.') === false) { + + $verb = strtolower((string)$action); + + if (in_array($verb, ['list','get','create','update','delete'], true)) $action = $resource.'.'.$verb; + + } + + + + /* ---- Multi-tenant ---- */ + + $multi = $conf['multi'] ?? []; + + $tenantCol = $multi['tenant_col'] ?? null; + + $mapSess = $multi['map_session_to'] ?? 'id'; // 'id'|'email'|'name' + + + + $tenantWhere = function(array $session) use ($tenantCol, $mapSess) { + + if (!$tenantCol) return ['', []]; + + if (!$session) return [' AND 1=0 ', []]; + + $val = $session[$mapSess] ?? null; + + if ($val===null || $val==='') return [' AND 1=0 ', []]; + + return [" AND `$tenantCol` = :__tenant", [':__tenant'=>$val]]; + + }; + + $tenantAssign = function(array $session, array $columns) use ($tenantCol, $mapSess) { + + if (!$tenantCol || !in_array($tenantCol, $columns, true)) return []; + + $val = $session[$mapSess] ?? null; + + return ($val===null || $val==='') ? [] : [$tenantCol => $val]; + + }; + + $requireAuth = function() { + + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + + return $_SESSION['auth']; + + }; + + + + /* ---- config tables/columns ---- */ + + $tables = $conf['tables'] ?? []; + + $tableMap = [ + + 'templates' => $tables['templates'] ?? 'emailtemplate_templates', + + 'sections' => $tables['sections'] ?? 'emailtemplate_sections', + + 'blocks' => $tables['blocks'] ?? 'emailtemplate_blocks', + + 'snippets' => $tables['snippets'] ?? 'emailtemplate_snippets', + + ]; + + $colsDefault = [ + + 'id' => 'id', + + 'name' => 'name', + + 'desc' => 'description', + + 'cat' => 'category', + + 'upd' => 'updated_at', + + ]; + + + + $pdo = pdo_templates($conf); + + + + /* helper: resolve id column for a table */ + + $resolveIdCol = function(string $kind) use ($conf, $colsDefault, $tableMap, $pdo) { + + $t = $tableMap[$kind]; + + $cfg = $conf['columns'][$kind] ?? []; + + $cols = table_columns($pdo, $t); + + $idCol = $cfg['id'] ?? (in_array('id', $cols, true) ? 'id' : primary_key($pdo, $t)); + + if (!$idCol) $idCol = 'id'; // fallback + + return [$idCol, $cols]; + + }; + + + + /* helper: accept many id aliases */ + + $pullId = function(array $src) { + + $aliases = ['id','item_id','template_id','tpl_id','section_id','sec_id','block_id','blk_id','snippet_id','snip_id']; + + foreach ($aliases as $a) if (isset($src[$a]) && $src[$a] !== '') return $src[$a]; + + return null; + + }; + + + + /* ===================== Router ===================== */ + + switch ($action) { + + case 'health': + + respond(['ok'=>true,'time'=>date('c')]); + + + + /* ---------- AUTH ---------- */ + + case 'auth.login': { + + $identifier = trim((string)val($in, ['username','user','email','login'], '')); + + $password = (string)val($in, ['password','pass','pwd'], ''); + + if ($identifier === '' || $password === '') fail('username/password required', null, 422); + + + + $authDb = $conf['auth']['db'] ?? []; + + $table = $authDb['table'] ?? 'emailtemplate_users'; + + $colUser = $authDb['col_user'] ?? 'email'; + + $colPass = $authDb['col_pass'] ?? 'password'; + + $colName = $authDb['col_name'] ?? 'name'; + + $colId = $authDb['col_id'] ?? 'id'; + + $colStatus = $authDb['col_status']?? null; + + $activeValues = $authDb['active_values'] ?? ['active','1',1]; + + + + $stmt = $pdo->prepare("SELECT * FROM `$table` WHERE `$colUser` = :u LIMIT 1"); + + $stmt->execute([':u'=>$identifier]); + + $row = $stmt->fetch(); + + if (!$row) fail('Invalid credentials', null, 401); + + + + if ($colStatus && isset($row[$colStatus])) { + + if (!in_array($row[$colStatus], $activeValues, true)) { + + fail('Account inactive', null, 403); + + } + + } + + + + $stored = (string)($row[$colPass] ?? ''); + + if ($stored === '' || !verify_password($password, $stored, $authDb)) { + + fail('Invalid credentials', null, 401); + + } + + + + $_SESSION['auth'] = [ + + 'id' => $row[$colId] ?? null, + + 'name' => $row[$colName] ?? ($row[$colUser] ?? $identifier), + + 'email' => $row[$colUser] ?? $identifier, + + 'at' => time(), + + ]; + + $token = base64_encode(hash('sha256', ($_SESSION['auth']['id'] ?? $identifier).'|'.session_id(), true)); + + respond(['ok'=>true,'user'=>$_SESSION['auth'],'token'=>$token]); + + } + + + + case 'auth.me': + + if (empty($_SESSION['auth'])) fail('Not authenticated', null, 401); + + respond(['ok'=>true,'user'=>$_SESSION['auth']]); + + + + case 'auth.logout': + + $_SESSION = []; + + if (session_id() !== '') session_destroy(); + + respond(['ok'=>true]); + + + + /* ---------- LIST (mit Parent-Filtern) ---------- */ + + case 'templates.list': + + case 'sections.list': + + case 'blocks.list': + + case 'snippets.list': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $q = trim((string)val($in,'q','')); + + $limit = max(1, (int)val($in,'limit', 500)); + + $offset = max(0, (int)val($in,'offset',0)); + + + + $where = ' WHERE 1=1 '; + + $params = []; + + + + if ($q !== '') { + + $parts = ["`$nameCol` LIKE :q"]; + + if ($descCol) $parts[] = "`$descCol` LIKE :q"; + + if ($catCol) $parts[] = "`$catCol` LIKE :q"; + + $where .= " AND (".implode(' OR ', $parts).") "; + + $params[':q'] = '%'.$q.'%'; + + } + + + + // Parent-Filtern (falls Spalten existieren) + + $parentFilters = [ + + 'template_id' => val($in, ['template_id','tpl_id'], null), + + 'section_id' => val($in, ['section_id','sec_id'], null), + + 'block_id' => val($in, ['block_id','blk_id'], null), + + ]; + + foreach ($parentFilters as $col => $v) { + + if ($v === null || $v === '') continue; + + if (in_array($col, $allCols, true)) { $where .= " AND `$col` = :$col "; $params[":$col"] = $v; } + + } + + + + // Mandant + + [$tw,$tp] = $tenantWhere($auth); + + $where .= $tw; foreach ($tp as $k=>$v) $params[$k]=$v; + + + + $order = $updCol ? " ORDER BY `$updCol` DESC " : " ORDER BY `$nameCol` ASC "; + + $sql = "SELECT * FROM `$t` $where $order LIMIT :off,:lim"; + + $stmt = $pdo->prepare($sql); + + foreach ($params as $k=>$v) $stmt->bindValue($k,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR); + + $stmt->bindValue(':off',$offset,PDO::PARAM_INT); + + $stmt->bindValue(':lim',$limit,PDO::PARAM_INT); + + $stmt->execute(); + + $rows = $stmt->fetchAll(); + + + + $out = []; + + foreach ($rows as $r) { + + $item = [ + + 'id' => $r[$idCol] ?? null, + + 'name' => $r[$nameCol] ?? null, + + ]; + + if ($descCol && isset($r[$descCol])) $item['desc'] = $r[$descCol]; + + if ($catCol && isset($r[$catCol])) $item['category'] = $r[$catCol]; + + if ($updCol && isset($r[$updCol])) $item['updated_at'] = $r[$updCol]; + + $out[] = $item; + + } + + respond(['ok'=>true,'kind'=>$kind,'items'=>$out,'data'=>$out,'count'=>count($out),'offset'=>$offset,'limit'=>$limit]); + + } + + + + /* ---------- GET (JETZT mit top-level html/content) ---------- */ + + case 'templates.get': + + case 'sections.get': + + case 'blocks.get': + + case 'snippets.get': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $sql = "SELECT * FROM `$t` WHERE `$idCol` = :id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + $stmt->bindValue(':id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + $row = $stmt->fetch(); + + if (!$row) fail('Not found', ['kind'=>$kind,'id'=>$id], 404); + + + + $rowOut = ['id' => $row[$idCol] ?? $id] + $row; + + + + // NEU: Spalten für HTML/JSON erkennen und top-level ausgeben + + $htmlCol = first_existing($allCols, ['html','body','markup']); + + $jsonCol = first_existing($allCols, ['content_json','json','content','structure_json']); + + $topHtml = ($htmlCol && isset($row[$htmlCol])) ? (string)$row[$htmlCol] : null; + + $topContent = ($jsonCol && isset($row[$jsonCol])) ? $row[$jsonCol] : null; + + + + respond([ + + 'ok'=>true, + + 'kind'=>$kind, + + 'id'=>$rowOut['id'], + + 'item'=>$rowOut, + + 'data'=>$rowOut, + + 'html'=>$topHtml, // <— wichtig für Vorschau + + 'content'=>$topContent // optional (z. B. GrapesJS JSON) + + ]); + + } + + + + /* ---------- CREATE ---------- */ + + case 'templates.create': + + case 'sections.create': + + case 'blocks.create': + + case 'snippets.create': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $name = trim((string)val($in, ['name','title'], '')); + + if ($name === '') fail('name required', null, 422); + + + + $desc = (string)val($in, ['description','desc'], null); + + $cat = (string)val($in, ['category','cat'], null); + + $html = (string)val($in, ['html','body','markup'], null); + + $json = val($in, ['content_json','json','content','structure_json'], null); + + $settings = val($in, ['settings_json','settings'], null); + + + + $templateId = val($in, ['template_id','tpl_id'], null); + + $sectionId = val($in, ['section_id','sec_id'], null); + + $blockId = val($in, ['block_id','blk_id'], null); + + + + $data = [ $nameCol => $name ]; + + if ($desc !== null && $descCol) $data[$descCol] = $desc; + + if ($cat !== null && $catCol) $data[$catCol] = $cat; + + + + $c = first_existing($allCols, ['html','body','markup']); if ($c && $html !== null) $data[$c]=$html; + + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($c && $json !== null) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + $c = first_existing($allCols, ['settings_json','settings']); if ($c && $settings !== null) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + + + if ($templateId !== null && in_array('template_id',$allCols,true)) $data['template_id']=$templateId; + + if ($sectionId !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sectionId; + + if ($blockId !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blockId; + + + + $data = $data + $tenantAssign($_SESSION['auth'] ?? [], $allCols); + + + + $now = date('Y-m-d H:i:s'); + + $createdCol = first_existing($allCols, ['created_at','created','createdAt']); + + if ($createdCol) $data[$createdCol] = $now; + + if ($updCol) $data[$updCol] = $now; + + + + $fields = array_keys($data); + + $place = array_map(fn($c)=>":$c", $fields); + + $sql = "INSERT INTO `$t` (".implode(',', array_map(fn($c)=>"`$c`",$fields)).") VALUES (".implode(',', $place).")"; + + $stmt = $pdo->prepare($sql); + + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + + $stmt->execute(); + + $newId = $pdo->lastInsertId(); + + + + $out = ['id'=>$newId,'name'=>$name]; + + if ($desc !== null) $out['desc']=$desc; + + if ($cat !== null) $out['category']=$cat; + + respond(['ok'=>true,'kind'=>$kind,'id'=>$newId,'item'=>$out,'data'=>$out]); + + } + + + + /* ---------- UPDATE ---------- */ + + case 'templates.update': + + case 'sections.update': + + case 'blocks.update': + + case 'snippets.update': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + $cfg = $conf['columns'][$kind] ?? []; + + $nameCol = $cfg['name'] ?? (in_array('name',$allCols,true) ? 'name' : $idCol); + + $descCol = $cfg['desc'] ?? first_existing($allCols, ['description','desc','descr']); + + $catCol = $cfg['cat'] ?? first_existing($allCols, ['category','cat']); + + $updCol = $cfg['upd'] ?? first_existing($allCols, ['updated_at','updated','updatedAt']); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + $data = []; + + $name = val($in, ['name','title'], null); + + $desc = val($in, ['description','desc'], null); + + $cat = val($in, ['category','cat'], null); + + $html = val($in, ['html','body','markup'], null); + + $json = val($in, ['content_json','json','content','structure_json'], null); + + $settings = val($in, ['settings_json','settings'], null); + + + + if ($name !== null) $data[$nameCol] = (string)$name; + + if ($desc !== null && $descCol) $data[$descCol] = (string)$desc; + + if ($cat !== null && $catCol) $data[$catCol] = (string)$cat; + + $c = first_existing($allCols, ['html','body','markup']); if ($html !== null && $c) $data[$c]=(string)$html; + + $c = first_existing($allCols, ['content_json','json','content','structure_json']); if ($json !== null && $c) $data[$c]= is_string($json)?$json:json_encode($json, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + $c = first_existing($allCols, ['settings_json','settings']); if ($settings !== null && $c) $data[$c]= is_string($settings)?$settings:json_encode($settings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + + + + $tpl = val($in, ['template_id','tpl_id'], null); if ($tpl !== null && in_array('template_id',$allCols,true)) $data['template_id']=$tpl; + + $sec = val($in, ['section_id','sec_id'], null); if ($sec !== null && in_array('section_id',$allCols,true)) $data['section_id']=$sec; + + $blk = val($in, ['block_id','blk_id'], null); if ($blk !== null && in_array('block_id',$allCols,true)) $data['block_id']=$blk; + + + + if ($updCol) $data[$updCol] = date('Y-m-d H:i:s'); + + if (!$data) fail('nothing to update', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $set = []; foreach (array_keys($data) as $c) $set[] = "`$c` = :$c"; + + $sql = "UPDATE `$t` SET ".implode(',',$set)." WHERE `$idCol` = :__id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + foreach ($data as $k=>$v) $stmt->bindValue(":$k", $v); + + $stmt->bindValue(':__id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + + + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'updated'=>array_keys($data)]); + + } + + + + /* ---------- DELETE ---------- */ + + case 'templates.delete': + + case 'sections.delete': + + case 'blocks.delete': + + case 'snippets.delete': { + + $auth = $requireAuth(); + + + + $kind = explode('.', $action)[0]; + + $t = $tableMap[$kind]; + + [$idCol, $allCols] = $resolveIdCol($kind); + + + + $id = $pullId($in); + + if ($id === null || $id === '') fail('id required', null, 422); + + + + [$tw,$tp] = $tenantWhere($auth); + + $sql = "DELETE FROM `$t` WHERE `$idCol` = :__id".$tw." LIMIT 1"; + + $stmt = $pdo->prepare($sql); + + $stmt->bindValue(':__id', $id); + + foreach ($tp as $k=>$v) $stmt->bindValue($k,$v); + + $stmt->execute(); + + + + respond(['ok'=>true,'kind'=>$kind,'id'=>$id,'deleted'=>true]); + + } + + + + /* ---------- Platzhalter für kommende Features ---------- */ + + case 'render.preview': + + fail('Not implemented', 'Preview wird im Feature-Patch geliefert', 501); + + case 'templates.test_send': + + fail('Not implemented', 'Testversand wird im Feature-Patch geliefert', 501); + + case 'export.render': + + fail('Not implemented', 'Export-API wird im Feature-Patch geliefert', 501); + + + + default: + + fail('Unknown action', $action ?: 'missing', 404); + + } + + + +} catch (Throwable $e) { + + fail('Server error', get_class($e).': '.$e->getMessage(), 500); + +} diff --git a/public/api.php b/public/api.php new file mode 100644 index 0000000..3541a75 --- /dev/null +++ b/public/api.php @@ -0,0 +1,15 @@ +run(); diff --git a/public/api.php.txt b/public/api.php.txt new file mode 100644 index 0000000..255b234 --- /dev/null +++ b/public/api.php.txt @@ -0,0 +1,492 @@ + false, + 'error' => 'internal', + 'type' => get_class($e), + 'msg' => $e->getMessage(), + 'file' => basename($e->getFile()), + 'line' => $e->getLine(), + ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; +}); + +/* ------------------------- Helpers ------------------------- */ +function json_out(array $data, int $code = 200): void { + http_response_code($code); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); + exit; +} +function in_json(): array { + $raw = file_get_contents('php://input') ?: ''; + if ($raw === '') return []; + $j = json_decode($raw, true); + return is_array($j) ? $j : []; +} + +/* ------------------------- Config laden ------------------------- */ +// Parent /inc/config.php (wie von dir beschrieben) +$cfgFile = dirname(__DIR__) . '/inc/config.php'; +if (!is_file($cfgFile)) { + json_out(['ok'=>false,'error'=>'config_missing','hint'=>'config.php nicht gefunden','path'=>$cfgFile], 500); +} +$CFG = include $cfgFile; +if (!is_array($CFG)) { + json_out(['ok'=>false,'error'=>'config_invalid','hint'=>'config.php muss ein Array zurückgeben'], 500); +} +$ENV = $CFG['env'] ?? 'prod'; + +/* ------------------------- PDO-Factories ------------------------- */ +function pdo_from_cfg(?array $dbc): ?PDO { + if (!$dbc) return null; + $dsn = sprintf( + 'mysql:host=%s;dbname=%s;charset=%s', + $dbc['db_host'] ?? 'localhost', + $dbc['db_name'] ?? '', + $dbc['db_charset']?? 'utf8mb4' + ); + return new PDO($dsn, $dbc['db_user'] ?? '', $dbc['db_pass'] ?? '', [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]); +} +$pdoTpl = pdo_from_cfg($CFG['templates'] ?? null); // Template-Daten +$pdoCust = pdo_from_cfg(($CFG['customers'] ?? null) ?: ($CFG['templates'] ?? null)); // Kunden/Users + +$TPL_DB = $CFG['templates']['db_name'] ?? null; // für information_schema + +function has_column(PDO $pdo, ?string $db, string $table, string $col): bool { + if (!$db) return false; + $st = $pdo->prepare("SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=:db AND TABLE_NAME=:t AND COLUMN_NAME=:c + LIMIT 1"); + $st->execute([':db'=>$db, ':t'=>$table, ':c'=>$col]); + return (bool)$st->fetchColumn(); +} + +/* ------------------------- Auth (Helper oder Fallback) ------------------------- */ +$authFile = dirname(__DIR__) . '/inc/auth_helpers.php'; +$useHelpers = is_file($authFile); +if ($useHelpers) { + require_once $authFile; // stellt auth_start_session(), auth_require(), auth_logout(), require_role() bereit +} else { + // interner Fallback – kompatibel zu deinen Erwartungen + function auth_start_session(array $CFG): void { + $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); + session_set_cookie_params([ + 'httponly' => true, + 'samesite' => 'Lax', + 'secure' => $secure, + 'path' => rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/' + ]); + session_name('et_session'); + if (session_status() !== PHP_SESSION_ACTIVE) session_start(); + } + function auth_require(array $CFG): void { + auth_start_session($CFG); + if (empty($_SESSION['user'])) { + json_out(['ok'=>false,'error'=>'unauthorized'], 401); + } + } + function auth_logout(array $CFG): void { + auth_start_session($CFG); + $_SESSION = []; + if (ini_get('session.use_cookies')) { + $p = session_get_cookie_params(); + setcookie(session_name(), '', time()-42000, $p['path'], $p['domain'] ?? '', $p['secure'], $p['httponly']); + } + session_destroy(); + } + function require_role(array $CFG, array $roles): void { + auth_start_session($CFG); + $r = $_SESSION['user']['role'] ?? null; + if (!$r || !in_array($r, $roles, true)) json_out(['ok'=>false,'error'=>'forbidden'], 403); + } +} + +/* ------------------------- Routing + Legacy-Mapping ------------------------- */ +$action = $_GET['action'] ?? $_POST['action'] ?? null; + +// Alt: ?resource=blocks&action=list|get|create|update|delete|sync +if (!empty($_GET['resource'])) { + $res = (string)$_GET['resource']; + $act = (string)($_GET['action'] ?? ''); + $allowed = ['templates','sections','blocks','snippets','assets','template_items','section_items']; + if (in_array($res, $allowed, true)) { + if ($act === 'list') $action = $res.'.list'; + if ($act === 'get') $action = $res.'.get'; + if ($act === 'create') $action = $res.'.create'; + if ($act === 'update') $action = $res.'.update'; + if ($act === 'delete') $action = $res.'.delete'; + if ($act === 'sync') $action = $res.'.sync'; + } +} + +/* ------------------------- Meta/Health ------------------------- */ +if ($action === 'health' || $action === 'ping') json_out(['ok'=>true,'env'=>$ENV,'time'=>date('c')]); +if ($action === 'version') json_out(['ok'=>true,'version'=>'2025-09-05','env'=>$ENV]); + +/* ------------------------- Diagnose (leichtgewichtig) ------------------------- */ +if ($action === 'debug.diag') { + $diag = [ + 'php' => PHP_VERSION, + 'pdo' => extension_loaded('pdo'), + 'pdo_mysql'=> extension_loaded('pdo_mysql'), + 'cfg' => ['templates'=>!!$pdoTpl, 'customers'=>!!$pdoCust], + ]; + json_out(['ok'=>true,'diag'=>$diag]); +} + +/* ------------------------- STAGING: User-Debug ------------------------- */ +if (in_array($action, ['debug.users','debug.users.check','debug.users.setpass','debug.users.peek'], true)) { + if ($ENV !== 'staging') json_out(['ok'=>false,'error'=>'forbidden'], 403); + if (!$pdoCust) json_out(['ok'=>false,'error'=>'customers_db_not_configured'], 500); + + if ($action === 'debug.users') { + $email = isset($_GET['email']) ? trim((string)$_GET['email']) : ''; + if ($email !== '') { + $st = $pdoCust->prepare("SELECT id, customer_id, email, role, is_active, created_at, updated_at + FROM customer_users WHERE email=:email"); + $st->execute([':email'=>$email]); + $rows = $st->fetchAll(); + } else { + $st = $pdoCust->query("SELECT id, customer_id, email, role, is_active, created_at, updated_at + FROM customer_users ORDER BY id DESC LIMIT 50"); + $rows = $st->fetchAll(); + } + json_out(['ok'=>true,'items'=>$rows]); + } + + if ($action === 'debug.users.check') { + $in = in_json(); + $email = trim((string)($in['email'] ?? '')); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_params'], 400); + $st = $pdoCust->prepare("SELECT id, customer_id, email, password_hash, role, is_active FROM customer_users + WHERE email=:email LIMIT 1"); + $st->execute([':email'=>$email]); + $u = $st->fetch(); + if (!$u) json_out(['ok'=>true,'exists'=>false,'password_match'=>false]); + json_out(['ok'=>true,'exists'=>true,'password_match'=>password_verify($pass,$u['password_hash'])]); + } + + if ($action === 'debug.users.setpass') { + $in = in_json(); + $email = trim((string)($in['email'] ?? '')); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_params'], 400); + $st = $pdoCust->prepare("SELECT id FROM customer_users WHERE email=:email LIMIT 1"); + $st->execute([':email'=>$email]); + $u = $st->fetch(); + if (!$u) json_out(['ok'=>false,'error'=>'user_not_found'], 404); + $hash = password_hash($pass, PASSWORD_DEFAULT); + $upd = $pdoCust->prepare("UPDATE customer_users SET password_hash=:h, is_active=1 WHERE id=:id"); + $upd->execute([':h'=>$hash, ':id'=>$u['id']]); + json_out(['ok'=>true,'set'=>true]); + } + + if ($action === 'debug.users.peek') { + $email = isset($_GET['email']) ? trim((string)$_GET['email']) : ''; + if ($email==='') json_out(['ok'=>false,'error'=>'missing_email'], 400); + $st = $pdoCust->prepare("SELECT id, customer_id, email, LENGTH(password_hash) len + FROM customer_users WHERE email=:email"); + $st->execute([':email'=>$email]); + json_out(['ok'=>true,'user'=>$st->fetch()]); + } +} + +/* ------------------------- AUTH: Login / Logout / Me ------------------------- */ +if ($action === 'auth.login') { + $in = in_json(); + $email = trim(strtolower((string)($in['email'] ?? ''))); + $pass = (string)($in['password'] ?? ''); + if ($email==='' || $pass==='') json_out(['ok'=>false,'error'=>'missing_credentials'], 400); + if (!$pdoCust) json_out(['ok'=>false,'error'=>'customers_db_not_configured'], 500); + + // Mehrfachkunden mit gleicher Mail erlauben → best match über password_verify + $st = $pdoCust->prepare("SELECT cu.id, cu.customer_id, cu.email, cu.password_hash, cu.role, cu.is_active, + c.slug AS customer_slug, c.plan, c.status + FROM customer_users cu + JOIN customers c ON c.id = cu.customer_id + WHERE cu.email=:email"); + $st->execute([':email'=>$email]); + $rows = $st->fetchAll(); + + $match = null; + foreach ($rows as $r) { + if ((int)$r['is_active'] === 1 && !empty($r['password_hash']) && password_verify($pass, $r['password_hash'])) { + $match = $r; break; + } + } + if (!$match) json_out(['ok'=>false,'error'=>'invalid_credentials'], 401); + if (($match['status'] ?? 'active') !== 'active') json_out(['ok'=>false,'error'=>'customer_inactive'], 403); + + auth_start_session($CFG); + $_SESSION['user'] = [ + 'id' => (int)$match['id'], + 'email' => $match['email'], + 'role' => $match['role'], + 'customer_id' => (int)$match['customer_id'], + 'customer_slug' => $match['customer_slug'], + 'plan' => $match['plan'] ?? null, + ]; + json_out(['ok'=>true,'user'=>$_SESSION['user']]); +} + +if ($action === 'auth.logout') { auth_logout($CFG); json_out(['ok'=>true]); } + +if ($action === 'auth.me') { + auth_start_session($CFG); + json_out(['ok'=>!empty($_SESSION['user']), 'user'=>$_SESSION['user'] ?? null]); +} + +/* ------------------------- ab hier: geschützt ------------------------- */ +$public = ['auth.login','auth.logout','auth.me','health','ping','version','debug.diag','debug.users','debug.users.check','debug.users.setpass','debug.users.peek']; +if (!in_array($action, $public, true)) auth_require($CFG); + +$customerId = (int)($_SESSION['user']['customer_id'] ?? 0); + +/* ------------------------- Templates ------------------------- */ +if ($action === 'templates.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st = $pdoTpl->prepare("SELECT id, name, updated_at + FROM emailtemplate_templates + WHERE customer_id = :cid + ORDER BY updated_at DESC, id DESC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'templates.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + $cols = $hasHtml ? "id, customer_id, name, html, updated_at" : "id, customer_id, name, NULL AS html, updated_at"; + $st = $pdoTpl->prepare("SELECT $cols FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +if ($action === 'templates.create') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $name = trim((string)($in['name'] ?? '')); + $html = (string)($in['html'] ?? ''); + if ($name==='') json_out(['ok'=>false,'error'=>'name_required'], 400); + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + + if ($hasHtml) { + $st = $pdoTpl->prepare("INSERT INTO emailtemplate_templates (customer_id,name,html,created_at,updated_at) + VALUES (:cid,:name,:html,NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name, ':html'=>$html]); + } else { + $st = $pdoTpl->prepare("INSERT INTO emailtemplate_templates (customer_id,name,created_at,updated_at) + VALUES (:cid,:name,NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name]); + } + json_out(['ok'=>true,'id'=>(int)$pdoTpl->lastInsertId()]); +} + +if ($action === 'templates.update') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $id = (int)($in['id'] ?? 0); + $name = array_key_exists('name',$in) ? trim((string)$in['name']) : null; + $html = array_key_exists('html',$in) ? (string)$in['html'] : null; + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + + $hasHtml = has_column($pdoTpl, $TPL_DB, 'emailtemplate_templates', 'html'); + $sets=[]; $p=[':id'=>$id, ':cid'=>$customerId]; + if ($name!==null) { $sets[]="name=:name"; $p[':name']=$name; } + if ($hasHtml && $html!==null) { $sets[]="html=:html"; $p[':html']=$html; } + if (!$sets) json_out(['ok'=>false,'error'=>'nothing_to_update'], 400); + + $sql = "UPDATE emailtemplate_templates SET ".implode(',',$sets).", updated_at=NOW() WHERE id=:id AND customer_id=:cid"; + $st = $pdoTpl->prepare($sql); + $st->execute($p); + json_out(['ok'=>true,'updated'=>$st->rowCount()]); +} + +if ($action === 'templates.delete') { + require_role($CFG, ['owner','admin']); + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); $id=(int)($in['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $pdoTpl->beginTransaction(); + try { + $pdoTpl->prepare("DELETE FROM emailtemplate_template_items WHERE template_id=:id AND customer_id=:cid")->execute([':id'=>$id, ':cid'=>$customerId]); + $pdoTpl->prepare("DELETE FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid")->execute([':id'=>$id, ':cid'=>$customerId]); + $pdoTpl->commit(); + json_out(['ok'=>true]); + } catch (Throwable $e) { $pdoTpl->rollBack(); throw $e; } +} + +/* ------------------------- Sections ------------------------- */ +if ($action === 'sections.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $templateId = isset($_GET['template_id']) ? (int)$_GET['template_id'] : 0; + if ($templateId>0) { + $st = $pdoTpl->prepare("SELECT id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE customer_id=:cid AND template_id=:tid + ORDER BY z_index ASC, id ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId, ':tid'=>$templateId]); + } else { + $st = $pdoTpl->prepare("SELECT id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE customer_id=:cid + ORDER BY template_id ASC, z_index ASC, id ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + } + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'sections.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st = $pdoTpl->prepare("SELECT id, customer_id, template_id, name, z_index, type, updated_at + FROM emailtemplate_sections + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +/* ------------------------- Blocks ------------------------- */ +if ($action === 'blocks.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st = $pdoTpl->prepare("SELECT id, name, category, updated_at + FROM emailtemplate_blocks + WHERE customer_id=:cid + ORDER BY name ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'blocks.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st = $pdoTpl->prepare("SELECT id, customer_id, name, category, updated_at + FROM emailtemplate_blocks + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row = $st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +if ($action === 'blocks.create') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $name=trim((string)($in['name']??'')); $cat=trim((string)($in['category']??'')); + if ($name==='') json_out(['ok'=>false,'error'=>'name_required'], 400); + $st=$pdoTpl->prepare("INSERT INTO emailtemplate_blocks (customer_id,name,category,created_at,updated_at) + VALUES (:cid,:name,COALESCE(NULLIF(:cat,''),'Default'),NOW(),NOW())"); + $st->execute([':cid'=>$customerId, ':name'=>$name, ':cat'=>$cat]); + json_out(['ok'=>true,'id'=>(int)$pdoTpl->lastInsertId()]); +} + +if ($action === 'blocks.update') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $id=(int)($in['id']??0); $name=trim((string)($in['name']??'')); $cat=trim((string)($in['category']??'')); + if ($id<=0 || $name==='') json_out(['ok'=>false,'error'=>'invalid_params'], 400); + $st=$pdoTpl->prepare("UPDATE emailtemplate_blocks + SET name=:name, category=COALESCE(NULLIF(:cat,''),category), updated_at=NOW() + WHERE id=:id AND customer_id=:cid"); + $st->execute([':name'=>$name, ':cat'=>$cat, ':id'=>$id, ':cid'=>$customerId]); + json_out(['ok'=>true,'updated'=>$st->rowCount()]); +} + +if ($action === 'blocks.delete') { + require_role($CFG, ['owner','admin']); + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in=in_json(); $id=(int)($in['id']??0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st=$pdoTpl->prepare("DELETE FROM emailtemplate_blocks WHERE id=:id AND customer_id=:cid"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + json_out(['ok'=>true,'deleted'=>$st->rowCount()]); +} + +/* ------------------------- Snippets ------------------------- */ +if ($action === 'snippets.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st=$pdoTpl->prepare("SELECT id, name, category, updated_at + FROM emailtemplate_snippets + WHERE customer_id=:cid + ORDER BY name ASC + LIMIT 1000"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +if ($action === 'snippets.get') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0); + if ($id<=0) json_out(['ok'=>false,'error'=>'missing_id'], 400); + $st=$pdoTpl->prepare("SELECT id, customer_id, name, category, updated_at + FROM emailtemplate_snippets + WHERE id=:id AND customer_id=:cid + LIMIT 1"); + $st->execute([':id'=>$id, ':cid'=>$customerId]); + $row=$st->fetch(); + if (!$row) json_out(['ok'=>false,'error'=>'not_found'], 404); + json_out(['ok'=>true,'item'=>$row]); +} + +/* ------------------------- Assets (READ) ------------------------- */ +if ($action === 'assets.list') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $st=$pdoTpl->prepare("SELECT id, name, type, mime_type, size_bytes, public_url, updated_at + FROM emailtemplate_assets + WHERE customer_id=:cid + ORDER BY updated_at DESC, id DESC + LIMIT 200"); + $st->execute([':cid'=>$customerId]); + json_out(['ok'=>true,'items'=>$st->fetchAll()]); +} + +/* ------------------------- Editor-Referenzen (Placeholders) ------------------------- */ +if ($action === 'template_items.sync') { json_out(['ok'=>true]); } +if ($action === 'section_items.sync') { json_out(['ok'=>true]); } + +/* ------------------------- Render (Fallback) ------------------------- */ +if ($action === 'render.preview') { + if (!$pdoTpl) json_out(['ok'=>false,'error'=>'templates_db_not_configured'], 500); + $in = in_json(); + $templateId = (int)($in['template_id'] ?? 0); + if ($templateId<=0) json_out(['ok'=>false,'error'=>'template_id_required'], 400); + $st = $pdoTpl->prepare("SELECT id, name FROM emailtemplate_templates WHERE id=:id AND customer_id=:cid LIMIT 1"); + $st->execute([':id'=>$templateId, ':cid'=>$customerId]); + $tpl = $st->fetch(); + if (!$tpl) json_out(['ok'=>false,'error'=>'not_found'], 404); + $html = "\n