Upload via GUI (267 Dateien)

This commit is contained in:
2026-10-19 18:05:53 +00:00
parent 42554bdadf
commit 1b29349219
7 changed files with 1570 additions and 1341 deletions
+958 -906
View File
File diff suppressed because it is too large Load Diff
@@ -22,6 +22,16 @@ if ($departmentIds !== null) {
} }
} }
// Optional: nur Textbausteine für die Abteilung eines Tickets (diese Abteilung plus die für alle Abteilungen)
$onlyDept = isset($_GET['departmentId']) && ctype_digit((string) $_GET['departmentId']) ? (int) $_GET['departmentId'] : null;
if ($onlyDept !== null) {
if ($departmentIds !== null && !in_array($onlyDept, $departmentIds, true)) {
api_error(403, 'FORBIDDEN', 'Kein Zugriff auf diese Abteilung.');
}
$deptFilter = ' AND (cr.department_id IS NULL OR cr.department_id = ?)';
$deptParams = [$onlyDept];
}
$stmt = $pdo->prepare( $stmt = $pdo->prepare(
"SELECT cr.id, cr.title, cr.body, cr.department_id "SELECT cr.id, cr.title, cr.body, cr.department_id
FROM canned_responses cr FROM canned_responses cr
+30 -12
View File
@@ -66,14 +66,20 @@ function api_require_https(): void
} }
} }
/**
* Liest die Anmeldung der Apps. Viele Hoster (Apache mit PHP-FPM/FastCGI, z. B. Plesk) reichen den Header "Authorization" nicht an PHP weiter.
* Deshalb senden die Apps denselben Wert zusätzlich als "X-DeskHub-Authorization", der überall ankommt; hier gilt der erste vorhandene.
*/
function api_authorization_header(): string function api_authorization_header(): string
{ {
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''; $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if ($header === '' && function_exists('getallheaders')) { if (trim((string) $header) === '') $header = $_SERVER['HTTP_X_DESKHUB_AUTHORIZATION'] ?? '';
$headers = getallheaders(); if (trim((string) $header) === '' && function_exists('getallheaders')) {
$header = $headers['Authorization'] ?? $headers['authorization'] ?? ''; foreach (getallheaders() as $name => $value) {
if (in_array(strtolower((string) $name), ['authorization', 'x-deskhub-authorization'], true) && trim((string) $value) !== '') { $header = $value; break; }
}
} }
return trim($header); return trim((string) $header);
} }
function api_bearer_token(): ?string function api_bearer_token(): ?string
@@ -204,11 +210,27 @@ function api_find_ticket(PDO $pdo, array $staff, string $number): array
return $ticket; return $ticket;
} }
/** Adresse des ersten Bildes in einem HTML-Text (absolut, nur http/https); leer, wenn keines vorhanden ist. */
function api_first_image_url(?string $html): string
{
if (!preg_match('/<img\b[^>]*\bsrc\s*=\s*(["\'])(.*?)\1/is', (string) $html, $m)) return '';
$src = trim(html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5, 'UTF-8'));
if (str_starts_with($src, '//')) $src = 'https:' . $src;
elseif (str_starts_with($src, '/')) $src = base_url() . $src;
return preg_match('#^https?://#i', $src) ? $src : '';
}
function api_plain_text(?string $html): string function api_plain_text(?string $html): string
{ {
$text = preg_replace('/<br\s*\/?>/i', "\n", (string) $html); $text = preg_replace('/<br\s*\/?>/i', "\n", (string) $html);
$text = preg_replace('/<\/p\s*>/i', "\n\n", $text); $text = preg_replace('/<\/p\s*>/i', "\n\n", $text);
return trim(html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8')); // Weitere Blöcke (div, Listen, Tabellenzeilen, Überschriften …) enden ebenfalls mit einem Zeilenumbruch, Listenpunkte bekommen einen Punkt
$text = preg_replace('/<li\b[^>]*>/i', '• ', $text);
$text = preg_replace('/<\/(div|li|tr|h[1-6]|blockquote|pre|ul|ol|table)\s*>/i', "\n", $text);
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = preg_replace('/[ \t]+\n/', "\n", $text); // Leerzeichen am Zeilenende
$text = preg_replace('/\n{3,}/', "\n\n", $text); // höchstens eine Leerzeile
return trim($text);
} }
function api_ticket_summary(array $ticket): array function api_ticket_summary(array $ticket): array
@@ -247,7 +269,7 @@ function api_ticket_summary(array $ticket): array
]; ];
} }
function api_add_ticket_message(PDO $pdo, array $staff, array $ticket, string $type, string $rawMessage, ?string $setStatus): int function api_add_ticket_message(PDO $pdo, array $staff, array $ticket, string $type, string $rawMessage, ?string $setStatus, ?string $signatureChoice = null): int
{ {
$permission = $type === 'note' ? 'post_note' : 'reply_ticket'; $permission = $type === 'note' ? 'post_note' : 'reply_ticket';
api_require_permission($staff, $permission, (int) $ticket['department_id']); api_require_permission($staff, $permission, (int) $ticket['department_id']);
@@ -331,12 +353,8 @@ function api_add_ticket_message(PDO $pdo, array $staff, array $ticket, string $t
} }
if (!$isNote) { if (!$isNote) {
$signature = trim((string) ($staff['signature'] ?? '')); // Signatur: optional vom Aufrufer gewählt (own, dept, none), sonst eigene, ersatzweise die der Abteilung
if ($signature === '') { $signature = resolve_reply_signature($pdo, $staff, (int) $ticket['department_id'], $signatureChoice);
$signatureStmt = $pdo->prepare('SELECT signature FROM departments WHERE id = ?');
$signatureStmt->execute([$ticket['department_id']]);
$signature = (string) $signatureStmt->fetchColumn();
}
$collabStmt = $pdo->prepare('SELECT email FROM ticket_collaborators WHERE ticket_id = ?'); $collabStmt = $pdo->prepare('SELECT email FROM ticket_collaborators WHERE ticket_id = ?');
$collabStmt->execute([$ticket['id']]); $collabStmt->execute([$ticket['id']]);
notify_customer_new_reply($ticket, $message, $signature, $collabStmt->fetchAll(PDO::FETCH_COLUMN)); notify_customer_new_reply($ticket, $message, $signature, $collabStmt->fetchAll(PDO::FETCH_COLUMN));
+44 -44
View File
@@ -1,44 +1,44 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
require_once __DIR__ . '/common.php'; require_once __DIR__ . '/common.php';
api_require_method('POST'); api_require_method('POST');
api_require_https(); api_require_https();
$body = api_request_body(); $body = api_request_body();
$email = mb_strtolower(trim((string) ($body['email'] ?? ''))); $email = mb_strtolower(trim((string) ($body['email'] ?? '')));
$password = (string) ($body['password'] ?? ''); $password = (string) ($body['password'] ?? '');
$totpCode = trim((string) ($body['totpCode'] ?? '')); $totpCode = trim((string) ($body['totpCode'] ?? ''));
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') { if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
api_error(422, 'CREDENTIALS_REQUIRED', 'E-Mail-Adresse und Passwort sind erforderlich.'); api_error(422, 'CREDENTIALS_REQUIRED', 'E-Mail-Adresse und Passwort sind erforderlich.');
} }
if (!rate_limit_check('mobile_staff_login_ip', client_ip(), 10, 15) if (!rate_limit_check('mobile_staff_login_ip', client_ip(), 10, 15)
|| !rate_limit_check('mobile_staff_login_email', $email, 5, 15)) { || !rate_limit_check('mobile_staff_login_email', strtolower($email), 5, 15)) {
api_error(429, 'RATE_LIMITED', 'Zu viele Anmeldeversuche. Bitte versuchen Sie es später erneut.'); api_error(429, 'RATE_LIMITED', 'Zu viele Anmeldeversuche. Bitte versuchen Sie es später erneut.');
} }
$pdo = get_db(); $pdo = get_db();
$stmt = $pdo->prepare('SELECT * FROM staff WHERE email = ? AND is_active = 1'); $stmt = $pdo->prepare('SELECT * FROM staff WHERE LOWER(email) = LOWER(?) AND is_active = 1');
$stmt->execute([$email]); $stmt->execute([$email]);
$staff = $stmt->fetch(); $staff = $stmt->fetch();
if (!$staff || !password_verify($password, $staff['password_hash'])) { if (!$staff || !password_verify($password, $staff['password_hash'])) {
api_error(401, 'INVALID_CREDENTIALS', 'E-Mail-Adresse oder Passwort ist falsch.'); api_error(401, 'INVALID_CREDENTIALS', 'E-Mail-Adresse oder Passwort ist falsch.');
} }
if (!empty($staff['totp_enabled'])) { if (!empty($staff['totp_enabled'])) {
if ($totpCode === '') { if ($totpCode === '') {
api_json(['requiresTotp' => true], 202); api_json(['requiresTotp' => true], 202);
} }
if (!preg_match('/^\d{6}$/', $totpCode) || !totp_verify($staff['totp_secret'], $totpCode)) { if (!preg_match('/^\d{6}$/', $totpCode) || !totp_verify($staff['totp_secret'], $totpCode)) {
api_error(401, 'INVALID_TOTP', 'Der Authenticator-Code ist ungültig.'); api_error(401, 'INVALID_TOTP', 'Der Authenticator-Code ist ungültig.');
} }
} }
rate_limit_reset('mobile_staff_login_email', $email); rate_limit_reset('mobile_staff_login_email', strtolower($email));
rate_limit_reset('mobile_staff_login_ip', client_ip()); rate_limit_reset('mobile_staff_login_ip', client_ip());
$issued = api_issue_token($pdo, (int) $staff['id'], isset($body['deviceName']) ? (string) $body['deviceName'] : null); $issued = api_issue_token($pdo, (int) $staff['id'], isset($body['deviceName']) ? (string) $body['deviceName'] : null);
audit_log((int) $staff['id'], 'Mobile App: Anmeldung'); audit_log((int) $staff['id'], 'Mobile App: Anmeldung');
api_json([ api_json([
'token' => $issued['token'], 'token' => $issued['token'],
'expiresAt' => $issued['expires_at'], 'expiresAt' => $issued['expires_at'],
'staff' => api_staff_payload($staff), 'staff' => api_staff_payload($staff),
]); ]);
+1 -1
View File
@@ -26,7 +26,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!$errors) { if (!$errors) {
$pdo = get_db(); $pdo = get_db();
$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?'); $stmt = $pdo->prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)');
$stmt->execute([$email]); $stmt->execute([$email]);
if ($stmt->fetch()) { if ($stmt->fetch()) {
$errors[] = 'Für diese E-Mail-Adresse existiert bereits ein Konto.'; $errors[] = 'Für diese E-Mail-Adresse existiert bereits ein Konto.';
+526 -378
View File
@@ -1,378 +1,526 @@
<?php <?php
require_once __DIR__ . '/includes/bootstrap.php'; require_once __DIR__ . '/includes/bootstrap.php';
$user = current_user(); $user = current_user();
$pdo = get_db(); $pdo = get_db();
$departments = departments_for_select($pdo); $departments = departments_for_select($pdo);
$priorities = $pdo->query('SELECT * FROM priorities ORDER BY sort_order')->fetchAll(); $priorities = $pdo->query('SELECT * FROM priorities ORDER BY sort_order')->fetchAll();
$helpTopics = help_topic_options($pdo, true); $helpTopics = help_topic_options($pdo, true);
$useHelpTopics = count($helpTopics) > 0; $useHelpTopics = count($helpTopics) > 0;
// Ohne Hilfe-Themen gibt es keine Themenauswahl auf dem Formular, daher nur themenunabhängige Felder anzeigen. // Ohne Hilfe-Themen gibt es keine Themenauswahl auf dem Formular, daher nur themenunabhängige Felder anzeigen.
$customFields = $useHelpTopics $customFields = $useHelpTopics
? $pdo->query('SELECT * FROM custom_fields WHERE is_active = 1 ORDER BY sort_order, label')->fetchAll() ? $pdo->query('SELECT * FROM custom_fields WHERE is_active = 1 AND department_id IS NULL ORDER BY sort_order, label')->fetchAll()
: $pdo->query('SELECT * FROM custom_fields WHERE is_active = 1 AND help_topic_id IS NULL ORDER BY sort_order, label')->fetchAll(); : $pdo->query('SELECT * FROM custom_fields WHERE is_active = 1 AND department_id IS NULL AND help_topic_id IS NULL ORDER BY sort_order, label')->fetchAll();
$errors = []; // Abteilungen mit eigenem Formular: Texte und Felder (erscheinen nur, wenn der Kunde diese Abteilung wählt)
$deptForms = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') { foreach ($departments as $d) {
verify_csrf(); $df = department_form($pdo, (int) $d['id']);
if ($df) {
// Honeypot: für Menschen unsichtbares Feld, das leer bleiben muss. Bots füllen $deptForms[(int) $d['id']] = $df;
// häufig alle Formularfelder aus, daher dient dies als einfache Spam-Bremse. }
if (!empty($_POST['website'])) { }
flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.'); $topicDept = [];
redirect('/ticket_new.php'); foreach ($helpTopics as $t) $topicDept[(int) $t['id']] = (int) $t['department_id'];
}
if (!$user && !rate_limit_check('ticket_create', client_ip(), 8, 60)) { $errors = [];
$errors[] = 'Sie haben in kurzer Zeit zu viele Tickets erstellt. Bitte versuchen Sie es später erneut.';
} if ($_SERVER['REQUEST_METHOD'] === 'POST') {
verify_csrf();
$name = trim($_POST['name'] ?? ($user['name'] ?? ''));
$email = trim($_POST['email'] ?? ($user['email'] ?? '')); // Honeypot: für Menschen unsichtbares Feld, das leer bleiben muss. Bots füllen
$subject = trim($_POST['subject'] ?? ''); // häufig alle Formularfelder aus, daher dient dies als einfache Spam-Bremse.
$message = trim($_POST['message'] ?? ''); if (!empty($_POST['website'])) {
flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.');
// Gesperrte Absender: Ticket wird wie beim Honeypot kommentarlos abgewiesen, redirect('/ticket_new.php');
// damit nicht erkennbar ist, dass die Adresse gezielt blockiert wurde. }
if ($email !== '' && is_banned($email)) { if (!$user && !rate_limit_check('ticket_create', client_ip(), 8, 60)) {
flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.'); $errors[] = 'Sie haben in kurzer Zeit zu viele Tickets erstellt. Bitte versuchen Sie es später erneut.';
redirect('/ticket_new.php'); }
}
$name = trim($_POST['name'] ?? ($user['name'] ?? ''));
$helpTopicId = null; $email = trim($_POST['email'] ?? ($user['email'] ?? ''));
$deptId = null; $subject = trim($_POST['subject'] ?? '');
$prioId = null; $message = trim($_POST['message'] ?? '');
if ($useHelpTopics) { // Gesperrte Absender: Ticket wird wie beim Honeypot kommentarlos abgewiesen,
$helpTopicId = (int) ($_POST['help_topic_id'] ?? 0); // damit nicht erkennbar ist, dass die Adresse gezielt blockiert wurde.
$topic = null; if ($email !== '' && is_banned($email)) {
foreach ($helpTopics as $t) { flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.');
if ($t['id'] == $helpTopicId) { $topic = $t; break; } redirect('/ticket_new.php');
} }
if (!$topic) {
$errors[] = 'Bitte wählen Sie ein Anliegen aus.'; $helpTopicId = null;
} else { $deptId = null;
$deptId = (int) $topic['department_id']; $prioId = null;
$prioId = (int) $topic['priority_id'];
} if ($useHelpTopics) {
} else { $helpTopicId = (int) ($_POST['help_topic_id'] ?? 0);
$deptId = (int) ($_POST['department_id'] ?? 0); $topic = null;
$prioId = (int) ($_POST['priority_id'] ?? 0); foreach ($helpTopics as $t) {
if (!in_array($deptId, array_column($departments, 'id'))) $errors[] = 'Bitte wählen Sie eine Abteilung.'; if ($t['id'] == $helpTopicId) { $topic = $t; break; }
if (!in_array($prioId, array_column($priorities, 'id'))) $errors[] = 'Bitte wählen Sie eine Priorität.'; }
} if (!$topic) {
$errors[] = 'Bitte wählen Sie ein Anliegen aus.';
if ($name === '') $errors[] = 'Bitte geben Sie Ihren Namen an.'; } else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Bitte geben Sie eine gültige E-Mail-Adresse an.'; $deptId = (int) $topic['department_id'];
if ($subject === '') $errors[] = 'Bitte geben Sie einen Betreff an.'; $prioId = (int) $topic['priority_id'];
if ($message === '') $errors[] = 'Bitte beschreiben Sie Ihr Anliegen.'; }
} else {
// Individuelle Felder validieren (nur Felder, die zum gewählten Hilfe-Thema gehören oder themenunabhängig sind) $deptId = (int) ($_POST['department_id'] ?? 0);
$customValues = []; // field id => submitted value $prioId = (int) ($_POST['priority_id'] ?? 0);
foreach ($customFields as $f) { if (!in_array($deptId, array_column($departments, 'id'))) $errors[] = 'Bitte wählen Sie eine Abteilung.';
if ($f['help_topic_id'] !== null && (int) $f['help_topic_id'] !== (int) $helpTopicId) continue; if (!in_array($prioId, array_column($priorities, 'id'))) $errors[] = 'Bitte wählen Sie eine Priorität.';
$fieldName = 'custom_' . $f['id']; }
$val = $f['field_type'] === 'checkbox' ? (!empty($_POST[$fieldName]) ? '1' : '0') : trim($_POST[$fieldName] ?? '');
if ($f['is_required'] && $f['field_type'] !== 'checkbox' && $val === '') { // Eigenes Formular der gewählten Abteilung: ersetzt Betreff-/Feld-/Anhang-Vorgaben des Standardformulars
$errors[] = 'Bitte füllen Sie das Feld „' . $f['label'] . '“ aus.'; $ownForm = $deptId ? ($deptForms[(int) $deptId] ?? null) : null;
} if ($ownForm && !$ownForm['subject_show']) $subject = 'Anfrage ' . $ownForm['department_name'];
$customValues[$f['id']] = $val; if ($ownForm && !$ownForm['message_show']) {
} // Ohne Beschreibungsfeld besteht der Ticket-Text aus den Angaben der eigenen Felder
$lines = [];
// Datei-Upload (optional, ein Anhang) foreach ($ownForm['fields'] as $ff) {
$uploadInfo = null; $raw = $ff['field_type'] === 'checkbox' ? (!empty($_POST['custom_' . $ff['id']]) ? 'Ja' : 'Nein') : trim((string) ($_POST['custom_' . $ff['id']] ?? ''));
if (!$errors && !empty($_FILES['attachment']['name'])) { if ($raw !== '') $lines[] = $ff['label'] . ': ' . $raw;
$uploadInfo = handle_ticket_upload($_FILES['attachment']); }
if (isset($uploadInfo['error'])) { $message = $lines ? implode("\n", $lines) : 'Anfrage ohne weitere Angaben';
$errors[] = $uploadInfo['error']; }
}
} if ($name === '') $errors[] = 'Bitte geben Sie Ihren Namen an.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Bitte geben Sie eine gültige E-Mail-Adresse an.';
if (!$errors) { if ($subject === '') $errors[] = 'Bitte geben Sie einen Betreff an.';
// Ticket-Regeln auswerten: koennen Abteilung/Prioritaet/Hilfe-Thema vor dem Anlegen if ($message === '') $errors[] = 'Bitte beschreiben Sie Ihr Anliegen.';
// ueberschreiben, das Ticket abweisen, oder nach dem Anlegen einen Mitarbeiter zuweisen/Tags setzen.
$ruleResult = evaluate_ticket_rules($pdo, [ // Individuelle Felder validieren (nur Felder, die zum gewählten Hilfe-Thema gehören oder themenunabhängig sind)
'subject' => $subject, $customValues = []; // field id => submitted value
'message' => $message, foreach ($ownForm ? $ownForm['fields'] : $customFields as $f) {
'requester_email' => $email, if (!$ownForm && ($f['department_id'] !== null || ($f['help_topic_id'] !== null && (int) $f['help_topic_id'] !== (int) $helpTopicId))) continue;
'requester_name' => $name, $fieldName = 'custom_' . $f['id'];
'source' => 'web', $val = $f['field_type'] === 'checkbox' ? (!empty($_POST[$fieldName]) ? '1' : '0') : trim($_POST[$fieldName] ?? '');
]); if ($f['is_required'] && $f['field_type'] !== 'checkbox' && $val === '') {
if ($ruleResult['reject']) { $errors[] = 'Bitte füllen Sie das Feld „' . $f['label'] . '“ aus.';
flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.'); }
redirect('/ticket_new.php'); if ($f['is_required'] && $f['field_type'] === 'checkbox' && $val !== '1') {
} $errors[] = 'Bitte bestätigen Sie „' . $f['label'] . '“.';
if ($ruleResult['set_department'] !== null) $deptId = $ruleResult['set_department']; }
if ($ruleResult['set_priority'] !== null) $prioId = $ruleResult['set_priority']; if (in_array($f['field_type'], ['select', 'radio'], true) && $val !== '' && !in_array($val, array_map('trim', preg_split('/\r?\n/', (string) $f['options'])), true)) {
if ($ruleResult['set_help_topic'] !== null) $helpTopicId = $ruleResult['set_help_topic']; $errors[] = 'Bitte wählen Sie bei „' . $f['label'] . '“ eine der angebotenen Möglichkeiten.';
$val = '';
$priority = null; }
foreach ($priorities as $p) { $customValues[$f['id']] = $val;
if ($p['id'] == $prioId) { $priority = $p; break; } }
}
$sla = calc_sla_dates($priority, null, (int) $deptId, !empty($helpTopicId) ? (int) $helpTopicId : null); // Datei-Upload (optional, ein Anhang)
$uploadInfo = null;
$stmt = $pdo->prepare( if (!$errors && (!$ownForm || $ownForm['attachment_show']) && !empty($_FILES['attachment']['name'])) {
'INSERT INTO tickets (ticket_number, subject, user_id, requester_name, requester_email, department_id, $uploadInfo = handle_ticket_upload($_FILES['attachment']);
help_topic_id, priority_id, status, source, requester_ip, first_response_due_at, resolution_due_at, created_at, updated_at) if (isset($uploadInfo['error'])) {
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)' $errors[] = $uploadInfo['error'];
); }
$ticketNumber = generate_ticket_number($pdo); }
$now = db_now();
// IP kürzen wenn Anonymisierung aktiv if (!$errors) {
$clientIp = client_ip(); // Ticket-Regeln auswerten: koennen Abteilung/Prioritaet/Hilfe-Thema vor dem Anlegen
if (get_setting('ip_anonymize', '0') === '1') { // ueberschreiben, das Ticket abweisen, oder nach dem Anlegen einen Mitarbeiter zuweisen/Tags setzen.
$clientIp = preg_replace('/\.(\d+)$/', '.0', $clientIp); $ruleResult = evaluate_ticket_rules($pdo, [
$clientIp = preg_replace('/:[0-9a-f]{1,4}$/', ':0', $clientIp); 'subject' => $subject,
} 'message' => $message,
$stmt->execute([ 'requester_email' => $email,
$ticketNumber, $subject, $user['id'] ?? null, $name, $email, $deptId, 'requester_name' => $name,
$helpTopicId, $prioId, 'open', 'web', $clientIp, $sla['first_response_due_at'], $sla['resolution_due_at'], $now, $now, 'source' => 'web',
]); ]);
$ticketId = (int) $pdo->lastInsertId(); if ($ruleResult['reject']) {
flash('error', 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.');
$stmt = $pdo->prepare( redirect('/ticket_new.php');
'INSERT INTO ticket_threads (ticket_id, author_type, user_id, message, is_internal_note, created_at) }
VALUES (?,?,?,?,0,?)' if ($ruleResult['set_department'] !== null) $deptId = $ruleResult['set_department'];
); if ($ruleResult['set_priority'] !== null) $prioId = $ruleResult['set_priority'];
$stmt->execute([$ticketId, 'customer', $user['id'] ?? null, $message, $now]); if ($ruleResult['set_help_topic'] !== null) $helpTopicId = $ruleResult['set_help_topic'];
$threadId = (int) $pdo->lastInsertId();
$priority = null;
if ($uploadInfo) { foreach ($priorities as $p) {
$stmt = $pdo->prepare( if ($p['id'] == $prioId) { $priority = $p; break; }
'INSERT INTO ticket_attachments (thread_id, original_name, stored_name, filesize, created_at) VALUES (?,?,?,?,?)' }
); $sla = calc_sla_dates($priority, null, (int) $deptId, !empty($helpTopicId) ? (int) $helpTopicId : null);
$stmt->execute([$threadId, $uploadInfo['original_name'], $uploadInfo['stored_name'], $uploadInfo['filesize'], $now]);
} $stmt = $pdo->prepare(
'INSERT INTO tickets (ticket_number, subject, user_id, requester_name, requester_email, department_id,
if ($customValues) { help_topic_id, priority_id, status, source, requester_ip, first_response_due_at, resolution_due_at, created_at, updated_at)
$cfStmt = $pdo->prepare('INSERT INTO ticket_field_values (ticket_id, custom_field_id, value) VALUES (?,?,?)'); VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
foreach ($customValues as $fieldId => $val) { );
if ($val === '' ) continue; $ticketNumber = generate_ticket_number($pdo);
$cfStmt->execute([$ticketId, $fieldId, $val]); $now = db_now();
} // IP kürzen wenn Anonymisierung aktiv
} $clientIp = client_ip();
if (get_setting('ip_anonymize', '0') === '1') {
log_activity($pdo, $ticketId, null, 'Ticket erstellt'); $clientIp = preg_replace('/\.(\d+)$/', '.0', $clientIp);
$clientIp = preg_replace('/:[0-9a-f]{1,4}$/', ':0', $clientIp);
// Verbleibende Regel-Aktionen, die eine vorhandene Ticket-ID benötigen }
$assignTo = $ruleResult['assign_staff']; $stmt->execute([
if ($assignTo === null) { $ticketNumber, $subject, $user['id'] ?? null, $name, $email, $deptId,
// Auto-Zuweisung: war der Kunde schon mal einem Mitarbeiter zugewiesen? $helpTopicId, $prioId, 'open', 'web', $clientIp, $sla['first_response_due_at'], $sla['resolution_due_at'], $now, $now,
$prevStmt = $pdo->prepare( ]);
"SELECT assigned_staff_id FROM tickets $ticketId = (int) $pdo->lastInsertId();
WHERE LOWER(requester_email) = LOWER(?)
AND assigned_staff_id IS NOT NULL $stmt = $pdo->prepare(
AND status NOT IN ('closed','resolved') 'INSERT INTO ticket_threads (ticket_id, author_type, user_id, message, is_internal_note, created_at)
AND id != ? VALUES (?,?,?,?,0,?)'
ORDER BY updated_at DESC LIMIT 1" );
); $stmt->execute([$ticketId, 'customer', $user['id'] ?? null, $message, $now]);
$prevStmt->execute([$email, $ticketId]); $threadId = (int) $pdo->lastInsertId();
$prevId = $prevStmt->fetchColumn();
if ($prevId) { if ($uploadInfo) {
$assignTo = (int) $prevId; $stmt = $pdo->prepare(
log_activity($pdo, $ticketId, null, 'Automatisch zugewiesen (letzter Bearbeiter)'); 'INSERT INTO ticket_attachments (thread_id, original_name, stored_name, filesize, created_at) VALUES (?,?,?,?,?)'
} );
} else { $stmt->execute([$threadId, $uploadInfo['original_name'], $uploadInfo['stored_name'], $uploadInfo['filesize'], $now]);
log_activity($pdo, $ticketId, null, 'Automatisch zugewiesen (Ticket-Regel)'); }
}
if ($assignTo !== null) { if ($customValues) {
$pdo->prepare('UPDATE tickets SET assigned_staff_id = ? WHERE id = ?')->execute([$assignTo, $ticketId]); $cfStmt = $pdo->prepare('INSERT INTO ticket_field_values (ticket_id, custom_field_id, value) VALUES (?,?,?)');
} foreach ($customValues as $fieldId => $val) {
foreach ($ruleResult['add_tags'] as $tagName) { if ($val === '' ) continue;
apply_tag_to_ticket($pdo, $ticketId, $tagName); $cfStmt->execute([$ticketId, $fieldId, $val]);
} }
if ($ruleResult['matched_rules']) { }
log_activity($pdo, $ticketId, null, 'Ticket-Regel angewendet: ' . implode(', ', $ruleResult['matched_rules']));
} log_activity($pdo, $ticketId, null, 'Ticket erstellt');
apply_auto_reply($pdo, $ticketId, $ruleResult['auto_reply']);
// Verbleibende Regel-Aktionen, die eine vorhandene Ticket-ID benötigen
$deptStmt = $pdo->prepare('SELECT name, email FROM departments WHERE id = ?'); $assignTo = $ruleResult['assign_staff'];
$deptStmt->execute([$deptId]); if ($assignTo === null) {
$dept = $deptStmt->fetch(); // Auto-Zuweisung: war der Kunde schon mal einem Mitarbeiter zugewiesen?
$ticketForNotify = [ $prevStmt = $pdo->prepare(
'ticket_number' => $ticketNumber, "SELECT assigned_staff_id FROM tickets
'subject' => $subject, WHERE LOWER(requester_email) = LOWER(?)
'requester_name' => $name, AND assigned_staff_id IS NOT NULL
'requester_email' => $email, AND status NOT IN ('closed','resolved')
'department_id' => $deptId, AND id != ?
'department_name' => $dept['name'] ?? null, ORDER BY updated_at DESC LIMIT 1"
]; );
notify_new_ticket_channels($ticketForNotify, $dept['email'] ?? null); $prevStmt->execute([$email, $ticketId]);
notify_staff_new_ticket($ticketForNotify); $prevId = $prevStmt->fetchColumn();
webhook_dispatch($pdo, 'ticket.created', $ticketId); if ($prevId) {
if (file_exists(__DIR__ . '/includes/push.php')) { $assignTo = (int) $prevId;
require_once __DIR__ . '/includes/push.php'; log_activity($pdo, $ticketId, null, 'Automatisch zugewiesen (letzter Bearbeiter)');
push_new_ticket($ticketForNotify); }
} } else {
notify_customer_ticket_created($ticketForNotify); log_activity($pdo, $ticketId, null, 'Automatisch zugewiesen (Ticket-Regel)');
}
$_SESSION['guest_ticket_access'][$ticketNumber] = true; if ($assignTo !== null) {
flash('success', "Ihr Ticket #{$ticketNumber} wurde erstellt. Wir melden uns so schnell wie möglich."); $pdo->prepare('UPDATE tickets SET assigned_staff_id = ? WHERE id = ?')->execute([$assignTo, $ticketId]);
redirect('/ticket_view.php?n=' . urlencode($ticketNumber)); }
} foreach ($ruleResult['add_tags'] as $tagName) {
} apply_tag_to_ticket($pdo, $ticketId, $tagName);
}
$pageTitle = 'Neues Ticket'; if ($ruleResult['matched_rules']) {
$activePage = 'new'; log_activity($pdo, $ticketId, null, 'Ticket-Regel angewendet: ' . implode(', ', $ruleResult['matched_rules']));
require __DIR__ . '/includes/header_customer.php'; }
?> apply_auto_reply($pdo, $ticketId, $ruleResult['auto_reply']);
$closedByRule = apply_rule_close($pdo, $ticketId, $ruleResult);
<div class="ticket-create-page">
<div class="topbar ticket-create-header"> $deptStmt = $pdo->prepare('SELECT name, email FROM departments WHERE id = ?');
<div> $deptStmt->execute([$deptId]);
<h1>Neues Ticket erstellen</h1> $dept = $deptStmt->fetch();
<p class="muted" style="margin:4px 0 0">Beschreiben Sie Ihr Anliegen so genau wie möglich – das hilft uns, schneller zu helfen.</p> $ticketForNotify = [
</div> 'ticket_number' => $ticketNumber,
<a href="/dashboard.php" class="btn secondary" style="white-space:nowrap">Meine Tickets</a> 'subject' => $subject,
</div> 'requester_name' => $name,
'requester_email' => $email,
<?php foreach ($errors as $err): ?> 'department_id' => $deptId,
<div class="flash error"><?= e($err) ?></div> 'department_name' => $dept['name'] ?? null,
<?php endforeach; ?> ];
if (!$closedByRule) {
<div class="card ticket-create-card"> notify_new_ticket_channels($ticketForNotify, $dept['email'] ?? null);
<form method="post" enctype="multipart/form-data" class="ticket-create-form"> notify_staff_new_ticket($ticketForNotify);
<?= csrf_field() ?> webhook_dispatch($pdo, 'ticket.created', $ticketId);
<!-- Honeypot --> if (file_exists(__DIR__ . '/includes/push.php')) {
<div style="position:absolute;left:-9999px;top:-9999px" aria-hidden="true"> require_once __DIR__ . '/includes/push.php';
<input type="text" name="website" tabindex="-1" autocomplete="off"> push_new_ticket($ticketForNotify);
</div> }
notify_customer_ticket_created($ticketForNotify);
<?php if (!$user): ?> }
<!-- Schritt 1: Kontaktdaten -->
<div class="ticket-form-section"> $_SESSION['guest_ticket_access'][$ticketNumber] = true;
<p class="ticket-section-label"><span class="ticket-section-number">1</span>Ihre Kontaktdaten</p> flash('success', "Ihr Ticket #{$ticketNumber} wurde erstellt. Wir melden uns so schnell wie möglich.");
<div class="field-row"> redirect('/ticket_view.php?n=' . urlencode($ticketNumber));
<div> }
<label for="name">Name <span style="color:var(--danger)">*</span></label> }
<input type="text" id="name" name="name" value="<?= e($_POST['name'] ?? '') ?>" placeholder="Max Mustermann" required autofocus>
</div> $pageTitle = 'Neues Ticket';
<div> $activePage = 'new';
<label for="email">E-Mail-Adresse <span style="color:var(--danger)">*</span></label> require __DIR__ . '/includes/header_customer.php';
<input type="email" id="email" name="email" value="<?= e($_POST['email'] ?? '') ?>" placeholder="max@beispiel.de" required> ?>
</div>
</div> <div class="ticket-create-page">
<p class="ticket-form-hint"> <div class="topbar ticket-create-header">
<a href="/register.php">Kostenloses Konto erstellen</a> um alle Ihre Tickets im Überblick zu behalten. <div>
</p> <h1>Neues Ticket erstellen</h1>
</div> <p class="muted" style="margin:4px 0 0">Beschreiben Sie Ihr Anliegen so genau wie möglich – das hilft uns, schneller zu helfen.</p>
<?php endif; ?> </div>
<a href="/dashboard.php" class="btn secondary" style="white-space:nowrap">Meine Tickets</a>
<!-- Schritt 2: Anliegen --> </div>
<div class="ticket-form-section">
<p class="ticket-section-label"><span class="ticket-section-number">2</span>Ihr Anliegen</p> <?php foreach ($errors as $err): ?>
<div class="flash error"><?= e($err) ?></div>
<?php if ($useHelpTopics): ?> <?php endforeach; ?>
<label for="help_topic_id">Kategorie <span style="color:var(--danger)">*</span></label>
<select id="help_topic_id" name="help_topic_id" required onchange="updateTopicFieldVisibility()" style="margin-bottom:14px"> <?php $renderField = function (array $f): void {
<option value="">– bitte wählen –</option> $fieldName = 'custom_' . $f['id'];
<?php foreach ($helpTopics as $t): ?> $posted = $_POST[$fieldName] ?? '';
<option value="<?= $t['id'] ?>" <?= (($_POST['help_topic_id'] ?? '') == $t['id']) ? 'selected' : '' ?>><?= e($t['path']) ?></option> ?>
<?php endforeach; ?> <?php $__hint = ($f['field_type'] !== 'checkbox' && !empty($f['help_text'])) ? form_help_html($f['help_text'], (string) $f['label']) : ''; ?>
</select> <div class="custom-field-group fw-<?= e($f['form_width'] ?? '') ?: 'full' ?>" data-topic="<?= $f['help_topic_id'] !== null ? (int) $f['help_topic_id'] : '' ?>" data-dept="<?= $f['department_id'] !== null ? (int) $f['department_id'] : '' ?>">
<?php else: ?> <label for="<?= $fieldName ?>"><?= e($f['label']) ?><?= $f['is_required'] ? ' <span style="color:var(--danger)">*</span>' : '' ?></label>
<div class="field-row" style="margin-bottom:14px"> <?php if ($f['field_type'] === 'textarea'): ?>
<div> <textarea id="<?= $fieldName ?>" name="<?= $fieldName ?>" <?= $f['is_required'] ? 'required' : '' ?>><?= e($posted) ?></textarea>
<label for="department_id">Abteilung <span style="color:var(--danger)">*</span></label> <?php elseif ($f['field_type'] === 'select'): ?>
<select id="department_id" name="department_id" required> <select id="<?= $fieldName ?>" name="<?= $fieldName ?>" <?= $f['is_required'] ? 'required' : '' ?>>
<option value="">– bitte wählen –</option> <option value="">– bitte wählen –</option>
<?php foreach ($departments as $d): ?> <?php foreach (preg_split('/\r?\n/', trim((string) $f['options'])) as $opt): $opt = trim($opt); if ($opt === '') continue; ?>
<option value="<?= $d['id'] ?>" <?= (($_POST['department_id'] ?? '') == $d['id']) ? 'selected' : '' ?>><?= e($d['name']) ?></option> <option value="<?= e($opt) ?>" <?= $posted === $opt ? 'selected' : '' ?>><?= e($opt) ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</div> <?php elseif ($f['field_type'] === 'radio'): ?>
<div> <div style="margin-top:4px<?= !empty($f['radio_inline']) ? ';display:flex;flex-wrap:wrap;gap:4px 20px' : '' ?>">
<label for="priority_id">Priorität <span style="color:var(--danger)">*</span></label> <?php foreach (preg_split('/\r?\n/', trim((string) $f['options'])) as $ri => $opt): $opt = trim($opt); if ($opt === '') continue; ?>
<select id="priority_id" name="priority_id" required> <label style="display:flex;align-items:center;gap:8px;font-weight:400;margin:4px 0">
<?php foreach ($priorities as $p): ?> <input type="radio" id="<?= $fieldName ?>_<?= (int) $ri ?>" name="<?= $fieldName ?>" value="<?= e($opt) ?>" style="width:auto" <?= $f['is_required'] ? 'required' : '' ?> <?= $posted === $opt ? 'checked' : '' ?>>
<option value="<?= $p['id'] ?>" <?= (($_POST['priority_id'] ?? '') == $p['id'] || (!isset($_POST['priority_id']) && $p['name']==='Normal')) ? 'selected' : '' ?>><?= e($p['name']) ?></option> <span><?= e($opt) ?></span>
<?php endforeach; ?> </label>
</select> <?php endforeach; ?>
</div> </div>
</div> <?php elseif ($f['field_type'] === 'checkbox'): ?>
<?php endif; ?> <label style="display:flex;align-items:flex-start;gap:8px;font-weight:400;margin-top:4px">
<input type="checkbox" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="1" style="width:auto;margin-top:3px" <?= $f['is_required'] ? 'required' : '' ?> <?= !empty($posted) ? 'checked' : '' ?>>
<label for="subject">Betreff <span style="color:var(--danger)">*</span></label> <span><?= !empty($f['help_text']) ? form_help_html($f['help_text'], (string) $f['label']) : e($f['label']) ?></span>
<input type="text" id="subject" name="subject" value="<?= e($_POST['subject'] ?? '') ?>" placeholder="Kurze Zusammenfassung Ihres Problems" required style="margin-bottom:14px"> </label>
<?php elseif ($f['field_type'] === 'number'): ?>
<label for="message">Beschreibung <span style="color:var(--danger)">*</span></label> <input type="number" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>>
<textarea id="message" name="message" required placeholder="Beschreiben Sie Ihr Anliegen so detailliert wie möglich…" style="min-height:140px"><?= e($_POST['message'] ?? '') ?></textarea> <?php elseif ($f['field_type'] === 'date'): ?>
</div> <input type="date" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>>
<?php else: ?>
<?php if ($customFields): ?> <input type="text" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>>
<div class="ticket-form-section"> <?php endif; ?>
<p class="ticket-section-label"><span class="ticket-section-number">3</span>Zusätzliche Angaben</p> <?php if ($__hint !== ''): ?><p class="muted" style="font-size:.8rem;margin:4px 0 0"><?= $__hint ?></p><?php endif; ?>
<?php foreach ($customFields as $f): </div>
$fieldName = 'custom_' . $f['id']; <?php }; ?>
$posted = $_POST[$fieldName] ?? '';
?> <?php $renderSlot = function (string $section, bool $wrap = true) use ($deptForms, $renderField): void {
<div class="custom-field-group" data-topic="<?= $f['help_topic_id'] !== null ? (int) $f['help_topic_id'] : '' ?>"> $list = [];
<label for="<?= $fieldName ?>"><?= e($f['label']) ?><?= $f['is_required'] ? ' <span style="color:var(--danger)">*</span>' : '' ?></label> foreach ($deptForms as $df) foreach ($df['fields'] as $ff) if ($ff['_section'] === $section) $list[] = $ff;
<?php if ($f['field_type'] === 'textarea'): ?> if (!$list) return;
<textarea id="<?= $fieldName ?>" name="<?= $fieldName ?>" <?= $f['is_required'] ? 'required' : '' ?>><?= e($posted) ?></textarea> if ($wrap) echo '<div class="dept-fields">';
<?php elseif ($f['field_type'] === 'select'): ?> foreach ($list as $ff) $renderField($ff);
<select id="<?= $fieldName ?>" name="<?= $fieldName ?>" <?= $f['is_required'] ? 'required' : '' ?>> if ($wrap) echo '</div>';
<option value="">– bitte wählen –</option> }; ?>
<?php foreach (preg_split('/\r?\n/', trim((string) $f['options'])) as $opt): $opt = trim($opt); if ($opt === '') continue; ?> <style>
<option value="<?= e($opt) ?>" <?= $posted === $opt ? 'selected' : '' ?>><?= e($opt) ?></option> .dept-fields{display:flex;flex-wrap:wrap;gap:14px 16px;margin-bottom:14px}
<?php endforeach; ?> .dept-fields>*{flex:1 1 100%;min-width:0}
</select> .dept-fields>.fw-half{flex:0 0 calc(50% - 8px)}
<?php elseif ($f['field_type'] === 'checkbox'): ?> .dept-fields>.fw-third{flex:0 0 calc(33.333% - 11px)}
<label style="display:flex;align-items:center;gap:8px;font-weight:400;margin-top:4px"> .dept-fields>.fw-twothirds{flex:0 0 calc(66.666% - 6px)}
<input type="checkbox" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="1" style="width:auto" <?= !empty($posted) ? 'checked' : '' ?>> .dept-fields input[type=text],.dept-fields input[type=email],.dept-fields input[type=number],.dept-fields input[type=date],.dept-fields select,.dept-fields textarea{width:100%;box-sizing:border-box;margin-bottom:0}
<span><?= e($f['label']) ?></span> @media (max-width:640px){.dept-fields>.fw-half,.dept-fields>.fw-third,.dept-fields>.fw-twothirds{flex:1 1 100%}}
</label> </style>
<?php elseif ($f['field_type'] === 'number'): ?> <div class="card ticket-create-card">
<input type="number" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>> <form method="post" enctype="multipart/form-data" class="ticket-create-form">
<?php elseif ($f['field_type'] === 'date'): ?> <?= csrf_field() ?>
<input type="date" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>> <!-- Honeypot -->
<?php else: ?> <div style="position:absolute;left:-9999px;top:-9999px" aria-hidden="true">
<input type="text" id="<?= $fieldName ?>" name="<?= $fieldName ?>" value="<?= e($posted) ?>" <?= $f['is_required'] ? 'required' : '' ?>> <input type="text" name="website" tabindex="-1" autocomplete="off">
<?php endif; ?> </div>
</div>
<?php endforeach; ?> <!-- Schritt 2: Anliegen -->
</div> <div class="ticket-form-section">
<?php endif; ?> <p class="ticket-section-label"><span class="ticket-section-number">2</span><span id="issue-title">Ihr Anliegen</span></p>
<!-- Anhang --> <div class="dept-fields">
<div class="ticket-form-section ticket-attachment-section"> <?php $renderSlot('topic_top', false); ?>
<p class="ticket-section-label"><span class="ticket-section-number"><?= $customFields ? '4' : '3' ?></span>Anhang <span class="ticket-section-optional">(optional)</span></p> <div>
<label for="attachment" style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;border:1.5px dashed var(--border);border-radius:var(--radius);cursor:pointer;font-size:.85rem;color:var(--muted);font-weight:400;transition:border-color .15s" onmouseover="this.style.borderColor='var(--primary)'" onmouseout="this.style.borderColor='var(--border)'"> <?php if ($useHelpTopics): ?>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg> <label for="help_topic_id">Kategorie <span style="color:var(--danger)">*</span></label>
<span id="att-label">Datei auswählen</span> <select id="help_topic_id" name="help_topic_id" required onchange="updateTopicFieldVisibility()">
</label> <option value="">– bitte wählen –</option>
<input type="file" id="attachment" name="attachment" style="display:none" onchange="document.getElementById('att-label').textContent=this.files[0]?this.files[0].name:'Datei auswählen'"> <?php foreach ($helpTopics as $t): ?>
</div> <option value="<?= $t['id'] ?>" <?= (($_POST['help_topic_id'] ?? '') == $t['id']) ? 'selected' : '' ?>><?= e($t['path']) ?></option>
<?php endforeach; ?>
<div class="ticket-form-actions"> </select>
<p class="ticket-form-hint">Pflichtfelder sind mit <span class="ticket-required">*</span> gekennzeichnet.</p> <?php else: ?>
<button type="submit" class="btn ticket-submit">Ticket erstellen</button> <div class="field-row" style="margin-bottom:14px">
</div> <div>
</form> <label for="department_id">Abteilung <span style="color:var(--danger)">*</span></label>
</div> <select id="department_id" name="department_id" required>
</div> <option value="">– bitte wählen –</option>
<?php foreach ($departments as $d): ?>
<?php if ($useHelpTopics): ?> <option value="<?= $d['id'] ?>" <?= (($_POST['department_id'] ?? '') == $d['id']) ? 'selected' : '' ?>><?= e($d['name']) ?></option>
<script> <?php endforeach; ?>
function updateTopicFieldVisibility() { </select>
var select = document.getElementById('help_topic_id'); </div>
var selectedTopic = select ? select.value : ''; <div>
document.querySelectorAll('.custom-field-group').forEach(function (group) { <label for="priority_id">Priorität <span style="color:var(--danger)">*</span></label>
var groupTopic = group.getAttribute('data-topic'); <select id="priority_id" name="priority_id" required>
var matches = groupTopic === '' || groupTopic === selectedTopic; <?php foreach ($priorities as $p): ?>
group.style.display = matches ? '' : 'none'; <option value="<?= $p['id'] ?>" <?= (($_POST['priority_id'] ?? '') == $p['id'] || (!isset($_POST['priority_id']) && $p['name']==='Normal')) ? 'selected' : '' ?>><?= e($p['name']) ?></option>
group.querySelectorAll('input, select, textarea').forEach(function (el) { <?php endforeach; ?>
if (!matches) { </select>
if (el.required) { el.dataset.wasRequired = '1'; el.required = false; } </div>
} else if (el.dataset.wasRequired === '1') { </div>
el.required = true; <?php endif; ?>
} </div>
}); <?php $renderSlot('topic', false); ?>
}); </div>
} </div>
document.addEventListener('DOMContentLoaded', updateTopicFieldVisibility);
</script> <?php if (!$user): ?>
<?php endif; ?> <!-- Schritt 1: Kontaktdaten -->
<div class="ticket-form-section">
<?php require __DIR__ . '/includes/footer_customer.php'; ?> <p class="ticket-section-label"><span class="ticket-section-number">1</span><span class="contact-title">Ihre Kontaktdaten</span></p>
<div class="dept-fields">
<?php $renderSlot('contact_top', false); ?>
<div class="fw-half">
<label for="name">Name <span style="color:var(--danger)">*</span></label>
<input type="text" id="name" name="name" value="<?= e($_POST['name'] ?? '') ?>" placeholder="Max Mustermann" required autofocus>
</div>
<div class="fw-half">
<label for="email">E-Mail-Adresse <span style="color:var(--danger)">*</span></label>
<input type="email" id="email" name="email" value="<?= e($_POST['email'] ?? '') ?>" placeholder="max@beispiel.de" required>
</div>
<?php $renderSlot('contact', false); ?>
</div>
<p class="ticket-form-hint">
<a href="/register.php">Kostenloses Konto erstellen</a> um alle Ihre Tickets im Überblick zu behalten.
</p>
</div>
<?php else: ?>
<div class="ticket-form-section" id="contact-extra" style="display:none">
<p class="ticket-section-label"><span class="ticket-section-number">1</span><span class="contact-title">Ihre Kontaktdaten</span></p>
<?php $renderSlot('contact_top'); ?>
<?php $renderSlot('contact'); ?>
</div>
<?php endif; ?>
<!-- Schritt 3: Details -->
<div class="ticket-form-section" id="details-section">
<p class="ticket-section-label"><span class="ticket-section-number"></span><span id="details-title">Ihr Anliegen</span></p>
<div id="dept-intro" style="display:none;margin-bottom:14px"><strong id="dept-title"></strong><p class="muted" id="dept-intro-text" style="margin:4px 0 0"></p></div>
<div class="dept-fields">
<?php $renderSlot('issue_top', false); ?>
<div id="subject-wrap">
<label for="subject"><span id="subject-label">Betreff</span> <span style="color:var(--danger)">*</span></label>
<input type="text" id="subject" name="subject" value="<?= e($_POST['subject'] ?? '') ?>" placeholder="Kurze Zusammenfassung Ihres Problems" required>
</div>
<?php $renderSlot('issue_mid', false); ?>
<div id="message-wrap">
<label for="message"><span id="message-label">Beschreibung</span> <span style="color:var(--danger)">*</span></label>
<textarea id="message" name="message" required placeholder="Beschreiben Sie Ihr Anliegen so detailliert wie möglich…" style="min-height:140px"><?= e($_POST['message'] ?? '') ?></textarea>
</div>
<?php $renderSlot('issue', false); ?>
</div>
</div>
<?php if ($customFields): ?>
<div class="ticket-form-section" id="custom-section">
<p class="ticket-section-label"><span class="ticket-section-number"></span>Zusätzliche Angaben</p>
<div class="dept-fields"><?php foreach ($customFields as $f) { $renderField($f); } ?></div>
</div>
<?php endif; ?>
<?php // Eigene Abschnitte der Abteilungsformulare (Abschnittsname frei wählbar)
foreach ($deptForms as $did => $df):
$groups = [];
foreach ($df['fields'] as $ff) if (!in_array($ff['_section'], ['contact', 'contact_top', 'issue', 'issue_top', 'issue_mid', 'topic', 'topic_top'], true)) $groups[$ff['_section_title']][] = $ff;
foreach ($groups as $title => $list): ?>
<div class="ticket-form-section dept-section" data-dept="<?= (int) $did ?>" style="display:none">
<p class="ticket-section-label"><span class="ticket-section-number"></span><?= e($title) ?></p>
<div class="dept-fields"><?php foreach ($list as $ff) $renderField($ff); ?></div>
</div>
<?php endforeach; endforeach; ?>
<!-- Anhang -->
<div class="ticket-form-section ticket-attachment-section" id="attachment-section">
<p class="ticket-section-label"><span class="ticket-section-number"></span>Anhang <span class="ticket-section-optional">(optional)</span></p>
<label for="attachment" style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;border:1.5px dashed var(--border);border-radius:var(--radius);cursor:pointer;font-size:.85rem;color:var(--muted);font-weight:400;transition:border-color .15s" onmouseover="this.style.borderColor='var(--primary)'" onmouseout="this.style.borderColor='var(--border)'">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
<span id="att-label">Datei auswählen</span>
</label>
<input type="file" id="attachment" name="attachment" style="display:none" onchange="document.getElementById('att-label').textContent=this.files[0]?this.files[0].name:'Datei auswählen'">
</div>
<div class="ticket-form-actions">
<p class="ticket-form-hint">Pflichtfelder sind mit <span class="ticket-required">*</span> gekennzeichnet.</p>
<button type="submit" class="btn ticket-submit" id="submit-btn">Ticket erstellen</button>
</div>
</form>
</div>
</div>
<script>
// Formular passt sich der gewählten Abteilung an: Abteilungen mit eigenem Formular zeigen nur ihre Felder und Texte.
var DEPT_FORMS = <?= json_encode($deptForms ? array_map(fn($f) => array_diff_key($f, ['fields' => 1]), $deptForms) : new stdClass(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) ?>;
var TOPIC_DEPT = <?= json_encode($topicDept ?: new stdClass()) ?>;
var DEFAULTS = { subjectLabel: 'Betreff', messageLabel: 'Beschreibung', hint: 'Beschreiben Sie Ihr Anliegen so detailliert wie möglich…', submit: 'Ticket erstellen' };
function setShown(el, on) {
if (!el) return;
el.style.display = on ? '' : 'none';
el.querySelectorAll('input, select, textarea').forEach(function (i) {
if (!on) { if (i.required) { i.dataset.wasRequired = '1'; i.required = false; } if (i.type !== 'hidden') i.disabled = true; }
else { if (i.dataset.wasRequired === '1') i.required = true; i.disabled = false; }
});
}
function applyDeptForm() {
var topicSel = document.getElementById('help_topic_id'), deptSel = document.getElementById('department_id');
var topic = topicSel ? topicSel.value : '';
var dept = topicSel ? (TOPIC_DEPT[topic] || '') : (deptSel ? deptSel.value : '');
var form = DEPT_FORMS[dept] || null;
var visible = 0, contactVisible = 0;
document.querySelectorAll('.custom-field-group').forEach(function (g) {
var gd = g.getAttribute('data-dept'), gt = g.getAttribute('data-topic');
var show = form ? gd === String(dept) : (gd === '' && (gt === '' || gt === topic));
setShown(g, show);
if (show && gd === '') visible++;
if (show && gd !== '' && g.closest('#contact-extra')) contactVisible++;
});
var sec = document.getElementById('custom-section');
if (sec) sec.style.display = visible > 0 ? '' : 'none';
document.querySelectorAll('.dept-fields').forEach(function (w) {
w.style.display = Array.prototype.some.call(w.children, function (c) { return c.style.display !== 'none'; }) ? '' : 'none';
});
var cx = document.getElementById('contact-extra');
if (cx) cx.style.display = contactVisible > 0 ? '' : 'none';
document.querySelectorAll('.dept-section').forEach(function (s) { s.style.display = (form && s.getAttribute('data-dept') === String(dept)) ? '' : 'none'; });
document.querySelectorAll('.contact-title').forEach(function (t) { t.textContent = form ? form.contact_title : 'Ihre Kontaktdaten'; });
document.getElementById('issue-title').textContent = form ? form.issue_title : 'Ihr Anliegen';
document.getElementById('details-title').textContent = form ? form.details_title : 'Ihr Anliegen'; document.getElementById('subject-label').textContent = form ? form.subject_label : DEFAULTS.subjectLabel;
document.getElementById('message-label').textContent = form ? form.message_label : DEFAULTS.messageLabel;
document.getElementById('message').placeholder = form ? form.message_hint : DEFAULTS.hint;
document.getElementById('submit-btn').textContent = form ? form.submit_label : DEFAULTS.submit;
setShown(document.getElementById('subject-wrap'), !form || form.subject_show);
setShown(document.getElementById('message-wrap'), !form || form.message_show);
[['subject-wrap', 'subject_width'], ['message-wrap', 'message_width']].forEach(function (p) {
var el = document.getElementById(p[0]);
['fw-full', 'fw-half', 'fw-third', 'fw-twothirds'].forEach(function (k) { el.classList.remove(k); });
el.classList.add('fw-' + ((form && form[p[1]]) || 'full'));
});
setShown(document.getElementById('attachment-section'), !form || form.attachment_show);
var has = form && (form.title || form.intro);
document.getElementById('dept-intro').style.display = has ? '' : 'none';
document.getElementById('dept-title').textContent = form ? form.title : '';
document.getElementById('dept-intro-text').textContent = form ? form.intro : '';
var num = 0;
document.querySelectorAll('.ticket-form-section').forEach(function (s) {
var n = s.querySelector('.ticket-section-number');
if (n && s.style.display !== 'none') n.textContent = ++num;
});
}
function updateTopicFieldVisibility() { applyDeptForm(); }
document.addEventListener('DOMContentLoaded', function () {
var d = document.getElementById('department_id');
if (d) d.addEventListener('change', applyDeptForm);
applyDeptForm();
});
</script>
<?php require __DIR__ . '/includes/footer_customer.php'; ?>
+1
View File
@@ -69,6 +69,7 @@ $siteName = get_setting('display_name', config()['site']['name'] ?? 'DeskHub');
.print-footer { margin-top: 20px; padding-top: 8px; border-top: 1px solid #e2e8f0; font-size: 8.5pt; color: #94a3b8; display: flex; justify-content: space-between; } .print-footer { margin-top: 20px; padding-top: 8px; border-top: 1px solid #e2e8f0; font-size: 8.5pt; color: #94a3b8; display: flex; justify-content: space-between; }
@media print { .no-print { display: none !important; } @page { margin: 15mm; } } @media print { .no-print { display: none !important; } @page { margin: 15mm; } }
</style> </style>
<?= site_icon_links() ?>
</head> </head>
<body> <body>