/* 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 '
'; echo '

Rozmowy czatu

'; if ($notice !== '') { echo '

' . esc_html($notice) . '

'; } echo '
'; echo '

Zużycie w tym miesiącu (' . esc_html($month) . ')

'; $lab = ($limit <= 0) ? ( (string) $month_n . ' (bez limitu)' ) : ( $month_n . ' / ' . $limit ); $st = ($limit > 0 && $month_n >= $limit) ? 'wyczerpany' : ( ($limit > 0 && $month_n >= (int) ceil($limit * 0.8)) ? '≥ 80%' : 'OK' ); echo '

' . 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 '
'; $base = admin_url('tools.php?page=kaktus-cc-rozmowy-czatu'); if ($view_id > 0) { $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $view_id), ARRAY_A); echo '

← Wróć do listy

'; if (!$row) { echo '

Nie znaleziono rozmowy.

'; return; } echo '

Rozmowa #' . esc_html((string) $row['id']) . '

'; echo '

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 '
'; if (is_array($msgs)) { foreach ($msgs as $m) { $role = isset($m['role']) ? $m['role'] : ''; $label = ($role === 'user') ? 'Klient' : 'Bot'; $bg = ($role === 'user') ? '#f0f4f8' : '#eef6ee'; echo '
' . esc_html($label) . ': ' . nl2br(esc_html(isset($m['content']) ? (string) $m['content'] : '')) . '
'; } } else { echo '

Brak transkryptu.

'; } echo '
'; echo '
'; wp_nonce_field('kaktus_cc_chatlog_delete'); echo ''; submit_button('Usuń tę rozmowę', 'delete', 'kaktus_cc_chatlog_delete', false); echo '
'; return; } $total = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}"); $offset = ($page - 1) * $per_page; $rows = $wpdb->get_results($wpdb->prepare( "SELECT id, created_at, updated_at, message_count, has_lead, first_user_message FROM {$table} ORDER BY updated_at DESC LIMIT %d OFFSET %d", $per_page, $offset ), ARRAY_A); echo '

Lista rozmów

'; echo '

Łącznie: ' . esc_html((string) $total) . '. Telefony i e-maile na liście są ukryte; pełna treść jest w podglądzie rozmowy.

'; echo ''; if (!$rows) { echo ''; } else { foreach ($rows as $row) { $q = kaktus_cc_chatlog_redact((string) $row['first_user_message']); if (function_exists('mb_strlen') && mb_strlen($q) > 160) { $q = mb_substr($q, 0, 160) . '…'; } elseif (strlen($q) > 160) { $q = substr($q, 0, 160) . '…'; } $link = add_query_arg(array('conversation' => (int) $row['id']), $base); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } } echo '
DataPytańLeadPierwsze pytanie
Brak zapisanych rozmów.
' . esc_html($row['updated_at']) . '' . esc_html((string) $row['message_count']) . '' . (!empty($row['has_lead']) ? 'tak' : '—') . '' . esc_html($q) . 'Otwórz
'; $pages = max(1, (int) ceil($total / $per_page)); if ($pages > 1) { 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 ''; } https://kaktus-ogrody.pl/post-sitemap.xml 2026-09-22T00:19:42+00:00 https://kaktus-ogrody.pl/page-sitemap.xml 2026-09-21T12:32:21+00:00 https://kaktus-ogrody.pl/attachment-sitemap.xml 2026-11-28T13:20:20+00:00 https://kaktus-ogrody.pl/category-sitemap.xml 2026-09-22T00:19:42+00:00 https://kaktus-ogrody.pl/post_tag-sitemap.xml 2026-09-22T00:19:42+00:00 https://kaktus-ogrody.pl/author-sitemap.xml 2019-09-05T20:03:17+00:00