PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.4.5
MxChat – AI Chatbot & Content Generation for WordPress v2.4.5
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | mxchat-basic.php +74 -1165 3.2.152.4.5 View file →
@@ -1,10 +1,9 @@
1 1 <?php
2 2 /**
3 3 * Plugin Name: MxChat
4 - * Plugin URI: https://mxchat.ai/
5 4 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
6 - * Version: 3.2.15
5 + * Version: 2.4.5
7 6 * Author: MxChat
8 7 * Author URI: https://mxchat.ai
9 8 * License: GPLv2 or later
10 9 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -15,405 +14,19 @@
15 14 if (!defined('ABSPATH')) {
16 15 exit; // Exit if accessed directly.
17 16 }
18 17
18 +// Define plugin version constant for asset versioning
19 +define('MXCHAT_VERSION', '2.4.5');
19 20
20 -if (!defined('MXCHAT_DEV_MODE')) {
21 - define('MXCHAT_DEV_MODE', false);
22 -}
23 -
24 -if (!defined('MXCHAT_VERSION')) {
25 - $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);
39 -}
40 -
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 21 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');
22 + load_plugin_textdomain('mxchat', false, dirname(plugin_basename(__FILE__)) . '/languages');
73 23 }
74 -add_action('init', 'mxchat_load_textdomain');
24 +add_action('plugins_loaded', 'mxchat_load_textdomain');
75 25
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 26 // Include classes with error handling
411 27 function mxchat_include_classes() {
412 28 $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 29 'includes/class-mxchat-integrator.php',
417 30 'includes/class-mxchat-admin.php',
418 31 'includes/class-mxchat-public.php',
419 32 'includes/class-mxchat-utils.php',
@@ -418,14 +31,10 @@
418 31 'includes/class-mxchat-public.php',
419 32 'includes/class-mxchat-utils.php',
420 33 'includes/class-mxchat-user.php',
421 34 'includes/class-mxchat-meta-box.php',
422 - 'includes/class-mxchat-chunker.php',
35 + 'includes/pdf-parser/alt_autoload.php',
423 36 'includes/class-mxchat-word-handler.php',
424 - 'includes/class-mxchat-content-generator.php',
425 - 'includes/class-mxchat-cache-purge.php',
426 - 'includes/class-mxchat-editor-assistant.php',
427 - 'includes/class-rest-api.php',
428 37 'admin/class-ajax-handler.php',
429 38 'admin/class-pinecone-manager.php',
430 39 'admin/class-knowledge-manager.php'
431 40 );
@@ -437,57 +46,11 @@
437 46 } else {
438 47 //error_log('MxChat: Missing class file - ' . $file);
439 48 }
440 49 }
441 -
442 - // Register the native function-calling admin-post save handler (a41dee).
443 - if (class_exists('MxChat_Tool_Registry')) {
444 - MxChat_Tool_Registry::init();
445 - }
446 -
447 - // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
448 - // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
449 - // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
450 - if (class_exists('MxChat_Editor_Assistant')) {
451 - MxChat_Editor_Assistant::init();
452 - }
453 -
454 - // Admin pages that aren't classes (procedural include).
455 - if (is_admin()) {
456 - $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
457 - if (file_exists($admin_api_page)) {
458 - require_once $admin_api_page;
459 - }
460 - // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
461 - // The require MUST live here (admin bootstrap) and not just inside
462 - // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
463 - // fire on admin-ajax.php requests, so the wizard's AJAX handlers
464 - // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
465 - // auto_graduate + the f7c7d4 dismiss handler) would never register.
466 - $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
467 - if (file_exists($admin_onboarding_page)) {
468 - require_once $admin_onboarding_page;
469 - }
470 - }
471 50 }
472 51
473 52 /**
474 - * Lazy-load the PDF parser library only when needed.
475 - * Avoids loading 44 files on every page request.
476 - */
477 -function mxchat_load_pdf_parser() {
478 - if (class_exists('\Smalot\PdfParser\Parser')) {
479 - return true;
480 - }
481 - $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
482 - if (file_exists($autoload_path)) {
483 - require_once $autoload_path;
484 - return true;
485 - }
486 - return false;
487 -}
488 -
489 -/**
490 53 * Create URL click tracking table
491 54 */
492 55 function mxchat_create_url_clicks_table() {
493 56 global $wpdb;
@@ -570,13 +133,12 @@
570 133
571 134 // Define all required columns and their types
572 135 $required_columns = [
573 136 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
574 - 'user_email' => 'VARCHAR(255) DEFAULT NULL',
137 + 'user_email' => 'VARCHAR(255) DEFAULT NULL',
575 138 'user_name' => 'VARCHAR(100) DEFAULT NULL',
576 139 'originating_page_url' => 'TEXT DEFAULT NULL',
577 - 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL',
578 - 'rag_context' => 'LONGTEXT DEFAULT NULL'
140 + 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL'
579 141 ];
580 142
581 143 // Get existing columns
582 144 $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
@@ -647,9 +209,9 @@
647 209 }
648 210 }
649 211
650 212 /**
651 - * Add enabled_bots column to intents table for multi-bot action filtering
213 + * NEW: Add enabled_bots column to intents table for multi-bot action filtering
652 214 */
653 215 function mxchat_add_enabled_bots_column() {
654 216 global $wpdb;
655 217 $table_name = $wpdb->prefix . 'mxchat_intents';
@@ -696,367 +258,31 @@
696 258 }
697 259 }
698 260
699 261 /**
700 - * Create Pinecone role restrictions table with multi-bot support
262 + * Create Pinecone role restrictions table
701 263 */
702 264 function mxchat_create_pinecone_roles_table() {
703 265 global $wpdb;
704 -
266 +
705 267 $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
706 268 $charset_collate = $wpdb->get_charset_collate();
707 -
269 +
708 270 $sql = "CREATE TABLE $table_name (
709 271 id mediumint(9) NOT NULL AUTO_INCREMENT,
710 272 vector_id varchar(255) NOT NULL,
711 - bot_id varchar(50) NOT NULL DEFAULT 'default',
712 273 source_url text,
713 274 role_restriction varchar(50) DEFAULT 'public',
714 275 updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
715 276 PRIMARY KEY (id),
716 - UNIQUE KEY vector_bot (vector_id, bot_id),
717 - KEY role_restriction (role_restriction),
718 - KEY bot_id (bot_id)
277 + UNIQUE KEY vector_id (vector_id),
278 + KEY role_restriction (role_restriction)
719 279 ) $charset_collate;";
720 -
721 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
722 - dbDelta($sql);
723 -}
724 -
725 -/**
726 - * Add bot_id column to mxchat_pinecone_roles table for multi-bot support
727 - * This migration runs once to update existing installations
728 - */
729 -function mxchat_migrate_pinecone_roles_add_bot_id() {
730 - global $wpdb;
731 -
732 - // Check if migration already ran
733 - $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0');
734 - if (version_compare($migration_version, '2.5.2', '>=')) {
735 - return; // Already migrated
736 - }
737 -
738 - $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
739 -
740 - // Check if table exists
741 - if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
742 - return; // Table doesn't exist yet
743 - }
744 -
745 - // Check if bot_id column already exists
746 - $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'");
747 -
748 - if (empty($column_exists)) {
749 - // Add bot_id column
750 - $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id");
751 -
752 - // Update the unique key to include bot_id
753 - $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id");
754 - $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)");
755 -
756 - // Add index for bot_id
757 - $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
758 -
759 - //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
760 - }
761 -
762 - // Mark migration as complete
763 - update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
764 -}
765 -
766 -/**
767 - * 2.5.6: Add content_type column to mxchat_system_prompt_content table
768 - * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.)
769 - */
770 -function mxchat_migrate_add_content_type_column() {
771 - global $wpdb;
772 -
773 - // Check if migration already ran
774 - $migration_version = get_option('mxchat_content_type_migration_version', '0');
775 - if (version_compare($migration_version, '2.5.6', '>=')) {
776 - return;
777 - }
778 -
779 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
780 -
781 - // Check if table exists
782 - if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
783 - return;
784 - }
785 -
786 - // Check if content_type column already exists
787 - $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'");
788 -
789 - if (empty($column_exists)) {
790 - // Add content_type column with default value 'content' for backwards compatibility
791 - $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction");
792 -
793 - // Add index for better query performance
794 - $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
795 -
796 - //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
797 - }
798 -
799 - // Mark migration as complete
800 - update_option('mxchat_content_type_migration_version', '2.5.6');
801 -}
802 -
803 -/**
804 - * 3.2.4: Backfill the active embedding model option for installs that already
805 - * have KB content but no stamped model. The mismatch warning compares this
806 - * against the user's currently selected model — no per-row column needed.
807 - */
808 -function mxchat_backfill_active_embedding_model() {
809 - global $wpdb;
810 -
811 - if (get_option('mxchat_active_embedding_model', '') !== '') {
812 - return;
813 - }
814 -
815 - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
816 - if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
817 - return;
818 - }
819 -
820 - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
821 - if ($kb_count > 0) {
822 - $options = get_option('mxchat_options', array());
823 - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
824 - update_option('mxchat_active_embedding_model', $current_model, false);
825 - }
826 -}
827 -
828 -/**
829 - * 2.5.2: Create queue processing tables for reliable background processing
830 - */
831 -function mxchat_create_queue_tables() {
832 - global $wpdb;
833 - $charset_collate = $wpdb->get_charset_collate();
834 280
835 - // Main queue table
836 - $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
837 - $sql_queue = "CREATE TABLE $queue_table (
838 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
839 - queue_id varchar(64) NOT NULL,
840 - item_type varchar(20) NOT NULL,
841 - item_data longtext NOT NULL,
842 - status varchar(20) NOT NULL DEFAULT 'pending',
843 - bot_id varchar(50) NOT NULL DEFAULT 'default',
844 - priority int(11) NOT NULL DEFAULT 0,
845 - attempts int(11) NOT NULL DEFAULT 0,
846 - max_attempts int(11) NOT NULL DEFAULT 3,
847 - error_message text DEFAULT NULL,
848 - created_at datetime NOT NULL,
849 - started_at datetime DEFAULT NULL,
850 - completed_at datetime DEFAULT NULL,
851 - PRIMARY KEY (id),
852 - KEY queue_id (queue_id),
853 - KEY status (status),
854 - KEY item_type (item_type),
855 - KEY priority (priority)
856 - ) $charset_collate;";
857 -
858 - // Queue metadata table
859 - $meta_table = $wpdb->prefix . 'mxchat_queue_meta';
860 - $sql_meta = "CREATE TABLE $meta_table (
861 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
862 - queue_id varchar(64) NOT NULL,
863 - meta_key varchar(255) NOT NULL,
864 - meta_value longtext,
865 - PRIMARY KEY (id),
866 - KEY queue_id (queue_id),
867 - KEY meta_key (meta_key)
868 - ) $charset_collate;";
869 -
870 281 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
871 - dbDelta($sql_queue);
872 - dbDelta($sql_meta);
873 -
874 - //error_log("MxChat: Queue tables created/updated successfully");
875 -}
876 -
877 -/**
878 - * Create transcript translations table for persisting translations
879 - */
880 -function mxchat_create_translations_table() {
881 - global $wpdb;
882 - $charset_collate = $wpdb->get_charset_collate();
883 -
884 - $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
885 - $sql = "CREATE TABLE $table_name (
886 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
887 - session_id varchar(255) NOT NULL,
888 - language_code varchar(10) NOT NULL,
889 - translations longtext NOT NULL,
890 - created_at datetime NOT NULL,
891 - updated_at datetime NOT NULL,
892 - PRIMARY KEY (id),
893 - UNIQUE KEY session_lang (session_id, language_code),
894 - KEY session_id (session_id)
895 - ) $charset_collate;";
896 -
897 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
898 282 dbDelta($sql);
899 283 }
900 284
901 -/**
902 - * Create per-session satisfaction ratings table (v3.2.6)
903 - * Stores one 👍/👎 rating + optional feedback per chat session.
904 - */
905 -function mxchat_create_session_ratings_table() {
906 - global $wpdb;
907 - $charset_collate = $wpdb->get_charset_collate();
908 -
909 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
910 - $sql = "CREATE TABLE $table_name (
911 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
912 - session_id varchar(255) NOT NULL,
913 - bot_id varchar(50) NOT NULL DEFAULT 'default',
914 - rating_value tinyint(1) NOT NULL,
915 - rating_feedback text DEFAULT NULL,
916 - created_at datetime NOT NULL,
917 - PRIMARY KEY (id),
918 - UNIQUE KEY session_id (session_id),
919 - KEY bot_id (bot_id),
920 - KEY created_at (created_at)
921 - ) $charset_collate;";
922 -
923 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
924 - dbDelta($sql);
925 -}
926 -
927 -/**
928 - * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
929 - * This fixes "url, source_url. The supplied values may be too long" errors
930 - */
931 -function mxchat_fix_url_column_size() {
932 - global $wpdb;
933 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
934 -
935 - // Check if table exists
936 - $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
937 - if (!$table_exists) {
938 - return;
939 - }
940 -
941 - // Change url and source_url from VARCHAR to TEXT to handle long URLs
942 - // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.)
943 - $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT");
944 - $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT");
945 -
946 - //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support");
947 -}
948 -
949 -/**
950 - * Migrate deprecated AI models to their replacements
951 - * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
952 - * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
953 - * Without utf8mb4, any bot response containing emojis silently fails to insert.
954 - */
955 -function mxchat_migrate_transcripts_charset() {
956 - global $wpdb;
957 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
958 - $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
959 -}
960 -
961 -/**
962 - * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
963 - */
964 -function mxchat_migrate_deprecated_models() {
965 - $options = get_option('mxchat_options', array());
966 - $migrated = false;
967 - $migration_message = '';
968 -
969 - if (!isset($options['model'])) {
970 - return;
971 - }
972 -
973 - $current_model = $options['model'];
974 -
975 - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
976 - $deprecated_claude_models = array(
977 - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
978 - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
979 - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
980 - 'claude-3-opus-20240229', // Retired Jan 5, 2026
981 - 'claude-3-sonnet-20240229', // Legacy
982 - 'claude-3-haiku-20240307', // Legacy
983 - );
984 - if (in_array($current_model, $deprecated_claude_models, true)) {
985 - $options['model'] = 'claude-opus-4-6';
986 - $migrated = true;
987 - $migration_message = sprintf(
988 - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.',
989 - $current_model
990 - );
991 - }
992 -
993 - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
994 - if ($current_model === 'claude-3-5-haiku-20241022') {
995 - $options['model'] = 'claude-haiku-4-5-20251001';
996 - $migrated = true;
997 - $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.';
998 - }
999 -
1000 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
1001 - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1002 - $options['model'] = 'gpt-5.1-chat-latest';
1003 - $migrated = true;
1004 - $migration_message = sprintf(
1005 - 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.',
1006 - $current_model
1007 - );
1008 - }
1009 -
1010 - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1011 - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1012 - $options['model'] = 'gpt-5-mini';
1013 - $migrated = true;
1014 - $migration_message = sprintf(
1015 - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
1016 - $current_model
1017 - );
1018 - }
1019 -
1020 - // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1021 - // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1022 - // request 400s). V4 Flash is DeepSeek's designated successor for the
1023 - // legacy deepseek-chat alias.
1024 - if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1025 - $options['model'] = 'deepseek-v4-flash';
1026 - $migrated = true;
1027 - $migration_message = sprintf(
1028 - 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1029 - $current_model
1030 - );
1031 - }
1032 -
1033 - if ($migrated) {
1034 - update_option('mxchat_options', $options);
1035 - update_option('mxchat_model_migrated_notice', true);
1036 - update_option('mxchat_model_migration_message', $migration_message);
1037 - }
1038 -}
1039 -
1040 -/**
1041 - * Show admin notice after model migration
1042 - */
1043 -function mxchat_show_migration_notice() {
1044 - if (get_option('mxchat_model_migrated_notice')) {
1045 - $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
1046 - ?>
1047 - <div class="notice notice-info is-dismissible">
1048 - <p>
1049 - <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
1050 - <?php echo esc_html($migration_message); ?>
1051 - </p>
1052 - </div>
1053 - <?php
1054 - delete_option('mxchat_model_migrated_notice');
1055 - delete_option('mxchat_model_migration_message');
1056 - }
1057 -}
1058 -
1059 285 function mxchat_activate() {
1060 286 global $wpdb;
1061 287 $charset_collate = $wpdb->get_charset_collate();
1062 288
@@ -1064,21 +290,19 @@
1064 290
1065 291 // Create chat transcripts table with improved function
1066 292 mxchat_create_chat_transcripts_table();
1067 293
1068 - // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
294 + // System Prompt Content Table
1069 295 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1070 296 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1071 297 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
1072 - url TEXT NOT NULL,
298 + url VARCHAR(255) NOT NULL,
1073 299 article_content LONGTEXT NOT NULL,
1074 300 embedding_vector LONGTEXT,
1075 - source_url TEXT DEFAULT NULL,
301 + source_url VARCHAR(255) DEFAULT NULL,
1076 302 role_restriction VARCHAR(50) DEFAULT 'public',
1077 - content_type VARCHAR(50) DEFAULT 'content',
1078 303 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1079 - PRIMARY KEY (id),
1080 - KEY content_type (content_type)
304 + PRIMARY KEY (id)
1081 305 ) $charset_collate;";
1082 306
1083 307 // Intents Table - NOW INCLUDES enabled_bots column from the start
1084 308 $intents_table = $wpdb->prefix . 'mxchat_intents';
@@ -1093,42 +317,20 @@
1093 317 enabled_bots LONGTEXT DEFAULT NULL,
1094 318 PRIMARY KEY (id)
1095 319 ) $charset_collate;";
1096 320
1097 - // Individual Intent Phrases Table - each phrase gets its own embedding vector
1098 - $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
1099 - $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table (
1100 - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1101 - intent_id BIGINT(20) UNSIGNED NOT NULL,
1102 - phrase TEXT NOT NULL,
1103 - embedding_vector LONGTEXT NOT NULL,
1104 - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1105 - PRIMARY KEY (id),
1106 - KEY intent_id (intent_id)
1107 - ) $charset_collate;";
1108 -
1109 321 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1110 322
1111 323 // Create other tables
1112 324 dbDelta($sql_system_prompt);
1113 325 dbDelta($sql_intents_table);
1114 - dbDelta($sql_intent_phrases_table);
1115 326
1116 327 // Create URL click tracking table
1117 328 mxchat_create_url_clicks_table();
1118 329
1119 - // Create Pinecone roles table
330 + //Create Pinecone roles table
1120 331 mxchat_create_pinecone_roles_table();
1121 -
1122 - // NEW 2.5.2: Create queue processing tables
1123 - mxchat_create_queue_tables();
1124 332
1125 - // Create transcript translations table
1126 - mxchat_create_translations_table();
1127 -
1128 - // Create per-session satisfaction ratings table (v3.2.6)
1129 - mxchat_create_session_ratings_table();
1130 -
1131 333 // Ensure additional columns in system prompt table
1132 334 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1133 335 if (!empty($existing_system_columns)) {
1134 336 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1136,9 +338,9 @@
1136 338 if (!in_array('embedding_vector', $existing_system_column_names)) {
1137 339 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT");
1138 340 }
1139 341 if (!in_array('source_url', $existing_system_column_names)) {
1140 - $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL");
342 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url VARCHAR(255) DEFAULT NULL");
1141 343 }
1142 344 if (!in_array('role_restriction', $existing_system_column_names)) {
1143 345 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
1144 346 }
@@ -1155,9 +357,9 @@
1155 357 if (!in_array('enabled', $existing_intent_column_names)) {
1156 358 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
1157 359 }
1158 360
1159 - // Ensure enabled_bots column exists for existing installations
361 + // NEW: Ensure enabled_bots column exists for existing installations
1160 362 if (!in_array('enabled_bots', $existing_intent_column_names)) {
1161 363 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled");
1162 364
1163 365 // Set existing actions to work with default bot
@@ -1168,21 +370,14 @@
1168 370 ));
1169 371 }
1170 372 }
1171 373
1172 - // Run migration for existing installations
1173 - mxchat_migrate_pinecone_roles_add_bot_id();
1174 -
1175 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1176 - mxchat_backfill_active_embedding_model();
1177 -
1178 374 // Setup cron jobs
1179 375 mxchat_setup_cron_jobs();
1180 376
1181 - // Update version (stable base version — never the dev time()-suffixed one,
1182 - // or the check_for_update comparison would churn every request)
1183 - update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
1184 -
377 + // Update version
378 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
379 +
1185 380 //error_log("MxChat: Activation function completed");
1186 381 }
1187 382
1188 383 /**
@@ -1196,42 +391,22 @@
1196 391 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1197 392 // Set flag to use fallback system
1198 393 update_option('mxchat_use_fallback_rate_limits', true);
1199 394 update_option('mxchat_next_rate_limit_check', time() + 3600);
1200 - // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1201 - // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1202 - // execute (a server-side runner hitting wp-cron.php instead of loopback
1203 - // spawns) — scheduling still just writes the cron option. The old early
1204 - // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1205 - // site permanently lost the transcript cleanup event while the retention
1206 - // setting still claimed to be active.
395 + return;
396 + }
397 +
398 + // Schedule the rate limit reset cron job
399 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
400 +
401 + if ($result === false) {
402 + // Fallback if scheduling fails
403 + update_option('mxchat_use_fallback_rate_limits', true);
404 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1207 405 } else {
1208 - // Schedule the rate limit reset cron job
1209 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1210 -
1211 - if ($result === false) {
1212 - // Fallback if scheduling fails
1213 - update_option('mxchat_use_fallback_rate_limits', true);
1214 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1215 - } else {
1216 - // Clear fallback flags if cron scheduling succeeded
1217 - delete_option('mxchat_use_fallback_rate_limits');
1218 - }
406 + // Clear fallback flags if cron scheduling succeeded
407 + delete_option('mxchat_use_fallback_rate_limits');
1219 408 }
1220 -
1221 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
1222 - $transcript_options = get_option('mxchat_transcripts_options', array());
1223 - $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1224 - $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1225 -
1226 - if ($cleanup_interval !== 'never' || $custom_retention > 0) {
1227 - // Check if not already scheduled
1228 - if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1229 - // Schedule to run daily at 3 AM
1230 - $next_run = strtotime('tomorrow 3:00 AM');
1231 - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1232 - }
1233 - }
1234 409 }
1235 410
1236 411 /**
1237 412 * Clean up on plugin deactivation
@@ -1238,18 +413,13 @@
1238 413 */
1239 414 function mxchat_deactivate() {
1240 415 // Clear scheduled cron jobs
1241 416 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1242 - wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1243 - wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1244 417
1245 418 // Clear fallback options
1246 419 delete_option('mxchat_use_fallback_rate_limits');
1247 420 delete_option('mxchat_next_rate_limit_check');
1248 421 delete_option('mxchat_fallback_check_interval');
1249 -
1250 - // NOTE: We do NOT delete queue tables on deactivation
1251 - // This preserves data if user accidentally deactivates the plugin
1252 422 }
1253 423
1254 424 /**
1255 425 * Check if fallback rate limit cleanup is needed
@@ -1261,127 +431,49 @@
1261 431 return;
1262 432 }
1263 433
1264 434 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1265 -
435 +
1266 436 if (time() >= $next_check) {
1267 - // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1268 - // plugins_loaded (before this init-priority-5 callback), so it's always set
1269 - // here. Constructing a second MxChat_Integrator just to call one method
1270 - // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1271 - // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1272 - // the request. Defensive construction only if the global is somehow unset.
1273 - // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1274 - // implementation of this same check — if either changes, change both.
1275 - global $mxchat_integrator;
1276 - $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1277 - ? $mxchat_integrator
1278 - : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1279 - if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1280 - $integrator->mxchat_reset_rate_limits();
1281 - update_option('mxchat_next_rate_limit_check', time() + 3600);
437 + // Only run reset if the MxChat_Integrator class exists
438 + if (class_exists('MxChat_Integrator')) {
439 + $integrator = new MxChat_Integrator();
440 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
441 + $integrator->mxchat_reset_rate_limits();
442 + update_option('mxchat_next_rate_limit_check', time() + 3600);
443 + }
1282 444 }
1283 445 }
1284 446 }
1285 447
1286 448 /**
1287 - * Robust update checking with role restriction migration, model deprecation, and queue tables
1288 - * CRITICAL: This runs on EVERY page load to ensure tables exist
449 + * Robust update checking with role restriction migration
1289 450 */
1290 451 function mxchat_check_for_update() {
1291 - global $wpdb;
452 + global $wpdb; // CRITICAL: Declare this at the top
1292 453
1293 454 try {
1294 455 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1295 - $plugin_version = MXCHAT_BASE_VERSION;
456 + $plugin_version = MXCHAT_VERSION;
1296 457
1297 - // Always ensure critical tables exist (even if version matches)
1298 - // This handles manual table deletion or fresh installs
1299 - $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1300 - $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1301 -
1302 - $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1303 - $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1304 -
1305 - if (!$chat_exists || !$queue_exists) {
1306 - //error_log("MxChat: Critical tables missing, running activation");
1307 - mxchat_activate();
1308 - }
1309 -
1310 - // Version-specific migrations
458 + // Always run activation to ensure tables exist (safe for existing installations)
1311 459 if ($current_version !== $plugin_version) {
1312 460 //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
1313 -
461 +
1314 462 // Run live agent update BEFORE updating the stored version
1315 463 mxchat_handle_live_agent_update();
1316 -
1317 - // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
1318 - mxchat_handle_theme_migration_notice();
1319 464
1320 - // Run role restriction migration for 2.4.1
465 + //Run role restriction migration for 2.4.1
1321 466 if (version_compare($current_version, '2.4.1', '<')) {
1322 467 mxchat_add_role_restriction_column();
1323 468 }
1324 469
1325 - // Run enabled_bots column migration for 2.4.4
470 + // NEW: Run enabled_bots column migration for 2.4.4
1326 471 if (version_compare($current_version, '2.4.4', '<')) {
1327 472 mxchat_add_enabled_bots_column();
1328 473 }
1329 474
1330 - // Run model migration for 2.5.1 (Claude deprecation)
1331 - if (version_compare($current_version, '2.5.1', '<')) {
1332 - mxchat_migrate_deprecated_models();
1333 - }
1334 -
1335 - // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2
1336 - if (version_compare($current_version, '2.5.2', '<')) {
1337 - mxchat_create_queue_tables();
1338 - mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs
1339 - //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2");
1340 - }
1341 -
1342 - // 2.6.0: Ensure rag_context column exists for retrieved documents feature
1343 - if (version_compare($current_version, '2.6.0', '<')) {
1344 - $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1345 - mxchat_ensure_all_columns($chat_table);
1346 - //error_log("MxChat: rag_context column migration for 2.6.0");
1347 - }
1348 -
1349 - // 3.0.5: Migrate deprecated Gemini embedding model
1350 - if (version_compare($current_version, '3.0.5', '<')) {
1351 - mxchat_migrate_gemini_embedding_model();
1352 - }
1353 -
1354 - // 3.0.6: Migrate deprecated OpenAI and Claude models
1355 - if (version_compare($current_version, '3.0.6', '<')) {
1356 - mxchat_migrate_deprecated_models();
1357 - }
1358 -
1359 - // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1360 - if (version_compare($current_version, '3.1.2', '<')) {
1361 - mxchat_migrate_transcripts_charset();
1362 - }
1363 -
1364 - // 3.1.7: Clean up stale shared session email/name entries
1365 - if (version_compare($current_version, '3.1.7', '<')) {
1366 - delete_option('mxchat_email_null');
1367 - delete_option('mxchat_name_null');
1368 - }
1369 -
1370 - // 3.2.4: Backfill active embedding model option for the warning UI
1371 - // (replaces the per-row column tracking from 3.2.3, which was reverted)
1372 - if (version_compare($current_version, '3.2.4', '<')) {
1373 - mxchat_backfill_active_embedding_model();
1374 - }
1375 -
1376 - // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1377 - // were shut off at the vendor on 2026-07-24). The function is idempotent —
1378 - // it only rewrites models on its deprecation lists.
1379 - if (version_compare($current_version, '3.2.15', '<')) {
1380 - mxchat_migrate_deprecated_models();
1381 - }
1382 -
1383 - // Run full activation to ensure everything is up to date
475 + // Run activation (this will create/update all tables and columns)
1384 476 mxchat_activate();
1385 477
1386 478 // Run migration functions
1387 479 mxchat_migrate_live_agent_status();
@@ -1396,8 +488,18 @@
1396 488
1397 489 //error_log("MxChat: Updated from version $current_version to $plugin_version");
1398 490 }
1399 491
492 + // CRITICAL: Always ensure tables exist, even if version matches
493 + // This handles cases where tables were manually deleted
494 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
495 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
496 +
497 + if (!$table_exists) {
498 + //error_log("MxChat: Chat transcripts table missing, recreating...");
499 + mxchat_activate(); // Run full activation instead of just table creation
500 + }
501 +
1400 502 } catch (Exception $e) {
1401 503 //error_log('MxChat update error: ' . $e->getMessage());
1402 504 // Don't update version if there was an error
1403 505 }
@@ -1403,10 +505,9 @@
1403 505 }
1404 506 }
1405 507
1406 508 /**
1407 - * Ensure tables exist on every admin load for fresh installations
1408 - * This is a safety net for cases where activation hook doesn't fire
509 + * Ensure tables exist on every load for fresh installations
1409 510 */
1410 511 function mxchat_ensure_tables_exist() {
1411 512 global $wpdb;
1412 513
@@ -1414,22 +515,12 @@
1414 515 if (!current_user_can('administrator')) {
1415 516 return;
1416 517 }
1417 518
1418 - // Check if we've already verified tables in this session
1419 - static $tables_checked = false;
1420 - if ($tables_checked) {
1421 - return;
1422 - }
1423 - $tables_checked = true;
1424 -
1425 519 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1426 - $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
520 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1427 521
1428 - $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1429 - $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1430 -
1431 - if (!$chat_exists || !$queue_exists) {
522 + if (!$table_exists) {
1432 523 //error_log("MxChat: Tables missing on admin load, running activation");
1433 524 mxchat_activate();
1434 525 }
1435 526 }
@@ -1512,76 +603,45 @@
1512 603 function mxchat_handle_live_agent_update() {
1513 604 // Get the CURRENT stored version (before it gets updated)
1514 605 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1515 606 $new_version = '2.2.2';
1516 -
607 +
1517 608 // Only run this once for the update to 2.2.2
1518 609 $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
1519 -
610 +
1520 611 // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1521 612 if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1522 613 $options = get_option('mxchat_options', array());
1523 -
614 +
1524 615 // Check if live agent was previously enabled
1525 616 if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1526 617 // Disable live agent
1527 618 $options['live_agent_status'] = 'off';
1528 619 update_option('mxchat_options', $options);
1529 -
620 +
1530 621 // Set flag to show the notification banner
1531 622 update_option('mxchat_show_live_agent_disabled_notice', true);
1532 623 }
1533 -
624 +
1534 625 // Mark this update as handled
1535 626 update_option('mxchat_live_agent_update_2_2_2_handled', true);
1536 627 }
1537 628 }
1538 629
1539 -/**
1540 - * Handle theme migration notice for version 3.0.1
1541 - * Shows a dismissible notice to Pro users about migrating AI-generated themes
1542 - */
1543 -function mxchat_handle_theme_migration_notice() {
1544 - // Get the CURRENT stored version (before it gets updated)
1545 - $current_version = get_option('mxchat_plugin_version', '0.0.0');
1546 - $target_version = '3.0.1';
1547 -
1548 - // Only run this once for the update to 3.0.1
1549 - $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1550 -
1551 - // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1552 - if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1553 - // Check if Pro is activated - only show to Pro users
1554 - $license_status = get_option('mxchat_license_status', 'inactive');
1555 - $is_pro = ($license_status === 'active');
1556 -
1557 - if ($is_pro) {
1558 - // Set flag to show the theme migration notification banner
1559 - update_option('mxchat_show_theme_migration_notice', true);
1560 - }
1561 -
1562 - // Mark this update as handled (whether Pro or not)
1563 - update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1564 - }
1565 -}
1566 -
1567 630 // Initialize plugin safely
1568 631 function mxchat_init() {
1569 632 // Include all class files first
1570 633 mxchat_include_classes();
1571 634
1572 - // Run update check (this also ensures tables exist)
635 + // Run update check
1573 636 mxchat_check_for_update();
1574 637
1575 - // CRITICAL: Ensure tables exist on admin pages (safety net)
638 + // CRITICAL: Ensure tables exist (for fresh installations that don't trigger activation hook)
1576 639 add_action('admin_init', 'mxchat_ensure_tables_exist', 1);
1577 640
1578 641 // Add fallback rate limit check
1579 642 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1580 643
1581 - // Add migration notice hook
1582 - add_action('admin_notices', 'mxchat_show_migration_notice');
1583 -
1584 644 // Initialize classes with error handling
1585 645 try {
1586 646 // Initialize admin classes
1587 647 if (is_admin()) {
@@ -1596,32 +656,10 @@
1596 656 // Initialize meta box class
1597 657 if (class_exists('MxChat_Meta_Box')) {
1598 658 new MxChat_Meta_Box();
1599 659 }
1600 -
1601 660 }
1602 -
1603 - // Initialize content generator globally — it registers wp_head hook
1604 - // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1605 - if (class_exists('MxChat_Content_Generator')) {
1606 - new MxChat_Content_Generator();
1607 - }
1608 -
1609 - // Initialize cache purge globally — settings writes can happen on any
1610 - // request type (admin screens, admin-ajax autosave, wp-cli), and the
1611 - // deferred-purge cron event fires on front-end requests.
1612 - if (class_exists('MxChat_Cache_Purge')) {
1613 - MxChat_Cache_Purge::init();
1614 - }
1615 -
1616 - // Initialize REST API globally — endpoints must be registered on
1617 - // every request (admin and frontend) so they're reachable via /wp-json/.
1618 - // Endpoints are auth-gated and locked until the site owner generates
1619 - // a token in MxChat → API Access.
1620 - if (class_exists('MxChat_Rest_Api')) {
1621 - new MxChat_Rest_Api();
1622 - }
1623 -
661 +
1624 662 // Initialize public classes
1625 663 if (class_exists('MxChat_Public')) {
1626 664 $mxchat_public = new MxChat_Public();
1627 665 }
@@ -1626,9 +664,8 @@
1626 664 $mxchat_public = new MxChat_Public();
1627 665 }
1628 666
1629 667 if (class_exists('MxChat_Integrator')) {
1630 - global $mxchat_integrator;
1631 668 $mxchat_integrator = new MxChat_Integrator();
1632 669 }
1633 670
1634 671 } catch (Exception $e) {
@@ -1648,74 +685,8 @@
1648 685
1649 686 // Run initialization on plugins_loaded
1650 687 add_action('plugins_loaded', 'mxchat_init');
1651 688
1652 -// Run migration check on admin init (for auto-updates without reactivation)
1653 -add_action('admin_init', 'mxchat_check_and_run_migrations');
1654 -
1655 -/**
1656 - * Check and run migrations on admin init
1657 - * This ensures migrations run even when plugin is auto-updated
1658 - */
1659 -function mxchat_check_and_run_migrations() {
1660 - // Only run in admin and not on every request
1661 - static $checked = false;
1662 - if ($checked) {
1663 - return;
1664 - }
1665 - $checked = true;
1666 -
1667 - mxchat_migrate_pinecone_roles_add_bot_id();
1668 - mxchat_migrate_add_content_type_column();
1669 - mxchat_migrate_add_translations_table();
1670 - mxchat_migrate_add_session_ratings_table();
1671 -}
1672 -
1673 -/**
1674 - * Migration: Create per-session satisfaction ratings table (v3.2.6)
1675 - * For users upgrading from versions before 3.2.6
1676 - */
1677 -function mxchat_migrate_add_session_ratings_table() {
1678 - $migration_key = 'mxchat_session_ratings_table_created';
1679 - if (get_option($migration_key)) {
1680 - return;
1681 - }
1682 - mxchat_create_session_ratings_table();
1683 - update_option($migration_key, '3.2.6');
1684 -}
1685 -
1686 -/**
1687 - * Migration: Create transcript translations table (v3.0.4)
1688 - * For users upgrading from versions before 3.0.4
1689 - */
1690 -function mxchat_migrate_add_translations_table() {
1691 - $migration_key = 'mxchat_translations_table_created';
1692 -
1693 - // Check if migration already ran
1694 - if (get_option($migration_key)) {
1695 - return;
1696 - }
1697 -
1698 - // Create the translations table
1699 - mxchat_create_translations_table();
1700 -
1701 - // Mark migration as complete
1702 - update_option($migration_key, '3.0.4');
1703 -}
1704 -
1705 -/**
1706 - * Migration: Update deprecated Gemini embedding model (v3.0.5)
1707 - * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
1708 - */
1709 -function mxchat_migrate_gemini_embedding_model() {
1710 - $options = get_option('mxchat_options', array());
1711 -
1712 - if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
1713 - $options['embedding_model'] = 'gemini-embedding-001';
1714 - update_option('mxchat_options', $options);
1715 - }
1716 -}
1717 -
1718 689 // Register activation hook
1719 690 register_activation_hook(__FILE__, 'mxchat_activate');
1720 691
1721 692 // Add cron schedule
@@ -1727,67 +698,5 @@
1727 698 return $schedules;
1728 699 });
1729 700
1730 701 // Register deactivation hook
1731 -register_deactivation_hook(__FILE__, 'mxchat_deactivate');
1732 -
1733 -/**
1734 - * Per-session satisfaction rating: AJAX save handler (v3.2.6).
1735 - * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
1736 - * session_id makes this naturally idempotent — only the first rating per
1737 - * session is stored; duplicate POSTs are silent no-ops.
1738 - */
1739 -function mxchat_save_session_rating() {
1740 - global $wpdb;
1741 -
1742 - $session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : '';
1743 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
1744 - $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
1745 - $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
1746 -
1747 - if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
1748 - wp_send_json_error(array('message' => 'invalid_input'), 400);
1749 - }
1750 -
1751 - if (strlen($feedback) > 1000) {
1752 - $feedback = substr($feedback, 0, 1000);
1753 - }
1754 -
1755 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
1756 - $existing = $wpdb->get_var($wpdb->prepare(
1757 - "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
1758 - $session_id
1759 - ));
1760 -
1761 - if ($existing) {
1762 - if ($feedback !== '') {
1763 - $wpdb->update(
1764 - $table_name,
1765 - array('rating_feedback' => $feedback),
1766 - array('id' => (int) $existing),
1767 - array('%s'),
1768 - array('%d')
1769 - );
1770 - }
1771 - wp_send_json_success(array('updated' => true));
1772 - }
1773 -
1774 - $inserted = $wpdb->insert(
1775 - $table_name,
1776 - array(
1777 - 'session_id' => $session_id,
1778 - 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
1779 - 'rating_value' => $rating_raw,
1780 - 'rating_feedback' => $feedback !== '' ? $feedback : null,
1781 - 'created_at' => current_time('mysql'),
1782 - ),
1783 - array('%s', '%s', '%d', '%s', '%s')
1784 - );
1785 -
1786 - if ($inserted === false) {
1787 - wp_send_json_error(array('message' => 'db_insert_failed'), 500);
1788 - }
1789 -
1790 - wp_send_json_success(array('saved' => true));
1791 -}
1792 -add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
1793 -add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');
702 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');