PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.5.9
MxChat – AI Chatbot & Content Generation for WordPress v2.5.9
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 +56 -1024 3.2.172.5.9 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.17
6 + * Version: 2.5.9
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,418 +15,31 @@
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 - * Honest, versioned User-Agent for MXChat remote-content ingestion fetches
43 - * (Knowledge Base PDF import, URL import, sitemap / website crawl).
44 - *
45 - * WAF rulesets (SiteGround/ModSecurity, Wordfence, Cloudflare managed rules)
46 - * flag stale spoofed-browser UAs as scrapers and return 403 — which silently
47 - * broke the single most common KB source: self-hosted media on the site's own
48 - * domain. A truthful crawler identifier is the industry norm for well-behaved
49 - * bots and lets a site owner allowlist "MXChatBot" in their WAF. Filterable so
50 - * a locked-down host can supply a different string without a code change.
51 - */
52 -if (!function_exists('mxchat_ingest_user_agent')) {
53 - function mxchat_ingest_user_agent() {
54 - $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '1.0';
55 - $ua = 'MXChatBot/' . $version . ' (+https://mxchat.ai/bot)';
56 - return apply_filters('mxchat_ingest_user_agent', $ua);
57 - }
58 -}
59 -
60 26 function mxchat_load_textdomain() {
61 - $domain = 'mxchat';
62 - $locale = determine_locale();
63 -
64 - // First, try to load from /wp-content/languages/plugins/ (preserved during updates)
65 - $mo_file = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo';
66 - if (file_exists($mo_file)) {
67 - load_textdomain($domain, $mo_file);
68 - return;
69 - }
70 -
71 - // Fallback to plugin's /languages directory
72 - load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages');
27 + load_plugin_textdomain('mxchat', false, dirname(plugin_basename(__FILE__)) . '/languages');
73 28 }
74 29 add_action('init', 'mxchat_load_textdomain');
75 30
76 -/**
77 - * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026.
78 - * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview
79 - * (Google's official migration target) the first time admin_init fires after update.
80 - */
81 -add_action('admin_init', function () {
82 - if (get_option('mxchat_gemini_3_remap_done')) {
83 - return;
84 - }
85 - $opts = get_option('mxchat_options');
86 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') {
87 - $opts['model'] = 'gemini-3.1-pro-preview';
88 - update_option('mxchat_options', $opts);
89 - }
90 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') {
91 - $opts['content_model'] = 'gemini-3.1-pro-preview';
92 - update_option('mxchat_options', $opts);
93 - }
94 - update_option('mxchat_gemini_3_remap_done', 1);
95 -});
96 -
97 -/**
98 - * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212,
99 - * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing
100 - * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning
101 - * (modern, fast, broadly available) the first time admin_init fires after update.
102 - */
103 -add_action('admin_init', function () {
104 - if (get_option('mxchat_grok_2_remap_done')) {
105 - return;
106 - }
107 - $opts = get_option('mxchat_options');
108 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') {
109 - $opts['model'] = 'grok-4-1-fast-non-reasoning';
110 - update_option('mxchat_options', $opts);
111 - }
112 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') {
113 - $opts['content_model'] = 'grok-4-1-fast-non-reasoning';
114 - update_option('mxchat_options', $opts);
115 - }
116 - update_option('mxchat_grok_2_remap_done', 1);
117 -});
118 -
119 -/**
120 - * One-time migration: Anthropic retired the Claude 4 (2025-05-14) snapshots on
121 - * June 15, 2026 — claude-opus-4-20250514 and claude-sonnet-4-20250514 now return
122 - * an API error. Existing installs with a dead ID get auto-remapped to the current
123 - * equivalents Anthropic recommends (Opus 4.8 / Sonnet 4.6) the first time admin_init
124 - * fires after update. Mirrors the gemini-3-pro-preview / grok-2 rescues above.
125 - */
126 -add_action('admin_init', function () {
127 - if (get_option('mxchat_claude_4_retire_remap_done')) {
128 - return;
129 - }
130 - $map = array(
131 - 'claude-opus-4-20250514' => 'claude-opus-4-8',
132 - 'claude-sonnet-4-20250514' => 'claude-sonnet-4-6',
133 - );
134 - $opts = get_option('mxchat_options');
135 - if (is_array($opts)) {
136 - $changed = false;
137 - if (isset($opts['model']) && isset($map[$opts['model']])) {
138 - $opts['model'] = $map[$opts['model']];
139 - $changed = true;
140 - }
141 - if (isset($opts['content_model']) && isset($map[$opts['content_model']])) {
142 - $opts['content_model'] = $map[$opts['content_model']];
143 - $changed = true;
144 - }
145 - if ($changed) {
146 - update_option('mxchat_options', $opts);
147 - }
148 - }
149 - update_option('mxchat_claude_4_retire_remap_done', 1);
150 -});
151 -
152 -/**
153 - * Exclude MxChat assets from caching plugin optimizations
154 - *
155 - * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
156 - * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
157 - * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery.
158 - *
159 - * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also
160 - * be excluded from any optimization that changes load order or timing.
161 - */
162 -
163 -// ── WP Rocket ────────────────────────────────────────────────────────────────
164 -
165 -// Exclude from Remove Unused CSS (RUCSS)
166 -add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) {
167 - if (!is_array($exclusions)) $exclusions = array();
168 - $exclusions[] = 'mxchat';
169 - return $exclusions;
170 -});
171 -
172 -// Exclude CSS from minification/combination
173 -add_filter('rocket_exclude_css', function($excluded) {
174 - if (!is_array($excluded)) $excluded = array();
175 - $excluded[] = '/plugins/mxchat-basic/css/chat-style.css';
176 - return $excluded;
177 -});
178 -
179 -// Exclude JS from minification/combination
180 -add_filter('rocket_exclude_js', function($excluded) {
181 - if (!is_array($excluded)) $excluded = array();
182 - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
183 - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
184 - $excluded[] = '/jquery-core';
185 - $excluded[] = '/jquery.min.js';
186 - $excluded[] = '/jquery.js';
187 - $excluded[] = '/jquery-migrate';
188 - return $excluded;
189 -});
190 -
191 -// Exclude JS from defer
192 -add_filter('rocket_exclude_defer_js', function($excluded) {
193 - if (!is_array($excluded)) $excluded = array();
194 - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
195 - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
196 - $excluded[] = '/jquery-core';
197 - $excluded[] = '/jquery.min.js';
198 - $excluded[] = '/jquery.js';
199 - $excluded[] = '/jquery-migrate';
200 - return $excluded;
201 -});
202 -
203 -// Exclude from delay JS execution
204 -add_filter('rocket_delay_js_exclusions', function($excluded) {
205 - if (!is_array($excluded)) $excluded = array();
206 - $excluded[] = 'mxchat';
207 - $excluded[] = 'chat-script';
208 - $excluded[] = 'floating-script';
209 - $excluded[] = '/jquery-core';
210 - $excluded[] = '/jquery.min.js';
211 - $excluded[] = '/jquery.js';
212 - $excluded[] = '/jquery-migrate';
213 - return $excluded;
214 -});
215 -
216 -// ── LiteSpeed Cache ──────────────────────────────────────────────────────────
217 -
218 -// Exclude CSS from optimization
219 -add_filter('litespeed_optimize_css_excludes', function($excluded) {
220 - if (!is_array($excluded)) $excluded = array();
221 - $excluded[] = 'chat-style.css';
222 - $excluded[] = 'mxchat';
223 - return $excluded;
224 -});
225 -
226 -// Exclude from UCSS (Unique CSS) - prevents LiteSpeed from stripping "unused" MxChat CSS
227 -add_filter('litespeed_ucss_whitelist', function($whitelist) {
228 - if (!is_array($whitelist)) $whitelist = array();
229 - $whitelist[] = '.mxchat-chatbot-wrapper';
230 - $whitelist[] = '.floating-chatbot';
231 - $whitelist[] = '.floating-chatbot-button';
232 - $whitelist[] = '.chatbot-top-bar';
233 - $whitelist[] = '.mxchat-chatbot';
234 - $whitelist[] = '.chat-container';
235 - $whitelist[] = '.chat-box';
236 - $whitelist[] = '.bot-message';
237 - $whitelist[] = '.input-container';
238 - $whitelist[] = '.chat-input';
239 - $whitelist[] = '.send-button';
240 - $whitelist[] = '.pre-chat-message';
241 - $whitelist[] = '.mxchat-popular-questions';
242 - $whitelist[] = '.chat-toolbar';
243 - $whitelist[] = '.exit-chat';
244 - $whitelist[] = '.email-blocker';
245 - return $whitelist;
246 -});
247 -
248 -// Exclude CSS from CCSS (Critical CSS) generation
249 -add_filter('litespeed_optm_ccss_exc', function($excluded) {
250 - if (!is_array($excluded)) $excluded = array();
251 - $excluded[] = 'chat-style.css';
252 - $excluded[] = 'mxchat';
253 - return $excluded;
254 -});
255 -
256 -// Exclude JS from defer
257 -add_filter('litespeed_optm_js_defer_exc', function($excluded) {
258 - if (!is_array($excluded)) $excluded = array();
259 - $excluded[] = 'chat-script.js';
260 - $excluded[] = 'floating-script.js';
261 - $excluded[] = 'mxchat';
262 - $excluded[] = 'jquery.min.js';
263 - $excluded[] = 'jquery.js';
264 - return $excluded;
265 -});
266 -
267 -// Exclude JS from combining
268 -add_filter('litespeed_optm_js_exc', function($excluded) {
269 - if (!is_array($excluded)) $excluded = array();
270 - $excluded[] = 'chat-script.js';
271 - $excluded[] = 'floating-script.js';
272 - $excluded[] = 'mxchat';
273 - $excluded[] = 'jquery.min.js';
274 - $excluded[] = 'jquery.js';
275 - return $excluded;
276 -});
277 -
278 -// Exclude JS from delayed execution
279 -add_filter('litespeed_optm_js_delay_exc', function($excluded) {
280 - if (!is_array($excluded)) $excluded = array();
281 - $excluded[] = 'chat-script.js';
282 - $excluded[] = 'floating-script.js';
283 - $excluded[] = 'mxchat';
284 - return $excluded;
285 -});
286 -
287 -// Exclude from Guest Mode optimization
288 -add_filter('litespeed_guest_optm_exc', function($excluded) {
289 - if (!is_array($excluded)) $excluded = array();
290 - $excluded[] = 'mxchat';
291 - $excluded[] = 'chat-style';
292 - $excluded[] = 'chat-script';
293 - $excluded[] = 'floating-script';
294 - return $excluded;
295 -});
296 -
297 -// ── Autoptimize ──────────────────────────────────────────────────────────────
298 -
299 -// Exclude CSS from optimization (comma-separated strings)
300 -add_filter('autoptimize_filter_css_exclude', function($excluded) {
301 - if (!is_string($excluded)) $excluded = '';
302 - return $excluded . ', mxchat, chat-style.css';
303 -});
304 -
305 -// Exclude JS from optimization (comma-separated strings)
306 -add_filter('autoptimize_filter_js_exclude', function($excluded) {
307 - if (!is_string($excluded)) $excluded = '';
308 - return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js';
309 -});
310 -
311 -// ── SG Optimizer (SiteGround) ────────────────────────────────────────────────
312 -
313 -add_filter('sgo_js_minify_exclude', function($excluded) {
314 - if (!is_array($excluded)) $excluded = array();
315 - $excluded[] = 'chat-script.js';
316 - $excluded[] = 'floating-script.js';
317 - $excluded[] = 'jquery.min.js';
318 - return $excluded;
319 -});
320 -
321 -add_filter('sgo_javascript_combine_exclude', function($excluded) {
322 - if (!is_array($excluded)) $excluded = array();
323 - $excluded[] = 'chat-script.js';
324 - $excluded[] = 'floating-script.js';
325 - $excluded[] = 'jquery.min.js';
326 - return $excluded;
327 -});
328 -
329 -add_filter('sgo_js_async_exclude', function($excluded) {
330 - if (!is_array($excluded)) $excluded = array();
331 - $excluded[] = 'chat-script.js';
332 - $excluded[] = 'floating-script.js';
333 - $excluded[] = 'jquery.min.js';
334 - return $excluded;
335 -});
336 -
337 -// ── W3 Total Cache ───────────────────────────────────────────────────────────
338 -
339 -add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) {
340 - if (strpos($file, 'chat-script.js') !== false ||
341 - strpos($file, 'floating-script.js') !== false ||
342 - strpos($file, 'jquery.min.js') !== false ||
343 - strpos($file, 'jquery.js') !== false) {
344 - return false;
345 - }
346 - return $do_minify;
347 -}, 10, 3);
348 -
349 -// ── WP Super Cache ──────────────────────────────────────────────────────────
350 -
351 -add_filter('wpsc_rejected_uri', function($rejected) {
352 - if (!is_array($rejected)) $rejected = array();
353 - $rejected[] = 'wp-admin/admin-ajax.php';
354 - return $rejected;
355 -});
356 -
357 -// ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix)
358 -// Each cache plugin gets its own filter export so that visitors hitting an
359 -// edge-cached page never receive cached chat-AJAX responses. The chat send /
360 -// stream send / file upload all POST to /wp-admin/admin-ajax.php with
361 -// `action=mxchat_*`. Without these exports, a cache plugin can stale a response
362 -// and break the per-session nonce flow on the first message.
363 -
364 -// WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings.
365 -add_filter('rocket_cache_reject_uri', function($uris) {
366 - if (!is_array($uris)) $uris = array();
367 - $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*';
368 - return $uris;
369 -});
370 -
371 -// LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits
372 -// caching when the request matches our chat-AJAX pattern.
373 -add_filter('litespeed_cache_no_cache_for_request', function($no_cache) {
374 - if ($no_cache) return $no_cache;
375 - if (!empty($_SERVER['REQUEST_URI']) &&
376 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
377 - !empty($_REQUEST['action']) &&
378 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
379 - return true;
380 - }
381 - return $no_cache;
382 -});
383 -
384 -// W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when
385 -// the URI matches.
386 -add_filter('w3tc_pgcache_request_skip_uri', function($skip) {
387 - if ($skip) return $skip;
388 - if (!empty($_SERVER['REQUEST_URI']) &&
389 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
390 - !empty($_REQUEST['action']) &&
391 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
392 - return true;
393 - }
394 - return $skip;
395 -});
396 -
397 -// FlyingPress — `flying_press_cacheable` takes a boolean and is run per
398 -// request. Same pattern as LiteSpeed / W3TC.
399 -add_filter('flying_press_cacheable', function($cacheable) {
400 - if (!$cacheable) return $cacheable;
401 - if (!empty($_SERVER['REQUEST_URI']) &&
402 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
403 - !empty($_REQUEST['action']) &&
404 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
405 - return false;
406 - }
407 - return $cacheable;
408 -});
409 -
410 31 // Include classes with error handling
411 32 function mxchat_include_classes() {
412 33 $class_files = array(
413 - 'includes/class-mxchat-model-catalog.php',
414 - 'includes/class-mxchat-live-agent-schedule.php',
415 - 'includes/class-mxchat-tool-registry.php',
416 34 'includes/class-mxchat-integrator.php',
417 35 'includes/class-mxchat-admin.php',
418 36 'includes/class-mxchat-public.php',
419 37 'includes/class-mxchat-utils.php',
420 38 'includes/class-mxchat-user.php',
421 - 'includes/class-mxchat-privacy.php',
422 39 'includes/class-mxchat-meta-box.php',
423 - 'includes/class-mxchat-chunker.php',
40 + 'includes/pdf-parser/alt_autoload.php',
424 41 'includes/class-mxchat-word-handler.php',
425 - 'includes/class-mxchat-content-generator.php',
426 - 'includes/class-mxchat-cache-purge.php',
427 - 'includes/class-mxchat-editor-assistant.php',
428 - 'includes/class-rest-api.php',
429 42 'admin/class-ajax-handler.php',
430 43 'admin/class-pinecone-manager.php',
431 44 'admin/class-knowledge-manager.php'
432 45 );
@@ -438,62 +51,11 @@
438 51 } else {
439 52 //error_log('MxChat: Missing class file - ' . $file);
440 53 }
441 54 }
442 -
443 - // Register the native function-calling admin-post save handler (a41dee).
444 - if (class_exists('MxChat_Tool_Registry')) {
445 - MxChat_Tool_Registry::init();
446 - }
447 -
448 - // GDPR: register with WP's personal-data export/erase tools (b81e42).
449 - if (class_exists('MxChat_Privacy')) {
450 - MxChat_Privacy::init();
451 - }
452 -
453 - // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
454 - // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
455 - // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
456 - if (class_exists('MxChat_Editor_Assistant')) {
457 - MxChat_Editor_Assistant::init();
458 - }
459 -
460 - // Admin pages that aren't classes (procedural include).
461 - if (is_admin()) {
462 - $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
463 - if (file_exists($admin_api_page)) {
464 - require_once $admin_api_page;
465 - }
466 - // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
467 - // The require MUST live here (admin bootstrap) and not just inside
468 - // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
469 - // fire on admin-ajax.php requests, so the wizard's AJAX handlers
470 - // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
471 - // auto_graduate + the f7c7d4 dismiss handler) would never register.
472 - $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
473 - if (file_exists($admin_onboarding_page)) {
474 - require_once $admin_onboarding_page;
475 - }
476 - }
477 55 }
478 56
479 57 /**
480 - * Lazy-load the PDF parser library only when needed.
481 - * Avoids loading 44 files on every page request.
482 - */
483 -function mxchat_load_pdf_parser() {
484 - if (class_exists('\Smalot\PdfParser\Parser')) {
485 - return true;
486 - }
487 - $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
488 - if (file_exists($autoload_path)) {
489 - require_once $autoload_path;
490 - return true;
491 - }
492 - return false;
493 -}
494 -
495 -/**
496 58 * Create URL click tracking table
497 59 */
498 60 function mxchat_create_url_clicks_table() {
499 61 global $wpdb;
@@ -576,13 +138,12 @@
576 138
577 139 // Define all required columns and their types
578 140 $required_columns = [
579 141 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
580 - 'user_email' => 'VARCHAR(255) DEFAULT NULL',
142 + 'user_email' => 'VARCHAR(255) DEFAULT NULL',
581 143 'user_name' => 'VARCHAR(100) DEFAULT NULL',
582 144 'originating_page_url' => 'TEXT DEFAULT NULL',
583 - 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL',
584 - 'rag_context' => 'LONGTEXT DEFAULT NULL'
145 + 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL'
585 146 ];
586 147
587 148 // Get existing columns
588 149 $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
@@ -761,9 +322,9 @@
761 322
762 323 // Add index for bot_id
763 324 $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
764 325
765 - //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
326 + error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
766 327 }
767 328
768 329 // Mark migration as complete
769 330 update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
@@ -798,9 +359,9 @@
798 359
799 360 // Add index for better query performance
800 361 $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
801 362
802 - //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
363 + error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
803 364 }
804 365
805 366 // Mark migration as complete
806 367 update_option('mxchat_content_type_migration_version', '2.5.6');
@@ -806,33 +367,8 @@
806 367 update_option('mxchat_content_type_migration_version', '2.5.6');
807 368 }
808 369
809 370 /**
810 - * 3.2.4: Backfill the active embedding model option for installs that already
811 - * have KB content but no stamped model. The mismatch warning compares this
812 - * against the user's currently selected model — no per-row column needed.
813 - */
814 -function mxchat_backfill_active_embedding_model() {
815 - global $wpdb;
816 -
817 - if (get_option('mxchat_active_embedding_model', '') !== '') {
818 - return;
819 - }
820 -
821 - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
822 - if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
823 - return;
824 - }
825 -
826 - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
827 - if ($kb_count > 0) {
828 - $options = get_option('mxchat_options', array());
829 - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
830 - update_option('mxchat_active_embedding_model', $current_model, false);
831 - }
832 -}
833 -
834 -/**
835 371 * 2.5.2: Create queue processing tables for reliable background processing
836 372 */
837 373 function mxchat_create_queue_tables() {
838 374 global $wpdb;
@@ -880,58 +416,8 @@
880 416 //error_log("MxChat: Queue tables created/updated successfully");
881 417 }
882 418
883 419 /**
884 - * Create transcript translations table for persisting translations
885 - */
886 -function mxchat_create_translations_table() {
887 - global $wpdb;
888 - $charset_collate = $wpdb->get_charset_collate();
889 -
890 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
891 - $sql = "CREATE TABLE $table_name (
892 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
893 - session_id varchar(255) NOT NULL,
894 - language_code varchar(10) NOT NULL,
895 - translations longtext NOT NULL,
896 - created_at datetime NOT NULL,
897 - updated_at datetime NOT NULL,
898 - PRIMARY KEY (id),
899 - UNIQUE KEY session_lang (session_id, language_code),
900 - KEY session_id (session_id)
901 - ) $charset_collate;";
902 -
903 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
904 - dbDelta($sql);
905 -}
906 -
907 -/**
908 - * Create per-session satisfaction ratings table (v3.2.6)
909 - * Stores one 👍/👎 rating + optional feedback per chat session.
910 - */
911 -function mxchat_create_session_ratings_table() {
912 - global $wpdb;
913 - $charset_collate = $wpdb->get_charset_collate();
914 -
915 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
916 - $sql = "CREATE TABLE $table_name (
917 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
918 - session_id varchar(255) NOT NULL,
919 - bot_id varchar(50) NOT NULL DEFAULT 'default',
920 - rating_value tinyint(1) NOT NULL,
921 - rating_feedback text DEFAULT NULL,
922 - created_at datetime NOT NULL,
923 - PRIMARY KEY (id),
924 - UNIQUE KEY session_id (session_id),
925 - KEY bot_id (bot_id),
926 - KEY created_at (created_at)
927 - ) $charset_collate;";
928 -
929 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
930 - dbDelta($sql);
931 -}
932 -
933 -/**
934 420 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
935 421 * This fixes "url, source_url. The supplied values may be too long" errors
936 422 */
937 423 function mxchat_fix_url_column_size() {
@@ -954,118 +440,22 @@
954 440
955 441 /**
956 442 * Migrate deprecated AI models to their replacements
957 443 * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
958 - * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
959 - * Without utf8mb4, any bot response containing emojis silently fails to insert.
960 444 */
961 -function mxchat_migrate_transcripts_charset() {
962 - global $wpdb;
963 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
964 - $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
965 -}
966 -
967 -/**
968 - * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
969 - */
970 445 function mxchat_migrate_deprecated_models() {
971 446 $options = get_option('mxchat_options', array());
972 - $migrated = false;
973 - $migration_message = '';
974 -
975 - if (!isset($options['model'])) {
976 - return;
977 - }
978 -
979 - $current_model = $options['model'];
980 -
981 - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
982 - $deprecated_claude_models = array(
983 - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
984 - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
985 - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
986 - 'claude-3-opus-20240229', // Retired Jan 5, 2026
987 - 'claude-3-sonnet-20240229', // Legacy
988 - 'claude-3-haiku-20240307', // Legacy
989 - );
990 - if (in_array($current_model, $deprecated_claude_models, true)) {
991 - $options['model'] = 'claude-opus-4-6';
992 - $migrated = true;
993 - $migration_message = sprintf(
994 - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.',
995 - $current_model
996 - );
997 - }
998 -
999 - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
1000 - if ($current_model === 'claude-3-5-haiku-20241022') {
1001 - $options['model'] = 'claude-haiku-4-5-20251001';
1002 - $migrated = true;
1003 - $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.';
1004 - }
1005 -
1006 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.6 Sol.
1007 - // (Previous target gpt-5.1-chat-latest itself retires 2026-08-10 — never
1008 - // migrate onto a model that is already on a deprecation list.)
1009 - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1010 - $options['model'] = 'gpt-5.6-sol';
1011 - $migrated = true;
1012 - $migration_message = sprintf(
1013 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
1014 - $current_model
1015 - );
1016 - }
1017 -
1018 - // Migrate the gpt-5.x-chat-latest aliases OpenAI retires on August 10, 2026.
1019 - // Replacement per OpenAI's deprecations page: gpt-5.6-sol (plan e46b8f).
1020 - if (in_array($current_model, array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1021 - $options['model'] = 'gpt-5.6-sol';
1022 - $migrated = true;
1023 - $migration_message = sprintf(
1024 - '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.',
1025 - $current_model
1026 - );
1027 - }
1028 -
1029 - // The content generator has its own model option — same retirement applies.
1030 - if (isset($options['content_model'])
1031 - && in_array($options['content_model'], array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1032 - $old_content_model = $options['content_model'];
1033 - $options['content_model'] = 'gpt-5.6-sol';
1034 - $migrated = true;
1035 - $migration_message = trim($migration_message . ' ' . sprintf(
1036 - 'Your content generation model has also been updated from %s to GPT-5.6 Sol for the same OpenAI retirement.',
1037 - $old_content_model
1038 - ));
1039 - }
1040 -
1041 - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1042 - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1043 - $options['model'] = 'gpt-5-mini';
1044 - $migrated = true;
1045 - $migration_message = sprintf(
1046 - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
1047 - $current_model
1048 - );
1049 - }
1050 -
1051 - // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1052 - // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1053 - // request 400s). V4 Flash is DeepSeek's designated successor for the
1054 - // legacy deepseek-chat alias.
1055 - if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1056 - $options['model'] = 'deepseek-v4-flash';
1057 - $migrated = true;
1058 - $migration_message = sprintf(
1059 - 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1060 - $current_model
1061 - );
1062 - }
1063 -
1064 - if ($migrated) {
447 +
448 + // Check if model is set and is the deprecated Claude 3.5 Sonnet
449 + if (isset($options['model']) && $options['model'] === 'claude-3-5-sonnet-20241022') {
450 + // Update to Claude 3.7 Sonnet (the replacement model)
451 + $options['model'] = 'claude-3-7-sonnet-20250219';
1065 452 update_option('mxchat_options', $options);
453 +
454 + // Set a flag to show admin notice
1066 455 update_option('mxchat_model_migrated_notice', true);
1067 - update_option('mxchat_model_migration_message', $migration_message);
456 +
457 + //error_log('MxChat: Migrated deprecated Claude 3.5 Sonnet to Claude 3.7 Sonnet');
1068 458 }
1069 459 }
1070 460
1071 461 /**
@@ -1072,60 +462,20 @@
1072 462 * Show admin notice after model migration
1073 463 */
1074 464 function mxchat_show_migration_notice() {
1075 465 if (get_option('mxchat_model_migrated_notice')) {
1076 - $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
1077 466 ?>
1078 467 <div class="notice notice-info is-dismissible">
1079 468 <p>
1080 469 <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
1081 - <?php echo esc_html($migration_message); ?>
470 + <?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'); ?>
1082 471 </p>
1083 472 </div>
1084 473 <?php
1085 474 delete_option('mxchat_model_migrated_notice');
1086 - delete_option('mxchat_model_migration_message');
1087 475 }
1088 476 }
1089 477
1090 -/**
1091 - * Persistent admin notice when the provider rejected the configured model
1092 - * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1093 - * integrator whenever a chat request fails on a model-access error — including
1094 - * requests from anonymous visitors, which is the case that otherwise stays
1095 - * invisible to the site owner for weeks (plan e46b8f).
1096 - *
1097 - * Deleted after render so it re-arms on the next failed chat: the notice keeps
1098 - * reappearing until the model is fixed, then stops on its own.
1099 - */
1100 -function mxchat_show_model_access_notice() {
1101 - if (!current_user_can('manage_options')) {
1102 - return;
1103 - }
1104 - $notice = get_option('mxchat_model_access_notice');
1105 - if (!is_array($notice) || empty($notice['model'])) {
1106 - return;
1107 - }
1108 - $settings_url = admin_url('admin.php?page=mxchat-max');
1109 - ?>
1110 - <div class="notice notice-error is-dismissible">
1111 - <p>
1112 - <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1113 - <?php
1114 - printf(
1115 - /* translators: 1: model id, 2: provider name */
1116 - 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'),
1117 - esc_html($notice['model']),
1118 - esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1119 - );
1120 - ?>
1121 - <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1122 - </p>
1123 - </div>
1124 - <?php
1125 - delete_option('mxchat_model_access_notice');
1126 -}
1127 -
1128 478 function mxchat_activate() {
1129 479 global $wpdb;
1130 480 $charset_collate = $wpdb->get_charset_collate();
1131 481
@@ -1162,26 +512,13 @@
1162 512 enabled_bots LONGTEXT DEFAULT NULL,
1163 513 PRIMARY KEY (id)
1164 514 ) $charset_collate;";
1165 515
1166 - // Individual Intent Phrases Table - each phrase gets its own embedding vector
1167 - $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
1168 - $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table (
1169 - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1170 - intent_id BIGINT(20) UNSIGNED NOT NULL,
1171 - phrase TEXT NOT NULL,
1172 - embedding_vector LONGTEXT NOT NULL,
1173 - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1174 - PRIMARY KEY (id),
1175 - KEY intent_id (intent_id)
1176 - ) $charset_collate;";
1177 -
1178 516 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1179 517
1180 518 // Create other tables
1181 519 dbDelta($sql_system_prompt);
1182 520 dbDelta($sql_intents_table);
1183 - dbDelta($sql_intent_phrases_table);
1184 521
1185 522 // Create URL click tracking table
1186 523 mxchat_create_url_clicks_table();
1187 524
@@ -1190,14 +527,8 @@
1190 527
1191 528 // NEW 2.5.2: Create queue processing tables
1192 529 mxchat_create_queue_tables();
1193 530
1194 - // Create transcript translations table
1195 - mxchat_create_translations_table();
1196 -
1197 - // Create per-session satisfaction ratings table (v3.2.6)
1198 - mxchat_create_session_ratings_table();
1199 -
1200 531 // Ensure additional columns in system prompt table
1201 532 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1202 533 if (!empty($existing_system_columns)) {
1203 534 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1240,17 +571,13 @@
1240 571
1241 572 // Run migration for existing installations
1242 573 mxchat_migrate_pinecone_roles_add_bot_id();
1243 574
1244 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1245 - mxchat_backfill_active_embedding_model();
1246 -
1247 575 // Setup cron jobs
1248 576 mxchat_setup_cron_jobs();
1249 577
1250 - // Update version (stable base version — never the dev time()-suffixed one,
1251 - // or the check_for_update comparison would churn every request)
1252 - update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
578 + // Update version
579 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
1253 580
1254 581 //error_log("MxChat: Activation function completed");
1255 582 }
1256 583
@@ -1265,35 +592,28 @@
1265 592 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1266 593 // Set flag to use fallback system
1267 594 update_option('mxchat_use_fallback_rate_limits', true);
1268 595 update_option('mxchat_next_rate_limit_check', time() + 3600);
1269 - // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1270 - // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1271 - // execute (a server-side runner hitting wp-cron.php instead of loopback
1272 - // spawns) — scheduling still just writes the cron option. The old early
1273 - // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1274 - // site permanently lost the transcript cleanup event while the retention
1275 - // setting still claimed to be active.
596 + return;
597 + }
598 +
599 + // Schedule the rate limit reset cron job
600 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
601 +
602 + if ($result === false) {
603 + // Fallback if scheduling fails
604 + update_option('mxchat_use_fallback_rate_limits', true);
605 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1276 606 } else {
1277 - // Schedule the rate limit reset cron job
1278 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1279 -
1280 - if ($result === false) {
1281 - // Fallback if scheduling fails
1282 - update_option('mxchat_use_fallback_rate_limits', true);
1283 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1284 - } else {
1285 - // Clear fallback flags if cron scheduling succeeded
1286 - delete_option('mxchat_use_fallback_rate_limits');
1287 - }
607 + // Clear fallback flags if cron scheduling succeeded
608 + delete_option('mxchat_use_fallback_rate_limits');
1288 609 }
1289 -
1290 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
610 +
611 + // Schedule transcript cleanup if configured
1291 612 $transcript_options = get_option('mxchat_transcripts_options', array());
1292 613 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1293 - $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1294 -
1295 - if ($cleanup_interval !== 'never' || $custom_retention > 0) {
614 +
615 + if ($cleanup_interval !== 'never') {
1296 616 // Check if not already scheduled
1297 617 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1298 618 // Schedule to run daily at 3 AM
1299 619 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1330,25 +650,17 @@
1330 650 return;
1331 651 }
1332 652
1333 653 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1334 -
654 +
1335 655 if (time() >= $next_check) {
1336 - // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1337 - // plugins_loaded (before this init-priority-5 callback), so it's always set
1338 - // here. Constructing a second MxChat_Integrator just to call one method
1339 - // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1340 - // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1341 - // the request. Defensive construction only if the global is somehow unset.
1342 - // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1343 - // implementation of this same check — if either changes, change both.
1344 - global $mxchat_integrator;
1345 - $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1346 - ? $mxchat_integrator
1347 - : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1348 - if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1349 - $integrator->mxchat_reset_rate_limits();
1350 - update_option('mxchat_next_rate_limit_check', time() + 3600);
656 + // Only run reset if the MxChat_Integrator class exists
657 + if (class_exists('MxChat_Integrator')) {
658 + $integrator = new MxChat_Integrator();
659 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
660 + $integrator->mxchat_reset_rate_limits();
661 + update_option('mxchat_next_rate_limit_check', time() + 3600);
662 + }
1351 663 }
1352 664 }
1353 665 }
1354 666
@@ -1360,9 +672,9 @@
1360 672 global $wpdb;
1361 673
1362 674 try {
1363 675 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1364 - $plugin_version = MXCHAT_BASE_VERSION;
676 + $plugin_version = MXCHAT_VERSION;
1365 677
1366 678 // Always ensure critical tables exist (even if version matches)
1367 679 // This handles manual table deletion or fresh installs
1368 680 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1378,14 +690,11 @@
1378 690
1379 691 // Version-specific migrations
1380 692 if ($current_version !== $plugin_version) {
1381 693 //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
1382 -
694 +
1383 695 // Run live agent update BEFORE updating the stored version
1384 696 mxchat_handle_live_agent_update();
1385 -
1386 - // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
1387 - mxchat_handle_theme_migration_notice();
1388 697
1389 698 // Run role restriction migration for 2.4.1
1390 699 if (version_compare($current_version, '2.4.1', '<')) {
1391 700 mxchat_add_role_restriction_column();
@@ -1406,67 +715,9 @@
1406 715 mxchat_create_queue_tables();
1407 716 mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs
1408 717 //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2");
1409 718 }
1410 -
1411 - // 2.6.0: Ensure rag_context column exists for retrieved documents feature
1412 - if (version_compare($current_version, '2.6.0', '<')) {
1413 - $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1414 - mxchat_ensure_all_columns($chat_table);
1415 - //error_log("MxChat: rag_context column migration for 2.6.0");
1416 - }
1417 -
1418 - // 3.0.5: Migrate deprecated Gemini embedding model
1419 - if (version_compare($current_version, '3.0.5', '<')) {
1420 - mxchat_migrate_gemini_embedding_model();
1421 - }
1422 -
1423 - // 3.0.6: Migrate deprecated OpenAI and Claude models
1424 - if (version_compare($current_version, '3.0.6', '<')) {
1425 - mxchat_migrate_deprecated_models();
1426 - }
1427 -
1428 - // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1429 - if (version_compare($current_version, '3.1.2', '<')) {
1430 - mxchat_migrate_transcripts_charset();
1431 - }
1432 -
1433 - // 3.1.7: Clean up stale shared session email/name entries
1434 - if (version_compare($current_version, '3.1.7', '<')) {
1435 - delete_option('mxchat_email_null');
1436 - delete_option('mxchat_name_null');
1437 - }
1438 -
1439 - // 3.2.4: Backfill active embedding model option for the warning UI
1440 - // (replaces the per-row column tracking from 3.2.3, which was reverted)
1441 - if (version_compare($current_version, '3.2.4', '<')) {
1442 - mxchat_backfill_active_embedding_model();
1443 - }
1444 -
1445 - // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1446 - // were shut off at the vendor on 2026-07-24). The function is idempotent —
1447 - // it only rewrites models on its deprecation lists.
1448 - if (version_compare($current_version, '3.2.15', '<')) {
1449 - mxchat_migrate_deprecated_models();
1450 - }
1451 -
1452 - // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1453 - // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1454 - // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1455 - if (version_compare($current_version, '3.2.16', '<')) {
1456 - mxchat_migrate_deprecated_models();
1457 - }
1458 -
1459 - // 3.2.17: Credential options must not autoload (af2400) — the two
1460 - // Pinecone-secret-holding rows were in alloptions, i.e. read into
1461 - // memory on every request including anonymous page views. Idempotent.
1462 - // Also carry the import modal's remembered ACF→PDF checkbox state
1463 - // into the new install-level option (11720c).
1464 - if (version_compare($current_version, '3.2.17', '<')) {
1465 - mxchat_fix_credential_option_autoload();
1466 - mxchat_migrate_acf_pdf_extraction_option();
1467 - }
1468 -
719 +
1469 720 // Run full activation to ensure everything is up to date
1470 721 mxchat_activate();
1471 722
1472 723 // Run migration functions
@@ -1489,67 +740,8 @@
1489 740 }
1490 741 }
1491 742
1492 743 /**
1493 - * Credential options must never enter the autoloaded alloptions set.
1494 - * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1495 - * Pinecone API secret; mxchat_options already stores its keys with autoload
1496 - * off and these two must match it. The filter covers every future
1497 - * add_option()/update_option() that creates the row — Settings API saves
1498 - * through options.php and WP-CLI included — on WP 6.6+; older cores are
1499 - * covered by the explicit autoload arguments at the plugin's own write
1500 - * sites plus the one-time migration below.
1501 - */
1502 -add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1503 -function mxchat_credential_option_autoload_value($autoload, $option) {
1504 - if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1505 - return false;
1506 - }
1507 - return $autoload;
1508 -}
1509 -
1510 -/**
1511 - * One-time upgrade migration: flip the autoload flag on credential option
1512 - * rows that existing installs are already carrying autoloaded. Includes
1513 - * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1514 - * when that add-on is not installed, since missing rows simply don't match.
1515 - */
1516 -function mxchat_fix_credential_option_autoload() {
1517 - $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1518 - if (function_exists('wp_set_option_autoload_values')) {
1519 - wp_set_option_autoload_values(array_fill_keys($keys, false));
1520 - return;
1521 - }
1522 - // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1523 - global $wpdb;
1524 - $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1525 - $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1526 - wp_cache_delete('alloptions', 'options');
1527 - foreach ($keys as $key) {
1528 - wp_cache_delete($key, 'options');
1529 - }
1530 -}
1531 -
1532 -/**
1533 - * One-time carry of the import modal's remembered ACF→PDF checkbox state
1534 - * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1535 - * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1536 - * Fresh installs and installs that never touched the checkbox default OFF,
1537 - * matching the setting's own "recommended only if…" guidance.
1538 - */
1539 -function mxchat_migrate_acf_pdf_extraction_option() {
1540 - if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1541 - return; // already set — never overwrite an owner's choice
1542 - }
1543 - $mxchat_options = get_option('mxchat_options', array());
1544 - if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1545 - update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1546 - unset($mxchat_options['acf_pdf_extract_default']);
1547 - update_option('mxchat_options', $mxchat_options);
1548 - }
1549 -}
1550 -
1551 -/**
1552 744 * Ensure tables exist on every admin load for fresh installations
1553 745 * This is a safety net for cases where activation hook doesn't fire
1554 746 */
1555 747 function mxchat_ensure_tables_exist() {
@@ -1657,59 +849,31 @@
1657 849 function mxchat_handle_live_agent_update() {
1658 850 // Get the CURRENT stored version (before it gets updated)
1659 851 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1660 852 $new_version = '2.2.2';
1661 -
853 +
1662 854 // Only run this once for the update to 2.2.2
1663 855 $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
1664 -
856 +
1665 857 // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1666 858 if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1667 859 $options = get_option('mxchat_options', array());
1668 -
860 +
1669 861 // Check if live agent was previously enabled
1670 862 if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1671 863 // Disable live agent
1672 864 $options['live_agent_status'] = 'off';
1673 865 update_option('mxchat_options', $options);
1674 -
866 +
1675 867 // Set flag to show the notification banner
1676 868 update_option('mxchat_show_live_agent_disabled_notice', true);
1677 869 }
1678 -
870 +
1679 871 // Mark this update as handled
1680 872 update_option('mxchat_live_agent_update_2_2_2_handled', true);
1681 873 }
1682 874 }
1683 875
1684 -/**
1685 - * Handle theme migration notice for version 3.0.1
1686 - * Shows a dismissible notice to Pro users about migrating AI-generated themes
1687 - */
1688 -function mxchat_handle_theme_migration_notice() {
1689 - // Get the CURRENT stored version (before it gets updated)
1690 - $current_version = get_option('mxchat_plugin_version', '0.0.0');
1691 - $target_version = '3.0.1';
1692 -
1693 - // Only run this once for the update to 3.0.1
1694 - $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1695 -
1696 - // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1697 - if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1698 - // Check if Pro is activated - only show to Pro users
1699 - $license_status = get_option('mxchat_license_status', 'inactive');
1700 - $is_pro = ($license_status === 'active');
1701 -
1702 - if ($is_pro) {
1703 - // Set flag to show the theme migration notification banner
1704 - update_option('mxchat_show_theme_migration_notice', true);
1705 - }
1706 -
1707 - // Mark this update as handled (whether Pro or not)
1708 - update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1709 - }
1710 -}
1711 -
1712 876 // Initialize plugin safely
1713 877 function mxchat_init() {
1714 878 // Include all class files first
1715 879 mxchat_include_classes();
@@ -1724,9 +888,8 @@
1724 888 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1725 889
1726 890 // Add migration notice hook
1727 891 add_action('admin_notices', 'mxchat_show_migration_notice');
1728 - add_action('admin_notices', 'mxchat_show_model_access_notice');
1729 892
1730 893 // Initialize classes with error handling
1731 894 try {
1732 895 // Initialize admin classes
@@ -1742,32 +905,10 @@
1742 905 // Initialize meta box class
1743 906 if (class_exists('MxChat_Meta_Box')) {
1744 907 new MxChat_Meta_Box();
1745 908 }
1746 -
1747 909 }
1748 -
1749 - // Initialize content generator globally — it registers wp_head hook
1750 - // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1751 - if (class_exists('MxChat_Content_Generator')) {
1752 - new MxChat_Content_Generator();
1753 - }
1754 -
1755 - // Initialize cache purge globally — settings writes can happen on any
1756 - // request type (admin screens, admin-ajax autosave, wp-cli), and the
1757 - // deferred-purge cron event fires on front-end requests.
1758 - if (class_exists('MxChat_Cache_Purge')) {
1759 - MxChat_Cache_Purge::init();
1760 - }
1761 -
1762 - // Initialize REST API globally — endpoints must be registered on
1763 - // every request (admin and frontend) so they're reachable via /wp-json/.
1764 - // Endpoints are auth-gated and locked until the site owner generates
1765 - // a token in MxChat → API Access.
1766 - if (class_exists('MxChat_Rest_Api')) {
1767 - new MxChat_Rest_Api();
1768 - }
1769 -
910 +
1770 911 // Initialize public classes
1771 912 if (class_exists('MxChat_Public')) {
1772 913 $mxchat_public = new MxChat_Public();
1773 914 }
@@ -1811,57 +952,10 @@
1811 952 $checked = true;
1812 953
1813 954 mxchat_migrate_pinecone_roles_add_bot_id();
1814 955 mxchat_migrate_add_content_type_column();
1815 - mxchat_migrate_add_translations_table();
1816 - mxchat_migrate_add_session_ratings_table();
1817 956 }
1818 957
1819 -/**
1820 - * Migration: Create per-session satisfaction ratings table (v3.2.6)
1821 - * For users upgrading from versions before 3.2.6
1822 - */
1823 -function mxchat_migrate_add_session_ratings_table() {
1824 - $migration_key = 'mxchat_session_ratings_table_created';
1825 - if (get_option($migration_key)) {
1826 - return;
1827 - }
1828 - mxchat_create_session_ratings_table();
1829 - update_option($migration_key, '3.2.6');
1830 -}
1831 -
1832 -/**
1833 - * Migration: Create transcript translations table (v3.0.4)
1834 - * For users upgrading from versions before 3.0.4
1835 - */
1836 -function mxchat_migrate_add_translations_table() {
1837 - $migration_key = 'mxchat_translations_table_created';
1838 -
1839 - // Check if migration already ran
1840 - if (get_option($migration_key)) {
1841 - return;
1842 - }
1843 -
1844 - // Create the translations table
1845 - mxchat_create_translations_table();
1846 -
1847 - // Mark migration as complete
1848 - update_option($migration_key, '3.0.4');
1849 -}
1850 -
1851 -/**
1852 - * Migration: Update deprecated Gemini embedding model (v3.0.5)
1853 - * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
1854 - */
1855 -function mxchat_migrate_gemini_embedding_model() {
1856 - $options = get_option('mxchat_options', array());
1857 -
1858 - if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
1859 - $options['embedding_model'] = 'gemini-embedding-001';
1860 - update_option('mxchat_options', $options);
1861 - }
1862 -}
1863 -
1864 958 // Register activation hook
1865 959 register_activation_hook(__FILE__, 'mxchat_activate');
1866 960
1867 961 // Add cron schedule
@@ -1873,67 +967,5 @@
1873 967 return $schedules;
1874 968 });
1875 969
1876 970 // Register deactivation hook
1877 -register_deactivation_hook(__FILE__, 'mxchat_deactivate');
1878 -
1879 -/**
1880 - * Per-session satisfaction rating: AJAX save handler (v3.2.6).
1881 - * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
1882 - * session_id makes this naturally idempotent — only the first rating per
1883 - * session is stored; duplicate POSTs are silent no-ops.
1884 - */
1885 -function mxchat_save_session_rating() {
1886 - global $wpdb;
1887 -
1888 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1889 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
1890 - $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
1891 - $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
1892 -
1893 - if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
1894 - wp_send_json_error(array('message' => 'invalid_input'), 400);
1895 - }
1896 -
1897 - if (strlen($feedback) > 1000) {
1898 - $feedback = substr($feedback, 0, 1000);
1899 - }
1900 -
1901 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
1902 - $existing = $wpdb->get_var($wpdb->prepare(
1903 - "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
1904 - $session_id
1905 - ));
1906 -
1907 - if ($existing) {
1908 - if ($feedback !== '') {
1909 - $wpdb->update(
1910 - $table_name,
1911 - array('rating_feedback' => $feedback),
1912 - array('id' => (int) $existing),
1913 - array('%s'),
1914 - array('%d')
1915 - );
1916 - }
1917 - wp_send_json_success(array('updated' => true));
1918 - }
1919 -
1920 - $inserted = $wpdb->insert(
1921 - $table_name,
1922 - array(
1923 - 'session_id' => $session_id,
1924 - 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
1925 - 'rating_value' => $rating_raw,
1926 - 'rating_feedback' => $feedback !== '' ? $feedback : null,
1927 - 'created_at' => current_time('mysql'),
1928 - ),
1929 - array('%s', '%s', '%d', '%s', '%s')
1930 - );
1931 -
1932 - if ($inserted === false) {
1933 - wp_send_json_error(array('message' => 'db_insert_failed'), 500);
1934 - }
1935 -
1936 - wp_send_json_success(array('saved' => true));
1937 -}
1938 -add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
1939 -add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');
971 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');