PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.25
MxChat – AI Chatbot & Content Generation for WordPress v3.2.25
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 +809 -103 3.2.9 → 3.2.25 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.9
6 + * Version: 3.2.25
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
@@ -89,8 +185,41 @@
89 185 update_option('mxchat_grok_2_remap_done', 1);
90 186 });
91 187
92 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 +/**
93 222 * Exclude MxChat assets from caching plugin optimizations
94 223 *
95 224 * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
96 225 * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
@@ -349,22 +478,34 @@
349 478
350 479 // Include classes with error handling
351 480 function mxchat_include_classes() {
352 481 $class_files = array(
482 + 'includes/class-mxchat-model-catalog.php',
483 + 'includes/class-mxchat-model-liveness.php',
484 + 'includes/class-mxchat-license-check.php',
485 + 'includes/class-mxchat-session-store.php',
486 + 'includes/class-mxchat-live-agent-schedule.php',
487 + 'includes/class-mxchat-tool-registry.php',
353 488 'includes/class-mxchat-integrator.php',
354 489 'includes/class-mxchat-admin.php',
355 490 'includes/class-mxchat-public.php',
491 + 'includes/class-mxchat-block.php',
492 + 'includes/class-mxchat-elementor.php',
356 493 'includes/class-mxchat-utils.php',
357 494 'includes/class-mxchat-user.php',
495 + 'includes/class-mxchat-privacy.php',
358 496 'includes/class-mxchat-meta-box.php',
359 497 'includes/class-mxchat-chunker.php',
360 498 'includes/class-mxchat-word-handler.php',
361 499 'includes/class-mxchat-content-generator.php',
362 500 'includes/class-mxchat-cache-purge.php',
501 + 'includes/class-mxchat-editor-assistant.php',
363 502 'includes/class-rest-api.php',
364 503 'admin/class-ajax-handler.php',
365 504 'admin/class-pinecone-manager.php',
366 - 'admin/class-knowledge-manager.php'
505 + 'admin/class-pinecone-documents.php',
506 + 'admin/class-knowledge-manager.php',
507 + 'admin/class-vectorstore-manager.php'
367 508 );
368 509
369 510 foreach ($class_files as $file) {
370 511 $file_path = plugin_dir_path(__FILE__) . $file;
@@ -374,8 +515,66 @@
374 515 //error_log('MxChat: Missing class file - ' . $file);
375 516 }
376 517 }
377 518
519 + // Register the native function-calling admin-post save handler (a41dee).
520 + if (class_exists('MxChat_Tool_Registry')) {
521 + MxChat_Tool_Registry::init();
522 + }
523 +
524 + // GDPR: register with WP's personal-data export/erase tools (b81e42).
525 + if (class_exists('MxChat_Privacy')) {
526 + MxChat_Privacy::init();
527 + }
528 +
529 + // Per-session state store: retention cron + the cron-independent
530 + // migration drain off admin_init (b64b77).
531 + if (class_exists('MxChat_Session_Store')) {
532 + MxChat_Session_Store::init();
533 + }
534 +
535 + // Daily model-liveness check + its warning notice (b65e8d). Read-only and
536 + // fail-open: one listing request per in-use provider per day, none at all
537 + // when no key is stored.
538 + if (class_exists('MxChat_Model_Liveness')) {
539 + MxChat_Model_Liveness::init();
540 + }
541 +
542 + // Licence domain check (c93ede): once a day asks mxchat.ai whether this
543 + // site's domain is still switched on for its key, honours an explicit
544 + // "off" after a three-day grace period, and fails open on everything else.
545 + if (class_exists('MxChat_License_Check')) {
546 + MxChat_License_Check::init();
547 + }
548 +
549 + // Gutenberg chatbot block (plan-95dd1e): a click-to-place wrapper over the
550 + // [mxchat_chatbot] shortcode. Registers on init; no-op below WP 5.0.
551 + if (class_exists('MxChat_Block')) {
552 + MxChat_Block::init();
553 + }
554 +
555 + // Elementor chatbot widget (plan-95dd1e part 2): registered ONLY inside
556 + // elementor/widgets/register (Elementor >= 3.5) — with Elementor absent or
557 + // older, the hook never fires and nothing further loads.
558 + if (class_exists('MxChat_Elementor')) {
559 + MxChat_Elementor::init();
560 + }
561 +
562 + // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
563 + // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
564 + // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
565 + if (class_exists('MxChat_Editor_Assistant')) {
566 + MxChat_Editor_Assistant::init();
567 + }
568 +
569 + // OpenAI Vector Store write path (plan-15b5c6): import/sync AJAX, the
570 + // import cron tick, the pending-delete sweeper, and the WP-CLI command
571 + // all register in the constructor. The sync itself only runs when the
572 + // sync toggle + store ID + OpenAI key are all present.
573 + if (class_exists('MxChat_Vectorstore_Manager')) {
574 + MxChat_Vectorstore_Manager::get_instance();
575 + }
576 +
378 577 // Admin pages that aren't classes (procedural include).
379 578 if (is_admin()) {
380 579 $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
381 580 if (file_exists($admin_api_page)) {
@@ -437,8 +636,26 @@
437 636 dbDelta($sql);
438 637 }
439 638
440 639 /**
640 + * Create the per-session state table (b64b77).
641 + *
642 + * Callable from the activation hook, which can run before plugins_loaded has
643 + * included the class files — so it loads the class itself when needed.
644 + */
645 +function mxchat_create_sessions_table() {
646 + if (!class_exists('MxChat_Session_Store')) {
647 + $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
648 + if (!file_exists($path)) {
649 + return false;
650 + }
651 + require_once $path;
652 + }
653 +
654 + return MxChat_Session_Store::create_table();
655 +}
656 +
657 +/**
441 658 * FIXED: Robust table creation and column management
442 659 */
443 660 function mxchat_create_chat_transcripts_table() {
444 661 global $wpdb;
@@ -749,8 +966,66 @@
749 966 }
750 967 }
751 968
752 969 /**
970 + * 3.2.20: One-time backfill of the caee10 catalog usage-hint defaults
971 + * (plan 64c1ad). persist() writes usage_hint for EVERY shown tool on every
972 + * autosave — as '' when the box is untouched — and resolve_tool_setting()
973 + * seeds a catalog default_hint ONLY onto an ABSENT key. So any install that
974 + * saved the AI Tools screen before 3.2.20 holds '' everywhere and the shipped
975 + * defaults can never reach it. On an upgrade from < 3.2.20 an empty stored
976 + * hint cannot be a deliberate clear of a rendered default (those builds never
977 + * rendered one), so seeding is safe. From 3.2.20 on, empty means the owner
978 + * cleared a visible default and is respected — this never runs again (version
979 + * gate + its own marker, deliberately not caee10's flag).
980 + *
981 + * Never touched: entries with owner text, legacy bare-bool entries and
982 + * absent-key entries (both already resolve to the default at read time), and
983 + * tools whose catalog entry ships no default_hint.
984 + */
985 +function mxchat_backfill_tool_hint_defaults() {
986 + if (get_option('mxchat_tool_hint_backfill_64c1ad') === '1') {
987 + return;
988 + }
989 +
990 + if (class_exists('MxChat_Tool_Registry')) {
991 + $map = get_option('mxchat_function_calling_tools', array());
992 + if (is_array($map) && !empty($map)) {
993 + $defaults = array();
994 + foreach (MxChat_Tool_Registry::core_tool_catalog() as $fn => $meta) {
995 + if (!empty($meta['default_hint'])) {
996 + $defaults[$fn] = (string) $meta['default_hint'];
997 + }
998 + }
999 +
1000 + $changed = false;
1001 + foreach ($map as $fn => $entry) {
1002 + if (!isset($defaults[$fn])) {
1003 + continue; // no catalog default — nothing to seed
1004 + }
1005 + if (!is_array($entry)) {
1006 + continue; // legacy bare bool: key absent, resolves to the default already
1007 + }
1008 + if (!array_key_exists('usage_hint', $entry)) {
1009 + continue; // absent key gets the default at read time — must stay absent
1010 + }
1011 + if (trim((string) $entry['usage_hint']) !== '') {
1012 + continue; // owner text — never touch
1013 + }
1014 + $map[$fn]['usage_hint'] = $defaults[$fn];
1015 + $changed = true;
1016 + }
1017 +
1018 + if ($changed) {
1019 + update_option('mxchat_function_calling_tools', $map);
1020 + }
1021 + }
1022 + }
1023 +
1024 + update_option('mxchat_tool_hint_backfill_64c1ad', '1', false);
1025 +}
1026 +
1027 +/**
753 1028 * 2.5.2: Create queue processing tables for reliable background processing
754 1029 */
755 1030 function mxchat_create_queue_tables() {
756 1031 global $wpdb;
@@ -848,8 +1123,41 @@
848 1123 dbDelta($sql);
849 1124 }
850 1125
851 1126 /**
1127 + * Create the OpenAI Vector Store file-mapping table (v3.2.20, plan 15b5c6).
1128 + * One row per mirrored KB entry: which store, which bot, which OpenAI file id,
1129 + * and a hash of the uploaded body for change detection. Vector store files are
1130 + * not patchable in place — without this mapping an update cannot find its
1131 + * predecessor, and the store silently accumulates stale duplicates.
1132 + * status: 'live' (serving) or 'pending_delete' (condemned, swept later).
1133 + */
1134 +function mxchat_create_vectorstore_files_table() {
1135 + global $wpdb;
1136 + $charset_collate = $wpdb->get_charset_collate();
1137 +
1138 + $table_name = $wpdb->prefix . 'mxchat_vectorstore_files';
1139 + $sql = "CREATE TABLE $table_name (
1140 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
1141 + store_id varchar(64) NOT NULL,
1142 + bot_id varchar(64) NOT NULL DEFAULT 'default',
1143 + entry_key char(32) NOT NULL,
1144 + source_url text,
1145 + file_id varchar(64) NOT NULL,
1146 + content_hash char(32) NOT NULL DEFAULT '',
1147 + status varchar(20) NOT NULL DEFAULT 'live',
1148 + last_error text,
1149 + updated_at datetime DEFAULT NULL,
1150 + PRIMARY KEY (id),
1151 + KEY store_entry (store_id, bot_id, entry_key, status),
1152 + KEY status (status)
1153 + ) $charset_collate;";
1154 +
1155 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
1156 + dbDelta($sql);
1157 +}
1158 +
1159 +/**
852 1160 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
853 1161 * This fixes "url, source_url. The supplied values may be too long" errors
854 1162 */
855 1163 function mxchat_fix_url_column_size() {
@@ -893,53 +1201,45 @@
893 1201 if (!isset($options['model'])) {
894 1202 return;
895 1203 }
896 1204
897 - $current_model = $options['model'];
898 -
899 - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
900 - $deprecated_claude_models = array(
901 - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
902 - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
903 - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
904 - 'claude-3-opus-20240229', // Retired Jan 5, 2026
905 - 'claude-3-sonnet-20240229', // Legacy
906 - 'claude-3-haiku-20240307', // Legacy
907 - );
908 - if (in_array($current_model, $deprecated_claude_models, true)) {
909 - $options['model'] = 'claude-opus-4-6';
910 - $migrated = true;
911 - $migration_message = sprintf(
912 - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.',
913 - $current_model
914 - );
1205 + // The retired-id → replacement mapping lives in ONE place:
1206 + // MxChat_Model_Catalog::retired_model_map() (plan 202df5). This function
1207 + // and every add-on that stores model ids consume that map — do not add a
1208 + // deprecation list here again.
1209 + if (!class_exists('MxChat_Model_Catalog') || !method_exists('MxChat_Model_Catalog', 'retired_model_map')) {
1210 + return; // catalog not loaded (defensive) — the next admin load retries
915 1211 }
1212 + $map = MxChat_Model_Catalog::retired_model_map();
916 1213
917 - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
918 - if ($current_model === 'claude-3-5-haiku-20241022') {
919 - $options['model'] = 'claude-haiku-4-5-20251001';
1214 + $current_model = $options['model'];
1215 + if (isset($map[$current_model])) {
1216 + $entry = $map[$current_model];
1217 + $options['model'] = $entry['to'];
920 1218 $migrated = true;
921 - $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.';
922 - }
923 -
924 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
925 - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
926 - $options['model'] = 'gpt-5.1-chat-latest';
927 - $migrated = true;
928 1219 $migration_message = sprintf(
929 - 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.',
930 - $current_model
1220 + 'Your chatbot model has been automatically updated from %s to %s %s.',
1221 + $current_model,
1222 + $entry['label'],
1223 + $entry['reason']
931 1224 );
932 1225 }
933 1226
934 - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
935 - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
936 - $options['model'] = 'gpt-5-mini';
1227 + // The content generator has its own model option — the same map applies.
1228 + // (Pre-202df5 this branch covered only the two gpt-5.x-chat-latest aliases;
1229 + // it now covers every retired id, so e.g. a content model stranded on a
1230 + // retired Claude id is rescued the same way the chat model is.)
1231 + if (isset($options['content_model']) && isset($map[$options['content_model']])) {
1232 + $old_content_model = $options['content_model'];
1233 + $entry = $map[$old_content_model];
1234 + $options['content_model'] = $entry['to'];
937 1235 $migrated = true;
938 - $migration_message = sprintf(
939 - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
940 - $current_model
941 - );
1236 + $migration_message = trim($migration_message . ' ' . sprintf(
1237 + 'Your content generation model has also been automatically updated from %s to %s %s.',
1238 + $old_content_model,
1239 + $entry['label'],
1240 + $entry['reason']
1241 + ));
942 1242 }
943 1243
944 1244 if ($migrated) {
945 1245 update_option('mxchat_options', $options);
@@ -966,8 +1266,100 @@
966 1266 delete_option('mxchat_model_migration_message');
967 1267 }
968 1268 }
969 1269
1270 +/**
1271 + * One-time recommendation on EXISTING installs (stamp 'legacy') that the new
1272 + * "Strip unapproved links" guard exists and is worth turning on (plan 58f8b4).
1273 + * Fresh 3.2.20+ installs default it on and never see this. Shown only on
1274 + * MxChat admin pages, gone for good once dismissed or once the site saves an
1275 + * explicit value for the toggle either way.
1276 + */
1277 +function mxchat_show_strip_links_notice() {
1278 + if (!current_user_can('manage_options')) {
1279 + return;
1280 + }
1281 + $page = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
1282 + if (strpos($page, 'mxchat') !== 0) {
1283 + return;
1284 + }
1285 + if (get_option('mxchat_strip_links_notice_dismissed', '') === '1') {
1286 + return;
1287 + }
1288 + if (get_option('mxchat_installed_at_version', '') !== 'legacy') {
1289 + return;
1290 + }
1291 + $opts = get_option('mxchat_options', array());
1292 + if (is_array($opts) && isset($opts['strip_unapproved_links_toggle'])) {
1293 + return; // The site already made its choice — stop recommending.
1294 + }
1295 + $dismiss_url = wp_nonce_url(
1296 + admin_url('admin-post.php?action=mxchat_dismiss_strip_links_notice'),
1297 + 'mxchat_dismiss_strip_links_notice'
1298 + );
1299 + ?>
1300 + <div class="notice notice-info">
1301 + <p>
1302 + <strong><?php esc_html_e('MxChat: new link protection available', 'mxchat'); ?></strong><br>
1303 + <?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'); ?>
1304 + <a href="<?php echo esc_url($dismiss_url); ?>"><?php esc_html_e('Dismiss', 'mxchat'); ?></a>
1305 + </p>
1306 + </div>
1307 + <?php
1308 +}
1309 +add_action('admin_notices', 'mxchat_show_strip_links_notice');
1310 +
1311 +/** Dismiss handler for the strip-links recommendation notice (plan 58f8b4). */
1312 +function mxchat_dismiss_strip_links_notice() {
1313 + if (!current_user_can('manage_options')) {
1314 + wp_die(esc_html__('Insufficient permissions.', 'mxchat'), '', array('response' => 403));
1315 + }
1316 + check_admin_referer('mxchat_dismiss_strip_links_notice');
1317 + update_option('mxchat_strip_links_notice_dismissed', '1', false);
1318 + $referer = wp_get_referer();
1319 + wp_safe_redirect($referer ? $referer : admin_url('admin.php?page=mxchat-max'));
1320 + exit;
1321 +}
1322 +add_action('admin_post_mxchat_dismiss_strip_links_notice', 'mxchat_dismiss_strip_links_notice');
1323 +
1324 +/**
1325 + * Persistent admin notice when the provider rejected the configured model
1326 + * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1327 + * integrator whenever a chat request fails on a model-access error — including
1328 + * requests from anonymous visitors, which is the case that otherwise stays
1329 + * invisible to the site owner for weeks (plan e46b8f).
1330 + *
1331 + * Deleted after render so it re-arms on the next failed chat: the notice keeps
1332 + * reappearing until the model is fixed, then stops on its own.
1333 + */
1334 +function mxchat_show_model_access_notice() {
1335 + if (!current_user_can('manage_options')) {
1336 + return;
1337 + }
1338 + $notice = get_option('mxchat_model_access_notice');
1339 + if (!is_array($notice) || empty($notice['model'])) {
1340 + return;
1341 + }
1342 + $settings_url = admin_url('admin.php?page=mxchat-max');
1343 + ?>
1344 + <div class="notice notice-error is-dismissible">
1345 + <p>
1346 + <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1347 + <?php
1348 + printf(
1349 + /* translators: 1: model id, 2: provider name */
1350 + 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'),
1351 + esc_html($notice['model']),
1352 + esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1353 + );
1354 + ?>
1355 + <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1356 + </p>
1357 + </div>
1358 + <?php
1359 + delete_option('mxchat_model_access_notice');
1360 +}
1361 +
970 1362 function mxchat_activate() {
971 1363 global $wpdb;
972 1364 $charset_collate = $wpdb->get_charset_collate();
973 1365
@@ -975,8 +1367,12 @@
975 1367
976 1368 // Create chat transcripts table with improved function
977 1369 mxchat_create_chat_transcripts_table();
978 1370
1371 + // Per-session state table (b64b77). Activation can run before
1372 + // plugins_loaded has included the class files, so require it directly.
1373 + mxchat_create_sessions_table();
1374 +
979 1375 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
980 1376 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
981 1377 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
982 1378 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -983,8 +1379,9 @@
983 1379 url TEXT NOT NULL,
984 1380 article_content LONGTEXT NOT NULL,
985 1381 embedding_vector LONGTEXT,
986 1382 source_url TEXT DEFAULT NULL,
1383 + title VARCHAR(255) DEFAULT NULL,
987 1384 role_restriction VARCHAR(50) DEFAULT 'public',
988 1385 content_type VARCHAR(50) DEFAULT 'content',
989 1386 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
990 1387 PRIMARY KEY (id),
@@ -1038,8 +1435,11 @@
1038 1435
1039 1436 // Create per-session satisfaction ratings table (v3.2.6)
1040 1437 mxchat_create_session_ratings_table();
1041 1438
1439 + // Create Vector Store file-mapping table (v3.2.20, plan 15b5c6)
1440 + mxchat_create_vectorstore_files_table();
1441 +
1042 1442 // Ensure additional columns in system prompt table
1043 1443 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1044 1444 if (!empty($existing_system_columns)) {
1045 1445 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1052,8 +1452,13 @@
1052 1452 }
1053 1453 if (!in_array('role_restriction', $existing_system_column_names)) {
1054 1454 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
1055 1455 }
1456 + // Page title captured at import time (3.2.23, plan d9ee66) - read by
1457 + // add-ons that name a source, e.g. AI Search's source cards.
1458 + if (!in_array('title', $existing_system_column_names)) {
1459 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN title VARCHAR(255) DEFAULT NULL AFTER source_url");
1460 + }
1056 1461 }
1057 1462
1058 1463 // Set default thresholds for existing intents
1059 1464 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
@@ -1088,10 +1493,11 @@
1088 1493
1089 1494 // Setup cron jobs
1090 1495 mxchat_setup_cron_jobs();
1091 1496
1092 - // Update version
1093 - update_option('mxchat_plugin_version', MXCHAT_VERSION);
1497 + // Update version (stable base version — never the dev time()-suffixed one,
1498 + // or the check_for_update comparison would churn every request)
1499 + update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
1094 1500
1095 1501 //error_log("MxChat: Activation function completed");
1096 1502 }
1097 1503
@@ -1106,23 +1512,29 @@
1106 1512 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1107 1513 // Set flag to use fallback system
1108 1514 update_option('mxchat_use_fallback_rate_limits', true);
1109 1515 update_option('mxchat_next_rate_limit_check', time() + 3600);
1110 - return;
1111 - }
1112 -
1113 - // Schedule the rate limit reset cron job
1114 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1115 -
1116 - if ($result === false) {
1117 - // Fallback if scheduling fails
1118 - update_option('mxchat_use_fallback_rate_limits', true);
1119 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1516 + // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1517 + // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1518 + // execute (a server-side runner hitting wp-cron.php instead of loopback
1519 + // spawns) — scheduling still just writes the cron option. The old early
1520 + // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1521 + // site permanently lost the transcript cleanup event while the retention
1522 + // setting still claimed to be active.
1120 1523 } else {
1121 - // Clear fallback flags if cron scheduling succeeded
1122 - delete_option('mxchat_use_fallback_rate_limits');
1524 + // Schedule the rate limit reset cron job
1525 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1526 +
1527 + if ($result === false) {
1528 + // Fallback if scheduling fails
1529 + update_option('mxchat_use_fallback_rate_limits', true);
1530 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1531 + } else {
1532 + // Clear fallback flags if cron scheduling succeeded
1533 + delete_option('mxchat_use_fallback_rate_limits');
1534 + }
1123 1535 }
1124 -
1536 +
1125 1537 // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
1126 1538 $transcript_options = get_option('mxchat_transcripts_options', array());
1127 1539 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1128 1540 $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
@@ -1144,9 +1556,11 @@
1144 1556 // Clear scheduled cron jobs
1145 1557 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1146 1558 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1147 1559 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1148 -
1560 + wp_clear_scheduled_hook('mxchat_model_liveness_check');
1561 + wp_clear_scheduled_hook('mxchat_license_check');
1562 +
1149 1563 // Clear fallback options
1150 1564 delete_option('mxchat_use_fallback_rate_limits');
1151 1565 delete_option('mxchat_next_rate_limit_check');
1152 1566 delete_option('mxchat_fallback_check_interval');
@@ -1165,17 +1579,25 @@
1165 1579 return;
1166 1580 }
1167 1581
1168 1582 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1169 -
1583 +
1170 1584 if (time() >= $next_check) {
1171 - // Only run reset if the MxChat_Integrator class exists
1172 - if (class_exists('MxChat_Integrator')) {
1173 - $integrator = new MxChat_Integrator();
1174 - if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
1175 - $integrator->mxchat_reset_rate_limits();
1176 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1177 - }
1585 + // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1586 + // plugins_loaded (before this init-priority-5 callback), so it's always set
1587 + // here. Constructing a second MxChat_Integrator just to call one method
1588 + // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1589 + // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1590 + // the request. Defensive construction only if the global is somehow unset.
1591 + // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1592 + // implementation of this same check — if either changes, change both.
1593 + global $mxchat_integrator;
1594 + $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1595 + ? $mxchat_integrator
1596 + : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1597 + if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1598 + $integrator->mxchat_reset_rate_limits();
1599 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1178 1600 }
1179 1601 }
1180 1602 }
1181 1603
@@ -1187,9 +1609,9 @@
1187 1609 global $wpdb;
1188 1610
1189 1611 try {
1190 1612 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1191 - $plugin_version = MXCHAT_VERSION;
1613 + $plugin_version = MXCHAT_BASE_VERSION;
1192 1614
1193 1615 // Always ensure critical tables exist (even if version matches)
1194 1616 // This handles manual table deletion or fresh installs
1195 1617 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1194,12 +1616,16 @@
1194 1616 // This handles manual table deletion or fresh installs
1195 1617 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1196 1618 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1197 1619
1620 + $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1621 +
1198 1622 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1199 1623 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1200 -
1201 - if (!$chat_exists || !$queue_exists) {
1624 + $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1625 + || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1626 +
1627 + if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1202 1628 //error_log("MxChat: Critical tables missing, running activation");
1203 1629 mxchat_activate();
1204 1630 }
1205 1631
@@ -1268,8 +1694,55 @@
1268 1694 if (version_compare($current_version, '3.2.4', '<')) {
1269 1695 mxchat_backfill_active_embedding_model();
1270 1696 }
1271 1697
1698 + // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1699 + // were shut off at the vendor on 2026-07-24). The function is idempotent —
1700 + // it only rewrites models on its deprecation lists.
1701 + if (version_compare($current_version, '3.2.15', '<')) {
1702 + mxchat_migrate_deprecated_models();
1703 + }
1704 +
1705 + // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1706 + // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1707 + // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1708 + if (version_compare($current_version, '3.2.16', '<')) {
1709 + mxchat_migrate_deprecated_models();
1710 + }
1711 +
1712 + // 3.2.17: Credential options must not autoload (af2400) — the two
1713 + // Pinecone-secret-holding rows were in alloptions, i.e. read into
1714 + // memory on every request including anonymous page views. Idempotent.
1715 + // Also carry the import modal's remembered ACF→PDF checkbox state
1716 + // into the new install-level option (11720c).
1717 + if (version_compare($current_version, '3.2.17', '<')) {
1718 + mxchat_fix_credential_option_autoload();
1719 + mxchat_migrate_acf_pdf_extraction_option();
1720 + }
1721 +
1722 + // 3.2.19: Claude Opus 4.1 retired Aug 5, 2026 — auto-move stranded
1723 + // sites (and the older tiers on the migration's lists) per the
1724 + // changelog's promise. Idempotent — only rewrites models on the
1725 + // deprecation lists. Without a gate at this release's version,
1726 + // nothing calls the migration for 3.2.18 upgraders (plan a5a598;
1727 + // the gate value must equal the version this block ships in).
1728 + if (version_compare($current_version, '3.2.19', '<')) {
1729 + mxchat_migrate_deprecated_models();
1730 + }
1731 +
1732 + // 3.2.20: Seed the caee10 usage-hint defaults onto tool entries a
1733 + // pre-3.2.20 autosave stamped with '' (plan 64c1ad). The gate value
1734 + // equals the version this block ships in (a5a598 rule); the
1735 + // function carries its own one-time marker on top.
1736 + // Also re-run the deprecated-models migration: 202df5 widened it to
1737 + // rescue a content_model stranded on ANY retired id (previously
1738 + // only the two gpt-5.x-chat-latest aliases). Idempotent — only
1739 + // rewrites models on the catalog's retired_model_map().
1740 + if (version_compare($current_version, '3.2.20', '<')) {
1741 + mxchat_backfill_tool_hint_defaults();
1742 + mxchat_migrate_deprecated_models();
1743 + }
1744 +
1272 1745 // Run full activation to ensure everything is up to date
1273 1746 mxchat_activate();
1274 1747
1275 1748 // Run migration functions
@@ -1274,12 +1747,11 @@
1274 1747
1275 1748 // Run migration functions
1276 1749 mxchat_migrate_live_agent_status();
1277 1750
1278 - // Add the cleanup function for version 2.1.8
1279 - if (version_compare($current_version, '2.1.8', '<')) {
1280 - $deleted = mxchat_cleanup_orphaned_chat_history();
1281 - }
1751 + // (The 2.1.8 orphaned-history reconciliation sweep is gone —
1752 + // 3.2.19's mxchat_history_backlog_* drain supersedes it, and it
1753 + // self-arms without a version gate: plan 839c4c.)
1282 1754
1283 1755 // Update version LAST
1284 1756 update_option('mxchat_plugin_version', $plugin_version);
1285 1757
@@ -1292,8 +1764,170 @@
1292 1764 }
1293 1765 }
1294 1766
1295 1767 /**
1768 + * Credential options must never enter the autoloaded alloptions set.
1769 + * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1770 + * Pinecone API secret; mxchat_options already stores its keys with autoload
1771 + * off and these two must match it. The filter covers every future
1772 + * add_option()/update_option() that creates the row — Settings API saves
1773 + * through options.php and WP-CLI included — on WP 6.6+; older cores are
1774 + * covered by the explicit autoload arguments at the plugin's own write
1775 + * sites plus the one-time migration below.
1776 + */
1777 +add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1778 +function mxchat_credential_option_autoload_value($autoload, $option) {
1779 + if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1780 + return false;
1781 + }
1782 + return $autoload;
1783 +}
1784 +
1785 +/**
1786 + * One-time upgrade migration: flip the autoload flag on credential option
1787 + * rows that existing installs are already carrying autoloaded. Includes
1788 + * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1789 + * when that add-on is not installed, since missing rows simply don't match.
1790 + */
1791 +function mxchat_fix_credential_option_autoload() {
1792 + $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1793 + if (function_exists('wp_set_option_autoload_values')) {
1794 + wp_set_option_autoload_values(array_fill_keys($keys, false));
1795 + return;
1796 + }
1797 + // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1798 + global $wpdb;
1799 + $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1800 + $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1801 + wp_cache_delete('alloptions', 'options');
1802 + foreach ($keys as $key) {
1803 + wp_cache_delete($key, 'options');
1804 + }
1805 +}
1806 +
1807 +/**
1808 + * One-time carry of the import modal's remembered ACF→PDF checkbox state
1809 + * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1810 + * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1811 + * Fresh installs and installs that never touched the checkbox default OFF,
1812 + * matching the setting's own "recommended only if…" guidance.
1813 + */
1814 +function mxchat_migrate_acf_pdf_extraction_option() {
1815 + if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1816 + return; // already set — never overwrite an owner's choice
1817 + }
1818 + $mxchat_options = get_option('mxchat_options', array());
1819 + if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1820 + update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1821 + unset($mxchat_options['acf_pdf_extract_default']);
1822 + update_option('mxchat_options', $mxchat_options);
1823 + }
1824 +}
1825 +
1826 +/**
1827 + * One-time migration of mxchat_acf_excluded_fields from field NAMES to field
1828 + * KEYS (plan 30e81f). Names are not unique across ACF groups, so two fields
1829 + * named the same in different groups shared one toggle, one saved state, and
1830 + * one exclusion — and the save-on-exit beacon could revert a save through the
1831 + * twin. Keys are unique; everything now runs on them.
1832 + *
1833 + * MIGRATION DIRECTION IS DELIBERATE: one stored name can match several keys —
1834 + * exclude EVERY one of them. The UI describes these as "sensitive or
1835 + * irrelevant fields"; an under-migration would silently start feeding a
1836 + * previously-excluded sensitive field into embeddings sent to a third-party
1837 + * provider. Over-excluding is visible in the UI and costs some retrieval
1838 + * quality; under-excluding is a silent privacy regression.
1839 + *
1840 + * Self-arming on acf/init (NOT the version-gated upgrade block): resolving
1841 + * names needs ACF fully booted with local JSON/PHP groups registered, and if
1842 + * ACF is deactivated at upgrade time the migration simply waits for the next
1843 + * load with ACF active. Until it runs, stored names keep working — every
1844 + * exclusion read site honors legacy name entries alongside keys. A name that
1845 + * matches no current key is KEPT (its group may be temporarily inactive), and
1846 + * the per-field include path lazily converts it if it ever resolves again.
1847 + */
1848 +function mxchat_migrate_acf_exclusions_to_keys() {
1849 + if (get_option('mxchat_acf_exclusions_migrated', '') === '1') {
1850 + return;
1851 + }
1852 + $stored = get_option('mxchat_acf_excluded_fields', array());
1853 + if (!is_array($stored) || empty($stored)) {
1854 + update_option('mxchat_acf_exclusions_migrated', '1', false);
1855 + return;
1856 + }
1857 + if (!function_exists('acf_get_field_groups') || !function_exists('acf_get_fields')) {
1858 + return; // acf/init fired without the API? Bail; retry next load.
1859 + }
1860 +
1861 + // Map every current top-level field: name => [keys], and the set of keys.
1862 + $name_to_keys = array();
1863 + $current_keys = array();
1864 + foreach (acf_get_field_groups() as $group) {
1865 + $group_fields = acf_get_fields($group['key']);
1866 + if (empty($group_fields)) {
1867 + continue;
1868 + }
1869 + foreach ($group_fields as $field) {
1870 + if (empty($field['key']) || !isset($field['name'])) {
1871 + continue;
1872 + }
1873 + $current_keys[$field['key']] = true;
1874 + $name_to_keys[$field['name']][] = $field['key'];
1875 + }
1876 + }
1877 +
1878 + $migrated = array();
1879 + $converted = 0;
1880 + foreach ($stored as $entry) {
1881 + if (!is_string($entry) || $entry === '') {
1882 + continue;
1883 + }
1884 + if (isset($current_keys[$entry])) {
1885 + $migrated[] = $entry; // already a live key
1886 + } elseif (isset($name_to_keys[$entry])) {
1887 + foreach ($name_to_keys[$entry] as $key) {
1888 + $migrated[] = $key; // every key wearing this name — fail toward more exclusion
1889 + }
1890 + $converted++;
1891 + } else {
1892 + $migrated[] = $entry; // unresolved — keep; still honored by name everywhere
1893 + }
1894 + }
1895 + $migrated = array_values(array_unique($migrated));
1896 +
1897 + update_option('mxchat_acf_excluded_fields', $migrated);
1898 + update_option('mxchat_acf_exclusions_migrated', '1', false);
1899 + if ($converted > 0) {
1900 + update_option('mxchat_acf_exclusions_migrated_notice', '1', false);
1901 + }
1902 +}
1903 +add_action('acf/init', 'mxchat_migrate_acf_exclusions_to_keys', 20);
1904 +
1905 +/**
1906 + * One-time notice after the ACF exclusion migration actually converted
1907 + * name entries — the settings are worth a review, especially where one name
1908 + * fanned out to several fields (every match is now excluded, on purpose).
1909 + */
1910 +function mxchat_show_acf_exclusions_migrated_notice() {
1911 + if (!current_user_can('manage_options')) {
1912 + return;
1913 + }
1914 + if (get_option('mxchat_acf_exclusions_migrated_notice', '') !== '1') {
1915 + return;
1916 + }
1917 + ?>
1918 + <div class="notice notice-info is-dismissible">
1919 + <p>
1920 + <strong><?php esc_html_e('MxChat: ACF field exclusions updated', 'mxchat'); ?></strong><br>
1921 + <?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'); ?>
1922 + </p>
1923 + </div>
1924 + <?php
1925 + delete_option('mxchat_acf_exclusions_migrated_notice');
1926 +}
1927 +add_action('admin_notices', 'mxchat_show_acf_exclusions_migrated_notice');
1928 +
1929 +/**
1296 1930 * Ensure tables exist on every admin load for fresh installations
1297 1931 * This is a safety net for cases where activation hook doesn't fire
1298 1932 */
1299 1933 function mxchat_ensure_tables_exist() {
@@ -1313,12 +1947,16 @@
1313 1947
1314 1948 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1315 1949 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1316 1950
1951 + $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1952 +
1317 1953 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1318 1954 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1319 -
1320 - if (!$chat_exists || !$queue_exists) {
1955 + $sessions_exists = get_option('mxchat_session_store_ready') !== false
1956 + || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1957 +
1958 + if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1321 1959 //error_log("MxChat: Tables missing on admin load, running activation");
1322 1960 mxchat_activate();
1323 1961 }
1324 1962 }
@@ -1323,49 +1961,116 @@
1323 1961 }
1324 1962 }
1325 1963
1326 1964 /**
1327 - * Clean up orphaned chat history options from the wp_options table
1328 - * @return int Number of options deleted
1965 + * One-shot cleanup of legacy mxchat_history_<sid> option rows (plan 839c4c).
1966 + *
1967 + * 3.2.19 deduplicated per-session chat history into the transcripts table
1968 + * (which already held a superset of every option copy measured), so nothing
1969 + * writes these options any more — but an upgraded install still carries one
1970 + * per session, at up to 64 KB a row (462 rows measured on one production
1971 + * install). This drain replaces the old mxchat_cleanup_orphaned_chat_history()
1972 + * reconciliation sweep, which existed only because there were two copies to
1973 + * reconcile.
1974 + *
1975 + * b64b77 pattern throughout: an option_id bookmark that only moves forward
1976 + * (a crash mid-batch re-processes at most one batch), delete_option() per row
1977 + * so the object + notoptions caches stay coherent, batches drained off
1978 + * non-AJAX admin_init plus the session-store maintenance cron. Once the
1979 + * backlog is gone the state marks done and every later call is one cached
1980 + * option read.
1329 1981 */
1330 -function mxchat_cleanup_orphaned_chat_history() {
1982 +function mxchat_history_backlog_state() {
1983 + // The state option name MUST NOT start with 'mxchat_history_' — the drain
1984 + // deletes everything matching that prefix, and a state option inside the
1985 + // pattern gets eaten by its own drain (caught by the 839c4c rig: batches
1986 + // ran 2,2,2,1 instead of 2,2,1 because the bookmark row was being deleted
1987 + // and re-created every pass).
1988 + $state = get_option('mxchat_legacy_history_cleanup', array());
1989 + if (!is_array($state)) {
1990 + $state = array();
1991 + }
1992 +
1993 + return wp_parse_args($state, array(
1994 + 'done' => false,
1995 + 'last_option_id' => 0,
1996 + 'deleted' => 0,
1997 + ));
1998 +}
1999 +
2000 +/**
2001 + * Delete one batch of legacy history options.
2002 + *
2003 + * @param int $batch Rows per pass — capped small; these can be 64 KB rows.
2004 + * @return int Option rows deleted in this pass.
2005 + */
2006 +function mxchat_history_backlog_batch($batch = 200) {
1331 2007 global $wpdb;
1332 - $count = 0;
1333 2008
1334 - // Get all option keys that match our pattern
1335 - $history_options = $wpdb->get_results(
1336 - "SELECT option_name FROM {$wpdb->options}
1337 - WHERE option_name LIKE 'mxchat_history_%'"
2009 + $state = mxchat_history_backlog_state();
2010 + if (!empty($state['done'])) {
2011 + return 0;
2012 + }
2013 +
2014 + $batch = max(1, (int) $batch);
2015 +
2016 + $rows = $wpdb->get_results(
2017 + $wpdb->prepare(
2018 + "SELECT option_id, option_name FROM {$wpdb->options}
2019 + WHERE option_id > %d AND option_name LIKE %s
2020 + ORDER BY option_id ASC LIMIT %d",
2021 + (int) $state['last_option_id'],
2022 + $wpdb->esc_like('mxchat_history_') . '%',
2023 + $batch
2024 + ),
2025 + ARRAY_A
1338 2026 );
1339 2027
1340 - if (!empty($history_options)) {
1341 - foreach ($history_options as $option) {
1342 - // Extract the session ID from the option name
1343 - $session_id = str_replace('mxchat_history_', '', $option->option_name);
2028 + if (empty($rows)) {
2029 + $state['done'] = true;
2030 + update_option('mxchat_legacy_history_cleanup', $state, 'no');
2031 + return 0;
2032 + }
1344 2033
1345 - // Check if this session still exists in the custom table
1346 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1347 - $exists = $wpdb->get_var(
1348 - $wpdb->prepare(
1349 - "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1350 - $session_id
1351 - )
1352 - );
2034 + foreach ($rows as $row) {
2035 + $state['last_option_id'] = max((int) $state['last_option_id'], (int) $row['option_id']);
2036 + delete_option($row['option_name']);
2037 + $state['deleted'] = (int) $state['deleted'] + 1;
2038 + }
1353 2039
1354 - // If session doesn't exist in the main table, delete the option
1355 - if ($exists == 0) {
1356 - delete_option($option->option_name);
1357 - // Also delete related metadata
1358 - delete_option("mxchat_email_{$session_id}");
1359 - delete_option("mxchat_name_{$session_id}");
1360 - delete_option("mxchat_agent_name_{$session_id}");
1361 - $count++;
1362 - }
2040 + if (count($rows) < $batch) {
2041 + $state['done'] = true;
2042 + }
2043 +
2044 + update_option('mxchat_legacy_history_cleanup', $state, 'no');
2045 +
2046 + return count($rows);
2047 +}
2048 +
2049 +/** One batch per admin page load until drained. */
2050 +function mxchat_history_backlog_drain() {
2051 + mxchat_history_backlog_batch();
2052 +}
2053 +
2054 +/** Cron leg: drain faster, same cap per batch. */
2055 +function mxchat_history_backlog_drain_cron() {
2056 + for ($i = 0; $i < 10; $i++) {
2057 + if (mxchat_history_backlog_batch() === 0) {
2058 + break;
1363 2059 }
1364 2060 }
2061 +}
1365 2062
1366 - return $count;
2063 +// wp_doing_ajax() guard is load-bearing, not defensive (b64b77's shipped-and-
2064 +// caught defect): admin-ajax.php fires admin_init too, and the chat widget's
2065 +// message endpoint is an admin-ajax action — without the guard an anonymous
2066 +// visitor would pay for a delete batch inside their own chat request.
2067 +if (!wp_doing_ajax()) {
2068 + add_action('admin_init', 'mxchat_history_backlog_drain', 21);
1367 2069 }
2070 +// Belt for installs whose admin is rarely visited: ride the session store's
2071 +// existing daily maintenance event rather than scheduling another.
2072 +add_action('mxchat_session_store_maintenance', 'mxchat_history_backlog_drain_cron');
1368 2073
1369 2074 function mxchat_migrate_live_agent_status() {
1370 2075 $options = get_option('mxchat_options', []);
1371 2076
@@ -1468,8 +2173,9 @@
1468 2173 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1469 2174
1470 2175 // Add migration notice hook
1471 2176 add_action('admin_notices', 'mxchat_show_migration_notice');
2177 + add_action('admin_notices', 'mxchat_show_model_access_notice');
1472 2178
1473 2179 // Initialize classes with error handling
1474 2180 try {
1475 2181 // Initialize admin classes
@@ -1627,9 +2333,9 @@
1627 2333 */
1628 2334 function mxchat_save_session_rating() {
1629 2335 global $wpdb;
1630 2336
1631 - $session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : '';
2337 + $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1632 2338 $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
1633 2339 $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
1634 2340 $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
1635 2341