Upload via GUI (30 Dateien)
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
/**
|
||||
* Verbindung zur öffentlichen DeskHub-API (api/public/v1/tickets.php).
|
||||
* Der API-Schlüssel wird nur hier und nur vom Server aus gesendet, nie an den Browser eines Besuchers.
|
||||
*/
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
class Deskhub_Tickets_Client
|
||||
{
|
||||
/** @var string Adresse der DeskHub-Installation ohne Schrägstrich am Ende, zum Beispiel https://support.example.de */
|
||||
private $base;
|
||||
/** @var string */
|
||||
private $key;
|
||||
|
||||
public function __construct(string $baseUrl, string $apiKey)
|
||||
{
|
||||
$this->base = rtrim($baseUrl, '/');
|
||||
$this->key = $apiKey;
|
||||
}
|
||||
|
||||
/** Client aus den Einstellungen; null, solange Adresse oder Schlüssel fehlen. */
|
||||
public static function from_settings(): ?self
|
||||
{
|
||||
$opts = deskhub_tickets_options();
|
||||
$url = self::normalize_url((string) $opts['server_url']);
|
||||
if (is_wp_error($url) || trim((string) $opts['api_key']) === '') {
|
||||
return null;
|
||||
}
|
||||
return new self($url, trim((string) $opts['api_key']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bereinigt die Server-Adresse: https ist Pflicht (http nur für lokale Tests), kein Benutzername, keine Parameter.
|
||||
*
|
||||
* @return string|WP_Error
|
||||
*/
|
||||
public static function normalize_url(string $input)
|
||||
{
|
||||
$s = trim($input);
|
||||
if ($s === '') {
|
||||
return new WP_Error('deskhub_url', __('Bitte die Adresse Ihres DeskHub-Servers eintragen.', 'deskhub-tickets'));
|
||||
}
|
||||
if (strpos($s, '://') === false) {
|
||||
$s = 'https://' . $s;
|
||||
}
|
||||
$p = wp_parse_url($s);
|
||||
if (!$p || empty($p['host']) || !empty($p['user']) || !empty($p['pass']) || !empty($p['query']) || !empty($p['fragment'])) {
|
||||
return new WP_Error('deskhub_url', __('Die Server-Adresse ist ungültig.', 'deskhub-tickets'));
|
||||
}
|
||||
$scheme = strtolower((string) ($p['scheme'] ?? ''));
|
||||
$host = strtolower((string) $p['host']);
|
||||
$local = in_array($host, ['localhost', '127.0.0.1', '[::1]', '::1'], true);
|
||||
$insecureOk = $local || (bool) apply_filters('deskhub_tickets_allow_insecure', false, $host);
|
||||
if ($scheme !== 'https' && !($scheme === 'http' && $insecureOk)) {
|
||||
return new WP_Error('deskhub_url', __('Die Server-Adresse muss mit https beginnen.', 'deskhub-tickets'));
|
||||
}
|
||||
$port = isset($p['port']) ? ':' . (int) $p['port'] : '';
|
||||
$path = isset($p['path']) ? rtrim((string) $p['path'], '/') : '';
|
||||
return $scheme . '://' . $host . $port . $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt ein Ticket an.
|
||||
*
|
||||
* @param array{name:string,email:string,subject:string,message:string,helpTopicId?:int,departmentId?:int,priorityId?:int,fields?:array<int,string>} $data
|
||||
* @return array{number:string,status:string}|WP_Error
|
||||
*/
|
||||
public function create_ticket(array $data)
|
||||
{
|
||||
$fields = $data['fields'] ?? null;
|
||||
unset($data['fields']);
|
||||
$payload = array_filter($data, static function ($v) {
|
||||
return $v !== null && $v !== '' && $v !== 0;
|
||||
});
|
||||
if (is_array($fields)) {
|
||||
$payload['fields'] = (object) $fields; // auch leer senden: Damit prüft DeskHub die Angaben gegen das Kundenformular
|
||||
}
|
||||
$res = $this->request('POST', [], $payload);
|
||||
if (is_wp_error($res)) {
|
||||
return $res;
|
||||
}
|
||||
if (empty($res['number']) || !is_string($res['number'])) {
|
||||
return new WP_Error('deskhub_response', __('Der Server hat eine unerwartete Antwort geliefert.', 'deskhub-tickets'));
|
||||
}
|
||||
return ['number' => $res['number'], 'status' => (string) ($res['status'] ?? 'open')];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Kundenformular aus DeskHub für ein Hilfethema oder eine Abteilung: eigene Felder, Texte, Reihenfolge, Pflichtfelder.
|
||||
* Das Ergebnis wird kurz zwischengespeichert, damit nicht jeder Seitenaufruf den Server fragt.
|
||||
* Kennt der Server die Schnittstelle noch nicht (ältere DeskHub-Version), kommt ein WP_Error "deskhub_form_unsupported":
|
||||
* Dann zeigt das Plugin das einfache Formular.
|
||||
*
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
public function get_form(?int $topicId, ?int $deptId)
|
||||
{
|
||||
$key = 'dht_form_' . md5($this->base . '|' . (int) $topicId . '|' . (int) $deptId);
|
||||
$cached = get_transient($key);
|
||||
if (is_array($cached)) {
|
||||
return !empty($cached['unsupported'])
|
||||
? new WP_Error('deskhub_form_unsupported', __('Der DeskHub-Server kennt die Formular-Schnittstelle noch nicht.', 'deskhub-tickets'))
|
||||
: $cached['form'];
|
||||
}
|
||||
$query = ['form' => '1'];
|
||||
if ($topicId) {
|
||||
$query['helpTopicId'] = (string) $topicId;
|
||||
}
|
||||
if ($deptId) {
|
||||
$query['departmentId'] = (string) $deptId;
|
||||
}
|
||||
$ttl = (int) apply_filters('deskhub_tickets_form_cache_seconds', 300);
|
||||
$res = $this->request('GET', $query);
|
||||
$data = is_wp_error($res) ? $res->get_error_data() : null;
|
||||
$apiCode = is_array($data) ? (string) ($data['api_code'] ?? '') : '';
|
||||
// Ältere Server lesen "form=1" als Ticketabfrage und antworten "Parameter fehlen"; unbekannte Antworten zählen ebenso als "nicht unterstützt"
|
||||
if ((is_wp_error($res) && $apiCode === 'MISSING_PARAMS') || (!is_wp_error($res) && empty($res['form']))) {
|
||||
set_transient($key, ['unsupported' => true], max(30, $ttl));
|
||||
return new WP_Error('deskhub_form_unsupported', __('Der DeskHub-Server kennt die Formular-Schnittstelle noch nicht.', 'deskhub-tickets'));
|
||||
}
|
||||
if (is_wp_error($res)) {
|
||||
return $res;
|
||||
}
|
||||
if ($ttl > 0) {
|
||||
set_transient($key, ['form' => $res['form']], $ttl);
|
||||
}
|
||||
return $res['form'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die öffentlichen Hilfethemen des Servers (für die Auswahl in den Einstellungen).
|
||||
*
|
||||
* @return array<int,array{id:int,name:string,path:string,departmentId:int}>|WP_Error
|
||||
*/
|
||||
public function get_topics()
|
||||
{
|
||||
$res = $this->request('GET', ['topics' => '1']);
|
||||
if (is_wp_error($res)) {
|
||||
return $res;
|
||||
}
|
||||
return isset($res['topics']) && is_array($res['topics']) ? $res['topics'] : new WP_Error('deskhub_form_unsupported', __('Der DeskHub-Server kennt die Formular-Schnittstelle noch nicht.', 'deskhub-tickets'));
|
||||
}
|
||||
|
||||
/** Leert den Zwischenspeicher der Formulare (zum Beispiel nach einer Änderung in DeskHub). */
|
||||
public static function clear_form_cache(): void
|
||||
{
|
||||
global $wpdb;
|
||||
if (isset($wpdb) && is_object($wpdb)) {
|
||||
$wpdb->query($wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
|
||||
$wpdb->esc_like('_transient_dht_form_') . '%',
|
||||
$wpdb->esc_like('_transient_timeout_dht_form_') . '%'
|
||||
));
|
||||
}
|
||||
if (function_exists('wp_cache_flush_group')) {
|
||||
@wp_cache_flush_group('transient');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Status und öffentlicher Verlauf eines Tickets (nur mit passender E-Mail-Adresse).
|
||||
*
|
||||
* @return array|WP_Error das Feld "ticket" der Antwort
|
||||
*/
|
||||
public function get_ticket(string $number, string $email)
|
||||
{
|
||||
$res = $this->request('GET', ['number' => $number, 'email' => $email]);
|
||||
if (is_wp_error($res)) {
|
||||
return $res;
|
||||
}
|
||||
if (empty($res['ticket']) || !is_array($res['ticket'])) {
|
||||
return new WP_Error('deskhub_response', __('Der Server hat eine unerwartete Antwort geliefert.', 'deskhub-tickets'));
|
||||
}
|
||||
return $res['ticket'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft Adresse und Schlüssel, ohne ein Ticket anzulegen. Ein Aufruf mit erfundenen Daten genügt: Antwortet der Server mit
|
||||
* "nicht gefunden" (404) oder "keine Leseberechtigung" (403), ist der Schlüssel gültig. 401 heißt: Schlüssel falsch.
|
||||
*
|
||||
* @return array{ok:bool,message:string,canRead:bool}
|
||||
*/
|
||||
public function test_connection(): array
|
||||
{
|
||||
$res = $this->request('GET', ['number' => 'VERBINDUNGSTEST', 'email' => 'test@example.invalid']);
|
||||
if (!is_wp_error($res)) {
|
||||
return ['ok' => true, 'message' => __('Verbindung steht.', 'deskhub-tickets'), 'canRead' => true];
|
||||
}
|
||||
$data = $res->get_error_data();
|
||||
$status = is_array($data) ? (int) ($data['status'] ?? 0) : 0;
|
||||
if ($status === 404) {
|
||||
return ['ok' => true, 'message' => __('Verbindung steht, der Schlüssel ist gültig und darf Tickets lesen.', 'deskhub-tickets'), 'canRead' => true];
|
||||
}
|
||||
if ($status === 403) {
|
||||
return ['ok' => true, 'message' => __('Verbindung steht, der Schlüssel ist gültig. Er darf aber keine Tickets lesen: Die Statusabfrage funktioniert damit nicht (in DeskHub unter Verwalten → API-Schlüssel das Recht „Tickets lesen“ geben).', 'deskhub-tickets'), 'canRead' => false];
|
||||
}
|
||||
$apiCode = is_array($data) ? (string) ($data['api_code'] ?? '') : '';
|
||||
if ($status === 401 && $apiCode === 'IP_NOT_ALLOWED') {
|
||||
// DeskHub nennt die Adresse, die es sieht (bei Cloudflare oder Proxy oft nicht die erwartete)
|
||||
return ['ok' => false, 'message' => sprintf(__('Der Schlüssel ist gültig, aber DeskHub lässt diese Adresse nicht zu. DeskHub meldet: %s', 'deskhub-tickets'), (string) ($data['api_message'] ?? '')), 'canRead' => false];
|
||||
}
|
||||
if ($status === 401) {
|
||||
return ['ok' => false, 'message' => __('Der Server hat den API-Schlüssel abgelehnt. Bitte den Schlüssel prüfen: Er muss genau so eingetragen sein, aktiv sein und darf bei „Erlaubte IPs“ keine andere Adresse verlangen als die dieses WordPress-Servers (im Zweifel das Feld leer lassen).', 'deskhub-tickets'), 'canRead' => false];
|
||||
}
|
||||
if ($status === 0) {
|
||||
$detail = is_array($data) && !empty($data['transport']) ? ' (' . (string) $data['transport'] . ')' : '';
|
||||
return ['ok' => false, 'message' => $res->get_error_message() . $detail, 'canRead' => false];
|
||||
}
|
||||
return ['ok' => false, 'message' => sprintf(__('Der Server antwortet mit einem Fehler (%d).', 'deskhub-tickets'), $status), 'canRead' => false];
|
||||
}
|
||||
|
||||
/**
|
||||
* Freundliche Meldung für Besucher. Technische Einzelheiten (auch der Schlüssel) gelangen nie in die Seite.
|
||||
*/
|
||||
public static function user_message(WP_Error $e): string
|
||||
{
|
||||
$data = $e->get_error_data();
|
||||
$api = is_array($data) ? (string) ($data['api_code'] ?? '') : '';
|
||||
switch ($api) {
|
||||
case 'INVALID_NAME':
|
||||
return __('Bitte geben Sie Ihren Namen an (höchstens 120 Zeichen).', 'deskhub-tickets');
|
||||
case 'INVALID_EMAIL':
|
||||
return __('Bitte geben Sie eine gültige E-Mail-Adresse an.', 'deskhub-tickets');
|
||||
case 'INVALID_SUBJECT':
|
||||
return __('Bitte geben Sie einen Betreff an (höchstens 255 Zeichen).', 'deskhub-tickets');
|
||||
case 'INVALID_MESSAGE':
|
||||
return __('Bitte beschreiben Sie Ihr Anliegen.', 'deskhub-tickets');
|
||||
case 'BANNED':
|
||||
case 'REJECTED':
|
||||
return __('Ihre Anfrage konnte leider nicht angenommen werden.', 'deskhub-tickets');
|
||||
case 'RATE_LIMITED':
|
||||
return __('Gerade sind sehr viele Anfragen eingegangen. Bitte versuchen Sie es in einer Minute noch einmal.', 'deskhub-tickets');
|
||||
case 'INVALID_FIELD':
|
||||
// Diese Meldungen schreibt DeskHub für Besucher („Bitte füllen Sie das Feld … aus.“)
|
||||
return is_array($data) && !empty($data['api_message']) ? (string) $data['api_message'] : __('Bitte prüfen Sie Ihre Angaben.', 'deskhub-tickets');
|
||||
case 'NOT_FOUND':
|
||||
return __('Zu dieser Kombination aus Ticketnummer und E-Mail-Adresse wurde nichts gefunden.', 'deskhub-tickets');
|
||||
}
|
||||
return __('Der Support ist gerade nicht erreichbar. Bitte versuchen Sie es später noch einmal.', 'deskhub-tickets');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Aufruf der API.
|
||||
*
|
||||
* @param array<string,string> $query
|
||||
* @param array<string,mixed>|null $body
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
private function request(string $method, array $query = [], ?array $body = null)
|
||||
{
|
||||
$url = $this->base . '/api/public/v1/tickets.php';
|
||||
if ($query) {
|
||||
$url = add_query_arg(array_map('rawurlencode', $query), $url);
|
||||
}
|
||||
$args = [
|
||||
'method' => $method,
|
||||
'timeout' => 15,
|
||||
'redirection' => 0,
|
||||
'headers' => [
|
||||
'X-API-Key' => $this->key,
|
||||
'Accept' => 'application/json',
|
||||
'User-Agent' => 'DeskHub-Tickets-WordPress/' . DESKHUB_TICKETS_VERSION,
|
||||
],
|
||||
];
|
||||
if ($body !== null) {
|
||||
$args['headers']['Content-Type'] = 'application/json';
|
||||
$args['body'] = wp_json_encode($body);
|
||||
}
|
||||
$response = wp_remote_request($url, $args);
|
||||
if (is_wp_error($response)) {
|
||||
error_log('DeskHub Tickets: Server nicht erreichbar: ' . $response->get_error_message());
|
||||
return new WP_Error('deskhub_unreachable', __('Der DeskHub-Server ist nicht erreichbar.', 'deskhub-tickets'), ['status' => 0, 'transport' => mb_substr(preg_replace('/\s+/', ' ', $response->get_error_message()), 0, 200)]);
|
||||
}
|
||||
$status = (int) wp_remote_retrieve_response_code($response);
|
||||
$decoded = json_decode((string) wp_remote_retrieve_body($response), true);
|
||||
if ($status >= 200 && $status < 300 && is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
$apiCode = is_array($decoded) ? (string) ($decoded['error']['code'] ?? '') : '';
|
||||
$apiMessage = is_array($decoded) ? (string) ($decoded['error']['message'] ?? '') : '';
|
||||
if ($status >= 500 || $status === 0 || !is_array($decoded)) {
|
||||
error_log('DeskHub Tickets: unerwartete Antwort (HTTP ' . $status . ')');
|
||||
} elseif ($status === 401 || $status === 403) {
|
||||
error_log('DeskHub Tickets: DeskHub antwortet ' . $status . ' ' . $apiCode . ': ' . $apiMessage); // enthält nie den Schlüssel
|
||||
}
|
||||
return new WP_Error(
|
||||
'deskhub_api_' . ($apiCode !== '' ? strtolower($apiCode) : 'error'),
|
||||
$apiMessage !== '' ? $apiMessage : __('Der Server hat die Anfrage abgelehnt.', 'deskhub-tickets'),
|
||||
['status' => $status, 'api_code' => $apiCode, 'api_message' => $apiMessage]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
<?php
|
||||
/**
|
||||
* Shortcodes [deskhub_ticket] (Ticket anlegen) und [deskhub_status] (Stand abfragen) samt Verarbeitung.
|
||||
*
|
||||
* Das Formular funktioniert ohne JavaScript und mit Seiten-Cache: Es nutzt keine WordPress-Nonce (die würde in einer
|
||||
* zwischengespeicherten Seite ablaufen), sondern einen unterschriebenen Zeitstempel, ein verstecktes Falle-Feld,
|
||||
* eine Mengenbegrenzung je Besucher und optional Cloudflare Turnstile.
|
||||
*/
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
class Deskhub_Tickets_Form
|
||||
{
|
||||
const MAX_MESSAGE = 10000;
|
||||
|
||||
public static function init(): void
|
||||
{
|
||||
add_shortcode('deskhub_ticket', [__CLASS__, 'render_ticket_form']);
|
||||
add_shortcode('deskhub_status', [__CLASS__, 'render_status_form']);
|
||||
add_action('admin_post_nopriv_deskhub_ticket_submit', [__CLASS__, 'handle_submit']);
|
||||
add_action('admin_post_deskhub_ticket_submit', [__CLASS__, 'handle_submit']);
|
||||
add_action('wp_enqueue_scripts', [__CLASS__, 'register_assets']);
|
||||
}
|
||||
|
||||
public static function register_assets(): void
|
||||
{
|
||||
wp_register_style('deskhub-tickets', DESKHUB_TICKETS_ASSETS . 'assets/form.css', [], DESKHUB_TICKETS_VERSION);
|
||||
}
|
||||
|
||||
private static function enqueue(): void
|
||||
{
|
||||
wp_enqueue_style('deskhub-tickets');
|
||||
wp_enqueue_script('deskhub-tickets-theme', DESKHUB_TICKETS_ASSETS . 'assets/theme.js', [], DESKHUB_TICKETS_VERSION, true);
|
||||
}
|
||||
|
||||
/** Knopffarbe aus den Einstellungen des aktiven Themes (theme.json / Styles-Editor), als #hex; leer, wenn nichts gefunden wird. */
|
||||
private static function theme_button_color(): string
|
||||
{
|
||||
if (!function_exists('wp_get_global_styles') || !function_exists('wp_get_global_settings')) {
|
||||
return '';
|
||||
}
|
||||
$v = wp_get_global_styles(['elements', 'button', 'color', 'background']);
|
||||
if (!is_string($v) || $v === '') {
|
||||
$v = wp_get_global_styles(['elements', 'link', 'color', 'text']);
|
||||
}
|
||||
if (!is_string($v)) {
|
||||
return '';
|
||||
}
|
||||
$slug = '';
|
||||
if (preg_match('/^var\(--wp--preset--color--([a-z0-9-]+)\)$/', $v, $m) || preg_match('/^var:preset\|color\|([a-z0-9-]+)$/', $v, $m)) {
|
||||
$slug = $m[1];
|
||||
} elseif (sanitize_hex_color($v)) {
|
||||
return $v;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
$palette = wp_get_global_settings(['color', 'palette']);
|
||||
foreach ((array) $palette as $list) {
|
||||
foreach ((array) $list as $entry) {
|
||||
if (is_array($entry) && ($entry['slug'] ?? '') === $slug && sanitize_hex_color((string) ($entry['color'] ?? ''))) {
|
||||
return (string) $entry['color'];
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Öffnendes Tag der Formular-Hülle; eine feste Akzentfarbe aus den Einstellungen setzt die Variable (sonst liest theme.js sie vom Theme). */
|
||||
private static function wrap_open(string $id): string
|
||||
{
|
||||
$accent = sanitize_hex_color((string) (deskhub_tickets_options()['accent_color'] ?? ''));
|
||||
$attr = $accent ? ' data-dht-accent="fixed" style="--dht-theme-accent:' . esc_attr($accent) . '"' : '';
|
||||
$server = $accent ? '' : self::theme_button_color();
|
||||
if ($server !== '') {
|
||||
$attr = ' style="--dht-server-accent:' . esc_attr($server) . '"';
|
||||
}
|
||||
return '<div class="dht-wrap" id="' . esc_attr($id) . '"' . $attr . '>';
|
||||
}
|
||||
|
||||
// ───────────────────────────── Ticket anlegen ─────────────────────────────
|
||||
|
||||
/** Plätze im Formular, die DeskHub für eigene Felder kennt (alles andere kommt als „Zusätzliche Angaben“ ans Ende). */
|
||||
const SLOTS = ['contact_top', 'contact', 'topic_top', 'topic', 'issue_top', 'issue_mid', 'issue'];
|
||||
|
||||
/**
|
||||
* @param array|string $atts
|
||||
*/
|
||||
public static function render_ticket_form($atts = []): string
|
||||
{
|
||||
$atts = shortcode_atts([
|
||||
'department' => '',
|
||||
'topic' => '',
|
||||
'priority' => '',
|
||||
'topics' => '',
|
||||
'title' => '',
|
||||
], is_array($atts) ? $atts : [], 'deskhub_ticket');
|
||||
self::enqueue();
|
||||
|
||||
$client = Deskhub_Tickets_Client::from_settings();
|
||||
if (!$client) {
|
||||
return current_user_can('manage_options')
|
||||
? '<p class="dht-notice dht-error">' . esc_html__('DeskHub Tickets ist noch nicht eingerichtet: Bitte unter Einstellungen → DeskHub Tickets Server-Adresse und API-Schlüssel eintragen. (Diese Meldung sehen nur Administratoren.)', 'deskhub-tickets') . '</p>'
|
||||
: '';
|
||||
}
|
||||
$opts = deskhub_tickets_options();
|
||||
$topics = self::parse_topics((string) $atts['topics']);
|
||||
$cfg = self::form_config($atts, $opts, $topics);
|
||||
$cfgB64 = base64_encode((string) wp_json_encode($cfg));
|
||||
|
||||
$state = self::take_state();
|
||||
$values = ['name' => '', 'email' => '', 'subject' => '', 'message' => '', 'topic' => 0, 'fields' => []];
|
||||
if (is_user_logged_in()) {
|
||||
$u = wp_get_current_user();
|
||||
$values['name'] = (string) $u->display_name;
|
||||
$values['email'] = (string) $u->user_email;
|
||||
}
|
||||
if ($state && !empty($state['values']) && is_array($state['values'])) {
|
||||
$values = array_merge($values, array_intersect_key($state['values'], $values));
|
||||
}
|
||||
|
||||
ob_start();
|
||||
echo self::wrap_open('deskhub-ticket');
|
||||
if ($state && !empty($state['ok'])) {
|
||||
$text = trim((string) $opts['success_text']) !== '' ? (string) $opts['success_text'] : __('Vielen Dank! Wir melden uns so schnell wie möglich per E-Mail.', 'deskhub-tickets');
|
||||
echo '<div class="dht-notice dht-success" role="status"><p>' . esc_html($text) . '</p>';
|
||||
if (!empty($state['number'])) {
|
||||
echo '<p>' . sprintf(esc_html__('Ihre Ticketnummer: %s', 'deskhub-tickets'), '<strong>' . esc_html((string) $state['number']) . '</strong>') . '</p>';
|
||||
}
|
||||
if ($opts['status_page_url'] !== '') {
|
||||
echo '<p><a href="' . esc_url((string) $opts['status_page_url']) . '">' . esc_html__('Stand abfragen', 'deskhub-tickets') . '</a></p>';
|
||||
}
|
||||
echo '</div></div>';
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
// Kundenformulare aus DeskHub: eines je Thema der Auswahl, sonst eines für das Thema/die Abteilung. Ohne Antwort: einfaches Formular.
|
||||
$forms = [];
|
||||
$unsupported = false;
|
||||
$topicIds = $topics ? array_map('intval', array_column($topics, 'id')) : [(int) $cfg['t']];
|
||||
foreach ($topicIds as $tid) {
|
||||
$f = $client->get_form($tid ?: null, (int) $cfg['d'] ?: null);
|
||||
if (is_wp_error($f)) {
|
||||
$forms = [];
|
||||
$unsupported = $f->get_error_code() === 'deskhub_form_unsupported';
|
||||
break;
|
||||
}
|
||||
$forms[$tid] = self::normalize_form($f);
|
||||
}
|
||||
if (!$forms) {
|
||||
$forms = [$topicIds[0] ?? 0 => self::normalize_form(null)];
|
||||
}
|
||||
$multi = count($topics) > 0;
|
||||
$selected = $multi ? (int) $values['topic'] : (int) array_key_first($forms);
|
||||
$active = $forms[$selected] ?? reset($forms);
|
||||
$texts = [];
|
||||
foreach ($forms as $tid => $fm) {
|
||||
$texts[$tid] = ['title' => $fm['title'], 'intro' => $fm['intro'], 'subjectShow' => $fm['subject']['show'], 'subjectLabel' => $fm['subject']['label'],
|
||||
'messageShow' => $fm['message']['show'], 'messageLabel' => $fm['message']['label'], 'messageHint' => $fm['message']['hint'], 'submitLabel' => $fm['submitLabel']];
|
||||
}
|
||||
if ($unsupported && current_user_can('manage_options')) {
|
||||
echo '<p class="dht-notice dht-error">' . esc_html__('Der DeskHub-Server kennt die Formular-Schnittstelle noch nicht (bitte DeskHub aktualisieren). Bis dahin wird das einfache Formular ohne eigene Felder gezeigt. (Diese Meldung sehen nur Administratoren.)', 'deskhub-tickets') . '</p>';
|
||||
}
|
||||
$title = $atts['title'] !== '' ? (string) $atts['title'] : (string) $active['title'];
|
||||
echo '<h3 class="dht-title dht-form-title"' . ($atts['title'] !== '' ? ' data-fixed="1"' : '') . ($title === '' ? ' hidden' : '') . '>' . esc_html($title) . '</h3>';
|
||||
echo '<p class="dht-intro dht-form-intro"' . ($active['intro'] === '' ? ' hidden' : '') . '>' . esc_html((string) $active['intro']) . '</p>';
|
||||
if ($state && !empty($state['errors'])) {
|
||||
echo '<div class="dht-notice dht-error" role="alert"><ul>';
|
||||
foreach ((array) $state['errors'] as $err) {
|
||||
echo '<li>' . esc_html((string) $err) . '</li>';
|
||||
}
|
||||
echo '</ul></div>';
|
||||
}
|
||||
$showSubject = (bool) $active['subject']['show'];
|
||||
$showMessage = (bool) $active['message']['show'];
|
||||
?>
|
||||
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="dht-form" data-dht-forms="<?php echo esc_attr((string) wp_json_encode($texts)); ?>">
|
||||
<input type="hidden" name="action" value="deskhub_ticket_submit">
|
||||
<input type="hidden" name="dht_cfg" value="<?php echo esc_attr($cfgB64); ?>">
|
||||
<input type="hidden" name="dht_sig" value="<?php echo esc_attr(deskhub_tickets_sign('cfg|' . $cfgB64)); ?>">
|
||||
<input type="hidden" name="dht_ts" value="<?php echo esc_attr(deskhub_tickets_timestamp_token()); ?>">
|
||||
<input type="hidden" name="dht_back" value="<?php echo esc_attr(self::current_url()); ?>">
|
||||
<div class="dht-trap" aria-hidden="true">
|
||||
<label>Website <input type="text" name="dht_website" value="" tabindex="-1" autocomplete="off"></label>
|
||||
</div>
|
||||
<?php echo self::render_slot($forms, ['contact_top'], $multi, $selected, $values['fields']); ?>
|
||||
<p>
|
||||
<label for="dht-name"><?php echo esc_html__('Ihr Name', 'deskhub-tickets'); ?> *</label>
|
||||
<input type="text" id="dht-name" name="dht_name" value="<?php echo esc_attr((string) $values['name']); ?>" maxlength="120" required autocomplete="name">
|
||||
</p>
|
||||
<p>
|
||||
<label for="dht-email"><?php echo esc_html__('Ihre E-Mail-Adresse', 'deskhub-tickets'); ?> *</label>
|
||||
<input type="email" id="dht-email" name="dht_email" value="<?php echo esc_attr((string) $values['email']); ?>" maxlength="190" required autocomplete="email">
|
||||
</p>
|
||||
<?php echo self::render_slot($forms, ['contact'], $multi, $selected, $values['fields']); ?>
|
||||
<?php echo self::render_slot($forms, ['topic_top'], $multi, $selected, $values['fields']); ?>
|
||||
<?php if ($topics): ?>
|
||||
<p>
|
||||
<label for="dht-topic"><?php echo esc_html__('Worum geht es?', 'deskhub-tickets'); ?> *</label>
|
||||
<select id="dht-topic" name="dht_topic" required>
|
||||
<option value=""><?php echo esc_html__('Bitte wählen …', 'deskhub-tickets'); ?></option>
|
||||
<?php foreach ($topics as $tp): ?>
|
||||
<option value="<?php echo (int) $tp['id']; ?>" <?php selected((int) $values['topic'], (int) $tp['id']); ?>><?php echo esc_html($tp['label']); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
<?php echo self::render_slot($forms, ['topic'], $multi, $selected, $values['fields']); ?>
|
||||
<?php echo self::render_slot($forms, ['issue_top'], $multi, $selected, $values['fields']); ?>
|
||||
<p class="dht-subject-wrap"<?php echo $showSubject ? '' : ' hidden'; ?>>
|
||||
<label for="dht-subject"><span class="dht-subject-label"><?php echo esc_html((string) $active['subject']['label']); ?></span> *</label>
|
||||
<input type="text" id="dht-subject" name="dht_subject" value="<?php echo esc_attr((string) $values['subject']); ?>" maxlength="255" <?php echo $showSubject ? 'required' : 'disabled'; ?>>
|
||||
</p>
|
||||
<?php echo self::render_slot($forms, ['issue_mid'], $multi, $selected, $values['fields']); ?>
|
||||
<p class="dht-message-wrap"<?php echo $showMessage ? '' : ' hidden'; ?>>
|
||||
<label for="dht-message"><span class="dht-message-label"><?php echo esc_html((string) $active['message']['label']); ?></span> *</label>
|
||||
<textarea id="dht-message" name="dht_message" rows="7" maxlength="<?php echo (int) self::MAX_MESSAGE; ?>" placeholder="<?php echo esc_attr((string) $active['message']['hint']); ?>" <?php echo $showMessage ? 'required' : 'disabled'; ?>><?php echo esc_textarea((string) $values['message']); ?></textarea>
|
||||
</p>
|
||||
<?php echo self::render_slot($forms, ['issue'], $multi, $selected, $values['fields']); ?>
|
||||
<?php echo self::render_slot($forms, [], $multi, $selected, $values['fields'], true); ?>
|
||||
<?php if (trim((string) $opts['consent_text']) !== ''): ?>
|
||||
<p class="dht-consent">
|
||||
<label><input type="checkbox" name="dht_consent" value="1" required> <span><?php echo wp_kses((string) $opts['consent_text'], ['a' => ['href' => [], 'target' => [], 'rel' => []], 'strong' => [], 'em' => []]); ?></span></label>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
<?php echo self::turnstile_widget(); ?>
|
||||
<p><button type="submit" class="dht-button dht-submit"><?php echo esc_html((string) $active['submitLabel']); ?></button></p>
|
||||
</form>
|
||||
<?php
|
||||
wp_enqueue_script('deskhub-tickets', DESKHUB_TICKETS_ASSETS . 'assets/form.js', [], DESKHUB_TICKETS_VERSION, true);
|
||||
echo '</div>';
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
/** Abteilung, Thema, Priorität und erlaubte Themen dieses Formulars (reisen unterschrieben im Formular). */
|
||||
private static function form_config(array $atts, array $opts, array $topics): array
|
||||
{
|
||||
$hasTopic = $topics || $atts['topic'] !== '' || (int) $opts['topic_id'] > 0;
|
||||
// Mit Thema bestimmt DeskHub die Abteilung (Thema und Abteilungsformular gehören zusammen), außer der Shortcode nennt eine ausdrücklich
|
||||
$dept = $atts['department'] !== '' ? absint($atts['department']) : ($hasTopic ? 0 : (int) $opts['department_id']);
|
||||
return [
|
||||
'd' => $dept,
|
||||
't' => $atts['topic'] !== '' ? absint($atts['topic']) : (int) $opts['topic_id'],
|
||||
'p' => $atts['priority'] !== '' ? absint($atts['priority']) : (int) $opts['priority_id'],
|
||||
'o' => array_values(array_map('intval', array_column($topics, 'id'))),
|
||||
];
|
||||
}
|
||||
|
||||
/** Bringt ein Formular von DeskHub (oder null) in eine feste Form mit Standardwerten, Feldern nach Plätzen sortiert. */
|
||||
public static function normalize_form(?array $f): array
|
||||
{
|
||||
$own = $f !== null && !empty($f['ownForm']);
|
||||
$str = static function ($v, string $default = ''): string { return is_string($v) && trim($v) !== '' ? trim($v) : $default; };
|
||||
$out = [
|
||||
'own' => $own,
|
||||
'title' => $f !== null ? $str($f['title'] ?? '') : '',
|
||||
'intro' => $f !== null ? $str($f['intro'] ?? '') : '',
|
||||
// DeskHub meldet für Standardformulare seine eigenen deutschen Standardtexte; hier gelten die (übersetzbaren) des Plugins
|
||||
'subject' => [
|
||||
'show' => $f === null || !isset($f['subject']['show']) || !empty($f['subject']['show']),
|
||||
'label' => $own ? $str($f['subject']['label'] ?? '', __('Betreff', 'deskhub-tickets')) : __('Betreff', 'deskhub-tickets'),
|
||||
],
|
||||
'message' => [
|
||||
'show' => $f === null || !isset($f['message']['show']) || !empty($f['message']['show']),
|
||||
'label' => $own ? $str($f['message']['label'] ?? '', __('Ihre Nachricht', 'deskhub-tickets')) : __('Ihre Nachricht', 'deskhub-tickets'),
|
||||
'hint' => $own ? $str($f['message']['hint'] ?? '') : '',
|
||||
],
|
||||
'submitLabel' => $own ? $str($f['submitLabel'] ?? '', __('Ticket absenden', 'deskhub-tickets')) : __('Ticket absenden', 'deskhub-tickets'),
|
||||
'fields' => [],
|
||||
];
|
||||
$allowed = ['text', 'textarea', 'select', 'radio', 'checkbox', 'number', 'date'];
|
||||
foreach ((array) ($f['fields'] ?? []) as $fd) {
|
||||
if (!is_array($fd) || empty($fd['id']) || !isset($fd['label'])) {
|
||||
continue;
|
||||
}
|
||||
$out['fields'][] = [
|
||||
'id' => (int) $fd['id'],
|
||||
'label' => (string) $fd['label'],
|
||||
'type' => in_array($fd['type'] ?? '', $allowed, true) ? (string) $fd['type'] : 'text',
|
||||
'required' => !empty($fd['required']),
|
||||
'options' => array_values(array_filter(array_map('strval', (array) ($fd['options'] ?? [])), static function ($o) { return $o !== ''; })),
|
||||
'helpHtml' => (string) ($fd['helpHtml'] ?? ''),
|
||||
'width' => in_array($fd['width'] ?? '', ['half', 'third', 'twothirds'], true) ? (string) $fd['width'] : 'full',
|
||||
'section' => (string) ($fd['section'] ?? 'extra'),
|
||||
'sectionTitle' => (string) ($fd['sectionTitle'] ?? ''),
|
||||
'radioInline' => !empty($fd['radioInline']),
|
||||
];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die Felder eines Platzes im Formular aus: je Thema ein Block (bei mehreren Themen schaltet form.js den passenden ein).
|
||||
* $rest = true: alle Felder, die zu keinem bekannten Platz gehören („Zusätzliche Angaben“ und eigene Abschnitte).
|
||||
*
|
||||
* @param array<int,array> $forms
|
||||
*/
|
||||
private static function render_slot(array $forms, array $slots, bool $multi, int $selected, array $posted, bool $rest = false): string
|
||||
{
|
||||
$html = '';
|
||||
foreach ($forms as $tid => $form) {
|
||||
$fields = array_values(array_filter($form['fields'], static function ($f) use ($slots, $rest) {
|
||||
return $rest ? !in_array($f['section'], self::SLOTS, true) : in_array($f['section'], $slots, true);
|
||||
}));
|
||||
if (!$fields) {
|
||||
continue;
|
||||
}
|
||||
$on = !$multi || $tid === $selected;
|
||||
$html .= '<div class="dht-topic-fields' . ($on ? ' dht-topic-active' : '') . '" data-topic="' . (int) $tid . '"><div class="dht-fields">';
|
||||
$group = null;
|
||||
foreach ($fields as $f) {
|
||||
$heading = $rest ? $f['sectionTitle'] : '';
|
||||
if ($rest && $heading !== $group) {
|
||||
$html .= '</div>' . ($heading !== '' ? '<h4 class="dht-group">' . esc_html($heading) . '</h4>' : '') . '<div class="dht-fields">';
|
||||
$group = $heading;
|
||||
}
|
||||
$html .= self::render_field($f, (string) $tid, isset($posted[$f['id']]) ? (string) $posted[$f['id']] : '', !$on);
|
||||
}
|
||||
$html .= '</div></div>';
|
||||
}
|
||||
return $html;
|
||||
}
|
||||
|
||||
private static function help_html(string $html): string
|
||||
{
|
||||
return wp_kses($html, ['a' => ['href' => [], 'target' => [], 'rel' => []], 'br' => []]);
|
||||
}
|
||||
|
||||
/** Ein Eingabefeld aus der Beschreibung von DeskHub. */
|
||||
private static function render_field(array $f, string $uid, string $posted, bool $disabled): string
|
||||
{
|
||||
$id = (int) $f['id'];
|
||||
$name = 'dht_f[' . $id . ']';
|
||||
$dom = 'dht-f-' . $uid . '-' . $id;
|
||||
$req = !empty($f['required']);
|
||||
$dis = $disabled ? ' disabled' : '';
|
||||
$reqAttr = $req ? ' required' : '';
|
||||
$star = $req ? ' <span class="dht-req" aria-hidden="true">*</span>' : '';
|
||||
$label = esc_html((string) $f['label']);
|
||||
$help = self::help_html((string) $f['helpHtml']);
|
||||
$o = '<div class="dht-field dht-w-' . esc_attr((string) $f['width']) . '">';
|
||||
switch ($f['type']) {
|
||||
case 'textarea':
|
||||
$o .= '<label for="' . esc_attr($dom) . '">' . $label . $star . '</label>'
|
||||
. '<textarea id="' . esc_attr($dom) . '" name="' . esc_attr($name) . '" rows="4"' . $reqAttr . $dis . '>' . esc_textarea($posted) . '</textarea>';
|
||||
break;
|
||||
case 'select':
|
||||
$o .= '<label for="' . esc_attr($dom) . '">' . $label . $star . '</label><select id="' . esc_attr($dom) . '" name="' . esc_attr($name) . '"' . $reqAttr . $dis . '>'
|
||||
. '<option value="">' . esc_html__('Bitte wählen …', 'deskhub-tickets') . '</option>';
|
||||
foreach ($f['options'] as $opt) {
|
||||
$o .= '<option value="' . esc_attr($opt) . '"' . ($posted === $opt ? ' selected="selected"' : '') . '>' . esc_html($opt) . '</option>';
|
||||
}
|
||||
$o .= '</select>';
|
||||
break;
|
||||
case 'radio':
|
||||
$o .= '<fieldset class="dht-radios' . (!empty($f['radioInline']) ? ' dht-inline' : '') . '"><legend>' . $label . $star . '</legend>';
|
||||
foreach ($f['options'] as $i => $opt) {
|
||||
$o .= '<label class="dht-check"><input type="radio" id="' . esc_attr($dom . '-' . $i) . '" name="' . esc_attr($name) . '" value="' . esc_attr($opt) . '"'
|
||||
. ($posted === $opt ? ' checked="checked"' : '') . $reqAttr . $dis . '> <span>' . esc_html($opt) . '</span></label>';
|
||||
}
|
||||
$o .= '</fieldset>';
|
||||
break;
|
||||
case 'checkbox':
|
||||
$o .= '<label class="dht-check"><input type="checkbox" id="' . esc_attr($dom) . '" name="' . esc_attr($name) . '" value="1"'
|
||||
. ($posted === '1' ? ' checked="checked"' : '') . $reqAttr . $dis . '> <span>' . ($help !== '' ? $help : $label) . $star . '</span></label>';
|
||||
$help = '';
|
||||
break;
|
||||
case 'number':
|
||||
case 'date':
|
||||
$o .= '<label for="' . esc_attr($dom) . '">' . $label . $star . '</label><input type="' . esc_attr((string) $f['type']) . '" id="' . esc_attr($dom) . '" name="' . esc_attr($name)
|
||||
. '" value="' . esc_attr($posted) . '"' . $reqAttr . $dis . '>';
|
||||
break;
|
||||
default:
|
||||
$o .= '<label for="' . esc_attr($dom) . '">' . $label . $star . '</label><input type="text" id="' . esc_attr($dom) . '" name="' . esc_attr($name)
|
||||
. '" value="' . esc_attr($posted) . '" maxlength="500"' . $reqAttr . $dis . '>';
|
||||
}
|
||||
if ($help !== '') {
|
||||
$o .= '<p class="dht-help">' . $help . '</p>';
|
||||
}
|
||||
return $o . '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Angaben zu den Feldern des Formulars wie DeskHub selbst (DeskHub prüft beim Anlegen noch einmal).
|
||||
*
|
||||
* @param array<int,array> $fields
|
||||
* @param array<int,string> $input Feld-ID => abgeschickter Wert
|
||||
* @return array{0:string[],1:array<int,string>} Fehlermeldungen und bereinigte Werte (Feld-ID => Wert)
|
||||
*/
|
||||
public static function validate_fields(array $fields, array $input): array
|
||||
{
|
||||
$errors = [];
|
||||
$values = [];
|
||||
foreach ($fields as $f) {
|
||||
$id = (int) $f['id'];
|
||||
$label = (string) $f['label'];
|
||||
$type = (string) $f['type'];
|
||||
$raw = isset($input[$id]) ? (string) $input[$id] : '';
|
||||
if ($type === 'checkbox') {
|
||||
$val = in_array(strtolower(trim($raw)), ['1', 'on', 'yes', 'ja', 'true'], true) ? '1' : '0';
|
||||
} else {
|
||||
$val = $type === 'textarea' ? sanitize_textarea_field($raw) : sanitize_text_field($raw);
|
||||
$val = mb_substr($val, 0, 10000);
|
||||
}
|
||||
if (!empty($f['required']) && $type !== 'checkbox' && $val === '') {
|
||||
$errors[] = sprintf(__('Bitte füllen Sie das Feld „%s“ aus.', 'deskhub-tickets'), $label);
|
||||
} elseif (!empty($f['required']) && $type === 'checkbox' && $val !== '1') {
|
||||
$errors[] = sprintf(__('Bitte bestätigen Sie „%s“.', 'deskhub-tickets'), $label);
|
||||
} elseif (in_array($type, ['select', 'radio'], true) && $val !== '' && !in_array($val, $f['options'], true)) {
|
||||
$errors[] = sprintf(__('Bitte wählen Sie bei „%s“ eine der angebotenen Möglichkeiten.', 'deskhub-tickets'), $label);
|
||||
} elseif ($type === 'number' && $val !== '' && !is_numeric($val)) {
|
||||
$errors[] = sprintf(__('Bitte geben Sie bei „%s“ eine Zahl an.', 'deskhub-tickets'), $label);
|
||||
} elseif ($type === 'date' && $val !== '' && !(preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $val, $m) && checkdate((int) $m[2], (int) $m[3], (int) $m[1]))) {
|
||||
$errors[] = sprintf(__('Bitte geben Sie bei „%s“ ein gültiges Datum an.', 'deskhub-tickets'), $label);
|
||||
}
|
||||
$values[$id] = $val;
|
||||
}
|
||||
return [$errors, $values];
|
||||
}
|
||||
|
||||
/** Ticket-Text aus den Feldern, wenn das Formular kein Beschreibungsfeld hat (wie im Kundenportal von DeskHub). */
|
||||
public static function compose_message(array $fields, array $values): string
|
||||
{
|
||||
$lines = [];
|
||||
foreach ($fields as $f) {
|
||||
$v = $values[(int) $f['id']] ?? '';
|
||||
if ($f['type'] === 'checkbox') {
|
||||
$v = $v === '1' ? __('Ja', 'deskhub-tickets') : __('Nein', 'deskhub-tickets');
|
||||
}
|
||||
if ($v !== '') {
|
||||
$lines[] = $f['label'] . ': ' . $v;
|
||||
}
|
||||
}
|
||||
return $lines ? implode("\n", $lines) : __('Anfrage ohne weitere Angaben', 'deskhub-tickets');
|
||||
}
|
||||
|
||||
/** Verarbeitet das abgeschickte Formular (admin-post.php) und leitet auf die Seite zurück. */
|
||||
public static function handle_submit(): void
|
||||
{
|
||||
$back = self::safe_back(isset($_POST['dht_back']) ? (string) wp_unslash($_POST['dht_back']) : '');
|
||||
$opts = deskhub_tickets_options();
|
||||
|
||||
// 1) Unterschriebene Angaben prüfen (Abteilung, Thema, Priorität)
|
||||
$cfgB64 = isset($_POST['dht_cfg']) ? (string) wp_unslash($_POST['dht_cfg']) : '';
|
||||
$sig = isset($_POST['dht_sig']) ? (string) wp_unslash($_POST['dht_sig']) : '';
|
||||
$cfg = null;
|
||||
if (deskhub_tickets_verify_signature('cfg|' . $cfgB64, $sig)) {
|
||||
$decoded = json_decode((string) base64_decode($cfgB64, true), true);
|
||||
if (is_array($decoded)) {
|
||||
$cfg = $decoded;
|
||||
}
|
||||
}
|
||||
if ($cfg === null) {
|
||||
self::fail($back, [__('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu und versuchen Sie es noch einmal.', 'deskhub-tickets')], []);
|
||||
}
|
||||
|
||||
// 2) Eingaben bereinigen
|
||||
$postedFields = [];
|
||||
if (isset($_POST['dht_f']) && is_array($_POST['dht_f'])) {
|
||||
foreach ((array) wp_unslash($_POST['dht_f']) as $fid => $v) {
|
||||
if (is_scalar($v)) {
|
||||
$postedFields[absint($fid)] = (string) $v;
|
||||
}
|
||||
}
|
||||
}
|
||||
$values = [
|
||||
'name' => mb_substr(sanitize_text_field(isset($_POST['dht_name']) ? (string) wp_unslash($_POST['dht_name']) : ''), 0, 120),
|
||||
'email' => sanitize_email(isset($_POST['dht_email']) ? (string) wp_unslash($_POST['dht_email']) : ''),
|
||||
'subject' => mb_substr(sanitize_text_field(isset($_POST['dht_subject']) ? (string) wp_unslash($_POST['dht_subject']) : ''), 0, 255),
|
||||
'message' => mb_substr(sanitize_textarea_field(isset($_POST['dht_message']) ? (string) wp_unslash($_POST['dht_message']) : ''), 0, self::MAX_MESSAGE),
|
||||
'topic' => isset($_POST['dht_topic']) ? absint(wp_unslash($_POST['dht_topic'])) : 0,
|
||||
'fields' => $postedFields,
|
||||
];
|
||||
|
||||
// 3) Falle-Feld: Wer es ausfüllt, ist ein Roboter. Er bekommt eine Erfolgsmeldung, es wird aber nichts angelegt.
|
||||
if (isset($_POST['dht_website']) && trim((string) wp_unslash($_POST['dht_website'])) !== '') {
|
||||
self::succeed($back, '');
|
||||
}
|
||||
|
||||
// 4) Zeit seit dem Anzeigen des Formulars
|
||||
$age = deskhub_tickets_timestamp_age(isset($_POST['dht_ts']) ? (string) wp_unslash($_POST['dht_ts']) : '');
|
||||
$minSeconds = (int) $opts['min_seconds'];
|
||||
if ($age === null || $age < $minSeconds) {
|
||||
self::fail($back, [__('Das ging etwas zu schnell. Bitte prüfen Sie Ihre Angaben und senden Sie noch einmal ab.', 'deskhub-tickets')], $values);
|
||||
}
|
||||
|
||||
// 5) Thema und Formular (aus DeskHub; ohne Antwort das einfache Formular)
|
||||
$errors = [];
|
||||
$allowedTopics = isset($cfg['o']) && is_array($cfg['o']) ? array_map('intval', $cfg['o']) : [];
|
||||
$topicId = (int) ($cfg['t'] ?? 0);
|
||||
if ($allowedTopics) {
|
||||
if (!in_array($values['topic'], $allowedTopics, true)) {
|
||||
$errors[] = __('Bitte wählen Sie ein Thema aus.', 'deskhub-tickets');
|
||||
} else {
|
||||
$topicId = $values['topic'];
|
||||
}
|
||||
}
|
||||
$client = Deskhub_Tickets_Client::from_settings();
|
||||
if (!$client) {
|
||||
self::fail($back, [__('Der Support ist gerade nicht erreichbar. Bitte versuchen Sie es später noch einmal.', 'deskhub-tickets')], $values);
|
||||
}
|
||||
$form = null;
|
||||
if (!$errors) {
|
||||
$remote = $client->get_form($topicId ?: null, (int) ($cfg['d'] ?? 0) ?: null);
|
||||
if (!is_wp_error($remote)) {
|
||||
$form = self::normalize_form($remote);
|
||||
}
|
||||
}
|
||||
$showSubject = $form === null || $form['subject']['show'];
|
||||
$showMessage = $form === null || $form['message']['show'];
|
||||
|
||||
// 6) Pflichtfelder
|
||||
if ($values['name'] === '') {
|
||||
$errors[] = __('Bitte geben Sie Ihren Namen an.', 'deskhub-tickets');
|
||||
}
|
||||
if ($values['email'] === '' || !is_email($values['email'])) {
|
||||
$errors[] = __('Bitte geben Sie eine gültige E-Mail-Adresse an.', 'deskhub-tickets');
|
||||
}
|
||||
if ($showSubject && $values['subject'] === '') {
|
||||
$errors[] = __('Bitte geben Sie einen Betreff an.', 'deskhub-tickets');
|
||||
}
|
||||
if ($showMessage && trim($values['message']) === '') {
|
||||
$errors[] = __('Bitte beschreiben Sie Ihr Anliegen.', 'deskhub-tickets');
|
||||
}
|
||||
$fieldValues = [];
|
||||
if ($form !== null) {
|
||||
[$fieldErrors, $fieldValues] = self::validate_fields($form['fields'], $postedFields);
|
||||
$errors = array_merge($errors, $fieldErrors);
|
||||
}
|
||||
if (trim((string) $opts['consent_text']) !== '' && empty($_POST['dht_consent'])) {
|
||||
$errors[] = __('Bitte stimmen Sie der Verarbeitung Ihrer Angaben zu.', 'deskhub-tickets');
|
||||
}
|
||||
if ($errors) {
|
||||
self::fail($back, $errors, $values);
|
||||
}
|
||||
|
||||
// 7) Captcha und Mengenbegrenzung
|
||||
$captcha = self::verify_turnstile();
|
||||
if ($captcha !== true) {
|
||||
self::fail($back, [$captcha], $values);
|
||||
}
|
||||
if (!deskhub_tickets_rate_allow('submit', (int) $opts['rate_limit_per_hour'], HOUR_IN_SECONDS)) {
|
||||
self::fail($back, [__('Sie haben in der letzten Stunde schon mehrere Tickets gesendet. Bitte versuchen Sie es später noch einmal.', 'deskhub-tickets')], $values);
|
||||
}
|
||||
|
||||
// 8) Ticket anlegen
|
||||
$text = $showMessage ? $values['message'] : self::compose_message($form['fields'], $fieldValues);
|
||||
$message = $text . "\n\n— " . sprintf(
|
||||
/* translators: %s: Adresse der Seite mit dem Formular */
|
||||
__('Gesendet über das Formular auf %s', 'deskhub-tickets'),
|
||||
$back
|
||||
);
|
||||
$payload = [
|
||||
'name' => $values['name'],
|
||||
'email' => $values['email'],
|
||||
'subject' => $showSubject ? $values['subject'] : '', // ohne Betrefffeld setzt DeskHub „Anfrage <Abteilung>“
|
||||
'message' => $message,
|
||||
'helpTopicId' => $topicId,
|
||||
'departmentId' => (int) ($cfg['d'] ?? 0),
|
||||
'priorityId' => (int) ($cfg['p'] ?? 0),
|
||||
];
|
||||
if ($form !== null) {
|
||||
$payload['fields'] = $fieldValues;
|
||||
}
|
||||
$payload = apply_filters('deskhub_tickets_payload', $payload, $values);
|
||||
$result = $client->create_ticket($payload);
|
||||
if (is_wp_error($result)) {
|
||||
self::fail($back, [Deskhub_Tickets_Client::user_message($result)], $values);
|
||||
}
|
||||
do_action('deskhub_tickets_created', $result['number'], $payload);
|
||||
self::succeed($back, $result['number']);
|
||||
}
|
||||
|
||||
// ───────────────────────────── Stand abfragen ─────────────────────────────
|
||||
|
||||
/**
|
||||
* @param array|string $atts
|
||||
*/
|
||||
public static function render_status_form($atts = []): string
|
||||
{
|
||||
self::enqueue();
|
||||
if (!Deskhub_Tickets_Client::from_settings()) {
|
||||
return current_user_can('manage_options')
|
||||
? '<p class="dht-notice dht-error">' . esc_html__('DeskHub Tickets ist noch nicht eingerichtet (Einstellungen → DeskHub Tickets). Diese Meldung sehen nur Administratoren.', 'deskhub-tickets') . '</p>'
|
||||
: '';
|
||||
}
|
||||
$number = '';
|
||||
$email = '';
|
||||
$error = '';
|
||||
$ticket = null;
|
||||
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['dht_status_submit'])) {
|
||||
$number = trim(sanitize_text_field((string) wp_unslash($_POST['dht_number'] ?? '')));
|
||||
$email = sanitize_email((string) wp_unslash($_POST['dht_status_email'] ?? ''));
|
||||
if (isset($_POST['dht_status_website']) && trim((string) wp_unslash($_POST['dht_status_website'])) !== '') {
|
||||
$error = __('Zu dieser Kombination aus Ticketnummer und E-Mail-Adresse wurde nichts gefunden.', 'deskhub-tickets');
|
||||
} elseif (!preg_match('/^[A-Za-z0-9._-]{1,40}$/', $number) || !is_email($email)) {
|
||||
$error = __('Bitte geben Sie Ihre Ticketnummer und die E-Mail-Adresse an, mit der Sie das Ticket gesendet haben.', 'deskhub-tickets');
|
||||
} elseif (!deskhub_tickets_rate_allow('status', 10, 10 * MINUTE_IN_SECONDS)) {
|
||||
// Bremst das Durchprobieren von Ticketnummern
|
||||
$error = __('Zu viele Abfragen. Bitte versuchen Sie es in einigen Minuten noch einmal.', 'deskhub-tickets');
|
||||
} else {
|
||||
$client = Deskhub_Tickets_Client::from_settings();
|
||||
$res = $client ? $client->get_ticket($number, $email) : new WP_Error('deskhub_config', 'x');
|
||||
if (is_wp_error($res)) {
|
||||
$error = Deskhub_Tickets_Client::user_message($res);
|
||||
} else {
|
||||
$ticket = $res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ob_start();
|
||||
echo self::wrap_open('deskhub-status');
|
||||
if ($error !== '') {
|
||||
echo '<div class="dht-notice dht-error" role="alert"><p>' . esc_html($error) . '</p></div>';
|
||||
}
|
||||
if ($ticket) {
|
||||
echo self::render_ticket_status($ticket);
|
||||
}
|
||||
?>
|
||||
<form method="post" class="dht-form" novalidate>
|
||||
<div class="dht-trap" aria-hidden="true">
|
||||
<label>Website <input type="text" name="dht_status_website" value="" tabindex="-1" autocomplete="off"></label>
|
||||
</div>
|
||||
<p>
|
||||
<label for="dht-number"><?php echo esc_html__('Ticketnummer', 'deskhub-tickets'); ?> *</label>
|
||||
<input type="text" id="dht-number" name="dht_number" value="<?php echo esc_attr($number); ?>" maxlength="40" required placeholder="260101-1234">
|
||||
</p>
|
||||
<p>
|
||||
<label for="dht-status-email"><?php echo esc_html__('E-Mail-Adresse', 'deskhub-tickets'); ?> *</label>
|
||||
<input type="email" id="dht-status-email" name="dht_status_email" value="<?php echo esc_attr($email); ?>" maxlength="190" required autocomplete="email">
|
||||
</p>
|
||||
<p><button type="submit" name="dht_status_submit" value="1" class="dht-button"><?php echo esc_html__('Stand abfragen', 'deskhub-tickets'); ?></button></p>
|
||||
</form>
|
||||
<?php
|
||||
echo '</div>';
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
/** Zeigt Status und öffentlichen Verlauf eines Tickets. Alles wird maskiert; die Texte kommen vom Server als Klartext. */
|
||||
public static function render_ticket_status(array $t): string
|
||||
{
|
||||
$labels = [
|
||||
'open' => __('Offen', 'deskhub-tickets'),
|
||||
'pending' => __('Wartet auf Ihre Antwort', 'deskhub-tickets'),
|
||||
'answered' => __('Beantwortet', 'deskhub-tickets'),
|
||||
'on_hold' => __('In Bearbeitung', 'deskhub-tickets'),
|
||||
'resolved' => __('Gelöst', 'deskhub-tickets'),
|
||||
'closed' => __('Geschlossen', 'deskhub-tickets'),
|
||||
];
|
||||
$status = (string) ($t['status'] ?? '');
|
||||
$fmt = function ($s): string {
|
||||
$ts = strtotime((string) $s);
|
||||
return $ts ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $ts) : '';
|
||||
};
|
||||
$out = '<div class="dht-ticket">';
|
||||
$out .= '<h3 class="dht-title">' . esc_html((string) ($t['subject'] ?? '')) . '</h3>';
|
||||
$out .= '<p class="dht-meta"><span class="dht-badge dht-status-' . esc_attr(preg_replace('/[^a-z_]/', '', $status)) . '">' . esc_html($labels[$status] ?? $status) . '</span> '
|
||||
. esc_html(sprintf(__('Ticket %s', 'deskhub-tickets'), (string) ($t['number'] ?? ''))) . ' · '
|
||||
. esc_html(sprintf(__('Zuletzt geändert: %s', 'deskhub-tickets'), $fmt($t['updatedAt'] ?? ''))) . '</p>';
|
||||
$messages = isset($t['messages']) && is_array($t['messages']) ? $t['messages'] : [];
|
||||
foreach ($messages as $m) {
|
||||
if (!is_array($m)) {
|
||||
continue;
|
||||
}
|
||||
$mine = ($m['author'] ?? '') === 'customer';
|
||||
$out .= '<div class="dht-msg ' . ($mine ? 'dht-msg-you' : 'dht-msg-staff') . '">'
|
||||
. '<div class="dht-msg-head"><strong>' . esc_html($mine ? __('Sie', 'deskhub-tickets') : __('Support', 'deskhub-tickets')) . '</strong> · ' . esc_html($fmt($m['createdAt'] ?? '')) . '</div>'
|
||||
. '<div class="dht-msg-body">' . nl2br(esc_html((string) ($m['message'] ?? ''))) . '</div></div>';
|
||||
}
|
||||
return $out . '</div>';
|
||||
}
|
||||
|
||||
// ───────────────────────────── Hilfsfunktionen ────────────────────────────
|
||||
|
||||
/** „Rechnung:3,Technik:4“ → [['label'=>'Rechnung','id'=>3], …] */
|
||||
public static function parse_topics(string $spec): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (explode(',', $spec) as $part) {
|
||||
$pos = strrpos($part, ':');
|
||||
if ($pos === false) {
|
||||
continue;
|
||||
}
|
||||
$label = trim(sanitize_text_field(substr($part, 0, $pos)));
|
||||
$id = absint(trim(substr($part, $pos + 1)));
|
||||
if ($label !== '' && $id > 0) {
|
||||
$out[] = ['label' => $label, 'id' => $id];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Adresse der Seite, auf der das Formular steht (dorthin geht es nach dem Absenden zurück). */
|
||||
private static function current_url(): string
|
||||
{
|
||||
$url = get_permalink();
|
||||
return $url ? (string) $url : home_url('/');
|
||||
}
|
||||
|
||||
/** Ziel für „zurück zur Seite“: nur Adressen dieser Website. */
|
||||
private static function safe_back(string $url): string
|
||||
{
|
||||
$url = remove_query_arg('dht', $url);
|
||||
$safe = wp_validate_redirect($url, home_url('/'));
|
||||
return $safe ?: home_url('/');
|
||||
}
|
||||
|
||||
/** Merkt sich Fehler oder Erfolg kurz und leitet auf die Seite zurück (kein erneutes Senden beim Neuladen). */
|
||||
private static function redirect_with_state(string $back, array $state): void
|
||||
{
|
||||
$id = bin2hex(random_bytes(8));
|
||||
set_transient('dht_state_' . $id, $state, 10 * MINUTE_IN_SECONDS);
|
||||
wp_safe_redirect(add_query_arg('dht', $id, $back) . '#deskhub-ticket');
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function fail(string $back, array $errors, array $values): void
|
||||
{
|
||||
// Die Eingaben bleiben erhalten, damit der Text der Nachricht nicht verloren geht
|
||||
self::redirect_with_state($back, ['errors' => $errors, 'values' => $values]);
|
||||
}
|
||||
|
||||
private static function succeed(string $back, string $number): void
|
||||
{
|
||||
self::redirect_with_state($back, ['ok' => true, 'number' => $number]);
|
||||
}
|
||||
|
||||
/** Liest den kurz gemerkten Zustand (Fehler/Erfolg) aus der Adresse und löscht ihn. */
|
||||
private static function take_state(): ?array
|
||||
{
|
||||
$id = isset($_GET['dht']) ? (string) wp_unslash($_GET['dht']) : '';
|
||||
if (!preg_match('/^[a-f0-9]{16}$/', $id)) {
|
||||
return null;
|
||||
}
|
||||
$state = get_transient('dht_state_' . $id);
|
||||
delete_transient('dht_state_' . $id);
|
||||
return is_array($state) ? $state : null;
|
||||
}
|
||||
|
||||
// ───────────────────────────── Cloudflare Turnstile ───────────────────────
|
||||
|
||||
private static function turnstile_enabled(): bool
|
||||
{
|
||||
$o = deskhub_tickets_options();
|
||||
return trim((string) $o['turnstile_site']) !== '' && trim((string) $o['turnstile_secret']) !== '';
|
||||
}
|
||||
|
||||
private static function turnstile_widget(): string
|
||||
{
|
||||
if (!self::turnstile_enabled()) {
|
||||
return '';
|
||||
}
|
||||
$site = (string) deskhub_tickets_option('turnstile_site');
|
||||
wp_enqueue_script('deskhub-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js', [], null, true);
|
||||
return '<div class="cf-turnstile" data-sitekey="' . esc_attr($site) . '"></div>';
|
||||
}
|
||||
|
||||
/** @return true|string true bei Erfolg, sonst die Meldung für den Besucher */
|
||||
private static function verify_turnstile()
|
||||
{
|
||||
if (!self::turnstile_enabled()) {
|
||||
return true;
|
||||
}
|
||||
$token = isset($_POST['cf-turnstile-response']) ? (string) wp_unslash($_POST['cf-turnstile-response']) : '';
|
||||
$fail = __('Die Sicherheitsprüfung ist fehlgeschlagen. Bitte versuchen Sie es noch einmal.', 'deskhub-tickets');
|
||||
if ($token === '' || strlen($token) > 2048) {
|
||||
return $fail;
|
||||
}
|
||||
$res = wp_remote_post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
|
||||
'timeout' => 10,
|
||||
'body' => ['secret' => (string) deskhub_tickets_option('turnstile_secret'), 'response' => $token, 'remoteip' => deskhub_tickets_client_ip()],
|
||||
]);
|
||||
if (is_wp_error($res)) {
|
||||
error_log('DeskHub Tickets: Turnstile nicht erreichbar: ' . $res->get_error_message());
|
||||
return $fail;
|
||||
}
|
||||
$data = json_decode((string) wp_remote_retrieve_body($res), true);
|
||||
return is_array($data) && !empty($data['success']) ? true : $fail;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
/**
|
||||
* Einstellungsseite (Einstellungen → DeskHub Tickets).
|
||||
*/
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
class Deskhub_Tickets_Settings
|
||||
{
|
||||
const PAGE = 'deskhub-tickets';
|
||||
const GROUP = 'deskhub_tickets';
|
||||
|
||||
public static function init(): void
|
||||
{
|
||||
add_action('admin_menu', [__CLASS__, 'menu']);
|
||||
add_action('admin_init', [__CLASS__, 'register']);
|
||||
add_action('admin_post_deskhub_tickets_clear_cache', [__CLASS__, 'handle_clear_cache']);
|
||||
add_filter('plugin_action_links_' . plugin_basename(DESKHUB_TICKETS_FILE), [__CLASS__, 'action_links']);
|
||||
}
|
||||
|
||||
public static function menu(): void
|
||||
{
|
||||
add_options_page(
|
||||
__('DeskHub Tickets', 'deskhub-tickets'),
|
||||
__('DeskHub Tickets', 'deskhub-tickets'),
|
||||
'manage_options',
|
||||
self::PAGE,
|
||||
[__CLASS__, 'render']
|
||||
);
|
||||
}
|
||||
|
||||
public static function action_links(array $links): array
|
||||
{
|
||||
array_unshift($links, '<a href="' . esc_url(admin_url('options-general.php?page=' . self::PAGE)) . '">' . esc_html__('Einstellungen', 'deskhub-tickets') . '</a>');
|
||||
return $links;
|
||||
}
|
||||
|
||||
public static function register(): void
|
||||
{
|
||||
register_setting(self::GROUP, 'deskhub_tickets_options', [
|
||||
'type' => 'array',
|
||||
'sanitize_callback' => [__CLASS__, 'sanitize'],
|
||||
'default' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft und bereinigt die abgeschickten Einstellungen. Der API-Schlüssel bleibt erhalten, wenn das Feld leer ist
|
||||
* (er wird nie wieder in die Seite geschrieben).
|
||||
*/
|
||||
public static function sanitize($input): array
|
||||
{
|
||||
$input = is_array($input) ? $input : [];
|
||||
$old = get_option('deskhub_tickets_options', []);
|
||||
$old = array_merge(deskhub_tickets_defaults(), is_array($old) ? $old : []);
|
||||
$out = deskhub_tickets_defaults();
|
||||
|
||||
$url = trim((string) ($input['server_url'] ?? ''));
|
||||
if ($url === '') {
|
||||
$out['server_url'] = '';
|
||||
} else {
|
||||
$norm = Deskhub_Tickets_Client::normalize_url($url);
|
||||
if (is_wp_error($norm)) {
|
||||
add_settings_error('deskhub_tickets_options', 'deskhub_url', $norm->get_error_message());
|
||||
$out['server_url'] = (string) $old['server_url'];
|
||||
} else {
|
||||
$out['server_url'] = $norm;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($input['clear_key'])) {
|
||||
$out['api_key'] = '';
|
||||
} else {
|
||||
$key = trim((string) ($input['api_key'] ?? ''));
|
||||
$key = preg_replace('/[^\x21-\x7E]/', '', $key);
|
||||
$out['api_key'] = $key !== '' ? $key : (string) $old['api_key'];
|
||||
}
|
||||
|
||||
foreach (['department_id', 'topic_id', 'priority_id'] as $f) {
|
||||
$out[$f] = absint($input[$f] ?? 0);
|
||||
}
|
||||
$out['consent_text'] = wp_kses((string) ($input['consent_text'] ?? ''), [
|
||||
'a' => ['href' => [], 'target' => [], 'rel' => []],
|
||||
'strong' => [],
|
||||
'em' => [],
|
||||
]);
|
||||
$accent = sanitize_hex_color((string) ($input['accent_color'] ?? ''));
|
||||
$out['accent_color'] = empty($input['accent_auto']) && $accent ? $accent : '';
|
||||
$out['success_text'] = mb_substr(sanitize_text_field((string) ($input['success_text'] ?? '')), 0, 500);
|
||||
$out['status_page_url'] = esc_url_raw((string) ($input['status_page_url'] ?? ''));
|
||||
$out['min_seconds'] = max(0, min(60, absint($input['min_seconds'] ?? 3)));
|
||||
$out['rate_limit_per_hour'] = max(0, min(100, absint($input['rate_limit_per_hour'] ?? 5)));
|
||||
$out['turnstile_site'] = sanitize_text_field((string) ($input['turnstile_site'] ?? ''));
|
||||
$secret = trim(sanitize_text_field((string) ($input['turnstile_secret'] ?? '')));
|
||||
$out['turnstile_secret'] = !empty($input['clear_turnstile']) ? '' : ($secret !== '' ? $secret : (string) $old['turnstile_secret']);
|
||||
|
||||
// „Speichern und Verbindung testen“: prüft gleich die Werte, die gerade gespeichert werden (nicht erst die schon gespeicherten)
|
||||
if (!empty($_POST['dht_test_after']) && current_user_can('manage_options')) {
|
||||
$key = deskhub_tickets_key_from_config() ? (string) DESKHUB_TICKETS_API_KEY : (string) $out['api_key'];
|
||||
$url = defined('DESKHUB_TICKETS_SERVER') && DESKHUB_TICKETS_SERVER !== '' ? (string) DESKHUB_TICKETS_SERVER : (string) $out['server_url'];
|
||||
$norm = Deskhub_Tickets_Client::normalize_url($url);
|
||||
$result = (is_wp_error($norm) || trim($key) === '')
|
||||
? ['ok' => false, 'message' => __('Bitte Server-Adresse und API-Schlüssel eintragen.', 'deskhub-tickets'), 'canRead' => false]
|
||||
: (new Deskhub_Tickets_Client($norm, trim($key)))->test_connection();
|
||||
set_transient('deskhub_tickets_test_' . get_current_user_id(), $result, 120);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** „Formulare neu laden“: leert den Zwischenspeicher der Kundenformulare aus DeskHub. */
|
||||
public static function handle_clear_cache(): void
|
||||
{
|
||||
if (!current_user_can('manage_options')) {
|
||||
wp_die(esc_html__('Dafür fehlt die Berechtigung.', 'deskhub-tickets'), '', ['response' => 403]);
|
||||
}
|
||||
check_admin_referer('deskhub_tickets_clear_cache');
|
||||
Deskhub_Tickets_Client::clear_form_cache();
|
||||
set_transient('deskhub_tickets_test_' . get_current_user_id(), ['ok' => true, 'message' => __('Die Formulare werden beim nächsten Aufruf neu aus DeskHub geladen.', 'deskhub-tickets'), 'canRead' => true], 120);
|
||||
wp_safe_redirect(admin_url('options-general.php?page=' . self::PAGE . '&dht_tested=1'));
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function render(): void
|
||||
{
|
||||
if (!current_user_can('manage_options')) {
|
||||
return;
|
||||
} $o = deskhub_tickets_options();
|
||||
$name = 'deskhub_tickets_options';
|
||||
$keyFromConfig = deskhub_tickets_key_from_config();
|
||||
$hasKey = trim((string) $o['api_key']) !== '';
|
||||
$hasSecret = trim((string) $o['turnstile_secret']) !== '';
|
||||
$topicList = [];
|
||||
$cl = Deskhub_Tickets_Client::from_settings();
|
||||
if ($cl) {
|
||||
$tl = $cl->get_topics();
|
||||
$topicList = is_array($tl) ? $tl : [];
|
||||
}
|
||||
$tk = 'deskhub_tickets_test_' . get_current_user_id();
|
||||
$test = get_transient($tk); // Ergebnis von „Speichern und Verbindung testen“ bzw. „Formulare neu laden“ (wird nur einmal gezeigt)
|
||||
delete_transient($tk);
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php echo esc_html__('DeskHub Tickets', 'deskhub-tickets'); ?></h1>
|
||||
<p><?php echo esc_html__('Verbindet WordPress mit Ihrem DeskHub-Helpdesk: Besucher legen Tickets über ein Formular an und können den Stand abfragen.', 'deskhub-tickets'); ?></p>
|
||||
|
||||
<?php if (is_array($test)): ?>
|
||||
<div class="notice <?php echo !empty($test['ok']) ? 'notice-success' : 'notice-error'; ?>"><p><?php echo esc_html((string) $test['message']); ?></p></div>
|
||||
<?php endif; ?>
|
||||
<?php settings_errors('deskhub_tickets_options'); ?>
|
||||
|
||||
<form method="post" action="options.php">
|
||||
<?php settings_fields(self::GROUP); ?>
|
||||
<h2><?php echo esc_html__('Verbindung', 'deskhub-tickets'); ?></h2>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_server"><?php echo esc_html__('Adresse des DeskHub-Servers', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<input type="text" id="dht_server" class="regular-text" name="<?php echo esc_attr($name); ?>[server_url]" value="<?php echo esc_attr((string) $o['server_url']); ?>" placeholder="https://support.example.de" autocomplete="off">
|
||||
<p class="description"><?php echo esc_html__('Die Adresse, unter der Ihr DeskHub erreichbar ist. Nur https (http nur für lokale Tests).', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_key"><?php echo esc_html__('API-Schlüssel', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<?php if ($keyFromConfig): ?>
|
||||
<input type="text" class="regular-text" value="<?php echo esc_attr__('aus der wp-config.php', 'deskhub-tickets'); ?>" disabled>
|
||||
<?php else: ?>
|
||||
<input type="password" id="dht_key" class="regular-text" name="<?php echo esc_attr($name); ?>[api_key]" value="" autocomplete="new-password" placeholder="<?php echo $hasKey ? esc_attr__('gespeichert, zum Ändern neuen Schlüssel eintragen', 'deskhub-tickets') : 'dh_…'; ?>">
|
||||
<?php if ($hasKey): ?>
|
||||
<label style="margin-left:8px"><input type="checkbox" name="<?php echo esc_attr($name); ?>[clear_key]" value="1"> <?php echo esc_html__('Schlüssel entfernen', 'deskhub-tickets'); ?></label>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
<p class="description"><?php echo wp_kses(
|
||||
__('In DeskHub unter <strong>Verwalten → API-Schlüssel</strong> einen Schlüssel erstellen. Er braucht das Recht „Tickets anlegen“, für die Statusabfrage zusätzlich „Tickets lesen“. Sicherer: den Schlüssel in der <code>wp-config.php</code> eintragen: <code>define(\'DESKHUB_TICKETS_API_KEY\', \'dh_…\');</code>', 'deskhub-tickets'),
|
||||
['strong' => [], 'code' => []]
|
||||
); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><?php echo esc_html__('Ticket-Voreinstellungen', 'deskhub-tickets'); ?></h2>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><?php echo esc_html__('Nummern in DeskHub', 'deskhub-tickets'); ?></th>
|
||||
<td>
|
||||
<label><?php echo esc_html__('Abteilung', 'deskhub-tickets'); ?> <input type="number" min="0" class="small-text" name="<?php echo esc_attr($name); ?>[department_id]" value="<?php echo esc_attr((string) (int) $o['department_id']); ?>"></label>
|
||||
<label style="margin-left:12px"><?php echo esc_html__('Hilfethema', 'deskhub-tickets'); ?> <?php if ($topicList): ?>
|
||||
<select name="<?php echo esc_attr($name); ?>[topic_id]">
|
||||
<option value="0"><?php echo esc_html__('DeskHub entscheidet', 'deskhub-tickets'); ?></option>
|
||||
<?php foreach ($topicList as $tp): ?><option value="<?php echo (int) $tp['id']; ?>" <?php selected((int) $o['topic_id'], (int) $tp['id']); ?>><?php echo esc_html((string) $tp['path']); ?> (<?php echo (int) $tp['id']; ?>)</option><?php endforeach; ?>
|
||||
</select>
|
||||
<?php else: ?><input type="number" min="0" class="small-text" name="<?php echo esc_attr($name); ?>[topic_id]" value="<?php echo esc_attr((string) (int) $o['topic_id']); ?>"><?php endif; ?></label>
|
||||
<label style="margin-left:12px"><?php echo esc_html__('Priorität', 'deskhub-tickets'); ?> <input type="number" min="0" class="small-text" name="<?php echo esc_attr($name); ?>[priority_id]" value="<?php echo esc_attr((string) (int) $o['priority_id']); ?>"></label>
|
||||
<p class="description"><?php echo esc_html__('Die Nummern stehen in DeskHub bei der jeweiligen Abteilung, dem Hilfethema und der Priorität. 0 = DeskHub entscheidet (Standardabteilung, Regeln des Hilfethemas). Im Shortcode lassen sich die Werte je Formular überschreiben.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><?php echo esc_html__('Formular', 'deskhub-tickets'); ?></h2>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_consent"><?php echo esc_html__('Einwilligung (Datenschutz)', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<textarea id="dht_consent" class="large-text" rows="3" name="<?php echo esc_attr($name); ?>[consent_text]" placeholder="<?php echo esc_attr__('Ich habe die <a href="/datenschutz">Datenschutzerklärung</a> gelesen und bin mit der Verarbeitung meiner Angaben einverstanden.', 'deskhub-tickets'); ?>"><?php echo esc_textarea((string) $o['consent_text']); ?></textarea>
|
||||
<p class="description"><?php echo esc_html__('Wenn ausgefüllt, muss der Besucher dieses Kästchen anhaken. Erlaubt sind Links (a), fett und kursiv.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_accent"><?php echo esc_html__('Akzentfarbe', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<input type="color" id="dht_accent" name="<?php echo esc_attr($name); ?>[accent_color]" value="<?php echo esc_attr((string) $o['accent_color'] !== '' ? (string) $o['accent_color'] : '#0f6f6a'); ?>">
|
||||
<label><input type="checkbox" name="<?php echo esc_attr($name); ?>[accent_auto]" value="1" <?php checked((string) $o['accent_color'] === ''); ?>> <?php echo esc_html__('Automatisch vom Theme übernehmen', 'deskhub-tickets'); ?></label>
|
||||
<p class="description"><?php echo esc_html__('Schrift, Hintergrund und Rahmen übernimmt das Formular immer vom Theme. Die Akzentfarbe (Knopf, Hervorhebung) wird automatisch aus Knöpfen und Links der Seite gelesen; hier lässt sie sich fest vorgeben.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_success"><?php echo esc_html__('Text nach dem Absenden', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<input type="text" id="dht_success" class="large-text" name="<?php echo esc_attr($name); ?>[success_text]" value="<?php echo esc_attr((string) $o['success_text']); ?>" placeholder="<?php echo esc_attr__('Vielen Dank! Wir melden uns so schnell wie möglich per E-Mail.', 'deskhub-tickets'); ?>">
|
||||
<p class="description"><?php echo esc_html__('Die Ticketnummer wird automatisch darunter angezeigt.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="dht_status_url"><?php echo esc_html__('Seite mit der Statusabfrage', 'deskhub-tickets'); ?></label></th>
|
||||
<td>
|
||||
<input type="url" id="dht_status_url" class="regular-text" name="<?php echo esc_attr($name); ?>[status_page_url]" value="<?php echo esc_attr((string) $o['status_page_url']); ?>" placeholder="https://ihre-seite.de/ticket-status">
|
||||
<p class="description"><?php echo esc_html__('Optional: Nach dem Absenden erscheint ein Link „Stand abfragen“ zu dieser Seite (dort steht der Shortcode [deskhub_status]).', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><?php echo esc_html__('Spamschutz', 'deskhub-tickets'); ?></h2>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><?php echo esc_html__('Eingebaut', 'deskhub-tickets'); ?></th>
|
||||
<td>
|
||||
<label><?php echo esc_html__('Mindestzeit bis zum Absenden', 'deskhub-tickets'); ?> <input type="number" min="0" max="60" class="small-text" name="<?php echo esc_attr($name); ?>[min_seconds]" value="<?php echo esc_attr((string) (int) $o['min_seconds']); ?>"> <?php echo esc_html__('Sekunden', 'deskhub-tickets'); ?></label><br>
|
||||
<label><?php echo esc_html__('Höchstens', 'deskhub-tickets'); ?> <input type="number" min="0" max="100" class="small-text" name="<?php echo esc_attr($name); ?>[rate_limit_per_hour]" value="<?php echo esc_attr((string) (int) $o['rate_limit_per_hour']); ?>"> <?php echo esc_html__('Tickets je Besucher und Stunde (0 = unbegrenzt)', 'deskhub-tickets'); ?></label>
|
||||
<p class="description"><?php echo esc_html__('Dazu kommt ein unsichtbares Feld, das nur Roboter ausfüllen. Das Formular funktioniert auch mit Seiten-Cache.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><?php echo esc_html__('Cloudflare Turnstile (optional)', 'deskhub-tickets'); ?></th>
|
||||
<td>
|
||||
<input type="text" class="regular-text" name="<?php echo esc_attr($name); ?>[turnstile_site]" value="<?php echo esc_attr((string) $o['turnstile_site']); ?>" placeholder="<?php echo esc_attr__('Website-Schlüssel (Site Key)', 'deskhub-tickets'); ?>" autocomplete="off"><br>
|
||||
<input type="password" class="regular-text" style="margin-top:6px" name="<?php echo esc_attr($name); ?>[turnstile_secret]" value="" placeholder="<?php echo $hasSecret ? esc_attr__('Geheimer Schlüssel gespeichert', 'deskhub-tickets') : esc_attr__('Geheimer Schlüssel (Secret Key)', 'deskhub-tickets'); ?>" autocomplete="new-password">
|
||||
<?php if ($hasSecret): ?><label style="margin-left:8px"><input type="checkbox" name="<?php echo esc_attr($name); ?>[clear_turnstile]" value="1"> <?php echo esc_html__('entfernen', 'deskhub-tickets'); ?></label><?php endif; ?>
|
||||
<p class="description"><?php echo esc_html__('Ein kostenloses Captcha ohne Rätsel. Beide Schlüssel eintragen, dann erscheint es im Formular. Dabei wird eine Verbindung zu Cloudflare aufgebaut: Das gehört in Ihre Datenschutzerklärung.', 'deskhub-tickets'); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p class="submit">
|
||||
<button type="submit" name="submit" class="button button-primary" value="1"><?php echo esc_html__('Speichern', 'deskhub-tickets'); ?></button>
|
||||
<button type="submit" name="dht_test_after" class="button" value="1"><?php echo esc_html__('Speichern und Verbindung testen', 'deskhub-tickets'); ?></button>
|
||||
<span class="description" style="margin-left:8px"><?php echo esc_html__('Der Test legt kein Ticket an.', 'deskhub-tickets'); ?></span>
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin:-8px 0 24px">
|
||||
<input type="hidden" name="action" value="deskhub_tickets_clear_cache">
|
||||
<?php wp_nonce_field('deskhub_tickets_clear_cache'); ?>
|
||||
<button type="submit" class="button"><?php echo esc_html__('Formulare neu laden', 'deskhub-tickets'); ?></button>
|
||||
<span class="description"><?php echo esc_html__('Eigene Felder und Texte kommen aus DeskHub und werden 5 Minuten gemerkt. Nach einer Änderung dort hier neu laden.', 'deskhub-tickets'); ?></span>
|
||||
</form>
|
||||
|
||||
<h2><?php echo esc_html__('So binden Sie es ein', 'deskhub-tickets'); ?></h2>
|
||||
<p><?php echo esc_html__('Die Shortcodes funktionieren in Seiten und Beiträgen (im Block-Editor mit dem Block „Shortcode“).', 'deskhub-tickets'); ?></p>
|
||||
<ul style="list-style:disc;margin-left:22px">
|
||||
<li><code>[deskhub_ticket]</code> – <?php echo esc_html__('Formular zum Anlegen eines Tickets', 'deskhub-tickets'); ?></li>
|
||||
<li><code>[deskhub_ticket department="2" topic="5" priority="1"]</code> – <?php echo esc_html__('mit festen Voreinstellungen für dieses Formular', 'deskhub-tickets'); ?></li>
|
||||
<li><code>[deskhub_ticket topics="Rechnung:3,Technik:4"]</code> – <?php echo esc_html__('Besucher wählen ein Thema aus (Bezeichnung:Nummer des Hilfethemas)', 'deskhub-tickets'); ?></li>
|
||||
<li><code>[deskhub_status]</code> – <?php echo esc_html__('Statusabfrage mit Ticketnummer und E-Mail-Adresse', 'deskhub-tickets'); ?></li>
|
||||
</ul>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
/**
|
||||
* Gemeinsame Hilfsfunktionen: Einstellungen lesen, Besucher erkennen, Signaturen für Formularangaben.
|
||||
*/
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/** Standardwerte aller Einstellungen. */
|
||||
function deskhub_tickets_defaults(): array
|
||||
{
|
||||
return [
|
||||
'server_url' => '',
|
||||
'api_key' => '',
|
||||
'department_id' => 0,
|
||||
'topic_id' => 0,
|
||||
'priority_id' => 0,
|
||||
'consent_text' => '',
|
||||
'accent_color' => '',
|
||||
'success_text' => '',
|
||||
'status_page_url' => '',
|
||||
'min_seconds' => 3,
|
||||
'rate_limit_per_hour' => 5,
|
||||
'turnstile_site' => '',
|
||||
'turnstile_secret' => '',
|
||||
];
|
||||
}
|
||||
|
||||
/** Alle Einstellungen (mit Standardwerten). Server-Adresse und Schlüssel lassen sich zusätzlich in der wp-config.php festlegen. */
|
||||
function deskhub_tickets_options(): array
|
||||
{
|
||||
$saved = get_option('deskhub_tickets_options', []);
|
||||
$opts = array_merge(deskhub_tickets_defaults(), is_array($saved) ? $saved : []);
|
||||
if (defined('DESKHUB_TICKETS_SERVER') && DESKHUB_TICKETS_SERVER !== '') {
|
||||
$opts['server_url'] = (string) DESKHUB_TICKETS_SERVER;
|
||||
}
|
||||
if (defined('DESKHUB_TICKETS_API_KEY') && DESKHUB_TICKETS_API_KEY !== '') {
|
||||
$opts['api_key'] = (string) DESKHUB_TICKETS_API_KEY;
|
||||
}
|
||||
return $opts;
|
||||
}
|
||||
|
||||
function deskhub_tickets_option(string $key)
|
||||
{
|
||||
$opts = deskhub_tickets_options();
|
||||
return $opts[$key] ?? null;
|
||||
}
|
||||
|
||||
/** Wird der API-Schlüssel aus der wp-config.php genommen (dann ist das Feld in den Einstellungen gesperrt)? */
|
||||
function deskhub_tickets_key_from_config(): bool
|
||||
{
|
||||
return defined('DESKHUB_TICKETS_API_KEY') && DESKHUB_TICKETS_API_KEY !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Erkennt den Besucher für die Mengenbegrenzung. Es zählt nur REMOTE_ADDR: Header wie X-Forwarded-For kann jeder selbst setzen.
|
||||
* Steht die Seite hinter einem Proxy, liefert der Filter "deskhub_tickets_client_ip" die richtige Adresse.
|
||||
*/
|
||||
function deskhub_tickets_client_ip(): string
|
||||
{
|
||||
$ip = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
|
||||
$ip = apply_filters('deskhub_tickets_client_ip', $ip);
|
||||
return filter_var($ip, FILTER_VALIDATE_IP) ? (string) $ip : 'unknown';
|
||||
}
|
||||
|
||||
/** Kurzer Schlüssel für einen Besucher (nicht umkehrbar, damit keine IP-Adressen in der Datenbank stehen). */
|
||||
function deskhub_tickets_visitor_key(string $scope): string
|
||||
{
|
||||
return 'dht_' . substr(hash_hmac('sha256', $scope . '|' . deskhub_tickets_client_ip(), wp_salt('auth')), 0, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zählt einen Vorgang für den Besucher und sagt, ob er noch erlaubt ist.
|
||||
* $max Vorgänge je $window Sekunden; false = Grenze erreicht (der Vorgang wird dann nicht mehr gezählt).
|
||||
*/
|
||||
function deskhub_tickets_rate_allow(string $scope, int $max, int $window): bool
|
||||
{
|
||||
if ($max <= 0) {
|
||||
return true;
|
||||
}
|
||||
$key = deskhub_tickets_visitor_key($scope);
|
||||
$count = (int) get_transient($key);
|
||||
if ($count >= $max) {
|
||||
return false;
|
||||
}
|
||||
set_transient($key, $count + 1, $window);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Unterschreibt Angaben, die durchs Formular laufen (Abteilung, Thema, Priorität), damit Besucher sie nicht ändern können. */
|
||||
function deskhub_tickets_sign(string $payload): string
|
||||
{
|
||||
return hash_hmac('sha256', $payload, wp_salt('auth'));
|
||||
}
|
||||
|
||||
function deskhub_tickets_verify_signature(string $payload, string $signature): bool
|
||||
{
|
||||
return $signature !== '' && hash_equals(deskhub_tickets_sign($payload), $signature);
|
||||
}
|
||||
|
||||
/** Zeitstempel mit Unterschrift: beweist, wann das Formular angezeigt wurde (Schutz vor Robotern, die sofort absenden). */
|
||||
function deskhub_tickets_timestamp_token(): string
|
||||
{
|
||||
$t = (string) time();
|
||||
return $t . '.' . deskhub_tickets_sign('ts|' . $t);
|
||||
}
|
||||
|
||||
/** Alter des Formulars in Sekunden; null, wenn der Wert fehlt oder gefälscht ist. */
|
||||
function deskhub_tickets_timestamp_age(string $token): ?int
|
||||
{
|
||||
if (!preg_match('/^(\d{9,11})\.([a-f0-9]{64})$/', $token, $m)) {
|
||||
return null;
|
||||
}
|
||||
if (!deskhub_tickets_verify_signature('ts|' . $m[1], $m[2])) {
|
||||
return null;
|
||||
}
|
||||
return time() - (int) $m[1];
|
||||
}
|
||||
Reference in New Issue
Block a user