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