PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.23
MxChat – AI Chatbot & Content Generation for WordPress v3.2.23
3.2.25 3.2.24 3.2.23 3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 All 156 releases
← All changes | mxchat-basic.php +1054 -143 3.2.3 → 3.2.23 View file →
@@ -2,9 +2,9 @@
2 2 /**
3 3 * Plugin Name: MxChat
4 4 * Plugin URI: https://mxchat.ai/
5 5 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
6 - * Version: 3.2.3
6 + * Version: 3.2.23
7 7 * Author: MxChat
8 8 * Author URI: https://mxchat.ai
9 9 * License: GPLv2 or later
10 10 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -23,8 +23,16 @@
23 23
24 24 if (!defined('MXCHAT_VERSION')) {
25 25 $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), 'plugin');
26 26 $version = $plugin_data['Version'];
27 + // MXCHAT_BASE_VERSION: the plain header version, stable across requests even in
28 + // dev mode. Use it for anything PERSISTED or COMPARED (the stored
29 + // mxchat_plugin_version option and the migration gate in
30 + // mxchat_check_for_update). MXCHAT_VERSION keeps the time() suffix in dev for
31 + // ASSET cache-busting only — persisting the suffixed value made the version
32 + // comparison churn every request, re-running the full activation/migration
33 + // suite per page load on dev installs.
34 + define('MXCHAT_BASE_VERSION', $version);
27 35 if (MXCHAT_DEV_MODE) {
28 36 $version .= '.' . time();
29 37 }
30 38 define('MXCHAT_VERSION', $version);
@@ -29,8 +37,96 @@
29 37 }
30 38 define('MXCHAT_VERSION', $version);
31 39 }
32 40
41 +/**
42 + * Toolbar items API level (plan-mxchat-20260916-65c9b6). Defined only by cores
43 + * that apply the `mxchat_chat_toolbar_items` filter while rendering the chat
44 + * toolbar and fire the `mxchat:toolbar-ready` / `mxchat:opened` document events.
45 + * Add-ons test `defined('MXCHAT_TOOLBAR_ITEMS_API')` and fall back to their
46 + * older DOM-injection path on cores without it, so a button is never rendered
47 + * twice. Bump the value only if the item shape (id / html / order) changes.
48 + */
49 +if (!defined('MXCHAT_TOOLBAR_ITEMS_API')) {
50 + define('MXCHAT_TOOLBAR_ITEMS_API', 1);
51 +}
52 +
53 +/**
54 + * Default confidence floor for the in-chat YouTube card, as a percentage
55 + * (plan-mxchat-20260813-f52492). Higher than the site-wide Similarity
56 + * Threshold default of 35 by design — see MxChat_Utils::video_embed_threshold().
57 + * Declared here so the gate, the admin field and the tests all read ONE number.
58 + */
59 +if (!defined('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT')) {
60 + define('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT', 55);
61 +}
62 +
63 +/**
64 + * One-time install stamp: records the plain version this site first ran, so
65 + * behavior defaults can differ between fresh installs and upgrades without
66 + * touching anyone's stored settings. Mirrors mxchat-mcp's 1.0.7 stamp shape
67 + * (plan 7b578e); first consumer is the "Strip unapproved links" default
68 + * (plan 58f8b4). Runs at init priority 1 — BEFORE initialize_default_options
69 + * (init 20) writes mxchat_options on a fresh site's first request, because
70 + * that option's pre-existing presence is how an upgrade is recognized.
71 + */
72 +function mxchat_stamp_install_version() {
73 + if (get_option('mxchat_installed_at_version', '') !== '') {
74 + return;
75 + }
76 + $existing = get_option('mxchat_options', false) !== false;
77 + $version = defined('MXCHAT_BASE_VERSION') ? MXCHAT_BASE_VERSION : '0.0.0';
78 + update_option('mxchat_installed_at_version', $existing ? 'legacy' : $version, false);
79 +}
80 +add_action('init', 'mxchat_stamp_install_version', 1);
81 +
82 +/**
83 + * Stamp-derived default for the "Strip unapproved links" toggle (plan 58f8b4,
84 + * option-c split of the old Citation Links conflation): 'on' only for installs
85 + * born at 3.2.20+. A missing or 'legacy' stamp means the site predates the
86 + * setting — keep 'off' so no existing site's links start vanishing on update.
87 + */
88 +function mxchat_strip_unapproved_links_default() {
89 + $stamp = get_option('mxchat_installed_at_version', '');
90 + if ($stamp === '' || $stamp === 'legacy') {
91 + return 'off';
92 + }
93 + return version_compare($stamp, '3.2.20', '>=') ? 'on' : 'off';
94 +}
95 +
96 +/**
97 + * Effective state of "Strip unapproved links": an explicitly saved option
98 + * always wins; until one exists the install-stamp default governs. Read via
99 + * a fresh get_option on purpose — the response URL guard runs late in the
100 + * request and must see a value saved moments earlier.
101 + */
102 +function mxchat_strip_unapproved_links_enabled() {
103 + $opts = get_option('mxchat_options', array());
104 + if (is_array($opts) && isset($opts['strip_unapproved_links_toggle'])) {
105 + return $opts['strip_unapproved_links_toggle'] === 'on';
106 + }
107 + return mxchat_strip_unapproved_links_default() === 'on';
108 +}
109 +
110 +/**
111 + * Honest, versioned User-Agent for MXChat remote-content ingestion fetches
112 + * (Knowledge Base PDF import, URL import, sitemap / website crawl).
113 + *
114 + * WAF rulesets (SiteGround/ModSecurity, Wordfence, Cloudflare managed rules)
115 + * flag stale spoofed-browser UAs as scrapers and return 403 — which silently
116 + * broke the single most common KB source: self-hosted media on the site's own
117 + * domain. A truthful crawler identifier is the industry norm for well-behaved
118 + * bots and lets a site owner allowlist "MXChatBot" in their WAF. Filterable so
119 + * a locked-down host can supply a different string without a code change.
120 + */
121 +if (!function_exists('mxchat_ingest_user_agent')) {
122 + function mxchat_ingest_user_agent() {
123 + $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '1.0';
124 + $ua = 'MXChatBot/' . $version . ' (+https://mxchat.ai/bot)';
125 + return apply_filters('mxchat_ingest_user_agent', $ua);
126 + }
127 +}
128 +
33 129 function mxchat_load_textdomain() {
34 130 $domain = 'mxchat';
35 131 $locale = determine_locale();
36 132
@@ -46,8 +142,84 @@
46 142 }
47 143 add_action('init', 'mxchat_load_textdomain');
48 144
49 145 /**
146 + * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026.
147 + * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview
148 + * (Google's official migration target) the first time admin_init fires after update.
149 + */
150 +add_action('admin_init', function () {
151 + if (get_option('mxchat_gemini_3_remap_done')) {
152 + return;
153 + }
154 + $opts = get_option('mxchat_options');
155 + if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') {
156 + $opts['model'] = 'gemini-3.1-pro-preview';
157 + update_option('mxchat_options', $opts);
158 + }
159 + if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') {
160 + $opts['content_model'] = 'gemini-3.1-pro-preview';
161 + update_option('mxchat_options', $opts);
162 + }
163 + update_option('mxchat_gemini_3_remap_done', 1);
164 +});
165 +
166 +/**
167 + * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212,
168 + * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing
169 + * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning
170 + * (modern, fast, broadly available) the first time admin_init fires after update.
171 + */
172 +add_action('admin_init', function () {
173 + if (get_option('mxchat_grok_2_remap_done')) {
174 + return;
175 + }
176 + $opts = get_option('mxchat_options');
177 + if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') {
178 + $opts['model'] = 'grok-4-1-fast-non-reasoning';
179 + update_option('mxchat_options', $opts);
180 + }
181 + if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') {
182 + $opts['content_model'] = 'grok-4-1-fast-non-reasoning';
183 + update_option('mxchat_options', $opts);
184 + }
185 + update_option('mxchat_grok_2_remap_done', 1);
186 +});
187 +
188 +/**
189 + * One-time migration: Anthropic retired the Claude 4 (2025-05-14) snapshots on
190 + * June 15, 2026 — claude-opus-4-20250514 and claude-sonnet-4-20250514 now return
191 + * an API error. Existing installs with a dead ID get auto-remapped to the current
192 + * equivalents Anthropic recommends (Opus 4.8 / Sonnet 4.6) the first time admin_init
193 + * fires after update. Mirrors the gemini-3-pro-preview / grok-2 rescues above.
194 + */
195 +add_action('admin_init', function () {
196 + if (get_option('mxchat_claude_4_retire_remap_done')) {
197 + return;
198 + }
199 + $map = array(
200 + 'claude-opus-4-20250514' => 'claude-opus-4-8',
201 + 'claude-sonnet-4-20250514' => 'claude-sonnet-4-6',
202 + );
203 + $opts = get_option('mxchat_options');
204 + if (is_array($opts)) {
205 + $changed = false;
206 + if (isset($opts['model']) && isset($map[$opts['model']])) {
207 + $opts['model'] = $map[$opts['model']];
208 + $changed = true;
209 + }
210 + if (isset($opts['content_model']) && isset($map[$opts['content_model']])) {
211 + $opts['content_model'] = $map[$opts['content_model']];
212 + $changed = true;
213 + }
214 + if ($changed) {
215 + update_option('mxchat_options', $opts);
216 + }
217 + }
218 + update_option('mxchat_claude_4_retire_remap_done', 1);
219 +});
220 +
221 +/**
50 222 * Exclude MxChat assets from caching plugin optimizations
51 223 *
52 224 * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
53 225 * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
@@ -250,23 +422,89 @@
250 422 $rejected[] = 'wp-admin/admin-ajax.php';
251 423 return $rejected;
252 424 });
253 425
426 +// ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix)
427 +// Each cache plugin gets its own filter export so that visitors hitting an
428 +// edge-cached page never receive cached chat-AJAX responses. The chat send /
429 +// stream send / file upload all POST to /wp-admin/admin-ajax.php with
430 +// `action=mxchat_*`. Without these exports, a cache plugin can stale a response
431 +// and break the per-session nonce flow on the first message.
432 +
433 +// WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings.
434 +add_filter('rocket_cache_reject_uri', function($uris) {
435 + if (!is_array($uris)) $uris = array();
436 + $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*';
437 + return $uris;
438 +});
439 +
440 +// LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits
441 +// caching when the request matches our chat-AJAX pattern.
442 +add_filter('litespeed_cache_no_cache_for_request', function($no_cache) {
443 + if ($no_cache) return $no_cache;
444 + if (!empty($_SERVER['REQUEST_URI']) &&
445 + strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
446 + !empty($_REQUEST['action']) &&
447 + strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
448 + return true;
449 + }
450 + return $no_cache;
451 +});
452 +
453 +// W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when
454 +// the URI matches.
455 +add_filter('w3tc_pgcache_request_skip_uri', function($skip) {
456 + if ($skip) return $skip;
457 + if (!empty($_SERVER['REQUEST_URI']) &&
458 + strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
459 + !empty($_REQUEST['action']) &&
460 + strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
461 + return true;
462 + }
463 + return $skip;
464 +});
465 +
466 +// FlyingPress — `flying_press_cacheable` takes a boolean and is run per
467 +// request. Same pattern as LiteSpeed / W3TC.
468 +add_filter('flying_press_cacheable', function($cacheable) {
469 + if (!$cacheable) return $cacheable;
470 + if (!empty($_SERVER['REQUEST_URI']) &&
471 + strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
472 + !empty($_REQUEST['action']) &&
473 + strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
474 + return false;
475 + }
476 + return $cacheable;
477 +});
478 +
254 479 // Include classes with error handling
255 480 function mxchat_include_classes() {
256 481 $class_files = array(
482 + 'includes/class-mxchat-model-catalog.php',
483 + 'includes/class-mxchat-model-liveness.php',
484 + 'includes/class-mxchat-session-store.php',
485 + 'includes/class-mxchat-live-agent-schedule.php',
486 + 'includes/class-mxchat-tool-registry.php',
257 487 'includes/class-mxchat-integrator.php',
258 488 'includes/class-mxchat-admin.php',
259 489 'includes/class-mxchat-public.php',
490 + 'includes/class-mxchat-block.php',
491 + 'includes/class-mxchat-elementor.php',
260 492 'includes/class-mxchat-utils.php',
261 493 'includes/class-mxchat-user.php',
494 + 'includes/class-mxchat-privacy.php',
262 495 'includes/class-mxchat-meta-box.php',
263 496 'includes/class-mxchat-chunker.php',
264 497 'includes/class-mxchat-word-handler.php',
265 498 'includes/class-mxchat-content-generator.php',
499 + 'includes/class-mxchat-cache-purge.php',
500 + 'includes/class-mxchat-editor-assistant.php',
501 + 'includes/class-rest-api.php',
266 502 'admin/class-ajax-handler.php',
267 503 'admin/class-pinecone-manager.php',
268 - 'admin/class-knowledge-manager.php'
504 + 'admin/class-pinecone-documents.php',
505 + 'admin/class-knowledge-manager.php',
506 + 'admin/class-vectorstore-manager.php'
269 507 );
270 508
271 509 foreach ($class_files as $file) {
272 510 $file_path = plugin_dir_path(__FILE__) . $file;
@@ -275,8 +513,77 @@
275 513 } else {
276 514 //error_log('MxChat: Missing class file - ' . $file);
277 515 }
278 516 }
517 +
518 + // Register the native function-calling admin-post save handler (a41dee).
519 + if (class_exists('MxChat_Tool_Registry')) {
520 + MxChat_Tool_Registry::init();
521 + }
522 +
523 + // GDPR: register with WP's personal-data export/erase tools (b81e42).
524 + if (class_exists('MxChat_Privacy')) {
525 + MxChat_Privacy::init();
526 + }
527 +
528 + // Per-session state store: retention cron + the cron-independent
529 + // migration drain off admin_init (b64b77).
530 + if (class_exists('MxChat_Session_Store')) {
531 + MxChat_Session_Store::init();
532 + }
533 +
534 + // Daily model-liveness check + its warning notice (b65e8d). Read-only and
535 + // fail-open: one listing request per in-use provider per day, none at all
536 + // when no key is stored.
537 + if (class_exists('MxChat_Model_Liveness')) {
538 + MxChat_Model_Liveness::init();
539 + }
540 +
541 + // Gutenberg chatbot block (plan-95dd1e): a click-to-place wrapper over the
542 + // [mxchat_chatbot] shortcode. Registers on init; no-op below WP 5.0.
543 + if (class_exists('MxChat_Block')) {
544 + MxChat_Block::init();
545 + }
546 +
547 + // Elementor chatbot widget (plan-95dd1e part 2): registered ONLY inside
548 + // elementor/widgets/register (Elementor >= 3.5) — with Elementor absent or
549 + // older, the hook never fires and nothing further loads.
550 + if (class_exists('MxChat_Elementor')) {
551 + MxChat_Elementor::init();
552 + }
553 +
554 + // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
555 + // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
556 + // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
557 + if (class_exists('MxChat_Editor_Assistant')) {
558 + MxChat_Editor_Assistant::init();
559 + }
560 +
561 + // OpenAI Vector Store write path (plan-15b5c6): import/sync AJAX, the
562 + // import cron tick, the pending-delete sweeper, and the WP-CLI command
563 + // all register in the constructor. The sync itself only runs when the
564 + // sync toggle + store ID + OpenAI key are all present.
565 + if (class_exists('MxChat_Vectorstore_Manager')) {
566 + MxChat_Vectorstore_Manager::get_instance();
567 + }
568 +
569 + // Admin pages that aren't classes (procedural include).
570 + if (is_admin()) {
571 + $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
572 + if (file_exists($admin_api_page)) {
573 + require_once $admin_api_page;
574 + }
575 + // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
576 + // The require MUST live here (admin bootstrap) and not just inside
577 + // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
578 + // fire on admin-ajax.php requests, so the wizard's AJAX handlers
579 + // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
580 + // auto_graduate + the f7c7d4 dismiss handler) would never register.
581 + $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
582 + if (file_exists($admin_onboarding_page)) {
583 + require_once $admin_onboarding_page;
584 + }
585 + }
279 586 }
280 587
281 588 /**
282 589 * Lazy-load the PDF parser library only when needed.
@@ -321,8 +628,26 @@
321 628 dbDelta($sql);
322 629 }
323 630
324 631 /**
632 + * Create the per-session state table (b64b77).
633 + *
634 + * Callable from the activation hook, which can run before plugins_loaded has
635 + * included the class files — so it loads the class itself when needed.
636 + */
637 +function mxchat_create_sessions_table() {
638 + if (!class_exists('MxChat_Session_Store')) {
639 + $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
640 + if (!file_exists($path)) {
641 + return false;
642 + }
643 + require_once $path;
644 + }
645 +
646 + return MxChat_Session_Store::create_table();
647 +}
648 +
649 +/**
325 650 * FIXED: Robust table creation and column management
326 651 */
327 652 function mxchat_create_chat_transcripts_table() {
328 653 global $wpdb;
@@ -608,51 +933,88 @@
608 933 update_option('mxchat_content_type_migration_version', '2.5.6');
609 934 }
610 935
611 936 /**
612 - * 3.2.3: Add embedding_model column to KB and intent tables so we can detect
613 - * when the active embedding model is changed while content is already embedded.
937 + * 3.2.4: Backfill the active embedding model option for installs that already
938 + * have KB content but no stamped model. The mismatch warning compares this
939 + * against the user's currently selected model — no per-row column needed.
614 940 */
615 -function mxchat_add_embedding_model_columns() {
941 +function mxchat_backfill_active_embedding_model() {
616 942 global $wpdb;
617 943
618 - $migration_version = get_option('mxchat_embedding_model_migration_version', '0');
619 - if (version_compare($migration_version, '3.2.3', '>=')) {
944 + if (get_option('mxchat_active_embedding_model', '') !== '') {
620 945 return;
621 946 }
622 947
623 - $tables = array(
624 - $wpdb->prefix . 'mxchat_system_prompt_content',
625 - $wpdb->prefix . 'mxchat_intents',
626 - $wpdb->prefix . 'mxchat_intent_phrases',
627 - );
948 + $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
949 + if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
950 + return;
951 + }
628 952
629 - foreach ($tables as $table) {
630 - if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
631 - continue;
632 - }
633 - $col_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table} LIKE 'embedding_model'");
634 - if (empty($col_exists)) {
635 - $wpdb->query("ALTER TABLE {$table} ADD COLUMN embedding_model VARCHAR(64) DEFAULT NULL");
636 - }
953 + $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
954 + if ($kb_count > 0) {
955 + $options = get_option('mxchat_options', array());
956 + $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
957 + update_option('mxchat_active_embedding_model', $current_model, false);
637 958 }
959 +}
638 960
639 - // Best-effort backfill: if any existing content lacks a stamped model, assume
640 - // it was embedded with whatever model is currently selected. This is the
641 - // safest assumption for installations upgrading to 3.2.3 — if it was wrong
642 - // already, the mismatch detection will surface it on the next switch.
643 - $options = get_option('mxchat_options', array());
644 - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
961 +/**
962 + * 3.2.20: One-time backfill of the caee10 catalog usage-hint defaults
963 + * (plan 64c1ad). persist() writes usage_hint for EVERY shown tool on every
964 + * autosave — as '' when the box is untouched — and resolve_tool_setting()
965 + * seeds a catalog default_hint ONLY onto an ABSENT key. So any install that
966 + * saved the AI Tools screen before 3.2.20 holds '' everywhere and the shipped
967 + * defaults can never reach it. On an upgrade from < 3.2.20 an empty stored
968 + * hint cannot be a deliberate clear of a rendered default (those builds never
969 + * rendered one), so seeding is safe. From 3.2.20 on, empty means the owner
970 + * cleared a visible default and is respected — this never runs again (version
971 + * gate + its own marker, deliberately not caee10's flag).
972 + *
973 + * Never touched: entries with owner text, legacy bare-bool entries and
974 + * absent-key entries (both already resolve to the default at read time), and
975 + * tools whose catalog entry ships no default_hint.
976 + */
977 +function mxchat_backfill_tool_hint_defaults() {
978 + if (get_option('mxchat_tool_hint_backfill_64c1ad') === '1') {
979 + return;
980 + }
645 981
646 - if (get_option('mxchat_active_embedding_model', '') === '') {
647 - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
648 - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
649 - if ($kb_count > 0) {
650 - update_option('mxchat_active_embedding_model', $current_model, false);
982 + if (class_exists('MxChat_Tool_Registry')) {
983 + $map = get_option('mxchat_function_calling_tools', array());
984 + if (is_array($map) && !empty($map)) {
985 + $defaults = array();
986 + foreach (MxChat_Tool_Registry::core_tool_catalog() as $fn => $meta) {
987 + if (!empty($meta['default_hint'])) {
988 + $defaults[$fn] = (string) $meta['default_hint'];
989 + }
990 + }
991 +
992 + $changed = false;
993 + foreach ($map as $fn => $entry) {
994 + if (!isset($defaults[$fn])) {
995 + continue; // no catalog default — nothing to seed
996 + }
997 + if (!is_array($entry)) {
998 + continue; // legacy bare bool: key absent, resolves to the default already
999 + }
1000 + if (!array_key_exists('usage_hint', $entry)) {
1001 + continue; // absent key gets the default at read time — must stay absent
1002 + }
1003 + if (trim((string) $entry['usage_hint']) !== '') {
1004 + continue; // owner text — never touch
1005 + }
1006 + $map[$fn]['usage_hint'] = $defaults[$fn];
1007 + $changed = true;
1008 + }
1009 +
1010 + if ($changed) {
1011 + update_option('mxchat_function_calling_tools', $map);
1012 + }
651 1013 }
652 1014 }
653 1015
654 - update_option('mxchat_embedding_model_migration_version', '3.2.3');
1016 + update_option('mxchat_tool_hint_backfill_64c1ad', '1', false);
655 1017 }
656 1018
657 1019 /**
658 1020 * 2.5.2: Create queue processing tables for reliable background processing
@@ -727,8 +1089,67 @@
727 1089 dbDelta($sql);
728 1090 }
729 1091
730 1092 /**
1093 + * Create per-session satisfaction ratings table (v3.2.6)
1094 + * Stores one 👍/👎 rating + optional feedback per chat session.
1095 + */
1096 +function mxchat_create_session_ratings_table() {
1097 + global $wpdb;
1098 + $charset_collate = $wpdb->get_charset_collate();
1099 +
1100 + $table_name = $wpdb->prefix . 'mxchat_session_ratings';
1101 + $sql = "CREATE TABLE $table_name (
1102 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
1103 + session_id varchar(255) NOT NULL,
1104 + bot_id varchar(50) NOT NULL DEFAULT 'default',
1105 + rating_value tinyint(1) NOT NULL,
1106 + rating_feedback text DEFAULT NULL,
1107 + created_at datetime NOT NULL,
1108 + PRIMARY KEY (id),
1109 + UNIQUE KEY session_id (session_id),
1110 + KEY bot_id (bot_id),
1111 + KEY created_at (created_at)
1112 + ) $charset_collate;";
1113 +
1114 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
1115 + dbDelta($sql);
1116 +}
1117 +
1118 +/**
1119 + * Create the OpenAI Vector Store file-mapping table (v3.2.20, plan 15b5c6).
1120 + * One row per mirrored KB entry: which store, which bot, which OpenAI file id,
1121 + * and a hash of the uploaded body for change detection. Vector store files are
1122 + * not patchable in place — without this mapping an update cannot find its
1123 + * predecessor, and the store silently accumulates stale duplicates.
1124 + * status: 'live' (serving) or 'pending_delete' (condemned, swept later).
1125 + */
1126 +function mxchat_create_vectorstore_files_table() {
1127 + global $wpdb;
1128 + $charset_collate = $wpdb->get_charset_collate();
1129 +
1130 + $table_name = $wpdb->prefix . 'mxchat_vectorstore_files';
1131 + $sql = "CREATE TABLE $table_name (
1132 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
1133 + store_id varchar(64) NOT NULL,
1134 + bot_id varchar(64) NOT NULL DEFAULT 'default',
1135 + entry_key char(32) NOT NULL,
1136 + source_url text,
1137 + file_id varchar(64) NOT NULL,
1138 + content_hash char(32) NOT NULL DEFAULT '',
1139 + status varchar(20) NOT NULL DEFAULT 'live',
1140 + last_error text,
1141 + updated_at datetime DEFAULT NULL,
1142 + PRIMARY KEY (id),
1143 + KEY store_entry (store_id, bot_id, entry_key, status),
1144 + KEY status (status)
1145 + ) $charset_collate;";
1146 +
1147 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
1148 + dbDelta($sql);
1149 +}
1150 +
1151 +/**
731 1152 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
732 1153 * This fixes "url, source_url. The supplied values may be too long" errors
733 1154 */
734 1155 function mxchat_fix_url_column_size() {
@@ -772,53 +1193,45 @@
772 1193 if (!isset($options['model'])) {
773 1194 return;
774 1195 }
775 1196
776 - $current_model = $options['model'];
777 -
778 - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
779 - $deprecated_claude_models = array(
780 - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
781 - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
782 - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
783 - 'claude-3-opus-20240229', // Retired Jan 5, 2026
784 - 'claude-3-sonnet-20240229', // Legacy
785 - 'claude-3-haiku-20240307', // Legacy
786 - );
787 - if (in_array($current_model, $deprecated_claude_models, true)) {
788 - $options['model'] = 'claude-opus-4-6';
789 - $migrated = true;
790 - $migration_message = sprintf(
791 - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.',
792 - $current_model
793 - );
1197 + // The retired-id → replacement mapping lives in ONE place:
1198 + // MxChat_Model_Catalog::retired_model_map() (plan 202df5). This function
1199 + // and every add-on that stores model ids consume that map — do not add a
1200 + // deprecation list here again.
1201 + if (!class_exists('MxChat_Model_Catalog') || !method_exists('MxChat_Model_Catalog', 'retired_model_map')) {
1202 + return; // catalog not loaded (defensive) — the next admin load retries
794 1203 }
1204 + $map = MxChat_Model_Catalog::retired_model_map();
795 1205
796 - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
797 - if ($current_model === 'claude-3-5-haiku-20241022') {
798 - $options['model'] = 'claude-haiku-4-5-20251001';
1206 + $current_model = $options['model'];
1207 + if (isset($map[$current_model])) {
1208 + $entry = $map[$current_model];
1209 + $options['model'] = $entry['to'];
799 1210 $migrated = true;
800 - $migration_message = 'Your chatbot model has been automatically updated from Claude Haiku 3.5 to Claude Haiku 4.5 due to Anthropic deprecating the older model.';
801 - }
802 -
803 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
804 - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
805 - $options['model'] = 'gpt-5.1-chat-latest';
806 - $migrated = true;
807 1211 $migration_message = sprintf(
808 - 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.',
809 - $current_model
1212 + 'Your chatbot model has been automatically updated from %s to %s %s.',
1213 + $current_model,
1214 + $entry['label'],
1215 + $entry['reason']
810 1216 );
811 1217 }
812 1218
813 - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
814 - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
815 - $options['model'] = 'gpt-5-mini';
1219 + // The content generator has its own model option — the same map applies.
1220 + // (Pre-202df5 this branch covered only the two gpt-5.x-chat-latest aliases;
1221 + // it now covers every retired id, so e.g. a content model stranded on a
1222 + // retired Claude id is rescued the same way the chat model is.)
1223 + if (isset($options['content_model']) && isset($map[$options['content_model']])) {
1224 + $old_content_model = $options['content_model'];
1225 + $entry = $map[$old_content_model];
1226 + $options['content_model'] = $entry['to'];
816 1227 $migrated = true;
817 - $migration_message = sprintf(
818 - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
819 - $current_model
820 - );
1228 + $migration_message = trim($migration_message . ' ' . sprintf(
1229 + 'Your content generation model has also been automatically updated from %s to %s %s.',
1230 + $old_content_model,
1231 + $entry['label'],
1232 + $entry['reason']
1233 + ));
821 1234 }
822 1235
823 1236 if ($migrated) {
824 1237 update_option('mxchat_options', $options);
@@ -845,8 +1258,100 @@
845 1258 delete_option('mxchat_model_migration_message');
846 1259 }
847 1260 }
848 1261
1262 +/**
1263 + * One-time recommendation on EXISTING installs (stamp 'legacy') that the new
1264 + * "Strip unapproved links" guard exists and is worth turning on (plan 58f8b4).
1265 + * Fresh 3.2.20+ installs default it on and never see this. Shown only on
1266 + * MxChat admin pages, gone for good once dismissed or once the site saves an
1267 + * explicit value for the toggle either way.
1268 + */
1269 +function mxchat_show_strip_links_notice() {
1270 + if (!current_user_can('manage_options')) {
1271 + return;
1272 + }
1273 + $page = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1274 + if (strpos($page, 'mxchat') !== 0) {
1275 + return;
1276 + }
1277 + if (get_option('mxchat_strip_links_notice_dismissed', '') === '1') {
1278 + return;
1279 + }
1280 + if (get_option('mxchat_installed_at_version', '') !== 'legacy') {
1281 + return;
1282 + }
1283 + $opts = get_option('mxchat_options', array());
1284 + if (is_array($opts) && isset($opts['strip_unapproved_links_toggle'])) {
1285 + return; // The site already made its choice — stop recommending.
1286 + }
1287 + $dismiss_url = wp_nonce_url(
1288 + admin_url('admin-post.php?action=mxchat_dismiss_strip_links_notice'),
1289 + 'mxchat_dismiss_strip_links_notice'
1290 + );
1291 + ?>
1292 + <div class="notice notice-info">
1293 + <p>
1294 + <strong><?php esc_html_e('MxChat: new link protection available', 'mxchat'); ?></strong><br>
1295 + <?php esc_html_e('The new "Strip Unapproved Links" setting removes links the AI invents from its answers even when Citation Links is off — links to real pages on your site and links your integrations return are always kept. It is off on existing sites so nothing changes without you; we recommend turning it on under MxChat → Settings → Chatbot Behavior.', 'mxchat'); ?>
1296 + <a href="<?php echo esc_url($dismiss_url); ?>"><?php esc_html_e('Dismiss', 'mxchat'); ?></a>
1297 + </p>
1298 + </div>
1299 + <?php
1300 +}
1301 +add_action('admin_notices', 'mxchat_show_strip_links_notice');
1302 +
1303 +/** Dismiss handler for the strip-links recommendation notice (plan 58f8b4). */
1304 +function mxchat_dismiss_strip_links_notice() {
1305 + if (!current_user_can('manage_options')) {
1306 + wp_die(esc_html__('Insufficient permissions.', 'mxchat'), '', array('response' => 403));
1307 + }
1308 + check_admin_referer('mxchat_dismiss_strip_links_notice');
1309 + update_option('mxchat_strip_links_notice_dismissed', '1', false);
1310 + $referer = wp_get_referer();
1311 + wp_safe_redirect($referer ? $referer : admin_url('admin.php?page=mxchat-max'));
1312 + exit;
1313 +}
1314 +add_action('admin_post_mxchat_dismiss_strip_links_notice', 'mxchat_dismiss_strip_links_notice');
1315 +
1316 +/**
1317 + * Persistent admin notice when the provider rejected the configured model
1318 + * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1319 + * integrator whenever a chat request fails on a model-access error — including
1320 + * requests from anonymous visitors, which is the case that otherwise stays
1321 + * invisible to the site owner for weeks (plan e46b8f).
1322 + *
1323 + * Deleted after render so it re-arms on the next failed chat: the notice keeps
1324 + * reappearing until the model is fixed, then stops on its own.
1325 + */
1326 +function mxchat_show_model_access_notice() {
1327 + if (!current_user_can('manage_options')) {
1328 + return;
1329 + }
1330 + $notice = get_option('mxchat_model_access_notice');
1331 + if (!is_array($notice) || empty($notice['model'])) {
1332 + return;
1333 + }
1334 + $settings_url = admin_url('admin.php?page=mxchat-max');
1335 + ?>
1336 + <div class="notice notice-error is-dismissible">
1337 + <p>
1338 + <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1339 + <?php
1340 + printf(
1341 + /* translators: 1: model id, 2: provider name */
1342 + esc_html__('Chat requests using the model "%1$s" are failing because %2$s reports it as unavailable on your API key (it may have been retired). Visitors may be seeing errors instead of replies.', 'mxchat'),
1343 + esc_html($notice['model']),
1344 + esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1345 + );
1346 + ?>
1347 + <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1348 + </p>
1349 + </div>
1350 + <?php
1351 + delete_option('mxchat_model_access_notice');
1352 +}
1353 +
849 1354 function mxchat_activate() {
850 1355 global $wpdb;
851 1356 $charset_collate = $wpdb->get_charset_collate();
852 1357
@@ -854,8 +1359,12 @@
854 1359
855 1360 // Create chat transcripts table with improved function
856 1361 mxchat_create_chat_transcripts_table();
857 1362
1363 + // Per-session state table (b64b77). Activation can run before
1364 + // plugins_loaded has included the class files, so require it directly.
1365 + mxchat_create_sessions_table();
1366 +
858 1367 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
859 1368 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
860 1369 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
861 1370 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -862,11 +1371,11 @@
862 1371 url TEXT NOT NULL,
863 1372 article_content LONGTEXT NOT NULL,
864 1373 embedding_vector LONGTEXT,
865 1374 source_url TEXT DEFAULT NULL,
1375 + title VARCHAR(255) DEFAULT NULL,
866 1376 role_restriction VARCHAR(50) DEFAULT 'public',
867 1377 content_type VARCHAR(50) DEFAULT 'content',
868 - embedding_model VARCHAR(64) DEFAULT NULL,
869 1378 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
870 1379 PRIMARY KEY (id),
871 1380 KEY content_type (content_type)
872 1381 ) $charset_collate;";
@@ -881,9 +1390,8 @@
881 1390 callback_function VARCHAR(255) NOT NULL,
882 1391 similarity_threshold FLOAT DEFAULT 0.85,
883 1392 enabled TINYINT(1) NOT NULL DEFAULT 1,
884 1393 enabled_bots LONGTEXT DEFAULT NULL,
885 - embedding_model VARCHAR(64) DEFAULT NULL,
886 1394 PRIMARY KEY (id)
887 1395 ) $charset_collate;";
888 1396
889 1397 // Individual Intent Phrases Table - each phrase gets its own embedding vector
@@ -892,9 +1400,8 @@
892 1400 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
893 1401 intent_id BIGINT(20) UNSIGNED NOT NULL,
894 1402 phrase TEXT NOT NULL,
895 1403 embedding_vector LONGTEXT NOT NULL,
896 - embedding_model VARCHAR(64) DEFAULT NULL,
897 1404 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
898 1405 PRIMARY KEY (id),
899 1406 KEY intent_id (intent_id)
900 1407 ) $charset_collate;";
@@ -917,8 +1424,14 @@
917 1424
918 1425 // Create transcript translations table
919 1426 mxchat_create_translations_table();
920 1427
1428 + // Create per-session satisfaction ratings table (v3.2.6)
1429 + mxchat_create_session_ratings_table();
1430 +
1431 + // Create Vector Store file-mapping table (v3.2.20, plan 15b5c6)
1432 + mxchat_create_vectorstore_files_table();
1433 +
921 1434 // Ensure additional columns in system prompt table
922 1435 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
923 1436 if (!empty($existing_system_columns)) {
924 1437 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -931,8 +1444,13 @@
931 1444 }
932 1445 if (!in_array('role_restriction', $existing_system_column_names)) {
933 1446 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
934 1447 }
1448 + // Page title captured at import time (3.2.23, plan d9ee66) - read by
1449 + // add-ons that name a source, e.g. AI Search's source cards.
1450 + if (!in_array('title', $existing_system_column_names)) {
1451 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN title VARCHAR(255) DEFAULT NULL AFTER source_url");
1452 + }
935 1453 }
936 1454
937 1455 // Set default thresholds for existing intents
938 1456 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
@@ -961,16 +1479,17 @@
961 1479
962 1480 // Run migration for existing installations
963 1481 mxchat_migrate_pinecone_roles_add_bot_id();
964 1482
965 - // 3.2.3: Add embedding_model column to KB and intent tables
966 - mxchat_add_embedding_model_columns();
1483 + // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1484 + mxchat_backfill_active_embedding_model();
967 1485
968 1486 // Setup cron jobs
969 1487 mxchat_setup_cron_jobs();
970 1488
971 - // Update version
972 - update_option('mxchat_plugin_version', MXCHAT_VERSION);
1489 + // Update version (stable base version — never the dev time()-suffixed one,
1490 + // or the check_for_update comparison would churn every request)
1491 + update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
973 1492
974 1493 //error_log("MxChat: Activation function completed");
975 1494 }
976 1495
@@ -985,28 +1504,35 @@
985 1504 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
986 1505 // Set flag to use fallback system
987 1506 update_option('mxchat_use_fallback_rate_limits', true);
988 1507 update_option('mxchat_next_rate_limit_check', time() + 3600);
989 - return;
990 - }
991 -
992 - // Schedule the rate limit reset cron job
993 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
994 -
995 - if ($result === false) {
996 - // Fallback if scheduling fails
997 - update_option('mxchat_use_fallback_rate_limits', true);
998 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1508 + // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1509 + // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1510 + // execute (a server-side runner hitting wp-cron.php instead of loopback
1511 + // spawns) — scheduling still just writes the cron option. The old early
1512 + // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1513 + // site permanently lost the transcript cleanup event while the retention
1514 + // setting still claimed to be active.
999 1515 } else {
1000 - // Clear fallback flags if cron scheduling succeeded
1001 - delete_option('mxchat_use_fallback_rate_limits');
1516 + // Schedule the rate limit reset cron job
1517 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1518 +
1519 + if ($result === false) {
1520 + // Fallback if scheduling fails
1521 + update_option('mxchat_use_fallback_rate_limits', true);
1522 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1523 + } else {
1524 + // Clear fallback flags if cron scheduling succeeded
1525 + delete_option('mxchat_use_fallback_rate_limits');
1526 + }
1002 1527 }
1003 -
1004 - // Schedule transcript cleanup if configured
1528 +
1529 + // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
1005 1530 $transcript_options = get_option('mxchat_transcripts_options', array());
1006 1531 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1007 -
1008 - if ($cleanup_interval !== 'never') {
1532 + $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1533 +
1534 + if ($cleanup_interval !== 'never' || $custom_retention > 0) {
1009 1535 // Check if not already scheduled
1010 1536 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1011 1537 // Schedule to run daily at 3 AM
1012 1538 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1022,8 +1548,9 @@
1022 1548 // Clear scheduled cron jobs
1023 1549 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1024 1550 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1025 1551 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1552 + wp_clear_scheduled_hook('mxchat_model_liveness_check');
1026 1553
1027 1554 // Clear fallback options
1028 1555 delete_option('mxchat_use_fallback_rate_limits');
1029 1556 delete_option('mxchat_next_rate_limit_check');
@@ -1043,17 +1570,25 @@
1043 1570 return;
1044 1571 }
1045 1572
1046 1573 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1047 -
1574 +
1048 1575 if (time() >= $next_check) {
1049 - // Only run reset if the MxChat_Integrator class exists
1050 - if (class_exists('MxChat_Integrator')) {
1051 - $integrator = new MxChat_Integrator();
1052 - if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
1053 - $integrator->mxchat_reset_rate_limits();
1054 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1055 - }
1576 + // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1577 + // plugins_loaded (before this init-priority-5 callback), so it's always set
1578 + // here. Constructing a second MxChat_Integrator just to call one method
1579 + // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1580 + // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1581 + // the request. Defensive construction only if the global is somehow unset.
1582 + // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1583 + // implementation of this same check — if either changes, change both.
1584 + global $mxchat_integrator;
1585 + $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1586 + ? $mxchat_integrator
1587 + : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1588 + if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1589 + $integrator->mxchat_reset_rate_limits();
1590 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1056 1591 }
1057 1592 }
1058 1593 }
1059 1594
@@ -1065,9 +1600,9 @@
1065 1600 global $wpdb;
1066 1601
1067 1602 try {
1068 1603 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1069 - $plugin_version = MXCHAT_VERSION;
1604 + $plugin_version = MXCHAT_BASE_VERSION;
1070 1605
1071 1606 // Always ensure critical tables exist (even if version matches)
1072 1607 // This handles manual table deletion or fresh installs
1073 1608 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1072,12 +1607,16 @@
1072 1607 // This handles manual table deletion or fresh installs
1073 1608 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1074 1609 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1075 1610
1611 + $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1612 +
1076 1613 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1077 1614 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1078 -
1079 - if (!$chat_exists || !$queue_exists) {
1615 + $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1616 + || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1617 +
1618 + if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1080 1619 //error_log("MxChat: Critical tables missing, running activation");
1081 1620 mxchat_activate();
1082 1621 }
1083 1622
@@ -1140,13 +1679,61 @@
1140 1679 delete_option('mxchat_email_null');
1141 1680 delete_option('mxchat_name_null');
1142 1681 }
1143 1682
1144 - // 3.2.3: Add embedding_model tracking columns and backfill active model
1145 - if (version_compare($current_version, '3.2.3', '<')) {
1146 - mxchat_add_embedding_model_columns();
1683 + // 3.2.4: Backfill active embedding model option for the warning UI
1684 + // (replaces the per-row column tracking from 3.2.3, which was reverted)
1685 + if (version_compare($current_version, '3.2.4', '<')) {
1686 + mxchat_backfill_active_embedding_model();
1147 1687 }
1148 1688
1689 + // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1690 + // were shut off at the vendor on 2026-07-24). The function is idempotent —
1691 + // it only rewrites models on its deprecation lists.
1692 + if (version_compare($current_version, '3.2.15', '<')) {
1693 + mxchat_migrate_deprecated_models();
1694 + }
1695 +
1696 + // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1697 + // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1698 + // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1699 + if (version_compare($current_version, '3.2.16', '<')) {
1700 + mxchat_migrate_deprecated_models();
1701 + }
1702 +
1703 + // 3.2.17: Credential options must not autoload (af2400) — the two
1704 + // Pinecone-secret-holding rows were in alloptions, i.e. read into
1705 + // memory on every request including anonymous page views. Idempotent.
1706 + // Also carry the import modal's remembered ACF→PDF checkbox state
1707 + // into the new install-level option (11720c).
1708 + if (version_compare($current_version, '3.2.17', '<')) {
1709 + mxchat_fix_credential_option_autoload();
1710 + mxchat_migrate_acf_pdf_extraction_option();
1711 + }
1712 +
1713 + // 3.2.19: Claude Opus 4.1 retired Aug 5, 2026 — auto-move stranded
1714 + // sites (and the older tiers on the migration's lists) per the
1715 + // changelog's promise. Idempotent — only rewrites models on the
1716 + // deprecation lists. Without a gate at this release's version,
1717 + // nothing calls the migration for 3.2.18 upgraders (plan a5a598;
1718 + // the gate value must equal the version this block ships in).
1719 + if (version_compare($current_version, '3.2.19', '<')) {
1720 + mxchat_migrate_deprecated_models();
1721 + }
1722 +
1723 + // 3.2.20: Seed the caee10 usage-hint defaults onto tool entries a
1724 + // pre-3.2.20 autosave stamped with '' (plan 64c1ad). The gate value
1725 + // equals the version this block ships in (a5a598 rule); the
1726 + // function carries its own one-time marker on top.
1727 + // Also re-run the deprecated-models migration: 202df5 widened it to
1728 + // rescue a content_model stranded on ANY retired id (previously
1729 + // only the two gpt-5.x-chat-latest aliases). Idempotent — only
1730 + // rewrites models on the catalog's retired_model_map().
1731 + if (version_compare($current_version, '3.2.20', '<')) {
1732 + mxchat_backfill_tool_hint_defaults();
1733 + mxchat_migrate_deprecated_models();
1734 + }
1735 +
1149 1736 // Run full activation to ensure everything is up to date
1150 1737 mxchat_activate();
1151 1738
1152 1739 // Run migration functions
@@ -1151,12 +1738,11 @@
1151 1738
1152 1739 // Run migration functions
1153 1740 mxchat_migrate_live_agent_status();
1154 1741
1155 - // Add the cleanup function for version 2.1.8
1156 - if (version_compare($current_version, '2.1.8', '<')) {
1157 - $deleted = mxchat_cleanup_orphaned_chat_history();
1158 - }
1742 + // (The 2.1.8 orphaned-history reconciliation sweep is gone —
1743 + // 3.2.19's mxchat_history_backlog_* drain supersedes it, and it
1744 + // self-arms without a version gate: plan 839c4c.)
1159 1745
1160 1746 // Update version LAST
1161 1747 update_option('mxchat_plugin_version', $plugin_version);
1162 1748
@@ -1169,8 +1755,170 @@
1169 1755 }
1170 1756 }
1171 1757
1172 1758 /**
1759 + * Credential options must never enter the autoloaded alloptions set.
1760 + * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1761 + * Pinecone API secret; mxchat_options already stores its keys with autoload
1762 + * off and these two must match it. The filter covers every future
1763 + * add_option()/update_option() that creates the row — Settings API saves
1764 + * through options.php and WP-CLI included — on WP 6.6+; older cores are
1765 + * covered by the explicit autoload arguments at the plugin's own write
1766 + * sites plus the one-time migration below.
1767 + */
1768 +add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1769 +function mxchat_credential_option_autoload_value($autoload, $option) {
1770 + if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1771 + return false;
1772 + }
1773 + return $autoload;
1774 +}
1775 +
1776 +/**
1777 + * One-time upgrade migration: flip the autoload flag on credential option
1778 + * rows that existing installs are already carrying autoloaded. Includes
1779 + * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1780 + * when that add-on is not installed, since missing rows simply don't match.
1781 + */
1782 +function mxchat_fix_credential_option_autoload() {
1783 + $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1784 + if (function_exists('wp_set_option_autoload_values')) {
1785 + wp_set_option_autoload_values(array_fill_keys($keys, false));
1786 + return;
1787 + }
1788 + // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1789 + global $wpdb;
1790 + $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1791 + $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1792 + wp_cache_delete('alloptions', 'options');
1793 + foreach ($keys as $key) {
1794 + wp_cache_delete($key, 'options');
1795 + }
1796 +}
1797 +
1798 +/**
1799 + * One-time carry of the import modal's remembered ACF→PDF checkbox state
1800 + * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1801 + * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1802 + * Fresh installs and installs that never touched the checkbox default OFF,
1803 + * matching the setting's own "recommended only if…" guidance.
1804 + */
1805 +function mxchat_migrate_acf_pdf_extraction_option() {
1806 + if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1807 + return; // already set — never overwrite an owner's choice
1808 + }
1809 + $mxchat_options = get_option('mxchat_options', array());
1810 + if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1811 + update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1812 + unset($mxchat_options['acf_pdf_extract_default']);
1813 + update_option('mxchat_options', $mxchat_options);
1814 + }
1815 +}
1816 +
1817 +/**
1818 + * One-time migration of mxchat_acf_excluded_fields from field NAMES to field
1819 + * KEYS (plan 30e81f). Names are not unique across ACF groups, so two fields
1820 + * named the same in different groups shared one toggle, one saved state, and
1821 + * one exclusion — and the save-on-exit beacon could revert a save through the
1822 + * twin. Keys are unique; everything now runs on them.
1823 + *
1824 + * MIGRATION DIRECTION IS DELIBERATE: one stored name can match several keys —
1825 + * exclude EVERY one of them. The UI describes these as "sensitive or
1826 + * irrelevant fields"; an under-migration would silently start feeding a
1827 + * previously-excluded sensitive field into embeddings sent to a third-party
1828 + * provider. Over-excluding is visible in the UI and costs some retrieval
1829 + * quality; under-excluding is a silent privacy regression.
1830 + *
1831 + * Self-arming on acf/init (NOT the version-gated upgrade block): resolving
1832 + * names needs ACF fully booted with local JSON/PHP groups registered, and if
1833 + * ACF is deactivated at upgrade time the migration simply waits for the next
1834 + * load with ACF active. Until it runs, stored names keep working — every
1835 + * exclusion read site honors legacy name entries alongside keys. A name that
1836 + * matches no current key is KEPT (its group may be temporarily inactive), and
1837 + * the per-field include path lazily converts it if it ever resolves again.
1838 + */
1839 +function mxchat_migrate_acf_exclusions_to_keys() {
1840 + if (get_option('mxchat_acf_exclusions_migrated', '') === '1') {
1841 + return;
1842 + }
1843 + $stored = get_option('mxchat_acf_excluded_fields', array());
1844 + if (!is_array($stored) || empty($stored)) {
1845 + update_option('mxchat_acf_exclusions_migrated', '1', false);
1846 + return;
1847 + }
1848 + if (!function_exists('acf_get_field_groups') || !function_exists('acf_get_fields')) {
1849 + return; // acf/init fired without the API? Bail; retry next load.
1850 + }
1851 +
1852 + // Map every current top-level field: name => [keys], and the set of keys.
1853 + $name_to_keys = array();
1854 + $current_keys = array();
1855 + foreach (acf_get_field_groups() as $group) {
1856 + $group_fields = acf_get_fields($group['key']);
1857 + if (empty($group_fields)) {
1858 + continue;
1859 + }
1860 + foreach ($group_fields as $field) {
1861 + if (empty($field['key']) || !isset($field['name'])) {
1862 + continue;
1863 + }
1864 + $current_keys[$field['key']] = true;
1865 + $name_to_keys[$field['name']][] = $field['key'];
1866 + }
1867 + }
1868 +
1869 + $migrated = array();
1870 + $converted = 0;
1871 + foreach ($stored as $entry) {
1872 + if (!is_string($entry) || $entry === '') {
1873 + continue;
1874 + }
1875 + if (isset($current_keys[$entry])) {
1876 + $migrated[] = $entry; // already a live key
1877 + } elseif (isset($name_to_keys[$entry])) {
1878 + foreach ($name_to_keys[$entry] as $key) {
1879 + $migrated[] = $key; // every key wearing this name — fail toward more exclusion
1880 + }
1881 + $converted++;
1882 + } else {
1883 + $migrated[] = $entry; // unresolved — keep; still honored by name everywhere
1884 + }
1885 + }
1886 + $migrated = array_values(array_unique($migrated));
1887 +
1888 + update_option('mxchat_acf_excluded_fields', $migrated);
1889 + update_option('mxchat_acf_exclusions_migrated', '1', false);
1890 + if ($converted > 0) {
1891 + update_option('mxchat_acf_exclusions_migrated_notice', '1', false);
1892 + }
1893 +}
1894 +add_action('acf/init', 'mxchat_migrate_acf_exclusions_to_keys', 20);
1895 +
1896 +/**
1897 + * One-time notice after the ACF exclusion migration actually converted
1898 + * name entries — the settings are worth a review, especially where one name
1899 + * fanned out to several fields (every match is now excluded, on purpose).
1900 + */
1901 +function mxchat_show_acf_exclusions_migrated_notice() {
1902 + if (!current_user_can('manage_options')) {
1903 + return;
1904 + }
1905 + if (get_option('mxchat_acf_exclusions_migrated_notice', '') !== '1') {
1906 + return;
1907 + }
1908 + ?>
1909 + <div class="notice notice-info is-dismissible">
1910 + <p>
1911 + <strong><?php esc_html_e('MxChat: ACF field exclusions updated', 'mxchat'); ?></strong><br>
1912 + <?php esc_html_e('Your ACF field exclusion settings were migrated to identify fields precisely, so same-named fields in different groups no longer share one toggle. Where a saved exclusion matched several fields, all of them are now excluded — please review the toggles under MxChat → Knowledge → ACF Field Settings.', 'mxchat'); ?>
1913 + </p>
1914 + </div>
1915 + <?php
1916 + delete_option('mxchat_acf_exclusions_migrated_notice');
1917 +}
1918 +add_action('admin_notices', 'mxchat_show_acf_exclusions_migrated_notice');
1919 +
1920 +/**
1173 1921 * Ensure tables exist on every admin load for fresh installations
1174 1922 * This is a safety net for cases where activation hook doesn't fire
1175 1923 */
1176 1924 function mxchat_ensure_tables_exist() {
@@ -1190,12 +1938,16 @@
1190 1938
1191 1939 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1192 1940 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1193 1941
1942 + $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1943 +
1194 1944 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1195 1945 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1196 -
1197 - if (!$chat_exists || !$queue_exists) {
1946 + $sessions_exists = get_option('mxchat_session_store_ready') !== false
1947 + || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1948 +
1949 + if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1198 1950 //error_log("MxChat: Tables missing on admin load, running activation");
1199 1951 mxchat_activate();
1200 1952 }
1201 1953 }
@@ -1200,49 +1952,116 @@
1200 1952 }
1201 1953 }
1202 1954
1203 1955 /**
1204 - * Clean up orphaned chat history options from the wp_options table
1205 - * @return int Number of options deleted
1956 + * One-shot cleanup of legacy mxchat_history_<sid> option rows (plan 839c4c).
1957 + *
1958 + * 3.2.19 deduplicated per-session chat history into the transcripts table
1959 + * (which already held a superset of every option copy measured), so nothing
1960 + * writes these options any more — but an upgraded install still carries one
1961 + * per session, at up to 64 KB a row (462 rows measured on one production
1962 + * install). This drain replaces the old mxchat_cleanup_orphaned_chat_history()
1963 + * reconciliation sweep, which existed only because there were two copies to
1964 + * reconcile.
1965 + *
1966 + * b64b77 pattern throughout: an option_id bookmark that only moves forward
1967 + * (a crash mid-batch re-processes at most one batch), delete_option() per row
1968 + * so the object + notoptions caches stay coherent, batches drained off
1969 + * non-AJAX admin_init plus the session-store maintenance cron. Once the
1970 + * backlog is gone the state marks done and every later call is one cached
1971 + * option read.
1206 1972 */
1207 -function mxchat_cleanup_orphaned_chat_history() {
1973 +function mxchat_history_backlog_state() {
1974 + // The state option name MUST NOT start with 'mxchat_history_' — the drain
1975 + // deletes everything matching that prefix, and a state option inside the
1976 + // pattern gets eaten by its own drain (caught by the 839c4c rig: batches
1977 + // ran 2,2,2,1 instead of 2,2,1 because the bookmark row was being deleted
1978 + // and re-created every pass).
1979 + $state = get_option('mxchat_legacy_history_cleanup', array());
1980 + if (!is_array($state)) {
1981 + $state = array();
1982 + }
1983 +
1984 + return wp_parse_args($state, array(
1985 + 'done' => false,
1986 + 'last_option_id' => 0,
1987 + 'deleted' => 0,
1988 + ));
1989 +}
1990 +
1991 +/**
1992 + * Delete one batch of legacy history options.
1993 + *
1994 + * @param int $batch Rows per pass — capped small; these can be 64 KB rows.
1995 + * @return int Option rows deleted in this pass.
1996 + */
1997 +function mxchat_history_backlog_batch($batch = 200) {
1208 1998 global $wpdb;
1209 - $count = 0;
1210 1999
1211 - // Get all option keys that match our pattern
1212 - $history_options = $wpdb->get_results(
1213 - "SELECT option_name FROM {$wpdb->options}
1214 - WHERE option_name LIKE 'mxchat_history_%'"
2000 + $state = mxchat_history_backlog_state();
2001 + if (!empty($state['done'])) {
2002 + return 0;
2003 + }
2004 +
2005 + $batch = max(1, (int) $batch);
2006 +
2007 + $rows = $wpdb->get_results(
2008 + $wpdb->prepare(
2009 + "SELECT option_id, option_name FROM {$wpdb->options}
2010 + WHERE option_id > %d AND option_name LIKE %s
2011 + ORDER BY option_id ASC LIMIT %d",
2012 + (int) $state['last_option_id'],
2013 + $wpdb->esc_like('mxchat_history_') . '%',
2014 + $batch
2015 + ),
2016 + ARRAY_A
1215 2017 );
1216 2018
1217 - if (!empty($history_options)) {
1218 - foreach ($history_options as $option) {
1219 - // Extract the session ID from the option name
1220 - $session_id = str_replace('mxchat_history_', '', $option->option_name);
2019 + if (empty($rows)) {
2020 + $state['done'] = true;
2021 + update_option('mxchat_legacy_history_cleanup', $state, 'no');
2022 + return 0;
2023 + }
1221 2024
1222 - // Check if this session still exists in the custom table
1223 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1224 - $exists = $wpdb->get_var(
1225 - $wpdb->prepare(
1226 - "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1227 - $session_id
1228 - )
1229 - );
2025 + foreach ($rows as $row) {
2026 + $state['last_option_id'] = max((int) $state['last_option_id'], (int) $row['option_id']);
2027 + delete_option($row['option_name']);
2028 + $state['deleted'] = (int) $state['deleted'] + 1;
2029 + }
1230 2030
1231 - // If session doesn't exist in the main table, delete the option
1232 - if ($exists == 0) {
1233 - delete_option($option->option_name);
1234 - // Also delete related metadata
1235 - delete_option("mxchat_email_{$session_id}");
1236 - delete_option("mxchat_name_{$session_id}");
1237 - delete_option("mxchat_agent_name_{$session_id}");
1238 - $count++;
1239 - }
2031 + if (count($rows) < $batch) {
2032 + $state['done'] = true;
2033 + }
2034 +
2035 + update_option('mxchat_legacy_history_cleanup', $state, 'no');
2036 +
2037 + return count($rows);
2038 +}
2039 +
2040 +/** One batch per admin page load until drained. */
2041 +function mxchat_history_backlog_drain() {
2042 + mxchat_history_backlog_batch();
2043 +}
2044 +
2045 +/** Cron leg: drain faster, same cap per batch. */
2046 +function mxchat_history_backlog_drain_cron() {
2047 + for ($i = 0; $i < 10; $i++) {
2048 + if (mxchat_history_backlog_batch() === 0) {
2049 + break;
1240 2050 }
1241 2051 }
2052 +}
1242 2053
1243 - return $count;
2054 +// wp_doing_ajax() guard is load-bearing, not defensive (b64b77's shipped-and-
2055 +// caught defect): admin-ajax.php fires admin_init too, and the chat widget's
2056 +// message endpoint is an admin-ajax action — without the guard an anonymous
2057 +// visitor would pay for a delete batch inside their own chat request.
2058 +if (!wp_doing_ajax()) {
2059 + add_action('admin_init', 'mxchat_history_backlog_drain', 21);
1244 2060 }
2061 +// Belt for installs whose admin is rarely visited: ride the session store's
2062 +// existing daily maintenance event rather than scheduling another.
2063 +add_action('mxchat_session_store_maintenance', 'mxchat_history_backlog_drain_cron');
1245 2064
1246 2065 function mxchat_migrate_live_agent_status() {
1247 2066 $options = get_option('mxchat_options', []);
1248 2067
@@ -1345,8 +2164,9 @@
1345 2164 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1346 2165
1347 2166 // Add migration notice hook
1348 2167 add_action('admin_notices', 'mxchat_show_migration_notice');
2168 + add_action('admin_notices', 'mxchat_show_model_access_notice');
1349 2169
1350 2170 // Initialize classes with error handling
1351 2171 try {
1352 2172 // Initialize admin classes
@@ -1371,8 +2191,23 @@
1371 2191 if (class_exists('MxChat_Content_Generator')) {
1372 2192 new MxChat_Content_Generator();
1373 2193 }
1374 2194
2195 + // Initialize cache purge globally — settings writes can happen on any
2196 + // request type (admin screens, admin-ajax autosave, wp-cli), and the
2197 + // deferred-purge cron event fires on front-end requests.
2198 + if (class_exists('MxChat_Cache_Purge')) {
2199 + MxChat_Cache_Purge::init();
2200 + }
2201 +
2202 + // Initialize REST API globally — endpoints must be registered on
2203 + // every request (admin and frontend) so they're reachable via /wp-json/.
2204 + // Endpoints are auth-gated and locked until the site owner generates
2205 + // a token in MxChat → API Access.
2206 + if (class_exists('MxChat_Rest_Api')) {
2207 + new MxChat_Rest_Api();
2208 + }
2209 +
1375 2210 // Initialize public classes
1376 2211 if (class_exists('MxChat_Public')) {
1377 2212 $mxchat_public = new MxChat_Public();
1378 2213 }
@@ -1417,11 +2252,25 @@
1417 2252
1418 2253 mxchat_migrate_pinecone_roles_add_bot_id();
1419 2254 mxchat_migrate_add_content_type_column();
1420 2255 mxchat_migrate_add_translations_table();
2256 + mxchat_migrate_add_session_ratings_table();
1421 2257 }
1422 2258
1423 2259 /**
2260 + * Migration: Create per-session satisfaction ratings table (v3.2.6)
2261 + * For users upgrading from versions before 3.2.6
2262 + */
2263 +function mxchat_migrate_add_session_ratings_table() {
2264 + $migration_key = 'mxchat_session_ratings_table_created';
2265 + if (get_option($migration_key)) {
2266 + return;
2267 + }
2268 + mxchat_create_session_ratings_table();
2269 + update_option($migration_key, '3.2.6');
2270 +}
2271 +
2272 +/**
1424 2273 * Migration: Create transcript translations table (v3.0.4)
1425 2274 * For users upgrading from versions before 3.0.4
1426 2275 */
1427 2276 function mxchat_migrate_add_translations_table() {
@@ -1464,5 +2313,67 @@
1464 2313 return $schedules;
1465 2314 });
1466 2315
1467 2316 // Register deactivation hook
1468 -register_deactivation_hook(__FILE__, 'mxchat_deactivate');
2317 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');
2318 +
2319 +/**
2320 + * Per-session satisfaction rating: AJAX save handler (v3.2.6).
2321 + * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
2322 + * session_id makes this naturally idempotent — only the first rating per
2323 + * session is stored; duplicate POSTs are silent no-ops.
2324 + */
2325 +function mxchat_save_session_rating() {
2326 + global $wpdb;
2327 +
2328 + $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2329 + $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
2330 + $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
2331 + $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
2332 +
2333 + if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
2334 + wp_send_json_error(array('message' => 'invalid_input'), 400);
2335 + }
2336 +
2337 + if (strlen($feedback) > 1000) {
2338 + $feedback = substr($feedback, 0, 1000);
2339 + }
2340 +
2341 + $table_name = $wpdb->prefix . 'mxchat_session_ratings';
2342 + $existing = $wpdb->get_var($wpdb->prepare(
2343 + "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
2344 + $session_id
2345 + ));
2346 +
2347 + if ($existing) {
2348 + if ($feedback !== '') {
2349 + $wpdb->update(
2350 + $table_name,
2351 + array('rating_feedback' => $feedback),
2352 + array('id' => (int) $existing),
2353 + array('%s'),
2354 + array('%d')
2355 + );
2356 + }
2357 + wp_send_json_success(array('updated' => true));
2358 + }
2359 +
2360 + $inserted = $wpdb->insert(
2361 + $table_name,
2362 + array(
2363 + 'session_id' => $session_id,
2364 + 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
2365 + 'rating_value' => $rating_raw,
2366 + 'rating_feedback' => $feedback !== '' ? $feedback : null,
2367 + 'created_at' => current_time('mysql'),
2368 + ),
2369 + array('%s', '%s', '%d', '%s', '%s')
2370 + );
2371 +
2372 + if ($inserted === false) {
2373 + wp_send_json_error(array('message' => 'db_insert_failed'), 500);
2374 + }
2375 +
2376 + wp_send_json_success(array('saved' => true));
2377 +}
2378 +add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
2379 +add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');