HifiPlanet-Website/hifi/api/src/Controllers/ContactController.php
Maaxxs d20b963970 Add rich-text formatting and font choice for email templates
Phase 4 of the dashboard roadmap. New RichTextEditor component
(Tiptap 3.31.3, pinned past a mergeAttributes XSS advisory affecting
2.x/older 3.x - GHSA-cp6q-959q-f8rh) replaces the plain textareas for
the customer/owner mail bodies in EmailSettings.jsx: bold, italic,
underline, lists, links, and a font-family dropdown. Font choices are
classic system fonts rather than self-hosted webfonts - most email
clients don't load custom @font-face at all, so system fonts are the
only choice that reliably renders as chosen once delivered.

Existing plain-text templates (including the built-in defaults) are
converted to HTML once on load so line breaks survive the switch.

Security fix that had to go with this: Mailer::render() does a raw
strtr() with no escaping, which was fine while bodies were plain text,
but ContactController now sends these as HTML mail - a customer's
public contact-form message could otherwise inject markup into the
HTML notification mail. New Mailer::renderHtml() escapes each
substituted value before it goes into the (admin-authored, otherwise
unchanged) HTML template; ContactController sets isHTML(true) and an
AltBody plain-text fallback for both the owner notification and
customer confirmation.

Known trade-off: Tiptap adds ~400KB (gzipped ~130KB) to the shared
admin+public JS bundle, since the app has no route-based code-splitting
anywhere yet - flagged for a possible follow-up, not fixed here since
it'd mean restructuring the whole admin bundle, not just this feature.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-09 01:49:13 +02:00

178 lines
6.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Controllers;
use App\Config\Database;
use App\Support\Http;
use App\Support\Mailer;
class ContactController
{
public static function store(): void
{
$body = Http::jsonBody();
$name = trim($body['name'] ?? '');
$email = trim($body['email'] ?? '');
if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
Http::error('Name und gültige E-Mail-Adresse erforderlich', 422);
}
$db = Database::connection();
$packageId = !empty($body['package_id']) ? (int) $body['package_id'] : null;
$selectedUpgrades = self::resolveUpgrades($db, $packageId, $body['upgrade_ids'] ?? []);
$stmt = $db->prepare(
'INSERT INTO contact_requests
(name, email, phone, vin, message, brand_name, model_name, package_name, product_name, package_id, package_product_id, selected_upgrades)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$name,
$email,
$body['phone'] ?? null,
$body['vin'] ?? null,
$body['message'] ?? null,
$body['brand_name'] ?? null,
$body['model_name'] ?? null,
$body['package_name'] ?? null,
$body['product_name'] ?? null,
$packageId,
!empty($body['package_product_id']) ? (int) $body['package_product_id'] : null,
$selectedUpgrades ? json_encode($selectedUpgrades) : null,
]);
$id = (int) $db->lastInsertId();
$vars = self::templateVars($body, $name, $email, $selectedUpgrades);
self::sendOwnerNotification($vars);
self::sendCustomerConfirmation($vars, $email);
Http::send(['ok' => true, 'id' => $id], 201);
}
/**
* Liest die vom Kunden ausgewählten Upgrades serverseitig aus der DB (statt dem Client zu
* vertrauen), damit Name/Preis in der Anfrage nicht manipuliert werden können.
*/
private static function resolveUpgrades(\PDO $db, ?int $packageId, mixed $upgradeIds): array
{
if (!$packageId || !is_array($upgradeIds) || count($upgradeIds) === 0) {
return [];
}
$ids = array_values(array_unique(array_map('intval', $upgradeIds)));
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stmt = $db->prepare(
"SELECT id, name, price FROM package_upgrades WHERE package_id = ? AND id IN ($placeholders)"
);
$stmt->execute([$packageId, ...$ids]);
return $stmt->fetchAll();
}
public static function index(): void
{
$stmt = Database::connection()->query(
'SELECT id, name, email, phone, vin, message, brand_name, model_name, package_name, product_name,
selected_upgrades, status, created_at
FROM contact_requests ORDER BY created_at DESC'
);
$rows = $stmt->fetchAll();
foreach ($rows as &$row) {
$row['selected_upgrades'] = $row['selected_upgrades'] ? json_decode($row['selected_upgrades'], true) : [];
}
unset($row);
Http::send($rows);
}
public static function updateStatus(array $params): void
{
$body = Http::jsonBody();
$status = $body['status'] ?? '';
if (!in_array($status, ['new', 'in_progress', 'done'], true)) {
Http::error('Ungültiger Status', 422);
}
$stmt = Database::connection()->prepare('UPDATE contact_requests SET status = ? WHERE id = ?');
$stmt->execute([$status, (int) $params['id']]);
Http::send(['ok' => true]);
}
public static function destroy(array $params): void
{
$stmt = Database::connection()->prepare('DELETE FROM contact_requests WHERE id = ?');
$stmt->execute([(int) $params['id']]);
Http::send(['ok' => true]);
}
/**
* Baut die Platzhalter-Werte fuer beide Vorlagen (Kundenbestaetigung + Shop-Benachrichtigung)
* einmal zentral, statt sie in jeder Mail-Methode einzeln zusammenzusetzen.
*/
private static function templateVars(array $body, string $name, string $email, array $selectedUpgrades): array
{
$upgradesText = '-';
if ($selectedUpgrades) {
$upgradesText = implode("\n", array_map(
fn($u) => sprintf('- %s (%.2f €)', $u['name'], $u['price']),
$selectedUpgrades
));
}
return [
'name' => $name,
'email' => $email,
'phone' => $body['phone'] ?? null,
'vin' => $body['vin'] ?? null,
'message' => $body['message'] ?? null,
'brand' => $body['brand_name'] ?? null,
'model' => $body['model_name'] ?? null,
'package' => $body['package_name'] ?? null,
'product' => $body['product_name'] ?? null,
'upgrades' => $upgradesText,
];
}
private static function sendOwnerNotification(array $vars): void
{
$config = Mailer::resolveConfig();
if (empty($config['host']) || empty($config['notify_email'])) {
return;
}
try {
$mail = Mailer::build($config);
$mail->addAddress($config['notify_email']);
$mail->addReplyTo($vars['email'], $vars['name']);
$mail->Subject = Mailer::render($config['owner_subject'], $vars);
$mail->isHTML(true);
$mail->Body = Mailer::renderHtml($config['owner_body'], $vars);
$mail->AltBody = strip_tags(Mailer::render($config['owner_body'], $vars));
$mail->send();
} catch (\Throwable $e) {
// Mailversand ist best effort – die Anfrage ist bereits in der DB gespeichert.
}
}
private static function sendCustomerConfirmation(array $vars, string $email): void
{
$config = Mailer::resolveConfig();
if (empty($config['host'])) {
return;
}
try {
$mail = Mailer::build($config);
$mail->addAddress($email, $vars['name']);
$mail->Subject = Mailer::render($config['customer_subject'], $vars);
$mail->isHTML(true);
$mail->Body = Mailer::renderHtml($config['customer_body'], $vars);
$mail->AltBody = strip_tags(Mailer::render($config['customer_body'], $vars));
$mail->send();
} catch (\Throwable $e) {
// Mailversand ist best effort – die Anfrage ist bereits in der DB gespeichert.
}
}
}