PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.6.3
MxChat – AI Chatbot & Content Generation for WordPress v2.6.3
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 +90 -1187 3.2.192.6.3 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: 2.6.3
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
@@ -15,59 +15,15 @@
15 15 if (!defined('ABSPATH')) {
16 16 exit; // Exit if accessed directly.
17 17 }
18 18
19 -
20 -if (!defined('MXCHAT_DEV_MODE')) {
21 - define('MXCHAT_DEV_MODE', false);
22 -}
23 -
19 +// Define plugin version constant for asset versioning
20 +// Reads version from plugin header automatically
24 21 if (!defined('MXCHAT_VERSION')) {
25 22 $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), 'plugin');
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 - if (MXCHAT_DEV_MODE) {
36 - $version .= '.' . time();
37 - }
38 - define('MXCHAT_VERSION', $version);
23 + define('MXCHAT_VERSION', $plugin_data['Version']);
39 24 }
40 25
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 26 function mxchat_load_textdomain() {
71 27 $domain = 'mxchat';
72 28 $locale = determine_locale();
73 29
@@ -82,363 +38,20 @@
82 38 load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages');
83 39 }
84 40 add_action('init', 'mxchat_load_textdomain');
85 41
86 -/**
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 - * Exclude MxChat assets from caching plugin optimizations
164 - *
165 - * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
166 - * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
167 - * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery.
168 - *
169 - * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also
170 - * be excluded from any optimization that changes load order or timing.
171 - */
172 -
173 -// ── WP Rocket ────────────────────────────────────────────────────────────────
174 -
175 -// Exclude from Remove Unused CSS (RUCSS)
176 -add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) {
177 - if (!is_array($exclusions)) $exclusions = array();
178 - $exclusions[] = 'mxchat';
179 - return $exclusions;
180 -});
181 -
182 -// Exclude CSS from minification/combination
183 -add_filter('rocket_exclude_css', function($excluded) {
184 - if (!is_array($excluded)) $excluded = array();
185 - $excluded[] = '/plugins/mxchat-basic/css/chat-style.css';
186 - return $excluded;
187 -});
188 -
189 -// Exclude JS from minification/combination
190 -add_filter('rocket_exclude_js', function($excluded) {
191 - if (!is_array($excluded)) $excluded = array();
192 - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
193 - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
194 - $excluded[] = '/jquery-core';
195 - $excluded[] = '/jquery.min.js';
196 - $excluded[] = '/jquery.js';
197 - $excluded[] = '/jquery-migrate';
198 - return $excluded;
199 -});
200 -
201 -// Exclude JS from defer
202 -add_filter('rocket_exclude_defer_js', function($excluded) {
203 - if (!is_array($excluded)) $excluded = array();
204 - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
205 - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
206 - $excluded[] = '/jquery-core';
207 - $excluded[] = '/jquery.min.js';
208 - $excluded[] = '/jquery.js';
209 - $excluded[] = '/jquery-migrate';
210 - return $excluded;
211 -});
212 -
213 -// Exclude from delay JS execution
214 -add_filter('rocket_delay_js_exclusions', function($excluded) {
215 - if (!is_array($excluded)) $excluded = array();
216 - $excluded[] = 'mxchat';
217 - $excluded[] = 'chat-script';
218 - $excluded[] = 'floating-script';
219 - $excluded[] = '/jquery-core';
220 - $excluded[] = '/jquery.min.js';
221 - $excluded[] = '/jquery.js';
222 - $excluded[] = '/jquery-migrate';
223 - return $excluded;
224 -});
225 -
226 -// ── LiteSpeed Cache ──────────────────────────────────────────────────────────
227 -
228 -// Exclude CSS from optimization
229 -add_filter('litespeed_optimize_css_excludes', function($excluded) {
230 - if (!is_array($excluded)) $excluded = array();
231 - $excluded[] = 'chat-style.css';
232 - $excluded[] = 'mxchat';
233 - return $excluded;
234 -});
235 -
236 -// Exclude from UCSS (Unique CSS) - prevents LiteSpeed from stripping "unused" MxChat CSS
237 -add_filter('litespeed_ucss_whitelist', function($whitelist) {
238 - if (!is_array($whitelist)) $whitelist = array();
239 - $whitelist[] = '.mxchat-chatbot-wrapper';
240 - $whitelist[] = '.floating-chatbot';
241 - $whitelist[] = '.floating-chatbot-button';
242 - $whitelist[] = '.chatbot-top-bar';
243 - $whitelist[] = '.mxchat-chatbot';
244 - $whitelist[] = '.chat-container';
245 - $whitelist[] = '.chat-box';
246 - $whitelist[] = '.bot-message';
247 - $whitelist[] = '.input-container';
248 - $whitelist[] = '.chat-input';
249 - $whitelist[] = '.send-button';
250 - $whitelist[] = '.pre-chat-message';
251 - $whitelist[] = '.mxchat-popular-questions';
252 - $whitelist[] = '.chat-toolbar';
253 - $whitelist[] = '.exit-chat';
254 - $whitelist[] = '.email-blocker';
255 - return $whitelist;
256 -});
257 -
258 -// Exclude CSS from CCSS (Critical CSS) generation
259 -add_filter('litespeed_optm_ccss_exc', function($excluded) {
260 - if (!is_array($excluded)) $excluded = array();
261 - $excluded[] = 'chat-style.css';
262 - $excluded[] = 'mxchat';
263 - return $excluded;
264 -});
265 -
266 -// Exclude JS from defer
267 -add_filter('litespeed_optm_js_defer_exc', function($excluded) {
268 - if (!is_array($excluded)) $excluded = array();
269 - $excluded[] = 'chat-script.js';
270 - $excluded[] = 'floating-script.js';
271 - $excluded[] = 'mxchat';
272 - $excluded[] = 'jquery.min.js';
273 - $excluded[] = 'jquery.js';
274 - return $excluded;
275 -});
276 -
277 -// Exclude JS from combining
278 -add_filter('litespeed_optm_js_exc', function($excluded) {
279 - if (!is_array($excluded)) $excluded = array();
280 - $excluded[] = 'chat-script.js';
281 - $excluded[] = 'floating-script.js';
282 - $excluded[] = 'mxchat';
283 - $excluded[] = 'jquery.min.js';
284 - $excluded[] = 'jquery.js';
285 - return $excluded;
286 -});
287 -
288 -// Exclude JS from delayed execution
289 -add_filter('litespeed_optm_js_delay_exc', function($excluded) {
290 - if (!is_array($excluded)) $excluded = array();
291 - $excluded[] = 'chat-script.js';
292 - $excluded[] = 'floating-script.js';
293 - $excluded[] = 'mxchat';
294 - return $excluded;
295 -});
296 -
297 -// Exclude from Guest Mode optimization
298 -add_filter('litespeed_guest_optm_exc', function($excluded) {
299 - if (!is_array($excluded)) $excluded = array();
300 - $excluded[] = 'mxchat';
301 - $excluded[] = 'chat-style';
302 - $excluded[] = 'chat-script';
303 - $excluded[] = 'floating-script';
304 - return $excluded;
305 -});
306 -
307 -// ── Autoptimize ──────────────────────────────────────────────────────────────
308 -
309 -// Exclude CSS from optimization (comma-separated strings)
310 -add_filter('autoptimize_filter_css_exclude', function($excluded) {
311 - if (!is_string($excluded)) $excluded = '';
312 - return $excluded . ', mxchat, chat-style.css';
313 -});
314 -
315 -// Exclude JS from optimization (comma-separated strings)
316 -add_filter('autoptimize_filter_js_exclude', function($excluded) {
317 - if (!is_string($excluded)) $excluded = '';
318 - return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js';
319 -});
320 -
321 -// ── SG Optimizer (SiteGround) ────────────────────────────────────────────────
322 -
323 -add_filter('sgo_js_minify_exclude', function($excluded) {
324 - if (!is_array($excluded)) $excluded = array();
325 - $excluded[] = 'chat-script.js';
326 - $excluded[] = 'floating-script.js';
327 - $excluded[] = 'jquery.min.js';
328 - return $excluded;
329 -});
330 -
331 -add_filter('sgo_javascript_combine_exclude', function($excluded) {
332 - if (!is_array($excluded)) $excluded = array();
333 - $excluded[] = 'chat-script.js';
334 - $excluded[] = 'floating-script.js';
335 - $excluded[] = 'jquery.min.js';
336 - return $excluded;
337 -});
338 -
339 -add_filter('sgo_js_async_exclude', function($excluded) {
340 - if (!is_array($excluded)) $excluded = array();
341 - $excluded[] = 'chat-script.js';
342 - $excluded[] = 'floating-script.js';
343 - $excluded[] = 'jquery.min.js';
344 - return $excluded;
345 -});
346 -
347 -// ── W3 Total Cache ───────────────────────────────────────────────────────────
348 -
349 -add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) {
350 - if (strpos($file, 'chat-script.js') !== false ||
351 - strpos($file, 'floating-script.js') !== false ||
352 - strpos($file, 'jquery.min.js') !== false ||
353 - strpos($file, 'jquery.js') !== false) {
354 - return false;
355 - }
356 - return $do_minify;
357 -}, 10, 3);
358 -
359 -// ── WP Super Cache ──────────────────────────────────────────────────────────
360 -
361 -add_filter('wpsc_rejected_uri', function($rejected) {
362 - if (!is_array($rejected)) $rejected = array();
363 - $rejected[] = 'wp-admin/admin-ajax.php';
364 - return $rejected;
365 -});
366 -
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 42 // Include classes with error handling
421 43 function mxchat_include_classes() {
422 44 $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 45 'includes/class-mxchat-integrator.php',
429 46 'includes/class-mxchat-admin.php',
430 47 'includes/class-mxchat-public.php',
431 48 'includes/class-mxchat-utils.php',
432 49 'includes/class-mxchat-user.php',
433 - 'includes/class-mxchat-privacy.php',
434 50 'includes/class-mxchat-meta-box.php',
435 51 'includes/class-mxchat-chunker.php',
52 + 'includes/pdf-parser/alt_autoload.php',
436 53 'includes/class-mxchat-word-handler.php',
437 - '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 54 'admin/class-ajax-handler.php',
442 55 'admin/class-pinecone-manager.php',
443 56 'admin/class-knowledge-manager.php'
444 57 );
@@ -450,75 +63,11 @@
450 63 } else {
451 64 //error_log('MxChat: Missing class file - ' . $file);
452 65 }
453 66 }
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 67 }
503 68
504 69 /**
505 - * Lazy-load the PDF parser library only when needed.
506 - * Avoids loading 44 files on every page request.
507 - */
508 -function mxchat_load_pdf_parser() {
509 - if (class_exists('\Smalot\PdfParser\Parser')) {
510 - return true;
511 - }
512 - $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
513 - if (file_exists($autoload_path)) {
514 - require_once $autoload_path;
515 - return true;
516 - }
517 - return false;
518 -}
519 -
520 -/**
521 70 * Create URL click tracking table
522 71 */
523 72 function mxchat_create_url_clicks_table() {
524 73 global $wpdb;
@@ -544,26 +93,8 @@
544 93 dbDelta($sql);
545 94 }
546 95
547 96 /**
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 97 * FIXED: Robust table creation and column management
567 98 */
568 99 function mxchat_create_chat_transcripts_table() {
569 100 global $wpdb;
@@ -804,9 +335,9 @@
804 335
805 336 // Add index for bot_id
806 337 $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
807 338
808 - //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
339 + error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
809 340 }
810 341
811 342 // Mark migration as complete
812 343 update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
@@ -841,9 +372,9 @@
841 372
842 373 // Add index for better query performance
843 374 $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
844 375
845 - //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
376 + error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
846 377 }
847 378
848 379 // Mark migration as complete
849 380 update_option('mxchat_content_type_migration_version', '2.5.6');
@@ -849,33 +380,8 @@
849 380 update_option('mxchat_content_type_migration_version', '2.5.6');
850 381 }
851 382
852 383 /**
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 384 * 2.5.2: Create queue processing tables for reliable background processing
879 385 */
880 386 function mxchat_create_queue_tables() {
881 387 global $wpdb;
@@ -923,58 +429,8 @@
923 429 //error_log("MxChat: Queue tables created/updated successfully");
924 430 }
925 431
926 432 /**
927 - * Create transcript translations table for persisting translations
928 - */
929 -function mxchat_create_translations_table() {
930 - global $wpdb;
931 - $charset_collate = $wpdb->get_charset_collate();
932 -
933 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
934 - $sql = "CREATE TABLE $table_name (
935 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
936 - session_id varchar(255) NOT NULL,
937 - language_code varchar(10) NOT NULL,
938 - translations longtext NOT NULL,
939 - created_at datetime NOT NULL,
940 - updated_at datetime NOT NULL,
941 - PRIMARY KEY (id),
942 - UNIQUE KEY session_lang (session_id, language_code),
943 - KEY session_id (session_id)
944 - ) $charset_collate;";
945 -
946 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
947 - dbDelta($sql);
948 -}
949 -
950 -/**
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 433 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
978 434 * This fixes "url, source_url. The supplied values may be too long" errors
979 435 */
980 436 function mxchat_fix_url_column_size() {
@@ -997,135 +453,22 @@
997 453
998 454 /**
999 455 * Migrate deprecated AI models to their replacements
1000 456 * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
1001 - * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1002 - * Without utf8mb4, any bot response containing emojis silently fails to insert.
1003 457 */
1004 -function mxchat_migrate_transcripts_charset() {
1005 - global $wpdb;
1006 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1007 - $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
1008 -}
1009 -
1010 -/**
1011 - * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
1012 - */
1013 458 function mxchat_migrate_deprecated_models() {
1014 459 $options = get_option('mxchat_options', array());
1015 - $migrated = false;
1016 - $migration_message = '';
1017 -
1018 - if (!isset($options['model'])) {
1019 - return;
1020 - }
1021 -
1022 - $current_model = $options['model'];
1023 -
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(
1033 - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
1034 - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
1035 - 'claude-3-7-sonnet-20250219', // Retired Feb 19, 2026
1036 - 'claude-3-sonnet-20240229', // Legacy
1037 - 'claude-sonnet-4-20250514', // Deprecated
1038 - );
1039 - $deprecated_claude_haiku = array(
1040 - 'claude-3-haiku-20240307', // Legacy
1041 - 'claude-3-5-haiku-20241022', // Deprecated
1042 - );
1043 - if (in_array($current_model, $deprecated_claude_opus, true)) {
1044 - $options['model'] = 'claude-opus-5';
1045 - $migrated = true;
1046 - $migration_message = sprintf(
1047 - 'Your chatbot model has been automatically updated from %s to Claude Opus 5 because Anthropic retired the older Claude model.',
1048 - $current_model
1049 - );
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)) {
1058 - $options['model'] = 'claude-haiku-4-5-20251001';
1059 - $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 - );
1064 - }
1065 -
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.)
1069 - 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';
1071 - $migrated = true;
1072 - $migration_message = sprintf(
1073 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
1074 - $current_model
1075 - );
1076 - }
1077 -
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 - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1102 - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1103 - $options['model'] = 'gpt-5-mini';
1104 - $migrated = true;
1105 - $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.',
1107 - $current_model
1108 - );
1109 - }
1110 -
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 - if ($migrated) {
460 +
461 + // Check if model is set and is the deprecated Claude 3.5 Sonnet
462 + if (isset($options['model']) && $options['model'] === 'claude-3-5-sonnet-20241022') {
463 + // Update to Claude 3.7 Sonnet (the replacement model)
464 + $options['model'] = 'claude-3-7-sonnet-20250219';
1125 465 update_option('mxchat_options', $options);
466 +
467 + // Set a flag to show admin notice
1126 468 update_option('mxchat_model_migrated_notice', true);
1127 - update_option('mxchat_model_migration_message', $migration_message);
469 +
470 + //error_log('MxChat: Migrated deprecated Claude 3.5 Sonnet to Claude 3.7 Sonnet');
1128 471 }
1129 472 }
1130 473
1131 474 /**
@@ -1132,60 +475,20 @@
1132 475 * Show admin notice after model migration
1133 476 */
1134 477 function mxchat_show_migration_notice() {
1135 478 if (get_option('mxchat_model_migrated_notice')) {
1136 - $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
1137 479 ?>
1138 480 <div class="notice notice-info is-dismissible">
1139 481 <p>
1140 482 <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
1141 - <?php echo esc_html($migration_message); ?>
483 + <?php esc_html_e('Your chatbot model has been automatically updated from Claude 3.5 Sonnet to Claude 3.7 Sonnet due to the deprecation of the previous model by Anthropic. Claude 3.7 Sonnet offers improved performance and capabilities.', 'mxchat'); ?>
1142 484 </p>
1143 485 </div>
1144 486 <?php
1145 487 delete_option('mxchat_model_migrated_notice');
1146 - delete_option('mxchat_model_migration_message');
1147 488 }
1148 489 }
1149 490
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 491 function mxchat_activate() {
1189 492 global $wpdb;
1190 493 $charset_collate = $wpdb->get_charset_collate();
1191 494
@@ -1193,12 +496,8 @@
1193 496
1194 497 // Create chat transcripts table with improved function
1195 498 mxchat_create_chat_transcripts_table();
1196 499
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 500 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
1202 501 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1203 502 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1204 503 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -1226,26 +525,13 @@
1226 525 enabled_bots LONGTEXT DEFAULT NULL,
1227 526 PRIMARY KEY (id)
1228 527 ) $charset_collate;";
1229 528
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 529 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1243 530
1244 531 // Create other tables
1245 532 dbDelta($sql_system_prompt);
1246 533 dbDelta($sql_intents_table);
1247 - dbDelta($sql_intent_phrases_table);
1248 534
1249 535 // Create URL click tracking table
1250 536 mxchat_create_url_clicks_table();
1251 537
@@ -1254,14 +540,8 @@
1254 540
1255 541 // NEW 2.5.2: Create queue processing tables
1256 542 mxchat_create_queue_tables();
1257 543
1258 - // Create transcript translations table
1259 - mxchat_create_translations_table();
1260 -
1261 - // Create per-session satisfaction ratings table (v3.2.6)
1262 - mxchat_create_session_ratings_table();
1263 -
1264 544 // Ensure additional columns in system prompt table
1265 545 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1266 546 if (!empty($existing_system_columns)) {
1267 547 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1304,17 +584,13 @@
1304 584
1305 585 // Run migration for existing installations
1306 586 mxchat_migrate_pinecone_roles_add_bot_id();
1307 587
1308 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1309 - mxchat_backfill_active_embedding_model();
1310 -
1311 588 // Setup cron jobs
1312 589 mxchat_setup_cron_jobs();
1313 590
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);
591 + // Update version
592 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
1317 593
1318 594 //error_log("MxChat: Activation function completed");
1319 595 }
1320 596
@@ -1329,35 +605,28 @@
1329 605 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1330 606 // Set flag to use fallback system
1331 607 update_option('mxchat_use_fallback_rate_limits', true);
1332 608 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.
609 + return;
610 + }
611 +
612 + // Schedule the rate limit reset cron job
613 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
614 +
615 + if ($result === false) {
616 + // Fallback if scheduling fails
617 + update_option('mxchat_use_fallback_rate_limits', true);
618 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1340 619 } 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 - }
620 + // Clear fallback flags if cron scheduling succeeded
621 + delete_option('mxchat_use_fallback_rate_limits');
1352 622 }
1353 -
1354 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
623 +
624 + // Schedule transcript cleanup if configured
1355 625 $transcript_options = get_option('mxchat_transcripts_options', array());
1356 626 $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) {
627 +
628 + if ($cleanup_interval !== 'never') {
1360 629 // Check if not already scheduled
1361 630 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1362 631 // Schedule to run daily at 3 AM
1363 632 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1373,9 +642,8 @@
1373 642 // Clear scheduled cron jobs
1374 643 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1375 644 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1376 645 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1377 - wp_clear_scheduled_hook('mxchat_model_liveness_check');
1378 646
1379 647 // Clear fallback options
1380 648 delete_option('mxchat_use_fallback_rate_limits');
1381 649 delete_option('mxchat_next_rate_limit_check');
@@ -1395,25 +663,17 @@
1395 663 return;
1396 664 }
1397 665
1398 666 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1399 -
667 +
1400 668 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);
669 + // Only run reset if the MxChat_Integrator class exists
670 + if (class_exists('MxChat_Integrator')) {
671 + $integrator = new MxChat_Integrator();
672 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
673 + $integrator->mxchat_reset_rate_limits();
674 + update_option('mxchat_next_rate_limit_check', time() + 3600);
675 + }
1416 676 }
1417 677 }
1418 678 }
1419 679
@@ -1425,9 +685,9 @@
1425 685 global $wpdb;
1426 686
1427 687 try {
1428 688 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1429 - $plugin_version = MXCHAT_BASE_VERSION;
689 + $plugin_version = MXCHAT_VERSION;
1430 690
1431 691 // Always ensure critical tables exist (even if version matches)
1432 692 // This handles manual table deletion or fresh installs
1433 693 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1432,16 +692,12 @@
1432 692 // This handles manual table deletion or fresh installs
1433 693 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1434 694 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1435 695
1436 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1437 -
1438 696 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1439 697 $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) {
698 +
699 + if (!$chat_exists || !$queue_exists) {
1444 700 //error_log("MxChat: Critical tables missing, running activation");
1445 701 mxchat_activate();
1446 702 }
1447 703
@@ -1447,14 +703,11 @@
1447 703
1448 704 // Version-specific migrations
1449 705 if ($current_version !== $plugin_version) {
1450 706 //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
1451 -
707 +
1452 708 // Run live agent update BEFORE updating the stored version
1453 709 mxchat_handle_live_agent_update();
1454 -
1455 - // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
1456 - mxchat_handle_theme_migration_notice();
1457 710
1458 711 // Run role restriction migration for 2.4.1
1459 712 if (version_compare($current_version, '2.4.1', '<')) {
1460 713 mxchat_add_role_restriction_column();
@@ -1483,69 +736,8 @@
1483 736 mxchat_ensure_all_columns($chat_table);
1484 737 //error_log("MxChat: rag_context column migration for 2.6.0");
1485 738 }
1486 739
1487 - // 3.0.5: Migrate deprecated Gemini embedding model
1488 - if (version_compare($current_version, '3.0.5', '<')) {
1489 - mxchat_migrate_gemini_embedding_model();
1490 - }
1491 -
1492 - // 3.0.6: Migrate deprecated OpenAI and Claude models
1493 - if (version_compare($current_version, '3.0.6', '<')) {
1494 - mxchat_migrate_deprecated_models();
1495 - }
1496 -
1497 - // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1498 - if (version_compare($current_version, '3.1.2', '<')) {
1499 - mxchat_migrate_transcripts_charset();
1500 - }
1501 -
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 740 // Run full activation to ensure everything is up to date
1549 741 mxchat_activate();
1550 742
1551 743 // Run migration functions
@@ -1550,11 +742,12 @@
1550 742
1551 743 // Run migration functions
1552 744 mxchat_migrate_live_agent_status();
1553 745
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.)
746 + // Add the cleanup function for version 2.1.8
747 + if (version_compare($current_version, '2.1.8', '<')) {
748 + $deleted = mxchat_cleanup_orphaned_chat_history();
749 + }
1557 750
1558 751 // Update version LAST
1559 752 update_option('mxchat_plugin_version', $plugin_version);
1560 753
@@ -1567,67 +760,8 @@
1567 760 }
1568 761 }
1569 762
1570 763 /**
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 764 * Ensure tables exist on every admin load for fresh installations
1631 765 * This is a safety net for cases where activation hook doesn't fire
1632 766 */
1633 767 function mxchat_ensure_tables_exist() {
@@ -1647,16 +781,12 @@
1647 781
1648 782 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1649 783 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1650 784
1651 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1652 -
1653 785 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1654 786 $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) {
787 +
788 + if (!$chat_exists || !$queue_exists) {
1659 789 //error_log("MxChat: Tables missing on admin load, running activation");
1660 790 mxchat_activate();
1661 791 }
1662 792 }
@@ -1661,116 +791,49 @@
1661 791 }
1662 792 }
1663 793
1664 794 /**
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.
795 + * Clean up orphaned chat history options from the wp_options table
796 + * @return int Number of options deleted
1681 797 */
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) {
798 +function mxchat_cleanup_orphaned_chat_history() {
1707 799 global $wpdb;
800 + $count = 0;
1708 801
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
802 + // Get all option keys that match our pattern
803 + $history_options = $wpdb->get_results(
804 + "SELECT option_name FROM {$wpdb->options}
805 + WHERE option_name LIKE 'mxchat_history_%'"
1726 806 );
1727 807
1728 - if (empty($rows)) {
1729 - $state['done'] = true;
1730 - update_option('mxchat_legacy_history_cleanup', $state, 'no');
1731 - return 0;
1732 - }
808 + if (!empty($history_options)) {
809 + foreach ($history_options as $option) {
810 + // Extract the session ID from the option name
811 + $session_id = str_replace('mxchat_history_', '', $option->option_name);
1733 812
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 - }
813 + // Check if this session still exists in the custom table
814 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
815 + $exists = $wpdb->get_var(
816 + $wpdb->prepare(
817 + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
818 + $session_id
819 + )
820 + );
1739 821
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;
822 + // If session doesn't exist in the main table, delete the option
823 + if ($exists == 0) {
824 + delete_option($option->option_name);
825 + // Also delete related metadata
826 + delete_option("mxchat_email_{$session_id}");
827 + delete_option("mxchat_name_{$session_id}");
828 + delete_option("mxchat_agent_name_{$session_id}");
829 + $count++;
830 + }
1759 831 }
1760 832 }
1761 -}
1762 833
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);
834 + return $count;
1769 835 }
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 836
1774 837 function mxchat_migrate_live_agent_status() {
1775 838 $options = get_option('mxchat_options', []);
1776 839
@@ -1806,59 +869,31 @@
1806 869 function mxchat_handle_live_agent_update() {
1807 870 // Get the CURRENT stored version (before it gets updated)
1808 871 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1809 872 $new_version = '2.2.2';
1810 -
873 +
1811 874 // Only run this once for the update to 2.2.2
1812 875 $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
1813 -
876 +
1814 877 // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1815 878 if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1816 879 $options = get_option('mxchat_options', array());
1817 -
880 +
1818 881 // Check if live agent was previously enabled
1819 882 if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1820 883 // Disable live agent
1821 884 $options['live_agent_status'] = 'off';
1822 885 update_option('mxchat_options', $options);
1823 -
886 +
1824 887 // Set flag to show the notification banner
1825 888 update_option('mxchat_show_live_agent_disabled_notice', true);
1826 889 }
1827 -
890 +
1828 891 // Mark this update as handled
1829 892 update_option('mxchat_live_agent_update_2_2_2_handled', true);
1830 893 }
1831 894 }
1832 895
1833 -/**
1834 - * Handle theme migration notice for version 3.0.1
1835 - * Shows a dismissible notice to Pro users about migrating AI-generated themes
1836 - */
1837 -function mxchat_handle_theme_migration_notice() {
1838 - // Get the CURRENT stored version (before it gets updated)
1839 - $current_version = get_option('mxchat_plugin_version', '0.0.0');
1840 - $target_version = '3.0.1';
1841 -
1842 - // Only run this once for the update to 3.0.1
1843 - $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1844 -
1845 - // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1846 - if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1847 - // Check if Pro is activated - only show to Pro users
1848 - $license_status = get_option('mxchat_license_status', 'inactive');
1849 - $is_pro = ($license_status === 'active');
1850 -
1851 - if ($is_pro) {
1852 - // Set flag to show the theme migration notification banner
1853 - update_option('mxchat_show_theme_migration_notice', true);
1854 - }
1855 -
1856 - // Mark this update as handled (whether Pro or not)
1857 - update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1858 - }
1859 -}
1860 -
1861 896 // Initialize plugin safely
1862 897 function mxchat_init() {
1863 898 // Include all class files first
1864 899 mxchat_include_classes();
@@ -1873,9 +908,8 @@
1873 908 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1874 909
1875 910 // Add migration notice hook
1876 911 add_action('admin_notices', 'mxchat_show_migration_notice');
1877 - add_action('admin_notices', 'mxchat_show_model_access_notice');
1878 912
1879 913 // Initialize classes with error handling
1880 914 try {
1881 915 // Initialize admin classes
@@ -1891,32 +925,10 @@
1891 925 // Initialize meta box class
1892 926 if (class_exists('MxChat_Meta_Box')) {
1893 927 new MxChat_Meta_Box();
1894 928 }
1895 -
1896 929 }
1897 -
1898 - // Initialize content generator globally — it registers wp_head hook
1899 - // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1900 - if (class_exists('MxChat_Content_Generator')) {
1901 - new MxChat_Content_Generator();
1902 - }
1903 -
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 -
930 +
1919 931 // Initialize public classes
1920 932 if (class_exists('MxChat_Public')) {
1921 933 $mxchat_public = new MxChat_Public();
1922 934 }
@@ -1960,57 +972,10 @@
1960 972 $checked = true;
1961 973
1962 974 mxchat_migrate_pinecone_roles_add_bot_id();
1963 975 mxchat_migrate_add_content_type_column();
1964 - mxchat_migrate_add_translations_table();
1965 - mxchat_migrate_add_session_ratings_table();
1966 976 }
1967 977
1968 -/**
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 - * Migration: Create transcript translations table (v3.0.4)
1983 - * For users upgrading from versions before 3.0.4
1984 - */
1985 -function mxchat_migrate_add_translations_table() {
1986 - $migration_key = 'mxchat_translations_table_created';
1987 -
1988 - // Check if migration already ran
1989 - if (get_option($migration_key)) {
1990 - return;
1991 - }
1992 -
1993 - // Create the translations table
1994 - mxchat_create_translations_table();
1995 -
1996 - // Mark migration as complete
1997 - update_option($migration_key, '3.0.4');
1998 -}
1999 -
2000 -/**
2001 - * Migration: Update deprecated Gemini embedding model (v3.0.5)
2002 - * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
2003 - */
2004 -function mxchat_migrate_gemini_embedding_model() {
2005 - $options = get_option('mxchat_options', array());
2006 -
2007 - if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
2008 - $options['embedding_model'] = 'gemini-embedding-001';
2009 - update_option('mxchat_options', $options);
2010 - }
2011 -}
2012 -
2013 978 // Register activation hook
2014 979 register_activation_hook(__FILE__, 'mxchat_activate');
2015 980
2016 981 // Add cron schedule
@@ -2022,67 +987,5 @@
2022 987 return $schedules;
2023 988 });
2024 989
2025 990 // 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');
991 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');