PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.0
MxChat – AI Chatbot & Content Generation for WordPress v3.2.0
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 +82 -759 3.2.193.2.0 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.2.0
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,85 +728,43 @@
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.',
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.';
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.',
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;
@@ -1107,21 +773,8 @@
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,
@@ -1257,11 +868,8 @@
1257 868
1258 869 // Create transcript translations table
1259 870 mxchat_create_translations_table();
1260 871
1261 - // Create per-session satisfaction ratings table (v3.2.6)
1262 - mxchat_create_session_ratings_table();
1263 -
1264 872 // Ensure additional columns in system prompt table
1265 873 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1266 874 if (!empty($existing_system_columns)) {
1267 875 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1304,17 +912,13 @@
1304 912
1305 913 // Run migration for existing installations
1306 914 mxchat_migrate_pinecone_roles_add_bot_id();
1307 915
1308 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1309 - mxchat_backfill_active_embedding_model();
1310 -
1311 916 // Setup cron jobs
1312 917 mxchat_setup_cron_jobs();
1313 918
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);
919 + // Update version
920 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
1317 921
1318 922 //error_log("MxChat: Activation function completed");
1319 923 }
1320 924
@@ -1329,35 +933,28 @@
1329 933 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1330 934 // Set flag to use fallback system
1331 935 update_option('mxchat_use_fallback_rate_limits', true);
1332 936 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.
937 + return;
938 + }
939 +
940 + // Schedule the rate limit reset cron job
941 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
942 +
943 + if ($result === false) {
944 + // Fallback if scheduling fails
945 + update_option('mxchat_use_fallback_rate_limits', true);
946 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1340 947 } 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 - }
948 + // Clear fallback flags if cron scheduling succeeded
949 + delete_option('mxchat_use_fallback_rate_limits');
1352 950 }
1353 -
1354 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
951 +
952 + // Schedule transcript cleanup if configured
1355 953 $transcript_options = get_option('mxchat_transcripts_options', array());
1356 954 $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) {
955 +
956 + if ($cleanup_interval !== 'never') {
1360 957 // Check if not already scheduled
1361 958 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1362 959 // Schedule to run daily at 3 AM
1363 960 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1373,9 +970,8 @@
1373 970 // Clear scheduled cron jobs
1374 971 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1375 972 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1376 973 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1377 - wp_clear_scheduled_hook('mxchat_model_liveness_check');
1378 974
1379 975 // Clear fallback options
1380 976 delete_option('mxchat_use_fallback_rate_limits');
1381 977 delete_option('mxchat_next_rate_limit_check');
@@ -1395,25 +991,17 @@
1395 991 return;
1396 992 }
1397 993
1398 994 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1399 -
995 +
1400 996 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);
997 + // Only run reset if the MxChat_Integrator class exists
998 + if (class_exists('MxChat_Integrator')) {
999 + $integrator = new MxChat_Integrator();
1000 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
1001 + $integrator->mxchat_reset_rate_limits();
1002 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1003 + }
1416 1004 }
1417 1005 }
1418 1006 }
1419 1007
@@ -1425,9 +1013,9 @@
1425 1013 global $wpdb;
1426 1014
1427 1015 try {
1428 1016 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1429 - $plugin_version = MXCHAT_BASE_VERSION;
1017 + $plugin_version = MXCHAT_VERSION;
1430 1018
1431 1019 // Always ensure critical tables exist (even if version matches)
1432 1020 // This handles manual table deletion or fresh installs
1433 1021 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1432,16 +1020,12 @@
1432 1020 // This handles manual table deletion or fresh installs
1433 1021 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1434 1022 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1435 1023
1436 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1437 -
1438 1024 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1439 1025 $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) {
1026 +
1027 + if (!$chat_exists || !$queue_exists) {
1444 1028 //error_log("MxChat: Critical tables missing, running activation");
1445 1029 mxchat_activate();
1446 1030 }
1447 1031
@@ -1504,48 +1088,8 @@
1504 1088 delete_option('mxchat_email_null');
1505 1089 delete_option('mxchat_name_null');
1506 1090 }
1507 1091
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 1092 // Run full activation to ensure everything is up to date
1549 1093 mxchat_activate();
1550 1094
1551 1095 // Run migration functions
@@ -1550,11 +1094,12 @@
1550 1094
1551 1095 // Run migration functions
1552 1096 mxchat_migrate_live_agent_status();
1553 1097
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.)
1098 + // Add the cleanup function for version 2.1.8
1099 + if (version_compare($current_version, '2.1.8', '<')) {
1100 + $deleted = mxchat_cleanup_orphaned_chat_history();
1101 + }
1557 1102
1558 1103 // Update version LAST
1559 1104 update_option('mxchat_plugin_version', $plugin_version);
1560 1105
@@ -1567,67 +1112,8 @@
1567 1112 }
1568 1113 }
1569 1114
1570 1115 /**
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 1116 * Ensure tables exist on every admin load for fresh installations
1631 1117 * This is a safety net for cases where activation hook doesn't fire
1632 1118 */
1633 1119 function mxchat_ensure_tables_exist() {
@@ -1647,16 +1133,12 @@
1647 1133
1648 1134 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1649 1135 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1650 1136
1651 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1652 -
1653 1137 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1654 1138 $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) {
1139 +
1140 + if (!$chat_exists || !$queue_exists) {
1659 1141 //error_log("MxChat: Tables missing on admin load, running activation");
1660 1142 mxchat_activate();
1661 1143 }
1662 1144 }
@@ -1661,116 +1143,49 @@
1661 1143 }
1662 1144 }
1663 1145
1664 1146 /**
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.
1147 + * Clean up orphaned chat history options from the wp_options table
1148 + * @return int Number of options deleted
1681 1149 */
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) {
1150 +function mxchat_cleanup_orphaned_chat_history() {
1707 1151 global $wpdb;
1152 + $count = 0;
1708 1153
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
1154 + // Get all option keys that match our pattern
1155 + $history_options = $wpdb->get_results(
1156 + "SELECT option_name FROM {$wpdb->options}
1157 + WHERE option_name LIKE 'mxchat_history_%'"
1726 1158 );
1727 1159
1728 - if (empty($rows)) {
1729 - $state['done'] = true;
1730 - update_option('mxchat_legacy_history_cleanup', $state, 'no');
1731 - return 0;
1732 - }
1160 + if (!empty($history_options)) {
1161 + foreach ($history_options as $option) {
1162 + // Extract the session ID from the option name
1163 + $session_id = str_replace('mxchat_history_', '', $option->option_name);
1733 1164
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 - }
1165 + // Check if this session still exists in the custom table
1166 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1167 + $exists = $wpdb->get_var(
1168 + $wpdb->prepare(
1169 + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1170 + $session_id
1171 + )
1172 + );
1739 1173
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;
1174 + // If session doesn't exist in the main table, delete the option
1175 + if ($exists == 0) {
1176 + delete_option($option->option_name);
1177 + // Also delete related metadata
1178 + delete_option("mxchat_email_{$session_id}");
1179 + delete_option("mxchat_name_{$session_id}");
1180 + delete_option("mxchat_agent_name_{$session_id}");
1181 + $count++;
1182 + }
1759 1183 }
1760 1184 }
1761 -}
1762 1185
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);
1186 + return $count;
1769 1187 }
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 1188
1774 1189 function mxchat_migrate_live_agent_status() {
1775 1190 $options = get_option('mxchat_options', []);
1776 1191
@@ -1873,9 +1288,8 @@
1873 1288 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1874 1289
1875 1290 // Add migration notice hook
1876 1291 add_action('admin_notices', 'mxchat_show_migration_notice');
1877 - add_action('admin_notices', 'mxchat_show_model_access_notice');
1878 1292
1879 1293 // Initialize classes with error handling
1880 1294 try {
1881 1295 // Initialize admin classes
@@ -1900,23 +1314,8 @@
1900 1314 if (class_exists('MxChat_Content_Generator')) {
1901 1315 new MxChat_Content_Generator();
1902 1316 }
1903 1317
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 1318 // Initialize public classes
1920 1319 if (class_exists('MxChat_Public')) {
1921 1320 $mxchat_public = new MxChat_Public();
1922 1321 }
@@ -1961,25 +1360,11 @@
1961 1360
1962 1361 mxchat_migrate_pinecone_roles_add_bot_id();
1963 1362 mxchat_migrate_add_content_type_column();
1964 1363 mxchat_migrate_add_translations_table();
1965 - mxchat_migrate_add_session_ratings_table();
1966 1364 }
1967 1365
1968 1366 /**
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 1367 * Migration: Create transcript translations table (v3.0.4)
1983 1368 * For users upgrading from versions before 3.0.4
1984 1369 */
1985 1370 function mxchat_migrate_add_translations_table() {
@@ -2022,67 +1407,5 @@
2022 1407 return $schedules;
2023 1408 });
2024 1409
2025 1410 // 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');
1411 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');