PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.2.19
MxChat – AI Chatbot & Content Generation for WordPress v3.2.19
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.19, at mxchat-basic.php

2,088 lines 80.4 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.19
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 * Default confidence floor for the in-chat YouTube card, as a percentage
43 * (plan-mxchat-20260813-f52492). Higher than the site-wide Similarity
44 * Threshold default of 35 by design — see MxChat_Utils::video_embed_threshold().
45 * Declared here so the gate, the admin field and the tests all read ONE number.
46 */
47 if (!defined('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT')) {
48 define('MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT', 55);
49 }
50
51 /**
52 * Honest, versioned User-Agent for MXChat remote-content ingestion fetches
53 * (Knowledge Base PDF import, URL import, sitemap / website crawl).
54 *
55 * WAF rulesets (SiteGround/ModSecurity, Wordfence, Cloudflare managed rules)
56 * flag stale spoofed-browser UAs as scrapers and return 403 — which silently
57 * broke the single most common KB source: self-hosted media on the site's own
58 * domain. A truthful crawler identifier is the industry norm for well-behaved
59 * bots and lets a site owner allowlist "MXChatBot" in their WAF. Filterable so
60 * a locked-down host can supply a different string without a code change.
61 */
62 if (!function_exists('mxchat_ingest_user_agent')) {
63 function mxchat_ingest_user_agent() {
64 $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '1.0';
65 $ua = 'MXChatBot/' . $version . ' (+https://mxchat.ai/bot)';
66 return apply_filters('mxchat_ingest_user_agent', $ua);
67 }
68 }
69
70 function mxchat_load_textdomain() {
71 $domain = 'mxchat';
72 $locale = determine_locale();
73
74 // First, try to load from /wp-content/languages/plugins/ (preserved during updates)
75 $mo_file = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo';
76 if (file_exists($mo_file)) {
77 load_textdomain($domain, $mo_file);
78 return;
79 }
80
81 // Fallback to plugin's /languages directory
82 load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages');
83 }
84 add_action('init', 'mxchat_load_textdomain');
85
86 /**
87 * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026.
88 * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview
89 * (Google's official migration target) the first time admin_init fires after update.
90 */
91 add_action('admin_init', function () {
92 if (get_option('mxchat_gemini_3_remap_done')) {
93 return;
94 }
95 $opts = get_option('mxchat_options');
96 if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') {
97 $opts['model'] = 'gemini-3.1-pro-preview';
98 update_option('mxchat_options', $opts);
99 }
100 if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') {
101 $opts['content_model'] = 'gemini-3.1-pro-preview';
102 update_option('mxchat_options', $opts);
103 }
104 update_option('mxchat_gemini_3_remap_done', 1);
105 });
106
107 /**
108 * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212,
109 * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing
110 * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning
111 * (modern, fast, broadly available) the first time admin_init fires after update.
112 */
113 add_action('admin_init', function () {
114 if (get_option('mxchat_grok_2_remap_done')) {
115 return;
116 }
117 $opts = get_option('mxchat_options');
118 if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') {
119 $opts['model'] = 'grok-4-1-fast-non-reasoning';
120 update_option('mxchat_options', $opts);
121 }
122 if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') {
123 $opts['content_model'] = 'grok-4-1-fast-non-reasoning';
124 update_option('mxchat_options', $opts);
125 }
126 update_option('mxchat_grok_2_remap_done', 1);
127 });
128
129 /**
130 * One-time migration: Anthropic retired the Claude 4 (2025-05-14) snapshots on
131 * June 15, 2026 — claude-opus-4-20250514 and claude-sonnet-4-20250514 now return
132 * an API error. Existing installs with a dead ID get auto-remapped to the current
133 * equivalents Anthropic recommends (Opus 4.8 / Sonnet 4.6) the first time admin_init
134 * fires after update. Mirrors the gemini-3-pro-preview / grok-2 rescues above.
135 */
136 add_action('admin_init', function () {
137 if (get_option('mxchat_claude_4_retire_remap_done')) {
138 return;
139 }
140 $map = array(
141 'claude-opus-4-20250514' => 'claude-opus-4-8',
142 'claude-sonnet-4-20250514' => 'claude-sonnet-4-6',
143 );
144 $opts = get_option('mxchat_options');
145 if (is_array($opts)) {
146 $changed = false;
147 if (isset($opts['model']) && isset($map[$opts['model']])) {
148 $opts['model'] = $map[$opts['model']];
149 $changed = true;
150 }
151 if (isset($opts['content_model']) && isset($map[$opts['content_model']])) {
152 $opts['content_model'] = $map[$opts['content_model']];
153 $changed = true;
154 }
155 if ($changed) {
156 update_option('mxchat_options', $opts);
157 }
158 }
159 update_option('mxchat_claude_4_retire_remap_done', 1);
160 });
161
162 /**
163 * Exclude MxChat assets from caching plugin optimizations
164 *
165 * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
166 * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
167 * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery.
168 *
169 * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also
170 * be excluded from any optimization that changes load order or timing.
171 */
172
173 // ── WP Rocket ────────────────────────────────────────────────────────────────
174
175 // Exclude from Remove Unused CSS (RUCSS)
176 add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) {
177 if (!is_array($exclusions)) $exclusions = array();
178 $exclusions[] = 'mxchat';
179 return $exclusions;
180 });
181
182 // Exclude CSS from minification/combination
183 add_filter('rocket_exclude_css', function($excluded) {
184 if (!is_array($excluded)) $excluded = array();
185 $excluded[] = '/plugins/mxchat-basic/css/chat-style.css';
186 return $excluded;
187 });
188
189 // Exclude JS from minification/combination
190 add_filter('rocket_exclude_js', function($excluded) {
191 if (!is_array($excluded)) $excluded = array();
192 $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
193 $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
194 $excluded[] = '/jquery-core';
195 $excluded[] = '/jquery.min.js';
196 $excluded[] = '/jquery.js';
197 $excluded[] = '/jquery-migrate';
198 return $excluded;
199 });
200
201 // Exclude JS from defer
202 add_filter('rocket_exclude_defer_js', function($excluded) {
203 if (!is_array($excluded)) $excluded = array();
204 $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
205 $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
206 $excluded[] = '/jquery-core';
207 $excluded[] = '/jquery.min.js';
208 $excluded[] = '/jquery.js';
209 $excluded[] = '/jquery-migrate';
210 return $excluded;
211 });
212
213 // Exclude from delay JS execution
214 add_filter('rocket_delay_js_exclusions', function($excluded) {
215 if (!is_array($excluded)) $excluded = array();
216 $excluded[] = 'mxchat';
217 $excluded[] = 'chat-script';
218 $excluded[] = 'floating-script';
219 $excluded[] = '/jquery-core';
220 $excluded[] = '/jquery.min.js';
221 $excluded[] = '/jquery.js';
222 $excluded[] = '/jquery-migrate';
223 return $excluded;
224 });
225
226 // ── LiteSpeed Cache ──────────────────────────────────────────────────────────
227
228 // Exclude CSS from optimization
229 add_filter('litespeed_optimize_css_excludes', function($excluded) {
230 if (!is_array($excluded)) $excluded = array();
231 $excluded[] = 'chat-style.css';
232 $excluded[] = 'mxchat';
233 return $excluded;
234 });
235
236 // Exclude from UCSS (Unique CSS) - prevents LiteSpeed from stripping "unused" MxChat CSS
237 add_filter('litespeed_ucss_whitelist', function($whitelist) {
238 if (!is_array($whitelist)) $whitelist = array();
239 $whitelist[] = '.mxchat-chatbot-wrapper';
240 $whitelist[] = '.floating-chatbot';
241 $whitelist[] = '.floating-chatbot-button';
242 $whitelist[] = '.chatbot-top-bar';
243 $whitelist[] = '.mxchat-chatbot';
244 $whitelist[] = '.chat-container';
245 $whitelist[] = '.chat-box';
246 $whitelist[] = '.bot-message';
247 $whitelist[] = '.input-container';
248 $whitelist[] = '.chat-input';
249 $whitelist[] = '.send-button';
250 $whitelist[] = '.pre-chat-message';
251 $whitelist[] = '.mxchat-popular-questions';
252 $whitelist[] = '.chat-toolbar';
253 $whitelist[] = '.exit-chat';
254 $whitelist[] = '.email-blocker';
255 return $whitelist;
256 });
257
258 // Exclude CSS from CCSS (Critical CSS) generation
259 add_filter('litespeed_optm_ccss_exc', function($excluded) {
260 if (!is_array($excluded)) $excluded = array();
261 $excluded[] = 'chat-style.css';
262 $excluded[] = 'mxchat';
263 return $excluded;
264 });
265
266 // Exclude JS from defer
267 add_filter('litespeed_optm_js_defer_exc', function($excluded) {
268 if (!is_array($excluded)) $excluded = array();
269 $excluded[] = 'chat-script.js';
270 $excluded[] = 'floating-script.js';
271 $excluded[] = 'mxchat';
272 $excluded[] = 'jquery.min.js';
273 $excluded[] = 'jquery.js';
274 return $excluded;
275 });
276
277 // Exclude JS from combining
278 add_filter('litespeed_optm_js_exc', function($excluded) {
279 if (!is_array($excluded)) $excluded = array();
280 $excluded[] = 'chat-script.js';
281 $excluded[] = 'floating-script.js';
282 $excluded[] = 'mxchat';
283 $excluded[] = 'jquery.min.js';
284 $excluded[] = 'jquery.js';
285 return $excluded;
286 });
287
288 // Exclude JS from delayed execution
289 add_filter('litespeed_optm_js_delay_exc', function($excluded) {
290 if (!is_array($excluded)) $excluded = array();
291 $excluded[] = 'chat-script.js';
292 $excluded[] = 'floating-script.js';
293 $excluded[] = 'mxchat';
294 return $excluded;
295 });
296
297 // Exclude from Guest Mode optimization
298 add_filter('litespeed_guest_optm_exc', function($excluded) {
299 if (!is_array($excluded)) $excluded = array();
300 $excluded[] = 'mxchat';
301 $excluded[] = 'chat-style';
302 $excluded[] = 'chat-script';
303 $excluded[] = 'floating-script';
304 return $excluded;
305 });
306
307 // ── Autoptimize ──────────────────────────────────────────────────────────────
308
309 // Exclude CSS from optimization (comma-separated strings)
310 add_filter('autoptimize_filter_css_exclude', function($excluded) {
311 if (!is_string($excluded)) $excluded = '';
312 return $excluded . ', mxchat, chat-style.css';
313 });
314
315 // Exclude JS from optimization (comma-separated strings)
316 add_filter('autoptimize_filter_js_exclude', function($excluded) {
317 if (!is_string($excluded)) $excluded = '';
318 return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js';
319 });
320
321 // ── SG Optimizer (SiteGround) ────────────────────────────────────────────────
322
323 add_filter('sgo_js_minify_exclude', function($excluded) {
324 if (!is_array($excluded)) $excluded = array();
325 $excluded[] = 'chat-script.js';
326 $excluded[] = 'floating-script.js';
327 $excluded[] = 'jquery.min.js';
328 return $excluded;
329 });
330
331 add_filter('sgo_javascript_combine_exclude', function($excluded) {
332 if (!is_array($excluded)) $excluded = array();
333 $excluded[] = 'chat-script.js';
334 $excluded[] = 'floating-script.js';
335 $excluded[] = 'jquery.min.js';
336 return $excluded;
337 });
338
339 add_filter('sgo_js_async_exclude', function($excluded) {
340 if (!is_array($excluded)) $excluded = array();
341 $excluded[] = 'chat-script.js';
342 $excluded[] = 'floating-script.js';
343 $excluded[] = 'jquery.min.js';
344 return $excluded;
345 });
346
347 // ── W3 Total Cache ───────────────────────────────────────────────────────────
348
349 add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) {
350 if (strpos($file, 'chat-script.js') !== false ||
351 strpos($file, 'floating-script.js') !== false ||
352 strpos($file, 'jquery.min.js') !== false ||
353 strpos($file, 'jquery.js') !== false) {
354 return false;
355 }
356 return $do_minify;
357 }, 10, 3);
358
359 // ── WP Super Cache ──────────────────────────────────────────────────────────
360
361 add_filter('wpsc_rejected_uri', function($rejected) {
362 if (!is_array($rejected)) $rejected = array();
363 $rejected[] = 'wp-admin/admin-ajax.php';
364 return $rejected;
365 });
366
367 // ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix)
368 // Each cache plugin gets its own filter export so that visitors hitting an
369 // edge-cached page never receive cached chat-AJAX responses. The chat send /
370 // stream send / file upload all POST to /wp-admin/admin-ajax.php with
371 // `action=mxchat_*`. Without these exports, a cache plugin can stale a response
372 // and break the per-session nonce flow on the first message.
373
374 // WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings.
375 add_filter('rocket_cache_reject_uri', function($uris) {
376 if (!is_array($uris)) $uris = array();
377 $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*';
378 return $uris;
379 });
380
381 // LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits
382 // caching when the request matches our chat-AJAX pattern.
383 add_filter('litespeed_cache_no_cache_for_request', function($no_cache) {
384 if ($no_cache) return $no_cache;
385 if (!empty($_SERVER['REQUEST_URI']) &&
386 strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
387 !empty($_REQUEST['action']) &&
388 strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
389 return true;
390 }
391 return $no_cache;
392 });
393
394 // W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when
395 // the URI matches.
396 add_filter('w3tc_pgcache_request_skip_uri', function($skip) {
397 if ($skip) return $skip;
398 if (!empty($_SERVER['REQUEST_URI']) &&
399 strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
400 !empty($_REQUEST['action']) &&
401 strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
402 return true;
403 }
404 return $skip;
405 });
406
407 // FlyingPress — `flying_press_cacheable` takes a boolean and is run per
408 // request. Same pattern as LiteSpeed / W3TC.
409 add_filter('flying_press_cacheable', function($cacheable) {
410 if (!$cacheable) return $cacheable;
411 if (!empty($_SERVER['REQUEST_URI']) &&
412 strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
413 !empty($_REQUEST['action']) &&
414 strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
415 return false;
416 }
417 return $cacheable;
418 });
419
420 // Include classes with error handling
421 function mxchat_include_classes() {
422 $class_files = array(
423 'includes/class-mxchat-model-catalog.php',
424 'includes/class-mxchat-model-liveness.php',
425 'includes/class-mxchat-session-store.php',
426 'includes/class-mxchat-live-agent-schedule.php',
427 'includes/class-mxchat-tool-registry.php',
428 'includes/class-mxchat-integrator.php',
429 'includes/class-mxchat-admin.php',
430 'includes/class-mxchat-public.php',
431 'includes/class-mxchat-utils.php',
432 'includes/class-mxchat-user.php',
433 'includes/class-mxchat-privacy.php',
434 'includes/class-mxchat-meta-box.php',
435 'includes/class-mxchat-chunker.php',
436 'includes/class-mxchat-word-handler.php',
437 'includes/class-mxchat-content-generator.php',
438 'includes/class-mxchat-cache-purge.php',
439 'includes/class-mxchat-editor-assistant.php',
440 'includes/class-rest-api.php',
441 'admin/class-ajax-handler.php',
442 'admin/class-pinecone-manager.php',
443 'admin/class-knowledge-manager.php'
444 );
445
446 foreach ($class_files as $file) {
447 $file_path = plugin_dir_path(__FILE__) . $file;
448 if (file_exists($file_path)) {
449 require_once $file_path;
450 } else {
451 //error_log('MxChat: Missing class file - ' . $file);
452 }
453 }
454
455 // Register the native function-calling admin-post save handler (a41dee).
456 if (class_exists('MxChat_Tool_Registry')) {
457 MxChat_Tool_Registry::init();
458 }
459
460 // GDPR: register with WP's personal-data export/erase tools (b81e42).
461 if (class_exists('MxChat_Privacy')) {
462 MxChat_Privacy::init();
463 }
464
465 // Per-session state store: retention cron + the cron-independent
466 // migration drain off admin_init (b64b77).
467 if (class_exists('MxChat_Session_Store')) {
468 MxChat_Session_Store::init();
469 }
470
471 // Daily model-liveness check + its warning notice (b65e8d). Read-only and
472 // fail-open: one listing request per in-use provider per day, none at all
473 // when no key is stored.
474 if (class_exists('MxChat_Model_Liveness')) {
475 MxChat_Model_Liveness::init();
476 }
477
478 // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
479 // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
480 // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
481 if (class_exists('MxChat_Editor_Assistant')) {
482 MxChat_Editor_Assistant::init();
483 }
484
485 // Admin pages that aren't classes (procedural include).
486 if (is_admin()) {
487 $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
488 if (file_exists($admin_api_page)) {
489 require_once $admin_api_page;
490 }
491 // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
492 // The require MUST live here (admin bootstrap) and not just inside
493 // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
494 // fire on admin-ajax.php requests, so the wizard's AJAX handlers
495 // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
496 // auto_graduate + the f7c7d4 dismiss handler) would never register.
497 $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
498 if (file_exists($admin_onboarding_page)) {
499 require_once $admin_onboarding_page;
500 }
501 }
502 }
503
504 /**
505 * Lazy-load the PDF parser library only when needed.
506 * Avoids loading 44 files on every page request.
507 */
508 function mxchat_load_pdf_parser() {
509 if (class_exists('\Smalot\PdfParser\Parser')) {
510 return true;
511 }
512 $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
513 if (file_exists($autoload_path)) {
514 require_once $autoload_path;
515 return true;
516 }
517 return false;
518 }
519
520 /**
521 * Create URL click tracking table
522 */
523 function mxchat_create_url_clicks_table() {
524 global $wpdb;
525
526 $table_name = $wpdb->prefix . 'mxchat_url_clicks';
527
528 $charset_collate = $wpdb->get_charset_collate();
529
530 $sql = "CREATE TABLE $table_name (
531 id mediumint(9) NOT NULL AUTO_INCREMENT,
532 session_id varchar(100) NOT NULL,
533 clicked_url text NOT NULL,
534 message_context text,
535 click_timestamp datetime DEFAULT CURRENT_TIMESTAMP,
536 user_ip varchar(45),
537 user_agent text,
538 PRIMARY KEY (id),
539 KEY session_id (session_id),
540 KEY click_timestamp (click_timestamp)
541 ) $charset_collate;";
542
543 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
544 dbDelta($sql);
545 }
546
547 /**
548 * Create the per-session state table (b64b77).
549 *
550 * Callable from the activation hook, which can run before plugins_loaded has
551 * included the class files — so it loads the class itself when needed.
552 */
553 function mxchat_create_sessions_table() {
554 if (!class_exists('MxChat_Session_Store')) {
555 $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
556 if (!file_exists($path)) {
557 return false;
558 }
559 require_once $path;
560 }
561
562 return MxChat_Session_Store::create_table();
563 }
564
565 /**
566 * FIXED: Robust table creation and column management
567 */
568 function mxchat_create_chat_transcripts_table() {
569 global $wpdb;
570
571 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
572 $charset_collate = $wpdb->get_charset_collate();
573
574 // Create table with ALL columns including user_name from the start
575 $sql = "CREATE TABLE $table_name (
576 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
577 user_id MEDIUMINT(9) DEFAULT 0,
578 session_id VARCHAR(255) NOT NULL,
579 role VARCHAR(255) NOT NULL,
580 message TEXT NOT NULL,
581 user_email VARCHAR(255) DEFAULT NULL,
582 user_name VARCHAR(100) DEFAULT NULL,
583 user_identifier VARCHAR(255) DEFAULT NULL,
584 originating_page_url TEXT DEFAULT NULL,
585 originating_page_title VARCHAR(500) DEFAULT NULL,
586 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
587 PRIMARY KEY (id),
588 KEY session_id (session_id),
589 KEY user_email (user_email),
590 KEY timestamp (timestamp)
591 ) $charset_collate;";
592
593 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
594 $result = dbDelta($sql);
595
596 // Log the result for debugging
597 if (empty($result)) {
598 //error_log("MxChat: dbDelta returned empty result for chat transcripts table");
599 } else {
600 //error_log("MxChat: dbDelta result: " . print_r($result, true));
601 }
602
603 // IMPORTANT: Ensure all columns exist for existing installations
604 mxchat_ensure_all_columns($table_name);
605 }
606
607 /**
608 * Ensure all required columns exist (for upgrades)
609 */
610 function mxchat_ensure_all_columns($table_name) {
611 global $wpdb;
612
613 // First check if table exists
614 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
615 if (!$table_exists) {
616 //error_log("MxChat: Table $table_name does not exist, cannot add columns");
617 return;
618 }
619
620 // Define all required columns and their types
621 $required_columns = [
622 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
623 'user_email' => 'VARCHAR(255) DEFAULT NULL',
624 'user_name' => 'VARCHAR(100) DEFAULT NULL',
625 'originating_page_url' => 'TEXT DEFAULT NULL',
626 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL',
627 'rag_context' => 'LONGTEXT DEFAULT NULL'
628 ];
629
630 // Get existing columns
631 $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
632 if (empty($existing_columns)) {
633 //error_log("MxChat: Could not get columns for table $table_name");
634 return;
635 }
636
637 $existing_column_names = array_column($existing_columns, 'Field');
638
639 // Add missing columns
640 foreach ($required_columns as $column_name => $column_definition) {
641 if (!in_array($column_name, $existing_column_names)) {
642 $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition";
643 $result = $wpdb->query($alter_sql);
644
645 if ($result === false) {
646 //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error);
647 } else {
648 //error_log("MxChat: Successfully added column $column_name to $table_name");
649 }
650 }
651 }
652 }
653
654 /**
655 * Add role restriction column to knowledge base table
656 */
657 function mxchat_add_role_restriction_column() {
658 global $wpdb;
659 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
660
661 // Check if table exists first
662 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
663 if (!$table_exists) {
664 //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column");
665 return;
666 }
667
668 // Check if column already exists
669 $column_exists = $wpdb->get_results(
670 $wpdb->prepare(
671 "SHOW COLUMNS FROM {$table_name} LIKE %s",
672 'role_restriction'
673 )
674 );
675
676 if (empty($column_exists)) {
677 $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url";
678 $result = $wpdb->query($alter_sql);
679
680 if ($result === false) {
681 //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error);
682 } else {
683 //error_log("MxChat: Successfully added role_restriction column");
684
685 // Set all existing records to 'public' (everyone can access)
686 $update_result = $wpdb->query(
687 "UPDATE {$table_name}
688 SET role_restriction = 'public'
689 WHERE role_restriction IS NULL OR role_restriction = ''"
690 );
691
692 if ($update_result !== false) {
693 //error_log("MxChat: Updated {$update_result} existing records to public access");
694 }
695 }
696 }
697 }
698
699 /**
700 * Add enabled_bots column to intents table for multi-bot action filtering
701 */
702 function mxchat_add_enabled_bots_column() {
703 global $wpdb;
704 $table_name = $wpdb->prefix . 'mxchat_intents';
705
706 // Check if table exists first
707 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
708 if (!$table_exists) {
709 //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column");
710 return;
711 }
712
713 // Check if column already exists
714 $column_exists = $wpdb->get_results(
715 $wpdb->prepare(
716 "SHOW COLUMNS FROM {$table_name} LIKE %s",
717 'enabled_bots'
718 )
719 );
720
721 if (empty($column_exists)) {
722 $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled";
723 $result = $wpdb->query($alter_sql);
724
725 if ($result === false) {
726 //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error);
727 } else {
728 //error_log("MxChat: Successfully added enabled_bots column");
729
730 // Set all existing actions to work with 'default' bot for backward compatibility
731 $default_bots = json_encode(['default']);
732 $update_result = $wpdb->query(
733 $wpdb->prepare(
734 "UPDATE {$table_name}
735 SET enabled_bots = %s
736 WHERE enabled_bots IS NULL OR enabled_bots = ''",
737 $default_bots
738 )
739 );
740
741 if ($update_result !== false) {
742 //error_log("MxChat: Updated {$update_result} existing actions to work with default bot");
743 }
744 }
745 }
746 }
747
748 /**
749 * Create Pinecone role restrictions table with multi-bot support
750 */
751 function mxchat_create_pinecone_roles_table() {
752 global $wpdb;
753
754 $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
755 $charset_collate = $wpdb->get_charset_collate();
756
757 $sql = "CREATE TABLE $table_name (
758 id mediumint(9) NOT NULL AUTO_INCREMENT,
759 vector_id varchar(255) NOT NULL,
760 bot_id varchar(50) NOT NULL DEFAULT 'default',
761 source_url text,
762 role_restriction varchar(50) DEFAULT 'public',
763 updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
764 PRIMARY KEY (id),
765 UNIQUE KEY vector_bot (vector_id, bot_id),
766 KEY role_restriction (role_restriction),
767 KEY bot_id (bot_id)
768 ) $charset_collate;";
769
770 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
771 dbDelta($sql);
772 }
773
774 /**
775 * Add bot_id column to mxchat_pinecone_roles table for multi-bot support
776 * This migration runs once to update existing installations
777 */
778 function mxchat_migrate_pinecone_roles_add_bot_id() {
779 global $wpdb;
780
781 // Check if migration already ran
782 $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0');
783 if (version_compare($migration_version, '2.5.2', '>=')) {
784 return; // Already migrated
785 }
786
787 $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
788
789 // Check if table exists
790 if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
791 return; // Table doesn't exist yet
792 }
793
794 // Check if bot_id column already exists
795 $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'");
796
797 if (empty($column_exists)) {
798 // Add bot_id column
799 $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id");
800
801 // Update the unique key to include bot_id
802 $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id");
803 $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)");
804
805 // Add index for bot_id
806 $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
807
808 //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
809 }
810
811 // Mark migration as complete
812 update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
813 }
814
815 /**
816 * 2.5.6: Add content_type column to mxchat_system_prompt_content table
817 * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.)
818 */
819 function mxchat_migrate_add_content_type_column() {
820 global $wpdb;
821
822 // Check if migration already ran
823 $migration_version = get_option('mxchat_content_type_migration_version', '0');
824 if (version_compare($migration_version, '2.5.6', '>=')) {
825 return;
826 }
827
828 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
829
830 // Check if table exists
831 if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
832 return;
833 }
834
835 // Check if content_type column already exists
836 $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'");
837
838 if (empty($column_exists)) {
839 // Add content_type column with default value 'content' for backwards compatibility
840 $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction");
841
842 // Add index for better query performance
843 $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
844
845 //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
846 }
847
848 // Mark migration as complete
849 update_option('mxchat_content_type_migration_version', '2.5.6');
850 }
851
852 /**
853 * 3.2.4: Backfill the active embedding model option for installs that already
854 * have KB content but no stamped model. The mismatch warning compares this
855 * against the user's currently selected model — no per-row column needed.
856 */
857 function mxchat_backfill_active_embedding_model() {
858 global $wpdb;
859
860 if (get_option('mxchat_active_embedding_model', '') !== '') {
861 return;
862 }
863
864 $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
865 if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
866 return;
867 }
868
869 $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
870 if ($kb_count > 0) {
871 $options = get_option('mxchat_options', array());
872 $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
873 update_option('mxchat_active_embedding_model', $current_model, false);
874 }
875 }
876
877 /**
878 * 2.5.2: Create queue processing tables for reliable background processing
879 */
880 function mxchat_create_queue_tables() {
881 global $wpdb;
882 $charset_collate = $wpdb->get_charset_collate();
883
884 // Main queue table
885 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
886 $sql_queue = "CREATE TABLE $queue_table (
887 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
888 queue_id varchar(64) NOT NULL,
889 item_type varchar(20) NOT NULL,
890 item_data longtext NOT NULL,
891 status varchar(20) NOT NULL DEFAULT 'pending',
892 bot_id varchar(50) NOT NULL DEFAULT 'default',
893 priority int(11) NOT NULL DEFAULT 0,
894 attempts int(11) NOT NULL DEFAULT 0,
895 max_attempts int(11) NOT NULL DEFAULT 3,
896 error_message text DEFAULT NULL,
897 created_at datetime NOT NULL,
898 started_at datetime DEFAULT NULL,
899 completed_at datetime DEFAULT NULL,
900 PRIMARY KEY (id),
901 KEY queue_id (queue_id),
902 KEY status (status),
903 KEY item_type (item_type),
904 KEY priority (priority)
905 ) $charset_collate;";
906
907 // Queue metadata table
908 $meta_table = $wpdb->prefix . 'mxchat_queue_meta';
909 $sql_meta = "CREATE TABLE $meta_table (
910 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
911 queue_id varchar(64) NOT NULL,
912 meta_key varchar(255) NOT NULL,
913 meta_value longtext,
914 PRIMARY KEY (id),
915 KEY queue_id (queue_id),
916 KEY meta_key (meta_key)
917 ) $charset_collate;";
918
919 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
920 dbDelta($sql_queue);
921 dbDelta($sql_meta);
922
923 //error_log("MxChat: Queue tables created/updated successfully");
924 }
925
926 /**
927 * Create transcript translations table for persisting translations
928 */
929 function mxchat_create_translations_table() {
930 global $wpdb;
931 $charset_collate = $wpdb->get_charset_collate();
932
933 $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
934 $sql = "CREATE TABLE $table_name (
935 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
936 session_id varchar(255) NOT NULL,
937 language_code varchar(10) NOT NULL,
938 translations longtext NOT NULL,
939 created_at datetime NOT NULL,
940 updated_at datetime NOT NULL,
941 PRIMARY KEY (id),
942 UNIQUE KEY session_lang (session_id, language_code),
943 KEY session_id (session_id)
944 ) $charset_collate;";
945
946 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
947 dbDelta($sql);
948 }
949
950 /**
951 * Create per-session satisfaction ratings table (v3.2.6)
952 * Stores one 👍/👎 rating + optional feedback per chat session.
953 */
954 function mxchat_create_session_ratings_table() {
955 global $wpdb;
956 $charset_collate = $wpdb->get_charset_collate();
957
958 $table_name = $wpdb->prefix . 'mxchat_session_ratings';
959 $sql = "CREATE TABLE $table_name (
960 id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
961 session_id varchar(255) NOT NULL,
962 bot_id varchar(50) NOT NULL DEFAULT 'default',
963 rating_value tinyint(1) NOT NULL,
964 rating_feedback text DEFAULT NULL,
965 created_at datetime NOT NULL,
966 PRIMARY KEY (id),
967 UNIQUE KEY session_id (session_id),
968 KEY bot_id (bot_id),
969 KEY created_at (created_at)
970 ) $charset_collate;";
971
972 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
973 dbDelta($sql);
974 }
975
976 /**
977 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
978 * This fixes "url, source_url. The supplied values may be too long" errors
979 */
980 function mxchat_fix_url_column_size() {
981 global $wpdb;
982 $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
983
984 // Check if table exists
985 $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
986 if (!$table_exists) {
987 return;
988 }
989
990 // Change url and source_url from VARCHAR to TEXT to handle long URLs
991 // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.)
992 $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT");
993 $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT");
994
995 //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support");
996 }
997
998 /**
999 * Migrate deprecated AI models to their replacements
1000 * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
1001 * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1002 * Without utf8mb4, any bot response containing emojis silently fails to insert.
1003 */
1004 function mxchat_migrate_transcripts_charset() {
1005 global $wpdb;
1006 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1007 $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
1008 }
1009
1010 /**
1011 * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
1012 */
1013 function mxchat_migrate_deprecated_models() {
1014 $options = get_option('mxchat_options', array());
1015 $migrated = false;
1016 $migration_message = '';
1017
1018 if (!isset($options['model'])) {
1019 return;
1020 }
1021
1022 $current_model = $options['model'];
1023
1024 // Migrate deprecated/retired Claude models BY TIER so a rescued site lands on
1025 // the current generation, not an older intermediate (plan dc91bd — the previous
1026 // single target, claude-opus-4-6, is now two Opus generations behind).
1027 $deprecated_claude_opus = array(
1028 'claude-3-opus-20240229', // Retired Jan 5, 2026
1029 'claude-opus-4-20250514', // Deprecated
1030 'claude-opus-4-1-20250805', // Retired Aug 5, 2026 (first-party API)
1031 );
1032 $deprecated_claude_sonnet = array(
1033 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
1034 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
1035 'claude-3-7-sonnet-20250219', // Retired Feb 19, 2026
1036 'claude-3-sonnet-20240229', // Legacy
1037 'claude-sonnet-4-20250514', // Deprecated
1038 );
1039 $deprecated_claude_haiku = array(
1040 'claude-3-haiku-20240307', // Legacy
1041 'claude-3-5-haiku-20241022', // Deprecated
1042 );
1043 if (in_array($current_model, $deprecated_claude_opus, true)) {
1044 $options['model'] = 'claude-opus-5';
1045 $migrated = true;
1046 $migration_message = sprintf(
1047 'Your chatbot model has been automatically updated from %s to Claude Opus 5 because Anthropic retired the older Claude model.',
1048 $current_model
1049 );
1050 } elseif (in_array($current_model, $deprecated_claude_sonnet, true)) {
1051 $options['model'] = 'claude-sonnet-5';
1052 $migrated = true;
1053 $migration_message = sprintf(
1054 'Your chatbot model has been automatically updated from %s to Claude Sonnet 5 because Anthropic retired the older Claude model.',
1055 $current_model
1056 );
1057 } elseif (in_array($current_model, $deprecated_claude_haiku, true)) {
1058 $options['model'] = 'claude-haiku-4-5-20251001';
1059 $migrated = true;
1060 $migration_message = sprintf(
1061 'Your chatbot model has been automatically updated from %s to Claude Haiku 4.5 because Anthropic retired the older Claude model.',
1062 $current_model
1063 );
1064 }
1065
1066 // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.6 Sol.
1067 // (Previous target gpt-5.1-chat-latest itself retires 2026-08-10 — never
1068 // migrate onto a model that is already on a deprecation list.)
1069 if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1070 $options['model'] = 'gpt-5.6-sol';
1071 $migrated = true;
1072 $migration_message = sprintf(
1073 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
1074 $current_model
1075 );
1076 }
1077
1078 // Migrate the gpt-5.x-chat-latest aliases OpenAI retires on August 10, 2026.
1079 // Replacement per OpenAI's deprecations page: gpt-5.6-sol (plan e46b8f).
1080 if (in_array($current_model, array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1081 $options['model'] = 'gpt-5.6-sol';
1082 $migrated = true;
1083 $migration_message = sprintf(
1084 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol because OpenAI retires the GPT-5.x Chat Latest models on August 10, 2026.',
1085 $current_model
1086 );
1087 }
1088
1089 // The content generator has its own model option — same retirement applies.
1090 if (isset($options['content_model'])
1091 && in_array($options['content_model'], array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1092 $old_content_model = $options['content_model'];
1093 $options['content_model'] = 'gpt-5.6-sol';
1094 $migrated = true;
1095 $migration_message = trim($migration_message . ' ' . sprintf(
1096 'Your content generation model has also been updated from %s to GPT-5.6 Sol for the same OpenAI retirement.',
1097 $old_content_model
1098 ));
1099 }
1100
1101 // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1102 if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1103 $options['model'] = 'gpt-5-mini';
1104 $migrated = true;
1105 $migration_message = sprintf(
1106 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.',
1107 $current_model
1108 );
1109 }
1110
1111 // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1112 // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1113 // request 400s). V4 Flash is DeepSeek's designated successor for the
1114 // legacy deepseek-chat alias.
1115 if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1116 $options['model'] = 'deepseek-v4-flash';
1117 $migrated = true;
1118 $migration_message = sprintf(
1119 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1120 $current_model
1121 );
1122 }
1123
1124 if ($migrated) {
1125 update_option('mxchat_options', $options);
1126 update_option('mxchat_model_migrated_notice', true);
1127 update_option('mxchat_model_migration_message', $migration_message);
1128 }
1129 }
1130
1131 /**
1132 * Show admin notice after model migration
1133 */
1134 function mxchat_show_migration_notice() {
1135 if (get_option('mxchat_model_migrated_notice')) {
1136 $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
1137 ?>
1138 <div class="notice notice-info is-dismissible">
1139 <p>
1140 <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
1141 <?php echo esc_html($migration_message); ?>
1142 </p>
1143 </div>
1144 <?php
1145 delete_option('mxchat_model_migrated_notice');
1146 delete_option('mxchat_model_migration_message');
1147 }
1148 }
1149
1150 /**
1151 * Persistent admin notice when the provider rejected the configured model
1152 * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1153 * integrator whenever a chat request fails on a model-access error — including
1154 * requests from anonymous visitors, which is the case that otherwise stays
1155 * invisible to the site owner for weeks (plan e46b8f).
1156 *
1157 * Deleted after render so it re-arms on the next failed chat: the notice keeps
1158 * reappearing until the model is fixed, then stops on its own.
1159 */
1160 function mxchat_show_model_access_notice() {
1161 if (!current_user_can('manage_options')) {
1162 return;
1163 }
1164 $notice = get_option('mxchat_model_access_notice');
1165 if (!is_array($notice) || empty($notice['model'])) {
1166 return;
1167 }
1168 $settings_url = admin_url('admin.php?page=mxchat-max');
1169 ?>
1170 <div class="notice notice-error is-dismissible">
1171 <p>
1172 <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1173 <?php
1174 printf(
1175 /* translators: 1: model id, 2: provider name */
1176 esc_html__('Chat requests using the model "%1$s" are failing because %2$s reports it as unavailable on your API key (it may have been retired). Visitors may be seeing errors instead of replies.', 'mxchat'),
1177 esc_html($notice['model']),
1178 esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1179 );
1180 ?>
1181 <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1182 </p>
1183 </div>
1184 <?php
1185 delete_option('mxchat_model_access_notice');
1186 }
1187
1188 function mxchat_activate() {
1189 global $wpdb;
1190 $charset_collate = $wpdb->get_charset_collate();
1191
1192 //error_log("MxChat: Running activation function");
1193
1194 // Create chat transcripts table with improved function
1195 mxchat_create_chat_transcripts_table();
1196
1197 // Per-session state table (b64b77). Activation can run before
1198 // plugins_loaded has included the class files, so require it directly.
1199 mxchat_create_sessions_table();
1200
1201 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
1202 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1203 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1204 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
1205 url TEXT NOT NULL,
1206 article_content LONGTEXT NOT NULL,
1207 embedding_vector LONGTEXT,
1208 source_url TEXT DEFAULT NULL,
1209 role_restriction VARCHAR(50) DEFAULT 'public',
1210 content_type VARCHAR(50) DEFAULT 'content',
1211 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1212 PRIMARY KEY (id),
1213 KEY content_type (content_type)
1214 ) $charset_collate;";
1215
1216 // Intents Table - NOW INCLUDES enabled_bots column from the start
1217 $intents_table = $wpdb->prefix . 'mxchat_intents';
1218 $sql_intents_table = "CREATE TABLE $intents_table (
1219 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1220 intent_label VARCHAR(255) NOT NULL,
1221 phrases TEXT NOT NULL,
1222 embedding_vector LONGTEXT NOT NULL,
1223 callback_function VARCHAR(255) NOT NULL,
1224 similarity_threshold FLOAT DEFAULT 0.85,
1225 enabled TINYINT(1) NOT NULL DEFAULT 1,
1226 enabled_bots LONGTEXT DEFAULT NULL,
1227 PRIMARY KEY (id)
1228 ) $charset_collate;";
1229
1230 // Individual Intent Phrases Table - each phrase gets its own embedding vector
1231 $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
1232 $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table (
1233 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
1234 intent_id BIGINT(20) UNSIGNED NOT NULL,
1235 phrase TEXT NOT NULL,
1236 embedding_vector LONGTEXT NOT NULL,
1237 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
1238 PRIMARY KEY (id),
1239 KEY intent_id (intent_id)
1240 ) $charset_collate;";
1241
1242 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
1243
1244 // Create other tables
1245 dbDelta($sql_system_prompt);
1246 dbDelta($sql_intents_table);
1247 dbDelta($sql_intent_phrases_table);
1248
1249 // Create URL click tracking table
1250 mxchat_create_url_clicks_table();
1251
1252 // Create Pinecone roles table
1253 mxchat_create_pinecone_roles_table();
1254
1255 // NEW 2.5.2: Create queue processing tables
1256 mxchat_create_queue_tables();
1257
1258 // Create transcript translations table
1259 mxchat_create_translations_table();
1260
1261 // Create per-session satisfaction ratings table (v3.2.6)
1262 mxchat_create_session_ratings_table();
1263
1264 // Ensure additional columns in system prompt table
1265 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1266 if (!empty($existing_system_columns)) {
1267 $existing_system_column_names = array_column($existing_system_columns, 'Field');
1268
1269 if (!in_array('embedding_vector', $existing_system_column_names)) {
1270 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT");
1271 }
1272 if (!in_array('source_url', $existing_system_column_names)) {
1273 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL");
1274 }
1275 if (!in_array('role_restriction', $existing_system_column_names)) {
1276 $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
1277 }
1278 }
1279
1280 // Set default thresholds for existing intents
1281 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
1282
1283 // Ensure enabled column exists in intents table
1284 $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table");
1285 if (!empty($existing_intent_columns)) {
1286 $existing_intent_column_names = array_column($existing_intent_columns, 'Field');
1287
1288 if (!in_array('enabled', $existing_intent_column_names)) {
1289 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
1290 }
1291
1292 // Ensure enabled_bots column exists for existing installations
1293 if (!in_array('enabled_bots', $existing_intent_column_names)) {
1294 $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled");
1295
1296 // Set existing actions to work with default bot
1297 $default_bots = json_encode(['default']);
1298 $wpdb->query($wpdb->prepare(
1299 "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL",
1300 $default_bots
1301 ));
1302 }
1303 }
1304
1305 // Run migration for existing installations
1306 mxchat_migrate_pinecone_roles_add_bot_id();
1307
1308 // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1309 mxchat_backfill_active_embedding_model();
1310
1311 // Setup cron jobs
1312 mxchat_setup_cron_jobs();
1313
1314 // Update version (stable base version — never the dev time()-suffixed one,
1315 // or the check_for_update comparison would churn every request)
1316 update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
1317
1318 //error_log("MxChat: Activation function completed");
1319 }
1320
1321 /**
1322 * Setup cron jobs on plugin activation
1323 */
1324 function mxchat_setup_cron_jobs() {
1325 // Clear any existing cron jobs first
1326 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1327
1328 // Check if WordPress cron is disabled
1329 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1330 // Set flag to use fallback system
1331 update_option('mxchat_use_fallback_rate_limits', true);
1332 update_option('mxchat_next_rate_limit_check', time() + 3600);
1333 // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1334 // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1335 // execute (a server-side runner hitting wp-cron.php instead of loopback
1336 // spawns) — scheduling still just writes the cron option. The old early
1337 // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1338 // site permanently lost the transcript cleanup event while the retention
1339 // setting still claimed to be active.
1340 } else {
1341 // Schedule the rate limit reset cron job
1342 $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1343
1344 if ($result === false) {
1345 // Fallback if scheduling fails
1346 update_option('mxchat_use_fallback_rate_limits', true);
1347 update_option('mxchat_next_rate_limit_check', time() + 3600);
1348 } else {
1349 // Clear fallback flags if cron scheduling succeeded
1350 delete_option('mxchat_use_fallback_rate_limits');
1351 }
1352 }
1353
1354 // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
1355 $transcript_options = get_option('mxchat_transcripts_options', array());
1356 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1357 $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1358
1359 if ($cleanup_interval !== 'never' || $custom_retention > 0) {
1360 // Check if not already scheduled
1361 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1362 // Schedule to run daily at 3 AM
1363 $next_run = strtotime('tomorrow 3:00 AM');
1364 wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
1365 }
1366 }
1367 }
1368
1369 /**
1370 * Clean up on plugin deactivation
1371 */
1372 function mxchat_deactivate() {
1373 // Clear scheduled cron jobs
1374 wp_clear_scheduled_hook('mxchat_reset_rate_limits');
1375 wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
1376 wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
1377 wp_clear_scheduled_hook('mxchat_model_liveness_check');
1378
1379 // Clear fallback options
1380 delete_option('mxchat_use_fallback_rate_limits');
1381 delete_option('mxchat_next_rate_limit_check');
1382 delete_option('mxchat_fallback_check_interval');
1383
1384 // NOTE: We do NOT delete queue tables on deactivation
1385 // This preserves data if user accidentally deactivates the plugin
1386 }
1387
1388 /**
1389 * Check if fallback rate limit cleanup is needed
1390 */
1391 function mxchat_check_fallback_rate_limits() {
1392 $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
1393
1394 if (!$use_fallback) {
1395 return;
1396 }
1397
1398 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1399
1400 if (time() >= $next_check) {
1401 // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1402 // plugins_loaded (before this init-priority-5 callback), so it's always set
1403 // here. Constructing a second MxChat_Integrator just to call one method
1404 // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1405 // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1406 // the request. Defensive construction only if the global is somehow unset.
1407 // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1408 // implementation of this same check — if either changes, change both.
1409 global $mxchat_integrator;
1410 $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1411 ? $mxchat_integrator
1412 : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1413 if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1414 $integrator->mxchat_reset_rate_limits();
1415 update_option('mxchat_next_rate_limit_check', time() + 3600);
1416 }
1417 }
1418 }
1419
1420 /**
1421 * Robust update checking with role restriction migration, model deprecation, and queue tables
1422 * CRITICAL: This runs on EVERY page load to ensure tables exist
1423 */
1424 function mxchat_check_for_update() {
1425 global $wpdb;
1426
1427 try {
1428 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1429 $plugin_version = MXCHAT_BASE_VERSION;
1430
1431 // Always ensure critical tables exist (even if version matches)
1432 // This handles manual table deletion or fresh installs
1433 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1434 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1435
1436 $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1437
1438 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1439 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1440 $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1441 || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1442
1443 if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1444 //error_log("MxChat: Critical tables missing, running activation");
1445 mxchat_activate();
1446 }
1447
1448 // Version-specific migrations
1449 if ($current_version !== $plugin_version) {
1450 //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
1451
1452 // Run live agent update BEFORE updating the stored version
1453 mxchat_handle_live_agent_update();
1454
1455 // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
1456 mxchat_handle_theme_migration_notice();
1457
1458 // Run role restriction migration for 2.4.1
1459 if (version_compare($current_version, '2.4.1', '<')) {
1460 mxchat_add_role_restriction_column();
1461 }
1462
1463 // Run enabled_bots column migration for 2.4.4
1464 if (version_compare($current_version, '2.4.4', '<')) {
1465 mxchat_add_enabled_bots_column();
1466 }
1467
1468 // Run model migration for 2.5.1 (Claude deprecation)
1469 if (version_compare($current_version, '2.5.1', '<')) {
1470 mxchat_migrate_deprecated_models();
1471 }
1472
1473 // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2
1474 if (version_compare($current_version, '2.5.2', '<')) {
1475 mxchat_create_queue_tables();
1476 mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs
1477 //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2");
1478 }
1479
1480 // 2.6.0: Ensure rag_context column exists for retrieved documents feature
1481 if (version_compare($current_version, '2.6.0', '<')) {
1482 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1483 mxchat_ensure_all_columns($chat_table);
1484 //error_log("MxChat: rag_context column migration for 2.6.0");
1485 }
1486
1487 // 3.0.5: Migrate deprecated Gemini embedding model
1488 if (version_compare($current_version, '3.0.5', '<')) {
1489 mxchat_migrate_gemini_embedding_model();
1490 }
1491
1492 // 3.0.6: Migrate deprecated OpenAI and Claude models
1493 if (version_compare($current_version, '3.0.6', '<')) {
1494 mxchat_migrate_deprecated_models();
1495 }
1496
1497 // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support
1498 if (version_compare($current_version, '3.1.2', '<')) {
1499 mxchat_migrate_transcripts_charset();
1500 }
1501
1502 // 3.1.7: Clean up stale shared session email/name entries
1503 if (version_compare($current_version, '3.1.7', '<')) {
1504 delete_option('mxchat_email_null');
1505 delete_option('mxchat_name_null');
1506 }
1507
1508 // 3.2.4: Backfill active embedding model option for the warning UI
1509 // (replaces the per-row column tracking from 3.2.3, which was reverted)
1510 if (version_compare($current_version, '3.2.4', '<')) {
1511 mxchat_backfill_active_embedding_model();
1512 }
1513
1514 // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1515 // were shut off at the vendor on 2026-07-24). The function is idempotent —
1516 // it only rewrites models on its deprecation lists.
1517 if (version_compare($current_version, '3.2.15', '<')) {
1518 mxchat_migrate_deprecated_models();
1519 }
1520
1521 // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1522 // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1523 // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1524 if (version_compare($current_version, '3.2.16', '<')) {
1525 mxchat_migrate_deprecated_models();
1526 }
1527
1528 // 3.2.17: Credential options must not autoload (af2400) — the two
1529 // Pinecone-secret-holding rows were in alloptions, i.e. read into
1530 // memory on every request including anonymous page views. Idempotent.
1531 // Also carry the import modal's remembered ACF→PDF checkbox state
1532 // into the new install-level option (11720c).
1533 if (version_compare($current_version, '3.2.17', '<')) {
1534 mxchat_fix_credential_option_autoload();
1535 mxchat_migrate_acf_pdf_extraction_option();
1536 }
1537
1538 // 3.2.19: Claude Opus 4.1 retired Aug 5, 2026 — auto-move stranded
1539 // sites (and the older tiers on the migration's lists) per the
1540 // changelog's promise. Idempotent — only rewrites models on the
1541 // deprecation lists. Without a gate at this release's version,
1542 // nothing calls the migration for 3.2.18 upgraders (plan a5a598;
1543 // the gate value must equal the version this block ships in).
1544 if (version_compare($current_version, '3.2.19', '<')) {
1545 mxchat_migrate_deprecated_models();
1546 }
1547
1548 // Run full activation to ensure everything is up to date
1549 mxchat_activate();
1550
1551 // Run migration functions
1552 mxchat_migrate_live_agent_status();
1553
1554 // (The 2.1.8 orphaned-history reconciliation sweep is gone —
1555 // 3.2.19's mxchat_history_backlog_* drain supersedes it, and it
1556 // self-arms without a version gate: plan 839c4c.)
1557
1558 // Update version LAST
1559 update_option('mxchat_plugin_version', $plugin_version);
1560
1561 //error_log("MxChat: Updated from version $current_version to $plugin_version");
1562 }
1563
1564 } catch (Exception $e) {
1565 //error_log('MxChat update error: ' . $e->getMessage());
1566 // Don't update version if there was an error
1567 }
1568 }
1569
1570 /**
1571 * Credential options must never enter the autoloaded alloptions set.
1572 * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1573 * Pinecone API secret; mxchat_options already stores its keys with autoload
1574 * off and these two must match it. The filter covers every future
1575 * add_option()/update_option() that creates the row — Settings API saves
1576 * through options.php and WP-CLI included — on WP 6.6+; older cores are
1577 * covered by the explicit autoload arguments at the plugin's own write
1578 * sites plus the one-time migration below.
1579 */
1580 add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1581 function mxchat_credential_option_autoload_value($autoload, $option) {
1582 if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1583 return false;
1584 }
1585 return $autoload;
1586 }
1587
1588 /**
1589 * One-time upgrade migration: flip the autoload flag on credential option
1590 * rows that existing installs are already carrying autoloaded. Includes
1591 * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1592 * when that add-on is not installed, since missing rows simply don't match.
1593 */
1594 function mxchat_fix_credential_option_autoload() {
1595 $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1596 if (function_exists('wp_set_option_autoload_values')) {
1597 wp_set_option_autoload_values(array_fill_keys($keys, false));
1598 return;
1599 }
1600 // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1601 global $wpdb;
1602 $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1603 $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1604 wp_cache_delete('alloptions', 'options');
1605 foreach ($keys as $key) {
1606 wp_cache_delete($key, 'options');
1607 }
1608 }
1609
1610 /**
1611 * One-time carry of the import modal's remembered ACF→PDF checkbox state
1612 * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1613 * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1614 * Fresh installs and installs that never touched the checkbox default OFF,
1615 * matching the setting's own "recommended only if…" guidance.
1616 */
1617 function mxchat_migrate_acf_pdf_extraction_option() {
1618 if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1619 return; // already set — never overwrite an owner's choice
1620 }
1621 $mxchat_options = get_option('mxchat_options', array());
1622 if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1623 update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1624 unset($mxchat_options['acf_pdf_extract_default']);
1625 update_option('mxchat_options', $mxchat_options);
1626 }
1627 }
1628
1629 /**
1630 * Ensure tables exist on every admin load for fresh installations
1631 * This is a safety net for cases where activation hook doesn't fire
1632 */
1633 function mxchat_ensure_tables_exist() {
1634 global $wpdb;
1635
1636 // Only run for admin users to avoid performance impact
1637 if (!current_user_can('administrator')) {
1638 return;
1639 }
1640
1641 // Check if we've already verified tables in this session
1642 static $tables_checked = false;
1643 if ($tables_checked) {
1644 return;
1645 }
1646 $tables_checked = true;
1647
1648 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1649 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1650
1651 $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1652
1653 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1654 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1655 $sessions_exists = get_option('mxchat_session_store_ready') !== false
1656 || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1657
1658 if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1659 //error_log("MxChat: Tables missing on admin load, running activation");
1660 mxchat_activate();
1661 }
1662 }
1663
1664 /**
1665 * One-shot cleanup of legacy mxchat_history_<sid> option rows (plan 839c4c).
1666 *
1667 * 3.2.19 deduplicated per-session chat history into the transcripts table
1668 * (which already held a superset of every option copy measured), so nothing
1669 * writes these options any more — but an upgraded install still carries one
1670 * per session, at up to 64 KB a row (462 rows measured on one production
1671 * install). This drain replaces the old mxchat_cleanup_orphaned_chat_history()
1672 * reconciliation sweep, which existed only because there were two copies to
1673 * reconcile.
1674 *
1675 * b64b77 pattern throughout: an option_id bookmark that only moves forward
1676 * (a crash mid-batch re-processes at most one batch), delete_option() per row
1677 * so the object + notoptions caches stay coherent, batches drained off
1678 * non-AJAX admin_init plus the session-store maintenance cron. Once the
1679 * backlog is gone the state marks done and every later call is one cached
1680 * option read.
1681 */
1682 function mxchat_history_backlog_state() {
1683 // The state option name MUST NOT start with 'mxchat_history_' — the drain
1684 // deletes everything matching that prefix, and a state option inside the
1685 // pattern gets eaten by its own drain (caught by the 839c4c rig: batches
1686 // ran 2,2,2,1 instead of 2,2,1 because the bookmark row was being deleted
1687 // and re-created every pass).
1688 $state = get_option('mxchat_legacy_history_cleanup', array());
1689 if (!is_array($state)) {
1690 $state = array();
1691 }
1692
1693 return wp_parse_args($state, array(
1694 'done' => false,
1695 'last_option_id' => 0,
1696 'deleted' => 0,
1697 ));
1698 }
1699
1700 /**
1701 * Delete one batch of legacy history options.
1702 *
1703 * @param int $batch Rows per pass — capped small; these can be 64 KB rows.
1704 * @return int Option rows deleted in this pass.
1705 */
1706 function mxchat_history_backlog_batch($batch = 200) {
1707 global $wpdb;
1708
1709 $state = mxchat_history_backlog_state();
1710 if (!empty($state['done'])) {
1711 return 0;
1712 }
1713
1714 $batch = max(1, (int) $batch);
1715
1716 $rows = $wpdb->get_results(
1717 $wpdb->prepare(
1718 "SELECT option_id, option_name FROM {$wpdb->options}
1719 WHERE option_id > %d AND option_name LIKE %s
1720 ORDER BY option_id ASC LIMIT %d",
1721 (int) $state['last_option_id'],
1722 $wpdb->esc_like('mxchat_history_') . '%',
1723 $batch
1724 ),
1725 ARRAY_A
1726 );
1727
1728 if (empty($rows)) {
1729 $state['done'] = true;
1730 update_option('mxchat_legacy_history_cleanup', $state, 'no');
1731 return 0;
1732 }
1733
1734 foreach ($rows as $row) {
1735 $state['last_option_id'] = max((int) $state['last_option_id'], (int) $row['option_id']);
1736 delete_option($row['option_name']);
1737 $state['deleted'] = (int) $state['deleted'] + 1;
1738 }
1739
1740 if (count($rows) < $batch) {
1741 $state['done'] = true;
1742 }
1743
1744 update_option('mxchat_legacy_history_cleanup', $state, 'no');
1745
1746 return count($rows);
1747 }
1748
1749 /** One batch per admin page load until drained. */
1750 function mxchat_history_backlog_drain() {
1751 mxchat_history_backlog_batch();
1752 }
1753
1754 /** Cron leg: drain faster, same cap per batch. */
1755 function mxchat_history_backlog_drain_cron() {
1756 for ($i = 0; $i < 10; $i++) {
1757 if (mxchat_history_backlog_batch() === 0) {
1758 break;
1759 }
1760 }
1761 }
1762
1763 // wp_doing_ajax() guard is load-bearing, not defensive (b64b77's shipped-and-
1764 // caught defect): admin-ajax.php fires admin_init too, and the chat widget's
1765 // message endpoint is an admin-ajax action — without the guard an anonymous
1766 // visitor would pay for a delete batch inside their own chat request.
1767 if (!wp_doing_ajax()) {
1768 add_action('admin_init', 'mxchat_history_backlog_drain', 21);
1769 }
1770 // Belt for installs whose admin is rarely visited: ride the session store's
1771 // existing daily maintenance event rather than scheduling another.
1772 add_action('mxchat_session_store_maintenance', 'mxchat_history_backlog_drain_cron');
1773
1774 function mxchat_migrate_live_agent_status() {
1775 $options = get_option('mxchat_options', []);
1776
1777 // Check if live_agent_status exists
1778 if (isset($options['live_agent_status'])) {
1779 $current_status = $options['live_agent_status'];
1780 $needs_update = false;
1781
1782 // Convert to new format if needed
1783 if ($current_status === 'online') {
1784 $options['live_agent_status'] = 'on';
1785 $needs_update = true;
1786 } else if ($current_status === 'offline') {
1787 $options['live_agent_status'] = 'off';
1788 $needs_update = true;
1789 } else if (!in_array($current_status, ['on', 'off'])) {
1790 // Default to off for any unexpected values
1791 $options['live_agent_status'] = 'off';
1792 $needs_update = true;
1793 }
1794
1795 // Only update if needed
1796 if ($needs_update) {
1797 update_option('mxchat_options', $options);
1798 }
1799 } else {
1800 // If status doesn't exist, set default to off
1801 $options['live_agent_status'] = 'off';
1802 update_option('mxchat_options', $options);
1803 }
1804 }
1805
1806 function mxchat_handle_live_agent_update() {
1807 // Get the CURRENT stored version (before it gets updated)
1808 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1809 $new_version = '2.2.2';
1810
1811 // Only run this once for the update to 2.2.2
1812 $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
1813
1814 // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1815 if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1816 $options = get_option('mxchat_options', array());
1817
1818 // Check if live agent was previously enabled
1819 if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1820 // Disable live agent
1821 $options['live_agent_status'] = 'off';
1822 update_option('mxchat_options', $options);
1823
1824 // Set flag to show the notification banner
1825 update_option('mxchat_show_live_agent_disabled_notice', true);
1826 }
1827
1828 // Mark this update as handled
1829 update_option('mxchat_live_agent_update_2_2_2_handled', true);
1830 }
1831 }
1832
1833 /**
1834 * Handle theme migration notice for version 3.0.1
1835 * Shows a dismissible notice to Pro users about migrating AI-generated themes
1836 */
1837 function mxchat_handle_theme_migration_notice() {
1838 // Get the CURRENT stored version (before it gets updated)
1839 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1840 $target_version = '3.0.1';
1841
1842 // Only run this once for the update to 3.0.1
1843 $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1844
1845 // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1846 if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1847 // Check if Pro is activated - only show to Pro users
1848 $license_status = get_option('mxchat_license_status', 'inactive');
1849 $is_pro = ($license_status === 'active');
1850
1851 if ($is_pro) {
1852 // Set flag to show the theme migration notification banner
1853 update_option('mxchat_show_theme_migration_notice', true);
1854 }
1855
1856 // Mark this update as handled (whether Pro or not)
1857 update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1858 }
1859 }
1860
1861 // Initialize plugin safely
1862 function mxchat_init() {
1863 // Include all class files first
1864 mxchat_include_classes();
1865
1866 // Run update check (this also ensures tables exist)
1867 mxchat_check_for_update();
1868
1869 // CRITICAL: Ensure tables exist on admin pages (safety net)
1870 add_action('admin_init', 'mxchat_ensure_tables_exist', 1);
1871
1872 // Add fallback rate limit check
1873 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1874
1875 // Add migration notice hook
1876 add_action('admin_notices', 'mxchat_show_migration_notice');
1877 add_action('admin_notices', 'mxchat_show_model_access_notice');
1878
1879 // Initialize classes with error handling
1880 try {
1881 // Initialize admin classes
1882 if (is_admin()) {
1883 if (class_exists('MxChat_Knowledge_Manager')) {
1884 $mxchat_knowledge_manager = new MxChat_Knowledge_Manager();
1885
1886 if (class_exists('MxChat_Admin')) {
1887 $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager);
1888 }
1889 }
1890
1891 // Initialize meta box class
1892 if (class_exists('MxChat_Meta_Box')) {
1893 new MxChat_Meta_Box();
1894 }
1895
1896 }
1897
1898 // Initialize content generator globally — it registers wp_head hook
1899 // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1900 if (class_exists('MxChat_Content_Generator')) {
1901 new MxChat_Content_Generator();
1902 }
1903
1904 // Initialize cache purge globally — settings writes can happen on any
1905 // request type (admin screens, admin-ajax autosave, wp-cli), and the
1906 // deferred-purge cron event fires on front-end requests.
1907 if (class_exists('MxChat_Cache_Purge')) {
1908 MxChat_Cache_Purge::init();
1909 }
1910
1911 // Initialize REST API globally — endpoints must be registered on
1912 // every request (admin and frontend) so they're reachable via /wp-json/.
1913 // Endpoints are auth-gated and locked until the site owner generates
1914 // a token in MxChat → API Access.
1915 if (class_exists('MxChat_Rest_Api')) {
1916 new MxChat_Rest_Api();
1917 }
1918
1919 // Initialize public classes
1920 if (class_exists('MxChat_Public')) {
1921 $mxchat_public = new MxChat_Public();
1922 }
1923
1924 if (class_exists('MxChat_Integrator')) {
1925 global $mxchat_integrator;
1926 $mxchat_integrator = new MxChat_Integrator();
1927 }
1928
1929 } catch (Exception $e) {
1930 //error_log('MxChat initialization error: ' . $e->getMessage());
1931
1932 // Show admin notice if there's an error
1933 if (is_admin()) {
1934 add_action('admin_notices', function() use ($e) {
1935 echo '<div class="notice notice-error"><p>';
1936 echo '<strong>MxChat Error:</strong> Plugin initialization failed. ';
1937 echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage());
1938 echo '</p></div>';
1939 });
1940 }
1941 }
1942 }
1943
1944 // Run initialization on plugins_loaded
1945 add_action('plugins_loaded', 'mxchat_init');
1946
1947 // Run migration check on admin init (for auto-updates without reactivation)
1948 add_action('admin_init', 'mxchat_check_and_run_migrations');
1949
1950 /**
1951 * Check and run migrations on admin init
1952 * This ensures migrations run even when plugin is auto-updated
1953 */
1954 function mxchat_check_and_run_migrations() {
1955 // Only run in admin and not on every request
1956 static $checked = false;
1957 if ($checked) {
1958 return;
1959 }
1960 $checked = true;
1961
1962 mxchat_migrate_pinecone_roles_add_bot_id();
1963 mxchat_migrate_add_content_type_column();
1964 mxchat_migrate_add_translations_table();
1965 mxchat_migrate_add_session_ratings_table();
1966 }
1967
1968 /**
1969 * Migration: Create per-session satisfaction ratings table (v3.2.6)
1970 * For users upgrading from versions before 3.2.6
1971 */
1972 function mxchat_migrate_add_session_ratings_table() {
1973 $migration_key = 'mxchat_session_ratings_table_created';
1974 if (get_option($migration_key)) {
1975 return;
1976 }
1977 mxchat_create_session_ratings_table();
1978 update_option($migration_key, '3.2.6');
1979 }
1980
1981 /**
1982 * Migration: Create transcript translations table (v3.0.4)
1983 * For users upgrading from versions before 3.0.4
1984 */
1985 function mxchat_migrate_add_translations_table() {
1986 $migration_key = 'mxchat_translations_table_created';
1987
1988 // Check if migration already ran
1989 if (get_option($migration_key)) {
1990 return;
1991 }
1992
1993 // Create the translations table
1994 mxchat_create_translations_table();
1995
1996 // Mark migration as complete
1997 update_option($migration_key, '3.0.4');
1998 }
1999
2000 /**
2001 * Migration: Update deprecated Gemini embedding model (v3.0.5)
2002 * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
2003 */
2004 function mxchat_migrate_gemini_embedding_model() {
2005 $options = get_option('mxchat_options', array());
2006
2007 if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
2008 $options['embedding_model'] = 'gemini-embedding-001';
2009 update_option('mxchat_options', $options);
2010 }
2011 }
2012
2013 // Register activation hook
2014 register_activation_hook(__FILE__, 'mxchat_activate');
2015
2016 // Add cron schedule
2017 add_filter('cron_schedules', function($schedules) {
2018 $schedules['one_minute'] = array(
2019 'interval' => 60,
2020 'display' => 'Every Minute'
2021 );
2022 return $schedules;
2023 });
2024
2025 // Register deactivation hook
2026 register_deactivation_hook(__FILE__, 'mxchat_deactivate');
2027
2028 /**
2029 * Per-session satisfaction rating: AJAX save handler (v3.2.6).
2030 * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
2031 * session_id makes this naturally idempotent — only the first rating per
2032 * session is stored; duplicate POSTs are silent no-ops.
2033 */
2034 function mxchat_save_session_rating() {
2035 global $wpdb;
2036
2037 $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
2038 $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
2039 $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
2040 $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
2041
2042 if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
2043 wp_send_json_error(array('message' => 'invalid_input'), 400);
2044 }
2045
2046 if (strlen($feedback) > 1000) {
2047 $feedback = substr($feedback, 0, 1000);
2048 }
2049
2050 $table_name = $wpdb->prefix . 'mxchat_session_ratings';
2051 $existing = $wpdb->get_var($wpdb->prepare(
2052 "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
2053 $session_id
2054 ));
2055
2056 if ($existing) {
2057 if ($feedback !== '') {
2058 $wpdb->update(
2059 $table_name,
2060 array('rating_feedback' => $feedback),
2061 array('id' => (int) $existing),
2062 array('%s'),
2063 array('%d')
2064 );
2065 }
2066 wp_send_json_success(array('updated' => true));
2067 }
2068
2069 $inserted = $wpdb->insert(
2070 $table_name,
2071 array(
2072 'session_id' => $session_id,
2073 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
2074 'rating_value' => $rating_raw,
2075 'rating_feedback' => $feedback !== '' ? $feedback : null,
2076 'created_at' => current_time('mysql'),
2077 ),
2078 array('%s', '%s', '%d', '%s', '%s')
2079 );
2080
2081 if ($inserted === false) {
2082 wp_send_json_error(array('message' => 'db_insert_failed'), 500);
2083 }
2084
2085 wp_send_json_success(array('saved' => true));
2086 }
2087 add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
2088 add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');