PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.1.5
MxChat – AI Chatbot & Content Generation for WordPress v3.1.5
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 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | mxchat-basic.php +84 -780 3.2.193.1.5 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.19
6 + * Version: 3.1.5
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,16 +23,8 @@
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);
35 27 if (MXCHAT_DEV_MODE) {
36 28 $version .= '.' . time();
37 29 }
38 30 define('MXCHAT_VERSION', $version);
@@ -37,37 +29,8 @@
37 29 }
38 30 define('MXCHAT_VERSION', $version);
39 31 }
40 32
41 -/**
42 - * Default confidence floor for the in-chat YouTube card, as a percentage
43 - * (plan-mxchat-20260813-f52492). Higher than the site-wide Similarity
44 - * Threshold default of 35 by design — see MxChat_Utils::video_embed_threshold().
45 - * Declared here so the gate, the admin field and the tests all read ONE number.
46 - */
47 -if (!defined('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT')) {
48 - define('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT', 55);
49 -}
50 -
51 -/**
52 - * Honest, versioned User-Agent for MXChat remote-content ingestion fetches
53 - * (Knowledge Base PDF import, URL import, sitemap / website crawl).
54 - *
55 - * WAF rulesets (SiteGround/ModSecurity, Wordfence, Cloudflare managed rules)
56 - * flag stale spoofed-browser UAs as scrapers and return 403 — which silently
57 - * broke the single most common KB source: self-hosted media on the site's own
58 - * domain. A truthful crawler identifier is the industry norm for well-behaved
59 - * bots and lets a site owner allowlist "MXChatBot" in their WAF. Filterable so
60 - * a locked-down host can supply a different string without a code change.
61 - */
62 -if (!function_exists('mxchat_ingest_user_agent')) {
63 - function mxchat_ingest_user_agent() {
64 - $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '1.0';
65 - $ua = 'MXChatBot/' . $version . ' (+https://mxchat.ai/bot)';
66 - return apply_filters('mxchat_ingest_user_agent', $ua);
67 - }
68 -}
69 -
70 33 function mxchat_load_textdomain() {
71 34 $domain = 'mxchat';
72 35 $locale = determine_locale();
73 36
@@ -83,84 +46,8 @@
83 46 }
84 47 add_action('init', 'mxchat_load_textdomain');
85 48
86 49 /**
87 - * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026.
88 - * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview
89 - * (Google's official migration target) the first time admin_init fires after update.
90 - */
91 -add_action('admin_init', function () {
92 - if (get_option('mxchat_gemini_3_remap_done')) {
93 - return;
94 - }
95 - $opts = get_option('mxchat_options');
96 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') {
97 - $opts['model'] = 'gemini-3.1-pro-preview';
98 - update_option('mxchat_options', $opts);
99 - }
100 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') {
101 - $opts['content_model'] = 'gemini-3.1-pro-preview';
102 - update_option('mxchat_options', $opts);
103 - }
104 - update_option('mxchat_gemini_3_remap_done', 1);
105 -});
106 -
107 -/**
108 - * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212,
109 - * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing
110 - * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning
111 - * (modern, fast, broadly available) the first time admin_init fires after update.
112 - */
113 -add_action('admin_init', function () {
114 - if (get_option('mxchat_grok_2_remap_done')) {
115 - return;
116 - }
117 - $opts = get_option('mxchat_options');
118 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') {
119 - $opts['model'] = 'grok-4-1-fast-non-reasoning';
120 - update_option('mxchat_options', $opts);
121 - }
122 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') {
123 - $opts['content_model'] = 'grok-4-1-fast-non-reasoning';
124 - update_option('mxchat_options', $opts);
125 - }
126 - update_option('mxchat_grok_2_remap_done', 1);
127 -});
128 -
129 -/**
130 - * One-time migration: Anthropic retired the Claude 4 (2025-05-14) snapshots on
131 - * June 15, 2026 — claude-opus-4-20250514 and claude-sonnet-4-20250514 now return
132 - * an API error. Existing installs with a dead ID get auto-remapped to the current
133 - * equivalents Anthropic recommends (Opus 4.8 / Sonnet 4.6) the first time admin_init
134 - * fires after update. Mirrors the gemini-3-pro-preview / grok-2 rescues above.
135 - */
136 -add_action('admin_init', function () {
137 - if (get_option('mxchat_claude_4_retire_remap_done')) {
138 - return;
139 - }
140 - $map = array(
141 - 'claude-opus-4-20250514' => 'claude-opus-4-8',
142 - 'claude-sonnet-4-20250514' => 'claude-sonnet-4-6',
143 - );
144 - $opts = get_option('mxchat_options');
145 - if (is_array($opts)) {
146 - $changed = false;
147 - if (isset($opts['model']) && isset($map[$opts['model']])) {
148 - $opts['model'] = $map[$opts['model']];
149 - $changed = true;
150 - }
151 - if (isset($opts['content_model']) && isset($map[$opts['content_model']])) {
152 - $opts['content_model'] = $map[$opts['content_model']];
153 - $changed = true;
154 - }
155 - if ($changed) {
156 - update_option('mxchat_options', $opts);
157 - }
158 - }
159 - update_option('mxchat_claude_4_retire_remap_done', 1);
160 -});
161 -
162 -/**
163 50 * Exclude MxChat assets from caching plugin optimizations
164 51 *
165 52 * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
166 53 * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
@@ -363,82 +250,20 @@
363 250 $rejected[] = 'wp-admin/admin-ajax.php';
364 251 return $rejected;
365 252 });
366 253
367 -// ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix)
368 -// Each cache plugin gets its own filter export so that visitors hitting an
369 -// edge-cached page never receive cached chat-AJAX responses. The chat send /
370 -// stream send / file upload all POST to /wp-admin/admin-ajax.php with
371 -// `action=mxchat_*`. Without these exports, a cache plugin can stale a response
372 -// and break the per-session nonce flow on the first message.
373 -
374 -// WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings.
375 -add_filter('rocket_cache_reject_uri', function($uris) {
376 - if (!is_array($uris)) $uris = array();
377 - $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*';
378 - return $uris;
379 -});
380 -
381 -// LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits
382 -// caching when the request matches our chat-AJAX pattern.
383 -add_filter('litespeed_cache_no_cache_for_request', function($no_cache) {
384 - if ($no_cache) return $no_cache;
385 - if (!empty($_SERVER['REQUEST_URI']) &&
386 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
387 - !empty($_REQUEST['action']) &&
388 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
389 - return true;
390 - }
391 - return $no_cache;
392 -});
393 -
394 -// W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when
395 -// the URI matches.
396 -add_filter('w3tc_pgcache_request_skip_uri', function($skip) {
397 - if ($skip) return $skip;
398 - if (!empty($_SERVER['REQUEST_URI']) &&
399 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
400 - !empty($_REQUEST['action']) &&
401 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
402 - return true;
403 - }
404 - return $skip;
405 -});
406 -
407 -// FlyingPress — `flying_press_cacheable` takes a boolean and is run per
408 -// request. Same pattern as LiteSpeed / W3TC.
409 -add_filter('flying_press_cacheable', function($cacheable) {
410 - if (!$cacheable) return $cacheable;
411 - if (!empty($_SERVER['REQUEST_URI']) &&
412 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
413 - !empty($_REQUEST['action']) &&
414 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
415 - return false;
416 - }
417 - return $cacheable;
418 -});
419 -
420 254 // Include classes with error handling
421 255 function mxchat_include_classes() {
422 256 $class_files = array(
423 - 'includes/class-mxchat-model-catalog.php',
424 - 'includes/class-mxchat-model-liveness.php',
425 - 'includes/class-mxchat-session-store.php',
426 - 'includes/class-mxchat-live-agent-schedule.php',
427 - 'includes/class-mxchat-tool-registry.php',
428 257 'includes/class-mxchat-integrator.php',
429 258 'includes/class-mxchat-admin.php',
430 259 'includes/class-mxchat-public.php',
431 260 'includes/class-mxchat-utils.php',
432 261 'includes/class-mxchat-user.php',
433 - 'includes/class-mxchat-privacy.php',
434 262 'includes/class-mxchat-meta-box.php',
435 263 'includes/class-mxchat-chunker.php',
436 264 'includes/class-mxchat-word-handler.php',
437 265 'includes/class-mxchat-content-generator.php',
438 - 'includes/class-mxchat-cache-purge.php',
439 - 'includes/class-mxchat-editor-assistant.php',
440 - 'includes/class-rest-api.php',
441 266 'admin/class-ajax-handler.php',
442 267 'admin/class-pinecone-manager.php',
443 268 'admin/class-knowledge-manager.php'
444 269 );
@@ -450,56 +275,8 @@
450 275 } else {
451 276 //error_log('MxChat: Missing class file - ' . $file);
452 277 }
453 278 }
454 -
455 - // Register the native function-calling admin-post save handler (a41dee).
456 - if (class_exists('MxChat_Tool_Registry')) {
457 - MxChat_Tool_Registry::init();
458 - }
459 -
460 - // GDPR: register with WP's personal-data export/erase tools (b81e42).
461 - if (class_exists('MxChat_Privacy')) {
462 - MxChat_Privacy::init();
463 - }
464 -
465 - // Per-session state store: retention cron + the cron-independent
466 - // migration drain off admin_init (b64b77).
467 - if (class_exists('MxChat_Session_Store')) {
468 - MxChat_Session_Store::init();
469 - }
470 -
471 - // Daily model-liveness check + its warning notice (b65e8d). Read-only and
472 - // fail-open: one listing request per in-use provider per day, none at all
473 - // when no key is stored.
474 - if (class_exists('MxChat_Model_Liveness')) {
475 - MxChat_Model_Liveness::init();
476 - }
477 -
478 - // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
479 - // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
480 - // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
481 - if (class_exists('MxChat_Editor_Assistant')) {
482 - MxChat_Editor_Assistant::init();
483 - }
484 -
485 - // Admin pages that aren't classes (procedural include).
486 - if (is_admin()) {
487 - $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
488 - if (file_exists($admin_api_page)) {
489 - require_once $admin_api_page;
490 - }
491 - // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
492 - // The require MUST live here (admin bootstrap) and not just inside
493 - // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
494 - // fire on admin-ajax.php requests, so the wizard's AJAX handlers
495 - // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
496 - // auto_graduate + the f7c7d4 dismiss handler) would never register.
497 - $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
498 - if (file_exists($admin_onboarding_page)) {
499 - require_once $admin_onboarding_page;
500 - }
501 - }
502 279 }
503 280
504 281 /**
505 282 * Lazy-load the PDF parser library only when needed.
@@ -544,26 +321,8 @@
544 321 dbDelta($sql);
545 322 }
546 323
547 324 /**
548 - * Create the per-session state table (b64b77).
549 - *
550 - * Callable from the activation hook, which can run before plugins_loaded has
551 - * included the class files — so it loads the class itself when needed.
552 - */
553 -function mxchat_create_sessions_table() {
554 - if (!class_exists('MxChat_Session_Store')) {
555 - $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
556 - if (!file_exists($path)) {
557 - return false;
558 - }
559 - require_once $path;
560 - }
561 -
562 - return MxChat_Session_Store::create_table();
563 -}
564 -
565 -/**
566 325 * FIXED: Robust table creation and column management
567 326 */
568 327 function mxchat_create_chat_transcripts_table() {
569 328 global $wpdb;
@@ -849,33 +608,8 @@
849 608 update_option('mxchat_content_type_migration_version', '2.5.6');
850 609 }
851 610
852 611 /**
853 - * 3.2.4: Backfill the active embedding model option for installs that already
854 - * have KB content but no stamped model. The mismatch warning compares this
855 - * against the user's currently selected model — no per-row column needed.
856 - */
857 -function mxchat_backfill_active_embedding_model() {
858 - global $wpdb;
859 -
860 - if (get_option('mxchat_active_embedding_model', '') !== '') {
861 - return;
862 - }
863 -
864 - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
865 - if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
866 - return;
867 - }
868 -
869 - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
870 - if ($kb_count > 0) {
871 - $options = get_option('mxchat_options', array());
872 - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
873 - update_option('mxchat_active_embedding_model', $current_model, false);
874 - }
875 -}
876 -
877 -/**
878 612 * 2.5.2: Create queue processing tables for reliable background processing
879 613 */
880 614 function mxchat_create_queue_tables() {
881 615 global $wpdb;
@@ -947,34 +681,8 @@
947 681 dbDelta($sql);
948 682 }
949 683
950 684 /**
951 - * Create per-session satisfaction ratings table (v3.2.6)
952 - * Stores one 👍/👎 rating + optional feedback per chat session.
953 - */
954 -function mxchat_create_session_ratings_table() {
955 - global $wpdb;
956 - $charset_collate = $wpdb->get_charset_collate();
957 -
958 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
959 - $sql = "CREATE TABLE $table_name (
960 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
961 - session_id varchar(255) NOT NULL,
962 - bot_id varchar(50) NOT NULL DEFAULT 'default',
963 - rating_value tinyint(1) NOT NULL,
964 - rating_feedback text DEFAULT NULL,
965 - created_at datetime NOT NULL,
966 - PRIMARY KEY (id),
967 - UNIQUE KEY session_id (session_id),
968 - KEY bot_id (bot_id),
969 - KEY created_at (created_at)
970 - ) $charset_collate;";
971 -
972 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
973 - dbDelta($sql);
974 -}
975 -
976 -/**
977 685 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
978 686 * This fixes "url, source_url. The supplied values may be too long" errors
979 687 */
980 688 function mxchat_fix_url_column_size() {
@@ -1020,108 +728,53 @@
1020 728 }
1021 729
1022 730 $current_model = $options['model'];
1023 731
1024 - // Migrate deprecated/retired Claude models BY TIER so a rescued site lands on
1025 - // the current generation, not an older intermediate (plan dc91bd — the previous
1026 - // single target, claude-opus-4-6, is now two Opus generations behind).
1027 - $deprecated_claude_opus = array(
1028 - 'claude-3-opus-20240229', // Retired Jan 5, 2026
1029 - 'claude-opus-4-20250514', // Deprecated
1030 - 'claude-opus-4-1-20250805', // Retired Aug 5, 2026 (first-party API)
1031 - );
1032 - $deprecated_claude_sonnet = array(
732 + // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
733 + $deprecated_claude_models = array(
1033 734 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
1034 735 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
1035 - 'claude-3-7-sonnet-20250219', // Retired Feb 19, 2026
736 + 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
737 + 'claude-3-opus-20240229', // Retired Jan 5, 2026
1036 738 'claude-3-sonnet-20240229', // Legacy
1037 - 'claude-sonnet-4-20250514', // Deprecated
1038 - );
1039 - $deprecated_claude_haiku = array(
1040 739 'claude-3-haiku-20240307', // Legacy
1041 - 'claude-3-5-haiku-20241022', // Deprecated
1042 740 );
1043 - if (in_array($current_model, $deprecated_claude_opus, true)) {
1044 - $options['model'] = 'claude-opus-5';
741 + if (in_array($current_model, $deprecated_claude_models, true)) {
742 + $options['model'] = 'claude-opus-4-6';
1045 743 $migrated = true;
1046 744 $migration_message = sprintf(
1047 - 'Your chatbot model has been automatically updated from %s to Claude Opus 5 because Anthropic retired the older Claude model.',
745 + __('Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.', 'mxchat'),
1048 746 $current_model
1049 747 );
1050 - } elseif (in_array($current_model, $deprecated_claude_sonnet, true)) {
1051 - $options['model'] = 'claude-sonnet-5';
1052 - $migrated = true;
1053 - $migration_message = sprintf(
1054 - 'Your chatbot model has been automatically updated from %s to Claude Sonnet 5 because Anthropic retired the older Claude model.',
1055 - $current_model
1056 - );
1057 - } elseif (in_array($current_model, $deprecated_claude_haiku, true)) {
748 + }
749 +
750 + // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
751 + if ($current_model === 'claude-3-5-haiku-20241022') {
1058 752 $options['model'] = 'claude-haiku-4-5-20251001';
1059 753 $migrated = true;
1060 - $migration_message = sprintf(
1061 - 'Your chatbot model has been automatically updated from %s to Claude Haiku 4.5 because Anthropic retired the older Claude model.',
1062 - $current_model
1063 - );
754 + $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.', 'mxchat');
1064 755 }
1065 756
1066 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.6 Sol.
1067 - // (Previous target gpt-5.1-chat-latest itself retires 2026-08-10 — never
1068 - // migrate onto a model that is already on a deprecation list.)
757 + // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
1069 758 if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1070 - $options['model'] = 'gpt-5.6-sol';
759 + $options['model'] = 'gpt-5.1-chat-latest';
1071 760 $migrated = true;
1072 761 $migration_message = sprintf(
1073 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
762 + __('Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.', 'mxchat'),
1074 763 $current_model
1075 764 );
1076 765 }
1077 766
1078 - // Migrate the gpt-5.x-chat-latest aliases OpenAI retires on August 10, 2026.
1079 - // Replacement per OpenAI's deprecations page: gpt-5.6-sol (plan e46b8f).
1080 - if (in_array($current_model, array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1081 - $options['model'] = 'gpt-5.6-sol';
1082 - $migrated = true;
1083 - $migration_message = sprintf(
1084 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol because OpenAI retires the GPT-5.x Chat Latest models on August 10, 2026.',
1085 - $current_model
1086 - );
1087 - }
1088 -
1089 - // The content generator has its own model option — same retirement applies.
1090 - if (isset($options['content_model'])
1091 - && in_array($options['content_model'], array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1092 - $old_content_model = $options['content_model'];
1093 - $options['content_model'] = 'gpt-5.6-sol';
1094 - $migrated = true;
1095 - $migration_message = trim($migration_message . ' ' . sprintf(
1096 - 'Your content generation model has also been updated from %s to GPT-5.6 Sol for the same OpenAI retirement.',
1097 - $old_content_model
1098 - ));
1099 - }
1100 -
1101 767 // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1102 768 if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1103 769 $options['model'] = 'gpt-5-mini';
1104 770 $migrated = true;
1105 771 $migration_message = sprintf(
1106 - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
772 + __('Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.', 'mxchat'),
1107 773 $current_model
1108 774 );
1109 775 }
1110 776
1111 - // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1112 - // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1113 - // request 400s). V4 Flash is DeepSeek's designated successor for the
1114 - // legacy deepseek-chat alias.
1115 - if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1116 - $options['model'] = 'deepseek-v4-flash';
1117 - $migrated = true;
1118 - $migration_message = sprintf(
1119 - 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1120 - $current_model
1121 - );
1122 - }
1123 -
1124 777 if ($migrated) {
1125 778 update_option('mxchat_options', $options);
1126 779 update_option('mxchat_model_migrated_notice', true);
1127 780 update_option('mxchat_model_migration_message', $migration_message);
@@ -1146,46 +799,8 @@
1146 799 delete_option('mxchat_model_migration_message');
1147 800 }
1148 801 }
1149 802
1150 -/**
1151 - * Persistent admin notice when the provider rejected the configured model
1152 - * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1153 - * integrator whenever a chat request fails on a model-access error — including
1154 - * requests from anonymous visitors, which is the case that otherwise stays
1155 - * invisible to the site owner for weeks (plan e46b8f).
1156 - *
1157 - * Deleted after render so it re-arms on the next failed chat: the notice keeps
1158 - * reappearing until the model is fixed, then stops on its own.
1159 - */
1160 -function mxchat_show_model_access_notice() {
1161 - if (!current_user_can('manage_options')) {
1162 - return;
1163 - }
1164 - $notice = get_option('mxchat_model_access_notice');
1165 - if (!is_array($notice) || empty($notice['model'])) {
1166 - return;
1167 - }
1168 - $settings_url = admin_url('admin.php?page=mxchat-max');
1169 - ?>
1170 - <div class="notice notice-error is-dismissible">
1171 - <p>
1172 - <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1173 - <?php
1174 - printf(
1175 - /* translators: 1: model id, 2: provider name */
1176 - 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'),
1177 - esc_html($notice['model']),
1178 - esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1179 - );
1180 - ?>
1181 - <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1182 - </p>
1183 - </div>
1184 - <?php
1185 - delete_option('mxchat_model_access_notice');
1186 -}
1187 -
1188 803 function mxchat_activate() {
1189 804 global $wpdb;
1190 805 $charset_collate = $wpdb->get_charset_collate();
1191 806
@@ -1193,12 +808,8 @@
1193 808
1194 809 // Create chat transcripts table with improved function
1195 810 mxchat_create_chat_transcripts_table();
1196 811
1197 - // Per-session state table (b64b77). Activation can run before
1198 - // plugins_loaded has included the class files, so require it directly.
1199 - mxchat_create_sessions_table();
1200 -
1201 812 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
1202 813 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1203 814 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1204 815 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -1226,26 +837,13 @@
1226 837 enabled_bots LONGTEXT DEFAULT NULL,
1227 838 PRIMARY KEY (id)
1228 839 ) $charset_collate;";
1229 840
1230 - // Individual Intent Phrases Table - each phrase gets its own embedding vector
1231 - $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
1232 - $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table (
1233 - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1234 - intent_id BIGINT(20) UNSIGNED NOT NULL,
1235 - phrase TEXT NOT NULL,
1236 - embedding_vector LONGTEXT NOT NULL,
1237 - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1238 - PRIMARY KEY (id),
1239 - KEY intent_id (intent_id)
1240 - ) $charset_collate;";
1241 -
1242 841 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1243 842
1244 843 // Create other tables
1245 844 dbDelta($sql_system_prompt);
1246 845 dbDelta($sql_intents_table);
1247 - dbDelta($sql_intent_phrases_table);
1248 846
1249 847 // Create URL click tracking table
1250 848 mxchat_create_url_clicks_table();
1251 849
@@ -1257,11 +855,8 @@
1257 855
1258 856 // Create transcript translations table
1259 857 mxchat_create_translations_table();
1260 858
1261 - // Create per-session satisfaction ratings table (v3.2.6)
1262 - mxchat_create_session_ratings_table();
1263 -
1264 859 // Ensure additional columns in system prompt table
1265 860 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1266 861 if (!empty($existing_system_columns)) {
1267 862 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1304,17 +899,13 @@
1304 899
1305 900 // Run migration for existing installations
1306 901 mxchat_migrate_pinecone_roles_add_bot_id();
1307 902
1308 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1309 - mxchat_backfill_active_embedding_model();
1310 -
1311 903 // Setup cron jobs
1312 904 mxchat_setup_cron_jobs();
1313 905
1314 - // Update version (stable base version — never the dev time()-suffixed one,
1315 - // or the check_for_update comparison would churn every request)
1316 - update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
906 + // Update version
907 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
1317 908
1318 909 //error_log("MxChat: Activation function completed");
1319 910 }
1320 911
@@ -1329,35 +920,28 @@
1329 920 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1330 921 // Set flag to use fallback system
1331 922 update_option('mxchat_use_fallback_rate_limits', true);
1332 923 update_option('mxchat_next_rate_limit_check', time() + 3600);
1333 - // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1334 - // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1335 - // execute (a server-side runner hitting wp-cron.php instead of loopback
1336 - // spawns) — scheduling still just writes the cron option. The old early
1337 - // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1338 - // site permanently lost the transcript cleanup event while the retention
1339 - // setting still claimed to be active.
924 + return;
925 + }
926 +
927 + // Schedule the rate limit reset cron job
928 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
929 +
930 + if ($result === false) {
931 + // Fallback if scheduling fails
932 + update_option('mxchat_use_fallback_rate_limits', true);
933 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1340 934 } else {
1341 - // Schedule the rate limit reset cron job
1342 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1343 -
1344 - if ($result === false) {
1345 - // Fallback if scheduling fails
1346 - update_option('mxchat_use_fallback_rate_limits', true);
1347 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1348 - } else {
1349 - // Clear fallback flags if cron scheduling succeeded
1350 - delete_option('mxchat_use_fallback_rate_limits');
1351 - }
935 + // Clear fallback flags if cron scheduling succeeded
936 + delete_option('mxchat_use_fallback_rate_limits');
1352 937 }
1353 -
1354 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
938 +
939 + // Schedule transcript cleanup if configured
1355 940 $transcript_options = get_option('mxchat_transcripts_options', array());
1356 941 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1357 - $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1358 -
1359 - if ($cleanup_interval !== 'never' || $custom_retention > 0) {
942 +
943 + if ($cleanup_interval !== 'never') {
1360 944 // Check if not already scheduled
1361 945 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1362 946 // Schedule to run daily at 3 AM
1363 947 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1373,9 +957,8 @@
1373 957 // Clear scheduled cron jobs
1374 958 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1375 959 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1376 960 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1377 - wp_clear_scheduled_hook('mxchat_model_liveness_check');
1378 961
1379 962 // Clear fallback options
1380 963 delete_option('mxchat_use_fallback_rate_limits');
1381 964 delete_option('mxchat_next_rate_limit_check');
@@ -1395,25 +978,17 @@
1395 978 return;
1396 979 }
1397 980
1398 981 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1399 -
982 +
1400 983 if (time() >= $next_check) {
1401 - // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1402 - // plugins_loaded (before this init-priority-5 callback), so it's always set
1403 - // here. Constructing a second MxChat_Integrator just to call one method
1404 - // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1405 - // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1406 - // the request. Defensive construction only if the global is somehow unset.
1407 - // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1408 - // implementation of this same check — if either changes, change both.
1409 - global $mxchat_integrator;
1410 - $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1411 - ? $mxchat_integrator
1412 - : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1413 - if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1414 - $integrator->mxchat_reset_rate_limits();
1415 - update_option('mxchat_next_rate_limit_check', time() + 3600);
984 + // Only run reset if the MxChat_Integrator class exists
985 + if (class_exists('MxChat_Integrator')) {
986 + $integrator = new MxChat_Integrator();
987 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
988 + $integrator->mxchat_reset_rate_limits();
989 + update_option('mxchat_next_rate_limit_check', time() + 3600);
990 + }
1416 991 }
1417 992 }
1418 993 }
1419 994
@@ -1425,9 +1000,9 @@
1425 1000 global $wpdb;
1426 1001
1427 1002 try {
1428 1003 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1429 - $plugin_version = MXCHAT_BASE_VERSION;
1004 + $plugin_version = MXCHAT_VERSION;
1430 1005
1431 1006 // Always ensure critical tables exist (even if version matches)
1432 1007 // This handles manual table deletion or fresh installs
1433 1008 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1432,16 +1007,12 @@
1432 1007 // This handles manual table deletion or fresh installs
1433 1008 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1434 1009 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1435 1010
1436 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1437 -
1438 1011 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1439 1012 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1440 - $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1441 - || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1442 -
1443 - if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1013 +
1014 + if (!$chat_exists || !$queue_exists) {
1444 1015 //error_log("MxChat: Critical tables missing, running activation");
1445 1016 mxchat_activate();
1446 1017 }
1447 1018
@@ -1498,54 +1069,8 @@
1498 1069 if (version_compare($current_version, '3.1.2', '<')) {
1499 1070 mxchat_migrate_transcripts_charset();
1500 1071 }
1501 1072
1502 - // 3.1.7: Clean up stale shared session email/name entries
1503 - if (version_compare($current_version, '3.1.7', '<')) {
1504 - delete_option('mxchat_email_null');
1505 - delete_option('mxchat_name_null');
1506 - }
1507 -
1508 - // 3.2.4: Backfill active embedding model option for the warning UI
1509 - // (replaces the per-row column tracking from 3.2.3, which was reverted)
1510 - if (version_compare($current_version, '3.2.4', '<')) {
1511 - mxchat_backfill_active_embedding_model();
1512 - }
1513 -
1514 - // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1515 - // were shut off at the vendor on 2026-07-24). The function is idempotent —
1516 - // it only rewrites models on its deprecation lists.
1517 - if (version_compare($current_version, '3.2.15', '<')) {
1518 - mxchat_migrate_deprecated_models();
1519 - }
1520 -
1521 - // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1522 - // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1523 - // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1524 - if (version_compare($current_version, '3.2.16', '<')) {
1525 - mxchat_migrate_deprecated_models();
1526 - }
1527 -
1528 - // 3.2.17: Credential options must not autoload (af2400) — the two
1529 - // Pinecone-secret-holding rows were in alloptions, i.e. read into
1530 - // memory on every request including anonymous page views. Idempotent.
1531 - // Also carry the import modal's remembered ACF→PDF checkbox state
1532 - // into the new install-level option (11720c).
1533 - if (version_compare($current_version, '3.2.17', '<')) {
1534 - mxchat_fix_credential_option_autoload();
1535 - mxchat_migrate_acf_pdf_extraction_option();
1536 - }
1537 -
1538 - // 3.2.19: Claude Opus 4.1 retired Aug 5, 2026 — auto-move stranded
1539 - // sites (and the older tiers on the migration's lists) per the
1540 - // changelog's promise. Idempotent — only rewrites models on the
1541 - // deprecation lists. Without a gate at this release's version,
1542 - // nothing calls the migration for 3.2.18 upgraders (plan a5a598;
1543 - // the gate value must equal the version this block ships in).
1544 - if (version_compare($current_version, '3.2.19', '<')) {
1545 - mxchat_migrate_deprecated_models();
1546 - }
1547 -
1548 1073 // Run full activation to ensure everything is up to date
1549 1074 mxchat_activate();
1550 1075
1551 1076 // Run migration functions
@@ -1550,11 +1075,12 @@
1550 1075
1551 1076 // Run migration functions
1552 1077 mxchat_migrate_live_agent_status();
1553 1078
1554 - // (The 2.1.8 orphaned-history reconciliation sweep is gone —
1555 - // 3.2.19's mxchat_history_backlog_* drain supersedes it, and it
1556 - // self-arms without a version gate: plan 839c4c.)
1079 + // Add the cleanup function for version 2.1.8
1080 + if (version_compare($current_version, '2.1.8', '<')) {
1081 + $deleted = mxchat_cleanup_orphaned_chat_history();
1082 + }
1557 1083
1558 1084 // Update version LAST
1559 1085 update_option('mxchat_plugin_version', $plugin_version);
1560 1086
@@ -1567,67 +1093,8 @@
1567 1093 }
1568 1094 }
1569 1095
1570 1096 /**
1571 - * Credential options must never enter the autoloaded alloptions set.
1572 - * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1573 - * Pinecone API secret; mxchat_options already stores its keys with autoload
1574 - * off and these two must match it. The filter covers every future
1575 - * add_option()/update_option() that creates the row — Settings API saves
1576 - * through options.php and WP-CLI included — on WP 6.6+; older cores are
1577 - * covered by the explicit autoload arguments at the plugin's own write
1578 - * sites plus the one-time migration below.
1579 - */
1580 -add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1581 -function mxchat_credential_option_autoload_value($autoload, $option) {
1582 - if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1583 - return false;
1584 - }
1585 - return $autoload;
1586 -}
1587 -
1588 -/**
1589 - * One-time upgrade migration: flip the autoload flag on credential option
1590 - * rows that existing installs are already carrying autoloaded. Includes
1591 - * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1592 - * when that add-on is not installed, since missing rows simply don't match.
1593 - */
1594 -function mxchat_fix_credential_option_autoload() {
1595 - $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1596 - if (function_exists('wp_set_option_autoload_values')) {
1597 - wp_set_option_autoload_values(array_fill_keys($keys, false));
1598 - return;
1599 - }
1600 - // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1601 - global $wpdb;
1602 - $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1603 - $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1604 - wp_cache_delete('alloptions', 'options');
1605 - foreach ($keys as $key) {
1606 - wp_cache_delete($key, 'options');
1607 - }
1608 -}
1609 -
1610 -/**
1611 - * One-time carry of the import modal's remembered ACF→PDF checkbox state
1612 - * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1613 - * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1614 - * Fresh installs and installs that never touched the checkbox default OFF,
1615 - * matching the setting's own "recommended only if…" guidance.
1616 - */
1617 -function mxchat_migrate_acf_pdf_extraction_option() {
1618 - if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1619 - return; // already set — never overwrite an owner's choice
1620 - }
1621 - $mxchat_options = get_option('mxchat_options', array());
1622 - if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1623 - update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1624 - unset($mxchat_options['acf_pdf_extract_default']);
1625 - update_option('mxchat_options', $mxchat_options);
1626 - }
1627 -}
1628 -
1629 -/**
1630 1097 * Ensure tables exist on every admin load for fresh installations
1631 1098 * This is a safety net for cases where activation hook doesn't fire
1632 1099 */
1633 1100 function mxchat_ensure_tables_exist() {
@@ -1647,16 +1114,12 @@
1647 1114
1648 1115 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1649 1116 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1650 1117
1651 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1652 -
1653 1118 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1654 1119 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1655 - $sessions_exists = get_option('mxchat_session_store_ready') !== false
1656 - || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1657 -
1658 - if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1120 +
1121 + if (!$chat_exists || !$queue_exists) {
1659 1122 //error_log("MxChat: Tables missing on admin load, running activation");
1660 1123 mxchat_activate();
1661 1124 }
1662 1125 }
@@ -1661,116 +1124,49 @@
1661 1124 }
1662 1125 }
1663 1126
1664 1127 /**
1665 - * One-shot cleanup of legacy mxchat_history_<sid> option rows (plan 839c4c).
1666 - *
1667 - * 3.2.19 deduplicated per-session chat history into the transcripts table
1668 - * (which already held a superset of every option copy measured), so nothing
1669 - * writes these options any more — but an upgraded install still carries one
1670 - * per session, at up to 64 KB a row (462 rows measured on one production
1671 - * install). This drain replaces the old mxchat_cleanup_orphaned_chat_history()
1672 - * reconciliation sweep, which existed only because there were two copies to
1673 - * reconcile.
1674 - *
1675 - * b64b77 pattern throughout: an option_id bookmark that only moves forward
1676 - * (a crash mid-batch re-processes at most one batch), delete_option() per row
1677 - * so the object + notoptions caches stay coherent, batches drained off
1678 - * non-AJAX admin_init plus the session-store maintenance cron. Once the
1679 - * backlog is gone the state marks done and every later call is one cached
1680 - * option read.
1128 + * Clean up orphaned chat history options from the wp_options table
1129 + * @return int Number of options deleted
1681 1130 */
1682 -function mxchat_history_backlog_state() {
1683 - // The state option name MUST NOT start with 'mxchat_history_' — the drain
1684 - // deletes everything matching that prefix, and a state option inside the
1685 - // pattern gets eaten by its own drain (caught by the 839c4c rig: batches
1686 - // ran 2,2,2,1 instead of 2,2,1 because the bookmark row was being deleted
1687 - // and re-created every pass).
1688 - $state = get_option('mxchat_legacy_history_cleanup', array());
1689 - if (!is_array($state)) {
1690 - $state = array();
1691 - }
1692 -
1693 - return wp_parse_args($state, array(
1694 - 'done' => false,
1695 - 'last_option_id' => 0,
1696 - 'deleted' => 0,
1697 - ));
1698 -}
1699 -
1700 -/**
1701 - * Delete one batch of legacy history options.
1702 - *
1703 - * @param int $batch Rows per pass — capped small; these can be 64 KB rows.
1704 - * @return int Option rows deleted in this pass.
1705 - */
1706 -function mxchat_history_backlog_batch($batch = 200) {
1131 +function mxchat_cleanup_orphaned_chat_history() {
1707 1132 global $wpdb;
1133 + $count = 0;
1708 1134
1709 - $state = mxchat_history_backlog_state();
1710 - if (!empty($state['done'])) {
1711 - return 0;
1712 - }
1713 -
1714 - $batch = max(1, (int) $batch);
1715 -
1716 - $rows = $wpdb->get_results(
1717 - $wpdb->prepare(
1718 - "SELECT option_id, option_name FROM {$wpdb->options}
1719 - WHERE option_id > %d AND option_name LIKE %s
1720 - ORDER BY option_id ASC LIMIT %d",
1721 - (int) $state['last_option_id'],
1722 - $wpdb->esc_like('mxchat_history_') . '%',
1723 - $batch
1724 - ),
1725 - ARRAY_A
1135 + // Get all option keys that match our pattern
1136 + $history_options = $wpdb->get_results(
1137 + "SELECT option_name FROM {$wpdb->options}
1138 + WHERE option_name LIKE 'mxchat_history_%'"
1726 1139 );
1727 1140
1728 - if (empty($rows)) {
1729 - $state['done'] = true;
1730 - update_option('mxchat_legacy_history_cleanup', $state, 'no');
1731 - return 0;
1732 - }
1141 + if (!empty($history_options)) {
1142 + foreach ($history_options as $option) {
1143 + // Extract the session ID from the option name
1144 + $session_id = str_replace('mxchat_history_', '', $option->option_name);
1733 1145
1734 - foreach ($rows as $row) {
1735 - $state['last_option_id'] = max((int) $state['last_option_id'], (int) $row['option_id']);
1736 - delete_option($row['option_name']);
1737 - $state['deleted'] = (int) $state['deleted'] + 1;
1738 - }
1146 + // Check if this session still exists in the custom table
1147 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1148 + $exists = $wpdb->get_var(
1149 + $wpdb->prepare(
1150 + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1151 + $session_id
1152 + )
1153 + );
1739 1154
1740 - if (count($rows) < $batch) {
1741 - $state['done'] = true;
1742 - }
1743 -
1744 - update_option('mxchat_legacy_history_cleanup', $state, 'no');
1745 -
1746 - return count($rows);
1747 -}
1748 -
1749 -/** One batch per admin page load until drained. */
1750 -function mxchat_history_backlog_drain() {
1751 - mxchat_history_backlog_batch();
1752 -}
1753 -
1754 -/** Cron leg: drain faster, same cap per batch. */
1755 -function mxchat_history_backlog_drain_cron() {
1756 - for ($i = 0; $i < 10; $i++) {
1757 - if (mxchat_history_backlog_batch() === 0) {
1758 - break;
1155 + // If session doesn't exist in the main table, delete the option
1156 + if ($exists == 0) {
1157 + delete_option($option->option_name);
1158 + // Also delete related metadata
1159 + delete_option("mxchat_email_{$session_id}");
1160 + delete_option("mxchat_name_{$session_id}");
1161 + delete_option("mxchat_agent_name_{$session_id}");
1162 + $count++;
1163 + }
1759 1164 }
1760 1165 }
1761 -}
1762 1166
1763 -// wp_doing_ajax() guard is load-bearing, not defensive (b64b77's shipped-and-
1764 -// caught defect): admin-ajax.php fires admin_init too, and the chat widget's
1765 -// message endpoint is an admin-ajax action — without the guard an anonymous
1766 -// visitor would pay for a delete batch inside their own chat request.
1767 -if (!wp_doing_ajax()) {
1768 - add_action('admin_init', 'mxchat_history_backlog_drain', 21);
1167 + return $count;
1769 1168 }
1770 -// Belt for installs whose admin is rarely visited: ride the session store's
1771 -// existing daily maintenance event rather than scheduling another.
1772 -add_action('mxchat_session_store_maintenance', 'mxchat_history_backlog_drain_cron');
1773 1169
1774 1170 function mxchat_migrate_live_agent_status() {
1775 1171 $options = get_option('mxchat_options', []);
1776 1172
@@ -1845,9 +1241,9 @@
1845 1241 // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1846 1242 if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1847 1243 // Check if Pro is activated - only show to Pro users
1848 1244 $license_status = get_option('mxchat_license_status', 'inactive');
1849 - $is_pro = ($license_status === 'active');
1245 + $is_pro = ($license_status === 'active' || $license_status === esc_html__('active', 'mxchat'));
1850 1246
1851 1247 if ($is_pro) {
1852 1248 // Set flag to show the theme migration notification banner
1853 1249 update_option('mxchat_show_theme_migration_notice', true);
@@ -1873,9 +1269,8 @@
1873 1269 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1874 1270
1875 1271 // Add migration notice hook
1876 1272 add_action('admin_notices', 'mxchat_show_migration_notice');
1877 - add_action('admin_notices', 'mxchat_show_model_access_notice');
1878 1273
1879 1274 // Initialize classes with error handling
1880 1275 try {
1881 1276 // Initialize admin classes
@@ -1900,23 +1295,8 @@
1900 1295 if (class_exists('MxChat_Content_Generator')) {
1901 1296 new MxChat_Content_Generator();
1902 1297 }
1903 1298
1904 - // Initialize cache purge globally — settings writes can happen on any
1905 - // request type (admin screens, admin-ajax autosave, wp-cli), and the
1906 - // deferred-purge cron event fires on front-end requests.
1907 - if (class_exists('MxChat_Cache_Purge')) {
1908 - MxChat_Cache_Purge::init();
1909 - }
1910 -
1911 - // Initialize REST API globally — endpoints must be registered on
1912 - // every request (admin and frontend) so they're reachable via /wp-json/.
1913 - // Endpoints are auth-gated and locked until the site owner generates
1914 - // a token in MxChat → API Access.
1915 - if (class_exists('MxChat_Rest_Api')) {
1916 - new MxChat_Rest_Api();
1917 - }
1918 -
1919 1299 // Initialize public classes
1920 1300 if (class_exists('MxChat_Public')) {
1921 1301 $mxchat_public = new MxChat_Public();
1922 1302 }
@@ -1961,25 +1341,11 @@
1961 1341
1962 1342 mxchat_migrate_pinecone_roles_add_bot_id();
1963 1343 mxchat_migrate_add_content_type_column();
1964 1344 mxchat_migrate_add_translations_table();
1965 - mxchat_migrate_add_session_ratings_table();
1966 1345 }
1967 1346
1968 1347 /**
1969 - * Migration: Create per-session satisfaction ratings table (v3.2.6)
1970 - * For users upgrading from versions before 3.2.6
1971 - */
1972 -function mxchat_migrate_add_session_ratings_table() {
1973 - $migration_key = 'mxchat_session_ratings_table_created';
1974 - if (get_option($migration_key)) {
1975 - return;
1976 - }
1977 - mxchat_create_session_ratings_table();
1978 - update_option($migration_key, '3.2.6');
1979 -}
1980 -
1981 -/**
1982 1348 * Migration: Create transcript translations table (v3.0.4)
1983 1349 * For users upgrading from versions before 3.0.4
1984 1350 */
1985 1351 function mxchat_migrate_add_translations_table() {
@@ -2022,67 +1388,5 @@
2022 1388 return $schedules;
2023 1389 });
2024 1390
2025 1391 // Register deactivation hook
2026 -register_deactivation_hook(__FILE__, 'mxchat_deactivate');
2027 -
2028 -/**
2029 - * Per-session satisfaction rating: AJAX save handler (v3.2.6).
2030 - * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
2031 - * session_id makes this naturally idempotent — only the first rating per
2032 - * session is stored; duplicate POSTs are silent no-ops.
2033 - */
2034 -function mxchat_save_session_rating() {
2035 - global $wpdb;
2036 -
2037 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2038 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
2039 - $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
2040 - $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
2041 -
2042 - if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
2043 - wp_send_json_error(array('message' => 'invalid_input'), 400);
2044 - }
2045 -
2046 - if (strlen($feedback) > 1000) {
2047 - $feedback = substr($feedback, 0, 1000);
2048 - }
2049 -
2050 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
2051 - $existing = $wpdb->get_var($wpdb->prepare(
2052 - "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
2053 - $session_id
2054 - ));
2055 -
2056 - if ($existing) {
2057 - if ($feedback !== '') {
2058 - $wpdb->update(
2059 - $table_name,
2060 - array('rating_feedback' => $feedback),
2061 - array('id' => (int) $existing),
2062 - array('%s'),
2063 - array('%d')
2064 - );
2065 - }
2066 - wp_send_json_success(array('updated' => true));
2067 - }
2068 -
2069 - $inserted = $wpdb->insert(
2070 - $table_name,
2071 - array(
2072 - 'session_id' => $session_id,
2073 - 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
2074 - 'rating_value' => $rating_raw,
2075 - 'rating_feedback' => $feedback !== '' ? $feedback : null,
2076 - 'created_at' => current_time('mysql'),
2077 - ),
2078 - array('%s', '%s', '%d', '%s', '%s')
2079 - );
2080 -
2081 - if ($inserted === false) {
2082 - wp_send_json_error(array('message' => 'db_insert_failed'), 500);
2083 - }
2084 -
2085 - wp_send_json_success(array('saved' => true));
2086 -}
2087 -add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
2088 -add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');
1392 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');