PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.18
MxChat – AI Chatbot & Content Generation for WordPress v3.2.18
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
mxchat-basic / mxchat-basic.php

mxchat-basic.php in MxChat – AI Chatbot & Content Generation for WordPress 3.2.18, at mxchat-basic.php

1,976 lines 75.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: MxChat
4 * Plugin URI: https://mxchat.ai/
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.18
7 * Author: MxChat
8 * Author URI: https://mxchat.ai
9 * License: GPLv2 or later
10 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
11 * Text Domain: mxchat
12 * Domain Path: /languages
13 */
14
15 if (!defined('ABSPATH')) {
16 exit; // Exit if accessed directly.
17 }
18
19
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 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');
73 }
74 add_action('init', 'mxchat_load_textdomain');
75
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 // Include classes with error handling
411 function mxchat_include_classes() {
412 $class_files = array(
413 'includes/class-mxchat-model-catalog.php',
414 'includes/class-mxchat-session-store.php',
415 'includes/class-mxchat-live-agent-schedule.php',
416 'includes/class-mxchat-tool-registry.php',
417 'includes/class-mxchat-integrator.php',
418 'includes/class-mxchat-admin.php',
419 'includes/class-mxchat-public.php',
420 'includes/class-mxchat-utils.php',
421 'includes/class-mxchat-user.php',
422 'includes/class-mxchat-privacy.php',
423 'includes/class-mxchat-meta-box.php',
424 'includes/class-mxchat-chunker.php',
425 'includes/class-mxchat-word-handler.php',
426 'includes/class-mxchat-content-generator.php',
427 'includes/class-mxchat-cache-purge.php',
428 'includes/class-mxchat-editor-assistant.php',
429 'includes/class-rest-api.php',
430 'admin/class-ajax-handler.php',
431 'admin/class-pinecone-manager.php',
432 'admin/class-knowledge-manager.php'
433 );
434
435 foreach ($class_files as $file) {
436 $file_path = plugin_dir_path(__FILE__) . $file;
437 if (file_exists($file_path)) {
438 require_once $file_path;
439 } else {
440 //error_log('MxChat: Missing class file - ' . $file);
441 }
442 }
443
444 // Register the native function-calling admin-post save handler (a41dee).
445 if (class_exists('MxChat_Tool_Registry')) {
446 MxChat_Tool_Registry::init();
447 }
448
449 // GDPR: register with WP's personal-data export/erase tools (b81e42).
450 if (class_exists('MxChat_Privacy')) {
451 MxChat_Privacy::init();
452 }
453
454 // Per-session state store: retention cron + the cron-independent
455 // migration drain off admin_init (b64b77).
456 if (class_exists('MxChat_Session_Store')) {
457 MxChat_Session_Store::init();
458 }
459
460 // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
461 // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
462 // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
463 if (class_exists('MxChat_Editor_Assistant')) {
464 MxChat_Editor_Assistant::init();
465 }
466
467 // Admin pages that aren't classes (procedural include).
468 if (is_admin()) {
469 $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
470 if (file_exists($admin_api_page)) {
471 require_once $admin_api_page;
472 }
473 // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
474 // The require MUST live here (admin bootstrap) and not just inside
475 // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
476 // fire on admin-ajax.php requests, so the wizard's AJAX handlers
477 // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
478 // auto_graduate + the f7c7d4 dismiss handler) would never register.
479 $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
480 if (file_exists($admin_onboarding_page)) {
481 require_once $admin_onboarding_page;
482 }
483 }
484 }
485
486 /**
487 * Lazy-load the PDF parser library only when needed.
488 * Avoids loading 44 files on every page request.
489 */
490 function mxchat_load_pdf_parser() {
491 if (class_exists('\Smalot\PdfParser\Parser')) {
492 return true;
493 }
494 $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
495 if (file_exists($autoload_path)) {
496 require_once $autoload_path;
497 return true;
498 }
499 return false;
500 }
501
502 /**
503 * Create URL click tracking table
504 */
505 function mxchat_create_url_clicks_table() {
506 global $wpdb;
507
508 $table_name = $wpdb->prefix . 'mxchat_url_clicks';
509
510 $charset_collate = $wpdb->get_charset_collate();
511
512 $sql = "CREATE TABLE $table_name (
513 id mediumint(9) NOT NULL AUTO_INCREMENT,
514 session_id varchar(100) NOT NULL,
515 clicked_url text NOT NULL,
516 message_context text,
517 click_timestamp datetime DEFAULT CURRENT_TIMESTAMP,
518 user_ip varchar(45),
519 user_agent text,
520 PRIMARY KEY (id),
521 KEY session_id (session_id),
522 KEY click_timestamp (click_timestamp)
523 ) $charset_collate;";
524
525 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
526 dbDelta($sql);
527 }
528
529 /**
530 * Create the per-session state table (b64b77).
531 *
532 * Callable from the activation hook, which can run before plugins_loaded has
533 * included the class files — so it loads the class itself when needed.
534 */
535 function mxchat_create_sessions_table() {
536 if (!class_exists('MxChat_Session_Store')) {
537 $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
538 if (!file_exists($path)) {
539 return false;
540 }
541 require_once $path;
542 }
543
544 return MxChat_Session_Store::create_table();
545 }
546
547 /**
548 * FIXED: Robust table creation and column management
549 */
550 function mxchat_create_chat_transcripts_table() {
551 global $wpdb;
552
553 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
554 $charset_collate = $wpdb->get_charset_collate();
555
556 // Create table with ALL columns including user_name from the start
557 $sql = "CREATE TABLE $table_name (
558 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
559 user_id MEDIUMINT(9) DEFAULT 0,
560 session_id VARCHAR(255) NOT NULL,
561 role VARCHAR(255) NOT NULL,
562 message TEXT NOT NULL,
563 user_email VARCHAR(255) DEFAULT NULL,
564 user_name VARCHAR(100) DEFAULT NULL,
565 user_identifier VARCHAR(255) DEFAULT NULL,
566 originating_page_url TEXT DEFAULT NULL,
567 originating_page_title VARCHAR(500) DEFAULT NULL,
568 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
569 PRIMARY KEY (id),
570 KEY session_id (session_id),
571 KEY user_email (user_email),
572 KEY timestamp (timestamp)
573 ) $charset_collate;";
574
575 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
576 $result = dbDelta($sql);
577
578 // Log the result for debugging
579 if (empty($result)) {
580 //error_log("MxChat: dbDelta returned empty result for chat transcripts table");
581 } else {
582 //error_log("MxChat: dbDelta result: " . print_r($result, true));
583 }
584
585 // IMPORTANT: Ensure all columns exist for existing installations
586 mxchat_ensure_all_columns($table_name);
587 }
588
589 /**
590 * Ensure all required columns exist (for upgrades)
591 */
592 function mxchat_ensure_all_columns($table_name) {
593 global $wpdb;
594
595 // First check if table exists
596 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
597 if (!$table_exists) {
598 //error_log("MxChat: Table $table_name does not exist, cannot add columns");
599 return;
600 }
601
602 // Define all required columns and their types
603 $required_columns = [
604 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
605 'user_email' => 'VARCHAR(255) DEFAULT NULL',
606 'user_name' => 'VARCHAR(100) DEFAULT NULL',
607 'originating_page_url' => 'TEXT DEFAULT NULL',
608 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL',
609 'rag_context' => 'LONGTEXT DEFAULT NULL'
610 ];
611
612 // Get existing columns
613 $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
614 if (empty($existing_columns)) {
615 //error_log("MxChat: Could not get columns for table $table_name");
616 return;
617 }
618
619 $existing_column_names = array_column($existing_columns, 'Field');
620
621 // Add missing columns
622 foreach ($required_columns as $column_name => $column_definition) {
623 if (!in_array($column_name, $existing_column_names)) {
624 $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition";
625 $result = $wpdb->query($alter_sql);
626
627 if ($result === false) {
628 //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error);
629 } else {
630 //error_log("MxChat: Successfully added column $column_name to $table_name");
631 }
632 }
633 }
634 }
635
636 /**
637 * Add role restriction column to knowledge base table
638 */
639 function mxchat_add_role_restriction_column() {
640 global $wpdb;
641 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
642
643 // Check if table exists first
644 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
645 if (!$table_exists) {
646 //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column");
647 return;
648 }
649
650 // Check if column already exists
651 $column_exists = $wpdb->get_results(
652 $wpdb->prepare(
653 "SHOW COLUMNS FROM {$table_name} LIKE %s",
654 'role_restriction'
655 )
656 );
657
658 if (empty($column_exists)) {
659 $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url";
660 $result = $wpdb->query($alter_sql);
661
662 if ($result === false) {
663 //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error);
664 } else {
665 //error_log("MxChat: Successfully added role_restriction column");
666
667 // Set all existing records to 'public' (everyone can access)
668 $update_result = $wpdb->query(
669 "UPDATE {$table_name}
670 SET role_restriction = 'public'
671 WHERE role_restriction IS NULL OR role_restriction = ''"
672 );
673
674 if ($update_result !== false) {
675 //error_log("MxChat: Updated {$update_result} existing records to public access");
676 }
677 }
678 }
679 }
680
681 /**
682 * Add enabled_bots column to intents table for multi-bot action filtering
683 */
684 function mxchat_add_enabled_bots_column() {
685 global $wpdb;
686 $table_name = $wpdb->prefix . 'mxchat_intents';
687
688 // Check if table exists first
689 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
690 if (!$table_exists) {
691 //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column");
692 return;
693 }
694
695 // Check if column already exists
696 $column_exists = $wpdb->get_results(
697 $wpdb->prepare(
698 "SHOW COLUMNS FROM {$table_name} LIKE %s",
699 'enabled_bots'
700 )
701 );
702
703 if (empty($column_exists)) {
704 $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled";
705 $result = $wpdb->query($alter_sql);
706
707 if ($result === false) {
708 //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error);
709 } else {
710 //error_log("MxChat: Successfully added enabled_bots column");
711
712 // Set all existing actions to work with 'default' bot for backward compatibility
713 $default_bots = json_encode(['default']);
714 $update_result = $wpdb->query(
715 $wpdb->prepare(
716 "UPDATE {$table_name}
717 SET enabled_bots = %s
718 WHERE enabled_bots IS NULL OR enabled_bots = ''",
719 $default_bots
720 )
721 );
722
723 if ($update_result !== false) {
724 //error_log("MxChat: Updated {$update_result} existing actions to work with default bot");
725 }
726 }
727 }
728 }
729
730 /**
731 * Create Pinecone role restrictions table with multi-bot support
732 */
733 function mxchat_create_pinecone_roles_table() {
734 global $wpdb;
735
736 $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
737 $charset_collate = $wpdb->get_charset_collate();
738
739 $sql = "CREATE TABLE $table_name (
740 id mediumint(9) NOT NULL AUTO_INCREMENT,
741 vector_id varchar(255) NOT NULL,
742 bot_id varchar(50) NOT NULL DEFAULT 'default',
743 source_url text,
744 role_restriction varchar(50) DEFAULT 'public',
745 updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
746 PRIMARY KEY (id),
747 UNIQUE KEY vector_bot (vector_id, bot_id),
748 KEY role_restriction (role_restriction),
749 KEY bot_id (bot_id)
750 ) $charset_collate;";
751
752 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
753 dbDelta($sql);
754 }
755
756 /**
757 * Add bot_id column to mxchat_pinecone_roles table for multi-bot support
758 * This migration runs once to update existing installations
759 */
760 function mxchat_migrate_pinecone_roles_add_bot_id() {
761 global $wpdb;
762
763 // Check if migration already ran
764 $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0');
765 if (version_compare($migration_version, '2.5.2', '>=')) {
766 return; // Already migrated
767 }
768
769 $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
770
771 // Check if table exists
772 if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
773 return; // Table doesn't exist yet
774 }
775
776 // Check if bot_id column already exists
777 $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'");
778
779 if (empty($column_exists)) {
780 // Add bot_id column
781 $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id");
782
783 // Update the unique key to include bot_id
784 $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id");
785 $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)");
786
787 // Add index for bot_id
788 $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
789
790 //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
791 }
792
793 // Mark migration as complete
794 update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
795 }
796
797 /**
798 * 2.5.6: Add content_type column to mxchat_system_prompt_content table
799 * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.)
800 */
801 function mxchat_migrate_add_content_type_column() {
802 global $wpdb;
803
804 // Check if migration already ran
805 $migration_version = get_option('mxchat_content_type_migration_version', '0');
806 if (version_compare($migration_version, '2.5.6', '>=')) {
807 return;
808 }
809
810 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
811
812 // Check if table exists
813 if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
814 return;
815 }
816
817 // Check if content_type column already exists
818 $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'");
819
820 if (empty($column_exists)) {
821 // Add content_type column with default value 'content' for backwards compatibility
822 $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction");
823
824 // Add index for better query performance
825 $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
826
827 //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
828 }
829
830 // Mark migration as complete
831 update_option('mxchat_content_type_migration_version', '2.5.6');
832 }
833
834 /**
835 * 3.2.4: Backfill the active embedding model option for installs that already
836 * have KB content but no stamped model. The mismatch warning compares this
837 * against the user's currently selected model — no per-row column needed.
838 */
839 function mxchat_backfill_active_embedding_model() {
840 global $wpdb;
841
842 if (get_option('mxchat_active_embedding_model', '') !== '') {
843 return;
844 }
845
846 $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
847 if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
848 return;
849 }
850
851 $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
852 if ($kb_count > 0) {
853 $options = get_option('mxchat_options', array());
854 $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
855 update_option('mxchat_active_embedding_model', $current_model, false);
856 }
857 }
858
859 /**
860 * 2.5.2: Create queue processing tables for reliable background processing
861 */
862 function mxchat_create_queue_tables() {
863 global $wpdb;
864 $charset_collate = $wpdb->get_charset_collate();
865
866 // Main queue table
867 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
868 $sql_queue = "CREATE TABLE $queue_table (
869 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
870 queue_id varchar(64) NOT NULL,
871 item_type varchar(20) NOT NULL,
872 item_data longtext NOT NULL,
873 status varchar(20) NOT NULL DEFAULT 'pending',
874 bot_id varchar(50) NOT NULL DEFAULT 'default',
875 priority int(11) NOT NULL DEFAULT 0,
876 attempts int(11) NOT NULL DEFAULT 0,
877 max_attempts int(11) NOT NULL DEFAULT 3,
878 error_message text DEFAULT NULL,
879 created_at datetime NOT NULL,
880 started_at datetime DEFAULT NULL,
881 completed_at datetime DEFAULT NULL,
882 PRIMARY KEY (id),
883 KEY queue_id (queue_id),
884 KEY status (status),
885 KEY item_type (item_type),
886 KEY priority (priority)
887 ) $charset_collate;";
888
889 // Queue metadata table
890 $meta_table = $wpdb->prefix . 'mxchat_queue_meta';
891 $sql_meta = "CREATE TABLE $meta_table (
892 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
893 queue_id varchar(64) NOT NULL,
894 meta_key varchar(255) NOT NULL,
895 meta_value longtext,
896 PRIMARY KEY (id),
897 KEY queue_id (queue_id),
898 KEY meta_key (meta_key)
899 ) $charset_collate;";
900
901 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
902 dbDelta($sql_queue);
903 dbDelta($sql_meta);
904
905 //error_log("MxChat: Queue tables created/updated successfully");
906 }
907
908 /**
909 * Create transcript translations table for persisting translations
910 */
911 function mxchat_create_translations_table() {
912 global $wpdb;
913 $charset_collate = $wpdb->get_charset_collate();
914
915 $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
916 $sql = "CREATE TABLE $table_name (
917 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
918 session_id varchar(255) NOT NULL,
919 language_code varchar(10) NOT NULL,
920 translations longtext NOT NULL,
921 created_at datetime NOT NULL,
922 updated_at datetime NOT NULL,
923 PRIMARY KEY (id),
924 UNIQUE KEY session_lang (session_id, language_code),
925 KEY session_id (session_id)
926 ) $charset_collate;";
927
928 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
929 dbDelta($sql);
930 }
931
932 /**
933 * Create per-session satisfaction ratings table (v3.2.6)
934 * Stores one 👍/👎 rating + optional feedback per chat session.
935 */
936 function mxchat_create_session_ratings_table() {
937 global $wpdb;
938 $charset_collate = $wpdb->get_charset_collate();
939
940 $table_name = $wpdb->prefix . 'mxchat_session_ratings';
941 $sql = "CREATE TABLE $table_name (
942 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
943 session_id varchar(255) NOT NULL,
944 bot_id varchar(50) NOT NULL DEFAULT 'default',
945 rating_value tinyint(1) NOT NULL,
946 rating_feedback text DEFAULT NULL,
947 created_at datetime NOT NULL,
948 PRIMARY KEY (id),
949 UNIQUE KEY session_id (session_id),
950 KEY bot_id (bot_id),
951 KEY created_at (created_at)
952 ) $charset_collate;";
953
954 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
955 dbDelta($sql);
956 }
957
958 /**
959 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
960 * This fixes "url, source_url. The supplied values may be too long" errors
961 */
962 function mxchat_fix_url_column_size() {
963 global $wpdb;
964 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
965
966 // Check if table exists
967 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
968 if (!$table_exists) {
969 return;
970 }
971
972 // Change url and source_url from VARCHAR to TEXT to handle long URLs
973 // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.)
974 $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT");
975 $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT");
976
977 //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support");
978 }
979
980 /**
981 * Migrate deprecated AI models to their replacements
982 * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
983 * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
984 * Without utf8mb4, any bot response containing emojis silently fails to insert.
985 */
986 function mxchat_migrate_transcripts_charset() {
987 global $wpdb;
988 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
989 $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
990 }
991
992 /**
993 * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
994 */
995 function mxchat_migrate_deprecated_models() {
996 $options = get_option('mxchat_options', array());
997 $migrated = false;
998 $migration_message = '';
999
1000 if (!isset($options['model'])) {
1001 return;
1002 }
1003
1004 $current_model = $options['model'];
1005
1006 // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
1007 $deprecated_claude_models = array(
1008 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
1009 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
1010 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
1011 'claude-3-opus-20240229', // Retired Jan 5, 2026
1012 'claude-3-sonnet-20240229', // Legacy
1013 'claude-3-haiku-20240307', // Legacy
1014 );
1015 if (in_array($current_model, $deprecated_claude_models, true)) {
1016 $options['model'] = 'claude-opus-4-6';
1017 $migrated = true;
1018 $migration_message = sprintf(
1019 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.',
1020 $current_model
1021 );
1022 }
1023
1024 // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
1025 if ($current_model === 'claude-3-5-haiku-20241022') {
1026 $options['model'] = 'claude-haiku-4-5-20251001';
1027 $migrated = true;
1028 $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.';
1029 }
1030
1031 // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.6 Sol.
1032 // (Previous target gpt-5.1-chat-latest itself retires 2026-08-10 — never
1033 // migrate onto a model that is already on a deprecation list.)
1034 if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1035 $options['model'] = 'gpt-5.6-sol';
1036 $migrated = true;
1037 $migration_message = sprintf(
1038 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
1039 $current_model
1040 );
1041 }
1042
1043 // Migrate the gpt-5.x-chat-latest aliases OpenAI retires on August 10, 2026.
1044 // Replacement per OpenAI's deprecations page: gpt-5.6-sol (plan e46b8f).
1045 if (in_array($current_model, array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1046 $options['model'] = 'gpt-5.6-sol';
1047 $migrated = true;
1048 $migration_message = sprintf(
1049 '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.',
1050 $current_model
1051 );
1052 }
1053
1054 // The content generator has its own model option — same retirement applies.
1055 if (isset($options['content_model'])
1056 && in_array($options['content_model'], array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1057 $old_content_model = $options['content_model'];
1058 $options['content_model'] = 'gpt-5.6-sol';
1059 $migrated = true;
1060 $migration_message = trim($migration_message . ' ' . sprintf(
1061 'Your content generation model has also been updated from %s to GPT-5.6 Sol for the same OpenAI retirement.',
1062 $old_content_model
1063 ));
1064 }
1065
1066 // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1067 if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1068 $options['model'] = 'gpt-5-mini';
1069 $migrated = true;
1070 $migration_message = sprintf(
1071 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
1072 $current_model
1073 );
1074 }
1075
1076 // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1077 // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1078 // request 400s). V4 Flash is DeepSeek's designated successor for the
1079 // legacy deepseek-chat alias.
1080 if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1081 $options['model'] = 'deepseek-v4-flash';
1082 $migrated = true;
1083 $migration_message = sprintf(
1084 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1085 $current_model
1086 );
1087 }
1088
1089 if ($migrated) {
1090 update_option('mxchat_options', $options);
1091 update_option('mxchat_model_migrated_notice', true);
1092 update_option('mxchat_model_migration_message', $migration_message);
1093 }
1094 }
1095
1096 /**
1097 * Show admin notice after model migration
1098 */
1099 function mxchat_show_migration_notice() {
1100 if (get_option('mxchat_model_migrated_notice')) {
1101 $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
1102 ?>
1103 <div class="notice notice-info is-dismissible">
1104 <p>
1105 <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
1106 <?php echo esc_html($migration_message); ?>
1107 </p>
1108 </div>
1109 <?php
1110 delete_option('mxchat_model_migrated_notice');
1111 delete_option('mxchat_model_migration_message');
1112 }
1113 }
1114
1115 /**
1116 * Persistent admin notice when the provider rejected the configured model
1117 * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1118 * integrator whenever a chat request fails on a model-access error — including
1119 * requests from anonymous visitors, which is the case that otherwise stays
1120 * invisible to the site owner for weeks (plan e46b8f).
1121 *
1122 * Deleted after render so it re-arms on the next failed chat: the notice keeps
1123 * reappearing until the model is fixed, then stops on its own.
1124 */
1125 function mxchat_show_model_access_notice() {
1126 if (!current_user_can('manage_options')) {
1127 return;
1128 }
1129 $notice = get_option('mxchat_model_access_notice');
1130 if (!is_array($notice) || empty($notice['model'])) {
1131 return;
1132 }
1133 $settings_url = admin_url('admin.php?page=mxchat-max');
1134 ?>
1135 <div class="notice notice-error is-dismissible">
1136 <p>
1137 <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1138 <?php
1139 printf(
1140 /* translators: 1: model id, 2: provider name */
1141 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'),
1142 esc_html($notice['model']),
1143 esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1144 );
1145 ?>
1146 <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1147 </p>
1148 </div>
1149 <?php
1150 delete_option('mxchat_model_access_notice');
1151 }
1152
1153 function mxchat_activate() {
1154 global $wpdb;
1155 $charset_collate = $wpdb->get_charset_collate();
1156
1157 //error_log("MxChat: Running activation function");
1158
1159 // Create chat transcripts table with improved function
1160 mxchat_create_chat_transcripts_table();
1161
1162 // Per-session state table (b64b77). Activation can run before
1163 // plugins_loaded has included the class files, so require it directly.
1164 mxchat_create_sessions_table();
1165
1166 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
1167 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1168 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1169 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
1170 url TEXT NOT NULL,
1171 article_content LONGTEXT NOT NULL,
1172 embedding_vector LONGTEXT,
1173 source_url TEXT DEFAULT NULL,
1174 role_restriction VARCHAR(50) DEFAULT 'public',
1175 content_type VARCHAR(50) DEFAULT 'content',
1176 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1177 PRIMARY KEY (id),
1178 KEY content_type (content_type)
1179 ) $charset_collate;";
1180
1181 // Intents Table - NOW INCLUDES enabled_bots column from the start
1182 $intents_table = $wpdb->prefix . 'mxchat_intents';
1183 $sql_intents_table = "CREATE TABLE $intents_table (
1184 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1185 intent_label VARCHAR(255) NOT NULL,
1186 phrases TEXT NOT NULL,
1187 embedding_vector LONGTEXT NOT NULL,
1188 callback_function VARCHAR(255) NOT NULL,
1189 similarity_threshold FLOAT DEFAULT 0.85,
1190 enabled TINYINT(1) NOT NULL DEFAULT 1,
1191 enabled_bots LONGTEXT DEFAULT NULL,
1192 PRIMARY KEY (id)
1193 ) $charset_collate;";
1194
1195 // Individual Intent Phrases Table - each phrase gets its own embedding vector
1196 $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
1197 $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table (
1198 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1199 intent_id BIGINT(20) UNSIGNED NOT NULL,
1200 phrase TEXT NOT NULL,
1201 embedding_vector LONGTEXT NOT NULL,
1202 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1203 PRIMARY KEY (id),
1204 KEY intent_id (intent_id)
1205 ) $charset_collate;";
1206
1207 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1208
1209 // Create other tables
1210 dbDelta($sql_system_prompt);
1211 dbDelta($sql_intents_table);
1212 dbDelta($sql_intent_phrases_table);
1213
1214 // Create URL click tracking table
1215 mxchat_create_url_clicks_table();
1216
1217 // Create Pinecone roles table
1218 mxchat_create_pinecone_roles_table();
1219
1220 // NEW 2.5.2: Create queue processing tables
1221 mxchat_create_queue_tables();
1222
1223 // Create transcript translations table
1224 mxchat_create_translations_table();
1225
1226 // Create per-session satisfaction ratings table (v3.2.6)
1227 mxchat_create_session_ratings_table();
1228
1229 // Ensure additional columns in system prompt table
1230 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1231 if (!empty($existing_system_columns)) {
1232 $existing_system_column_names = array_column($existing_system_columns, 'Field');
1233
1234 if (!in_array('embedding_vector', $existing_system_column_names)) {
1235 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT");
1236 }
1237 if (!in_array('source_url', $existing_system_column_names)) {
1238 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL");
1239 }
1240 if (!in_array('role_restriction', $existing_system_column_names)) {
1241 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
1242 }
1243 }
1244
1245 // Set default thresholds for existing intents
1246 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
1247
1248 // Ensure enabled column exists in intents table
1249 $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table");
1250 if (!empty($existing_intent_columns)) {
1251 $existing_intent_column_names = array_column($existing_intent_columns, 'Field');
1252
1253 if (!in_array('enabled', $existing_intent_column_names)) {
1254 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
1255 }
1256
1257 // Ensure enabled_bots column exists for existing installations
1258 if (!in_array('enabled_bots', $existing_intent_column_names)) {
1259 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled");
1260
1261 // Set existing actions to work with default bot
1262 $default_bots = json_encode(['default']);
1263 $wpdb->query($wpdb->prepare(
1264 "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL",
1265 $default_bots
1266 ));
1267 }
1268 }
1269
1270 // Run migration for existing installations
1271 mxchat_migrate_pinecone_roles_add_bot_id();
1272
1273 // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1274 mxchat_backfill_active_embedding_model();
1275
1276 // Setup cron jobs
1277 mxchat_setup_cron_jobs();
1278
1279 // Update version (stable base version — never the dev time()-suffixed one,
1280 // or the check_for_update comparison would churn every request)
1281 update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
1282
1283 //error_log("MxChat: Activation function completed");
1284 }
1285
1286 /**
1287 * Setup cron jobs on plugin activation
1288 */
1289 function mxchat_setup_cron_jobs() {
1290 // Clear any existing cron jobs first
1291 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1292
1293 // Check if WordPress cron is disabled
1294 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1295 // Set flag to use fallback system
1296 update_option('mxchat_use_fallback_rate_limits', true);
1297 update_option('mxchat_next_rate_limit_check', time() + 3600);
1298 // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1299 // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1300 // execute (a server-side runner hitting wp-cron.php instead of loopback
1301 // spawns) — scheduling still just writes the cron option. The old early
1302 // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1303 // site permanently lost the transcript cleanup event while the retention
1304 // setting still claimed to be active.
1305 } else {
1306 // Schedule the rate limit reset cron job
1307 $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1308
1309 if ($result === false) {
1310 // Fallback if scheduling fails
1311 update_option('mxchat_use_fallback_rate_limits', true);
1312 update_option('mxchat_next_rate_limit_check', time() + 3600);
1313 } else {
1314 // Clear fallback flags if cron scheduling succeeded
1315 delete_option('mxchat_use_fallback_rate_limits');
1316 }
1317 }
1318
1319 // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
1320 $transcript_options = get_option('mxchat_transcripts_options', array());
1321 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1322 $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1323
1324 if ($cleanup_interval !== 'never' || $custom_retention > 0) {
1325 // Check if not already scheduled
1326 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1327 // Schedule to run daily at 3 AM
1328 $next_run = strtotime('tomorrow 3:00 AM');
1329 wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1330 }
1331 }
1332 }
1333
1334 /**
1335 * Clean up on plugin deactivation
1336 */
1337 function mxchat_deactivate() {
1338 // Clear scheduled cron jobs
1339 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1340 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1341 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1342
1343 // Clear fallback options
1344 delete_option('mxchat_use_fallback_rate_limits');
1345 delete_option('mxchat_next_rate_limit_check');
1346 delete_option('mxchat_fallback_check_interval');
1347
1348 // NOTE: We do NOT delete queue tables on deactivation
1349 // This preserves data if user accidentally deactivates the plugin
1350 }
1351
1352 /**
1353 * Check if fallback rate limit cleanup is needed
1354 */
1355 function mxchat_check_fallback_rate_limits() {
1356 $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
1357
1358 if (!$use_fallback) {
1359 return;
1360 }
1361
1362 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1363
1364 if (time() >= $next_check) {
1365 // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1366 // plugins_loaded (before this init-priority-5 callback), so it's always set
1367 // here. Constructing a second MxChat_Integrator just to call one method
1368 // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1369 // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1370 // the request. Defensive construction only if the global is somehow unset.
1371 // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1372 // implementation of this same check — if either changes, change both.
1373 global $mxchat_integrator;
1374 $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1375 ? $mxchat_integrator
1376 : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1377 if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1378 $integrator->mxchat_reset_rate_limits();
1379 update_option('mxchat_next_rate_limit_check', time() + 3600);
1380 }
1381 }
1382 }
1383
1384 /**
1385 * Robust update checking with role restriction migration, model deprecation, and queue tables
1386 * CRITICAL: This runs on EVERY page load to ensure tables exist
1387 */
1388 function mxchat_check_for_update() {
1389 global $wpdb;
1390
1391 try {
1392 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1393 $plugin_version = MXCHAT_BASE_VERSION;
1394
1395 // Always ensure critical tables exist (even if version matches)
1396 // This handles manual table deletion or fresh installs
1397 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1398 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1399
1400 $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1401
1402 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1403 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1404 $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1405 || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1406
1407 if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1408 //error_log("MxChat: Critical tables missing, running activation");
1409 mxchat_activate();
1410 }
1411
1412 // Version-specific migrations
1413 if ($current_version !== $plugin_version) {
1414 //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
1415
1416 // Run live agent update BEFORE updating the stored version
1417 mxchat_handle_live_agent_update();
1418
1419 // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
1420 mxchat_handle_theme_migration_notice();
1421
1422 // Run role restriction migration for 2.4.1
1423 if (version_compare($current_version, '2.4.1', '<')) {
1424 mxchat_add_role_restriction_column();
1425 }
1426
1427 // Run enabled_bots column migration for 2.4.4
1428 if (version_compare($current_version, '2.4.4', '<')) {
1429 mxchat_add_enabled_bots_column();
1430 }
1431
1432 // Run model migration for 2.5.1 (Claude deprecation)
1433 if (version_compare($current_version, '2.5.1', '<')) {
1434 mxchat_migrate_deprecated_models();
1435 }
1436
1437 // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2
1438 if (version_compare($current_version, '2.5.2', '<')) {
1439 mxchat_create_queue_tables();
1440 mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs
1441 //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2");
1442 }
1443
1444 // 2.6.0: Ensure rag_context column exists for retrieved documents feature
1445 if (version_compare($current_version, '2.6.0', '<')) {
1446 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1447 mxchat_ensure_all_columns($chat_table);
1448 //error_log("MxChat: rag_context column migration for 2.6.0");
1449 }
1450
1451 // 3.0.5: Migrate deprecated Gemini embedding model
1452 if (version_compare($current_version, '3.0.5', '<')) {
1453 mxchat_migrate_gemini_embedding_model();
1454 }
1455
1456 // 3.0.6: Migrate deprecated OpenAI and Claude models
1457 if (version_compare($current_version, '3.0.6', '<')) {
1458 mxchat_migrate_deprecated_models();
1459 }
1460
1461 // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1462 if (version_compare($current_version, '3.1.2', '<')) {
1463 mxchat_migrate_transcripts_charset();
1464 }
1465
1466 // 3.1.7: Clean up stale shared session email/name entries
1467 if (version_compare($current_version, '3.1.7', '<')) {
1468 delete_option('mxchat_email_null');
1469 delete_option('mxchat_name_null');
1470 }
1471
1472 // 3.2.4: Backfill active embedding model option for the warning UI
1473 // (replaces the per-row column tracking from 3.2.3, which was reverted)
1474 if (version_compare($current_version, '3.2.4', '<')) {
1475 mxchat_backfill_active_embedding_model();
1476 }
1477
1478 // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1479 // were shut off at the vendor on 2026-07-24). The function is idempotent —
1480 // it only rewrites models on its deprecation lists.
1481 if (version_compare($current_version, '3.2.15', '<')) {
1482 mxchat_migrate_deprecated_models();
1483 }
1484
1485 // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1486 // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1487 // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1488 if (version_compare($current_version, '3.2.16', '<')) {
1489 mxchat_migrate_deprecated_models();
1490 }
1491
1492 // 3.2.17: Credential options must not autoload (af2400) — the two
1493 // Pinecone-secret-holding rows were in alloptions, i.e. read into
1494 // memory on every request including anonymous page views. Idempotent.
1495 // Also carry the import modal's remembered ACF→PDF checkbox state
1496 // into the new install-level option (11720c).
1497 if (version_compare($current_version, '3.2.17', '<')) {
1498 mxchat_fix_credential_option_autoload();
1499 mxchat_migrate_acf_pdf_extraction_option();
1500 }
1501
1502 // Run full activation to ensure everything is up to date
1503 mxchat_activate();
1504
1505 // Run migration functions
1506 mxchat_migrate_live_agent_status();
1507
1508 // Add the cleanup function for version 2.1.8
1509 if (version_compare($current_version, '2.1.8', '<')) {
1510 $deleted = mxchat_cleanup_orphaned_chat_history();
1511 }
1512
1513 // Update version LAST
1514 update_option('mxchat_plugin_version', $plugin_version);
1515
1516 //error_log("MxChat: Updated from version $current_version to $plugin_version");
1517 }
1518
1519 } catch (Exception $e) {
1520 //error_log('MxChat update error: ' . $e->getMessage());
1521 // Don't update version if there was an error
1522 }
1523 }
1524
1525 /**
1526 * Credential options must never enter the autoloaded alloptions set.
1527 * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1528 * Pinecone API secret; mxchat_options already stores its keys with autoload
1529 * off and these two must match it. The filter covers every future
1530 * add_option()/update_option() that creates the row — Settings API saves
1531 * through options.php and WP-CLI included — on WP 6.6+; older cores are
1532 * covered by the explicit autoload arguments at the plugin's own write
1533 * sites plus the one-time migration below.
1534 */
1535 add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1536 function mxchat_credential_option_autoload_value($autoload, $option) {
1537 if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1538 return false;
1539 }
1540 return $autoload;
1541 }
1542
1543 /**
1544 * One-time upgrade migration: flip the autoload flag on credential option
1545 * rows that existing installs are already carrying autoloaded. Includes
1546 * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1547 * when that add-on is not installed, since missing rows simply don't match.
1548 */
1549 function mxchat_fix_credential_option_autoload() {
1550 $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1551 if (function_exists('wp_set_option_autoload_values')) {
1552 wp_set_option_autoload_values(array_fill_keys($keys, false));
1553 return;
1554 }
1555 // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1556 global $wpdb;
1557 $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1558 $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1559 wp_cache_delete('alloptions', 'options');
1560 foreach ($keys as $key) {
1561 wp_cache_delete($key, 'options');
1562 }
1563 }
1564
1565 /**
1566 * One-time carry of the import modal's remembered ACF→PDF checkbox state
1567 * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1568 * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1569 * Fresh installs and installs that never touched the checkbox default OFF,
1570 * matching the setting's own "recommended only if…" guidance.
1571 */
1572 function mxchat_migrate_acf_pdf_extraction_option() {
1573 if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1574 return; // already set — never overwrite an owner's choice
1575 }
1576 $mxchat_options = get_option('mxchat_options', array());
1577 if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1578 update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1579 unset($mxchat_options['acf_pdf_extract_default']);
1580 update_option('mxchat_options', $mxchat_options);
1581 }
1582 }
1583
1584 /**
1585 * Ensure tables exist on every admin load for fresh installations
1586 * This is a safety net for cases where activation hook doesn't fire
1587 */
1588 function mxchat_ensure_tables_exist() {
1589 global $wpdb;
1590
1591 // Only run for admin users to avoid performance impact
1592 if (!current_user_can('administrator')) {
1593 return;
1594 }
1595
1596 // Check if we've already verified tables in this session
1597 static $tables_checked = false;
1598 if ($tables_checked) {
1599 return;
1600 }
1601 $tables_checked = true;
1602
1603 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1604 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1605
1606 $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1607
1608 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1609 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1610 $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1611 || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1612
1613 if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1614 //error_log("MxChat: Tables missing on admin load, running activation");
1615 mxchat_activate();
1616 }
1617 }
1618
1619 /**
1620 * Clean up orphaned chat history options from the wp_options table
1621 * @return int Number of options deleted
1622 */
1623 function mxchat_cleanup_orphaned_chat_history() {
1624 global $wpdb;
1625 $count = 0;
1626
1627 // Get all option keys that match our pattern
1628 $history_options = $wpdb->get_results(
1629 "SELECT option_name FROM {$wpdb->options}
1630 WHERE option_name LIKE 'mxchat_history_%'"
1631 );
1632
1633 if (!empty($history_options)) {
1634 foreach ($history_options as $option) {
1635 // Extract the session ID from the option name
1636 $session_id = str_replace('mxchat_history_', '', $option->option_name);
1637
1638 // Check if this session still exists in the custom table
1639 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1640 $exists = $wpdb->get_var(
1641 $wpdb->prepare(
1642 "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1643 $session_id
1644 )
1645 );
1646
1647 // If session doesn't exist in the main table, delete the option
1648 if ($exists == 0) {
1649 delete_option($option->option_name);
1650 // Also delete related metadata
1651 delete_option("mxchat_email_{$session_id}");
1652 delete_option("mxchat_name_{$session_id}");
1653 delete_option("mxchat_agent_name_{$session_id}");
1654 $count++;
1655 }
1656 }
1657 }
1658
1659 return $count;
1660 }
1661
1662 function mxchat_migrate_live_agent_status() {
1663 $options = get_option('mxchat_options', []);
1664
1665 // Check if live_agent_status exists
1666 if (isset($options['live_agent_status'])) {
1667 $current_status = $options['live_agent_status'];
1668 $needs_update = false;
1669
1670 // Convert to new format if needed
1671 if ($current_status === 'online') {
1672 $options['live_agent_status'] = 'on';
1673 $needs_update = true;
1674 } else if ($current_status === 'offline') {
1675 $options['live_agent_status'] = 'off';
1676 $needs_update = true;
1677 } else if (!in_array($current_status, ['on', 'off'])) {
1678 // Default to off for any unexpected values
1679 $options['live_agent_status'] = 'off';
1680 $needs_update = true;
1681 }
1682
1683 // Only update if needed
1684 if ($needs_update) {
1685 update_option('mxchat_options', $options);
1686 }
1687 } else {
1688 // If status doesn't exist, set default to off
1689 $options['live_agent_status'] = 'off';
1690 update_option('mxchat_options', $options);
1691 }
1692 }
1693
1694 function mxchat_handle_live_agent_update() {
1695 // Get the CURRENT stored version (before it gets updated)
1696 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1697 $new_version = '2.2.2';
1698
1699 // Only run this once for the update to 2.2.2
1700 $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
1701
1702 // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1703 if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1704 $options = get_option('mxchat_options', array());
1705
1706 // Check if live agent was previously enabled
1707 if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1708 // Disable live agent
1709 $options['live_agent_status'] = 'off';
1710 update_option('mxchat_options', $options);
1711
1712 // Set flag to show the notification banner
1713 update_option('mxchat_show_live_agent_disabled_notice', true);
1714 }
1715
1716 // Mark this update as handled
1717 update_option('mxchat_live_agent_update_2_2_2_handled', true);
1718 }
1719 }
1720
1721 /**
1722 * Handle theme migration notice for version 3.0.1
1723 * Shows a dismissible notice to Pro users about migrating AI-generated themes
1724 */
1725 function mxchat_handle_theme_migration_notice() {
1726 // Get the CURRENT stored version (before it gets updated)
1727 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1728 $target_version = '3.0.1';
1729
1730 // Only run this once for the update to 3.0.1
1731 $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1732
1733 // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1734 if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1735 // Check if Pro is activated - only show to Pro users
1736 $license_status = get_option('mxchat_license_status', 'inactive');
1737 $is_pro = ($license_status === 'active');
1738
1739 if ($is_pro) {
1740 // Set flag to show the theme migration notification banner
1741 update_option('mxchat_show_theme_migration_notice', true);
1742 }
1743
1744 // Mark this update as handled (whether Pro or not)
1745 update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1746 }
1747 }
1748
1749 // Initialize plugin safely
1750 function mxchat_init() {
1751 // Include all class files first
1752 mxchat_include_classes();
1753
1754 // Run update check (this also ensures tables exist)
1755 mxchat_check_for_update();
1756
1757 // CRITICAL: Ensure tables exist on admin pages (safety net)
1758 add_action('admin_init', 'mxchat_ensure_tables_exist', 1);
1759
1760 // Add fallback rate limit check
1761 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1762
1763 // Add migration notice hook
1764 add_action('admin_notices', 'mxchat_show_migration_notice');
1765 add_action('admin_notices', 'mxchat_show_model_access_notice');
1766
1767 // Initialize classes with error handling
1768 try {
1769 // Initialize admin classes
1770 if (is_admin()) {
1771 if (class_exists('MxChat_Knowledge_Manager')) {
1772 $mxchat_knowledge_manager = new MxChat_Knowledge_Manager();
1773
1774 if (class_exists('MxChat_Admin')) {
1775 $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager);
1776 }
1777 }
1778
1779 // Initialize meta box class
1780 if (class_exists('MxChat_Meta_Box')) {
1781 new MxChat_Meta_Box();
1782 }
1783
1784 }
1785
1786 // Initialize content generator globally — it registers wp_head hook
1787 // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1788 if (class_exists('MxChat_Content_Generator')) {
1789 new MxChat_Content_Generator();
1790 }
1791
1792 // Initialize cache purge globally — settings writes can happen on any
1793 // request type (admin screens, admin-ajax autosave, wp-cli), and the
1794 // deferred-purge cron event fires on front-end requests.
1795 if (class_exists('MxChat_Cache_Purge')) {
1796 MxChat_Cache_Purge::init();
1797 }
1798
1799 // Initialize REST API globally — endpoints must be registered on
1800 // every request (admin and frontend) so they're reachable via /wp-json/.
1801 // Endpoints are auth-gated and locked until the site owner generates
1802 // a token in MxChat → API Access.
1803 if (class_exists('MxChat_Rest_Api')) {
1804 new MxChat_Rest_Api();
1805 }
1806
1807 // Initialize public classes
1808 if (class_exists('MxChat_Public')) {
1809 $mxchat_public = new MxChat_Public();
1810 }
1811
1812 if (class_exists('MxChat_Integrator')) {
1813 global $mxchat_integrator;
1814 $mxchat_integrator = new MxChat_Integrator();
1815 }
1816
1817 } catch (Exception $e) {
1818 //error_log('MxChat initialization error: ' . $e->getMessage());
1819
1820 // Show admin notice if there's an error
1821 if (is_admin()) {
1822 add_action('admin_notices', function() use ($e) {
1823 echo '<div class="notice notice-error"><p>';
1824 echo '<strong>MxChat Error:</strong> Plugin initialization failed. ';
1825 echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage());
1826 echo '</p></div>';
1827 });
1828 }
1829 }
1830 }
1831
1832 // Run initialization on plugins_loaded
1833 add_action('plugins_loaded', 'mxchat_init');
1834
1835 // Run migration check on admin init (for auto-updates without reactivation)
1836 add_action('admin_init', 'mxchat_check_and_run_migrations');
1837
1838 /**
1839 * Check and run migrations on admin init
1840 * This ensures migrations run even when plugin is auto-updated
1841 */
1842 function mxchat_check_and_run_migrations() {
1843 // Only run in admin and not on every request
1844 static $checked = false;
1845 if ($checked) {
1846 return;
1847 }
1848 $checked = true;
1849
1850 mxchat_migrate_pinecone_roles_add_bot_id();
1851 mxchat_migrate_add_content_type_column();
1852 mxchat_migrate_add_translations_table();
1853 mxchat_migrate_add_session_ratings_table();
1854 }
1855
1856 /**
1857 * Migration: Create per-session satisfaction ratings table (v3.2.6)
1858 * For users upgrading from versions before 3.2.6
1859 */
1860 function mxchat_migrate_add_session_ratings_table() {
1861 $migration_key = 'mxchat_session_ratings_table_created';
1862 if (get_option($migration_key)) {
1863 return;
1864 }
1865 mxchat_create_session_ratings_table();
1866 update_option($migration_key, '3.2.6');
1867 }
1868
1869 /**
1870 * Migration: Create transcript translations table (v3.0.4)
1871 * For users upgrading from versions before 3.0.4
1872 */
1873 function mxchat_migrate_add_translations_table() {
1874 $migration_key = 'mxchat_translations_table_created';
1875
1876 // Check if migration already ran
1877 if (get_option($migration_key)) {
1878 return;
1879 }
1880
1881 // Create the translations table
1882 mxchat_create_translations_table();
1883
1884 // Mark migration as complete
1885 update_option($migration_key, '3.0.4');
1886 }
1887
1888 /**
1889 * Migration: Update deprecated Gemini embedding model (v3.0.5)
1890 * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
1891 */
1892 function mxchat_migrate_gemini_embedding_model() {
1893 $options = get_option('mxchat_options', array());
1894
1895 if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
1896 $options['embedding_model'] = 'gemini-embedding-001';
1897 update_option('mxchat_options', $options);
1898 }
1899 }
1900
1901 // Register activation hook
1902 register_activation_hook(__FILE__, 'mxchat_activate');
1903
1904 // Add cron schedule
1905 add_filter('cron_schedules', function($schedules) {
1906 $schedules['one_minute'] = array(
1907 'interval' => 60,
1908 'display' => 'Every Minute'
1909 );
1910 return $schedules;
1911 });
1912
1913 // Register deactivation hook
1914 register_deactivation_hook(__FILE__, 'mxchat_deactivate');
1915
1916 /**
1917 * Per-session satisfaction rating: AJAX save handler (v3.2.6).
1918 * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
1919 * session_id makes this naturally idempotent — only the first rating per
1920 * session is stored; duplicate POSTs are silent no-ops.
1921 */
1922 function mxchat_save_session_rating() {
1923 global $wpdb;
1924
1925 $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1926 $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
1927 $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
1928 $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
1929
1930 if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
1931 wp_send_json_error(array('message' => 'invalid_input'), 400);
1932 }
1933
1934 if (strlen($feedback) > 1000) {
1935 $feedback = substr($feedback, 0, 1000);
1936 }
1937
1938 $table_name = $wpdb->prefix . 'mxchat_session_ratings';
1939 $existing = $wpdb->get_var($wpdb->prepare(
1940 "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
1941 $session_id
1942 ));
1943
1944 if ($existing) {
1945 if ($feedback !== '') {
1946 $wpdb->update(
1947 $table_name,
1948 array('rating_feedback' => $feedback),
1949 array('id' => (int) $existing),
1950 array('%s'),
1951 array('%d')
1952 );
1953 }
1954 wp_send_json_success(array('updated' => true));
1955 }
1956
1957 $inserted = $wpdb->insert(
1958 $table_name,
1959 array(
1960 'session_id' => $session_id,
1961 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
1962 'rating_value' => $rating_raw,
1963 'rating_feedback' => $feedback !== '' ? $feedback : null,
1964 'created_at' => current_time('mysql'),
1965 ),
1966 array('%s', '%s', '%d', '%s', '%s')
1967 );
1968
1969 if ($inserted === false) {
1970 wp_send_json_error(array('message' => 'db_insert_failed'), 500);
1971 }
1972
1973 wp_send_json_success(array('saved' => true));
1974 }
1975 add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
1976 add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');