/* Odbiornik rozmów czatu Kaktus (lustrzana kopia z freelancer007.pl). * REST POST /wp-json/kaktus-cc/v1/conversations, auth: HMAC-SHA256 (opcja kaktus_cc_mirror_secret, autoload=no). * Admin: Narzędzia → Rozmowy czatu. Retencja 90 dni. Rollback: usunąć ten include z functions.php. */ if (!defined('ABSPATH')) { return; } define('KAKTUS_CC_CHATLOG_DB_VER', 1); define('KAKTUS_CC_CHATLOG_RETENTION_DAYS', 90); define('KAKTUS_CC_CHATLOG_DEFAULT_LIMIT', 200); function kaktus_cc_chatlog_table() { global $wpdb; return $wpdb->prefix . 'kaktus_cc_chat_logs'; } function kaktus_cc_chatlog_maybe_install() { $installed = (int) get_option('kaktus_cc_chatlog_db_ver', 0); if ($installed >= KAKTUS_CC_CHATLOG_DB_VER) { return; } global $wpdb; $table = kaktus_cc_chatlog_table(); $collate = $wpdb->get_charset_collate(); require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, session_id varchar(80) NOT NULL, month_key char(6) NOT NULL, created_at datetime NOT NULL, updated_at datetime NOT NULL, message_count smallint unsigned NOT NULL DEFAULT 0, has_lead tinyint(1) NOT NULL DEFAULT 0, monthly_limit smallint unsigned NOT NULL DEFAULT 200, first_user_message text NULL, transcript longtext NULL, PRIMARY KEY (id), UNIQUE KEY session_id (session_id), KEY month_key (month_key), KEY created_at (created_at) ) {$collate};"; dbDelta($sql); update_option('kaktus_cc_chatlog_db_ver', KAKTUS_CC_CHATLOG_DB_VER, false); } function kaktus_cc_chatlog_redact($text) { if (!is_string($text) || $text === '') { return ''; } $text = preg_replace('/(?:\+?48[\s\-]?)?[1-9]\d(?:[\s\-]?\d){7}/u', '[telefon]', $text); $text = preg_replace('/[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,}/i', '[email]', $text); return $text; } function kaktus_cc_chatlog_month_key() { return wp_date('Ym'); } function kaktus_cc_chatlog_month_count($month_key = null) { global $wpdb; if ($month_key === null) { $month_key = kaktus_cc_chatlog_month_key(); } $table = kaktus_cc_chatlog_table(); return (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE month_key = %s", $month_key )); } function kaktus_cc_chatlog_verify_request($request) { $secret = get_option('kaktus_cc_mirror_secret'); if (!is_string($secret) || strlen($secret) < 20) { return new WP_Error('forbidden', 'Forbidden', array('status' => 403)); } $ts = $request->get_header('x-f7-timestamp'); $sig = $request->get_header('x-f7-signature'); if (!is_string($ts) || !is_string($sig) || !ctype_digit($ts) || $sig === '') { return new WP_Error('forbidden', 'Forbidden', array('status' => 403)); } if (abs(time() - (int) $ts) > 300) { return new WP_Error('expired', 'Forbidden', array('status' => 403)); } $body = (string) $request->get_body(); if ($body === '' || strlen($body) > 200000) { return new WP_Error('forbidden', 'Forbidden', array('status' => 403)); } $calc = hash_hmac('sha256', $ts . '.' . $body, $secret); if (!hash_equals($calc, $sig)) { return new WP_Error('forbidden', 'Forbidden', array('status' => 403)); } return true; } function kaktus_cc_chatlog_sanitize_messages($raw) { if (!is_array($raw)) { return array(); } $out = array(); foreach ($raw as $m) { if (!is_array($m)) { continue; } $role = isset($m['role']) ? sanitize_key((string) $m['role']) : ''; if ($role !== 'user' && $role !== 'assistant') { continue; } $content = isset($m['content']) ? wp_strip_all_tags((string) $m['content']) : ''; $content = trim(preg_replace('/\s+/u', ' ', $content)); if ($content === '') { continue; } if (function_exists('mb_strlen') && mb_strlen($content) > 500) { $content = mb_substr($content, 0, 500); } elseif (strlen($content) > 500) { $content = substr($content, 0, 500); } $out[] = array('role' => $role, 'content' => $content); if (count($out) >= 40) { break; } } return $out; } function kaktus_cc_chatlog_upsert($data) { global $wpdb; $session_id = isset($data['session_id']) ? sanitize_text_field((string) $data['session_id']) : ''; if ($session_id === '' || strlen($session_id) > 80) { return new WP_Error('invalid', 'Invalid session', array('status' => 400)); } $transcript = kaktus_cc_chatlog_sanitize_messages(isset($data['transcript']) ? $data['transcript'] : array()); $first = isset($data['first_user_message']) ? wp_strip_all_tags((string) $data['first_user_message']) : ''; $first = trim(preg_replace('/\s+/u', ' ', $first)); if ($first === '' && $transcript) { foreach ($transcript as $m) { if ($m['role'] === 'user') { $first = $m['content']; break; } } } if (function_exists('mb_strlen') && mb_strlen($first) > 500) { $first = mb_substr($first, 0, 500); } $month_key = isset($data['month_key']) ? preg_replace('/\D/', '', (string) $data['month_key']) : kaktus_cc_chatlog_month_key(); if (strlen($month_key) !== 6) { $month_key = kaktus_cc_chatlog_month_key(); } $created = isset($data['created_at']) ? sanitize_text_field((string) $data['created_at']) : wp_date('Y-m-d H:i:s'); $updated = isset($data['updated_at']) ? sanitize_text_field((string) $data['updated_at']) : wp_date('Y-m-d H:i:s'); if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $created)) { $created = wp_date('Y-m-d H:i:s'); } if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $updated)) { $updated = wp_date('Y-m-d H:i:s'); } $count = isset($data['message_count']) ? max(0, min(9999, (int) $data['message_count'])) : 0; if ($count === 0) { foreach ($transcript as $m) { if ($m['role'] === 'user') { $count++; } } } $has_lead = !empty($data['has_lead']) ? 1 : 0; $limit = isset($data['monthly_limit']) ? max(0, min(100000, (int) $data['monthly_limit'])) : KAKTUS_CC_CHATLOG_DEFAULT_LIMIT; $table = kaktus_cc_chatlog_table(); $existing = $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$table} WHERE session_id = %s LIMIT 1", $session_id )); $payload = array( 'month_key' => $month_key, 'updated_at' => $updated, 'message_count' => $count, 'has_lead' => $has_lead, 'monthly_limit' => $limit, 'first_user_message' => $first, 'transcript' => wp_json_encode($transcript, JSON_UNESCAPED_UNICODE), ); if ($existing) { $wpdb->update($table, $payload, array('id' => (int) $existing), null, array('%d')); $id = (int) $existing; } else { $payload['session_id'] = $session_id; $payload['created_at'] = $created; $wpdb->insert($table, $payload); $id = (int) $wpdb->insert_id; } if ($id <= 0) { return new WP_Error('db', 'Save failed', array('status' => 500)); } return array('ok' => true, 'id' => $id); } add_action('init', 'kaktus_cc_chatlog_maybe_install', 1); add_action('rest_api_init', function () { register_rest_route('kaktus-cc/v1', '/conversations', array( 'methods' => 'POST', 'permission_callback' => 'kaktus_cc_chatlog_verify_request', 'callback' => function ($request) { kaktus_cc_chatlog_maybe_install(); $json = $request->get_json_params(); if (!is_array($json)) { return new WP_Error('invalid', 'Invalid payload', array('status' => 400)); } $tenant = isset($json['tenant']) ? sanitize_key((string) $json['tenant']) : ''; if ($tenant !== '' && $tenant !== 'kaktus') { return new WP_Error('forbidden', 'Forbidden', array('status' => 403)); } $result = kaktus_cc_chatlog_upsert($json); if (is_wp_error($result)) { return $result; } return new WP_REST_Response($result, 200); }, )); }); function kaktus_cc_chatlog_purge_old() { global $wpdb; $table = kaktus_cc_chatlog_table(); $cutoff = wp_date('Y-m-d H:i:s', time() - (KAKTUS_CC_CHATLOG_RETENTION_DAYS * DAY_IN_SECONDS)); $wpdb->query($wpdb->prepare("DELETE FROM {$table} WHERE created_at < %s", $cutoff)); } function kaktus_cc_chatlog_ensure_cron() { if (!wp_next_scheduled('kaktus_cc_chatlog_daily_event')) { $tz = wp_timezone(); $next = new DateTimeImmutable('tomorrow 06:20', $tz); wp_schedule_event($next->getTimestamp(), 'daily', 'kaktus_cc_chatlog_daily_event'); } } add_action('init', 'kaktus_cc_chatlog_ensure_cron', 20); add_action('kaktus_cc_chatlog_daily_event', 'kaktus_cc_chatlog_purge_old'); function kaktus_cc_chatlog_admin_menu() { add_management_page( 'Rozmowy czatu', 'Rozmowy czatu', 'manage_options', 'kaktus-cc-rozmowy-czatu', 'kaktus_cc_chatlog_admin_page' ); } add_action('admin_menu', 'kaktus_cc_chatlog_admin_menu'); function kaktus_cc_chatlog_admin_page() { if (!current_user_can('manage_options')) { return; } kaktus_cc_chatlog_maybe_install(); global $wpdb; $table = kaktus_cc_chatlog_table(); $notice = ''; if (isset($_POST['kaktus_cc_chatlog_delete']) && check_admin_referer('kaktus_cc_chatlog_delete')) { $del_id = isset($_POST['conv_id']) ? (int) $_POST['conv_id'] : 0; if ($del_id > 0) { $wpdb->delete($table, array('id' => $del_id), array('%d')); $notice = 'Rozmowa usunięta.'; } } $view_id = isset($_GET['conversation']) ? (int) $_GET['conversation'] : 0; $page = isset($_GET['paged']) ? max(1, (int) $_GET['paged']) : 1; $per_page = 20; $month = kaktus_cc_chatlog_month_key(); $month_n = kaktus_cc_chatlog_month_count($month); $limit = (int) $wpdb->get_var($wpdb->prepare( "SELECT monthly_limit FROM {$table} WHERE month_key = %s ORDER BY updated_at DESC LIMIT 1", $month )); if ($limit <= 0) { $limit = KAKTUS_CC_CHATLOG_DEFAULT_LIMIT; } echo '
' . esc_html($notice) . '
' . esc_html($lab) . ' — ' . esc_html($st) . '
'; echo 'Rozmowy asystenta AI z kaktus-ogrody.pl (kopia z centrali). Automatyczne usuwanie po ' . esc_html((string) KAKTUS_CC_CHATLOG_RETENTION_DAYS) . ' dniach. Lista tylko dla administratora.
'; echo 'Nie znaleziono rozmowy.
Start: ' . esc_html($row['created_at']) . ' · Ostatnia wiadomość: ' . esc_html($row['updated_at']) . ' · Pytań: ' . esc_html((string) $row['message_count']) . ' · Lead (telefon w czacie): ' . (!empty($row['has_lead']) ? 'tak' : 'nie') . '
'; $msgs = json_decode((string) $row['transcript'], true); echo 'Brak transkryptu.
'; } echo 'Łącznie: ' . esc_html((string) $total) . '. Telefony i e-maile na liście są ukryte; pełna treść jest w podglądzie rozmowy.
'; echo '| Data | Pytań | Lead | Pierwsze pytanie | |
|---|---|---|---|---|
| Brak zapisanych rozmów. | ||||
| ' . esc_html($row['updated_at']) . ' | '; echo '' . esc_html((string) $row['message_count']) . ' | '; echo '' . (!empty($row['has_lead']) ? 'tak' : '—') . ' | '; echo '' . esc_html($q) . ' | '; echo 'Otwórz | '; echo '
Strony: '; for ($i = 1; $i <= $pages; $i++) { $url = add_query_arg(array('paged' => $i), $base); if ($i === $page) { echo '' . $i . ' '; } else { echo '' . $i . ' '; } } echo '
'; } echo ''; }