| @@ -1,1674 +1,1385 @@ | ||
| 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.8 | |
| 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 | - if (MXCHAT_DEV_MODE) { | |
| 28 | - $version .= '.' . time(); | |
| 29 | - } | |
| 30 | - define('MXCHAT_VERSION', $version); | |
| 31 | -} | |
| 32 | - | |
| 33 | -function mxchat_load_textdomain() { | |
| 34 | - $domain = 'mxchat'; | |
| 35 | - $locale = determine_locale(); | |
| 36 | - | |
| 37 | - // First, try to load from /wp-content/languages/plugins/ (preserved during updates) | |
| 38 | - $mo_file = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo'; | |
| 39 | - if (file_exists($mo_file)) { | |
| 40 | - load_textdomain($domain, $mo_file); | |
| 41 | - return; | |
| 42 | - } | |
| 43 | - | |
| 44 | - // Fallback to plugin's /languages directory | |
| 45 | - load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages'); | |
| 46 | -} | |
| 47 | -add_action('init', 'mxchat_load_textdomain'); | |
| 48 | - | |
| 49 | -/** | |
| 50 | - * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026. | |
| 51 | - * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview | |
| 52 | - * (Google's official migration target) the first time admin_init fires after update. | |
| 53 | - */ | |
| 54 | -add_action('admin_init', function () { | |
| 55 | - if (get_option('mxchat_gemini_3_remap_done')) { | |
| 56 | - return; | |
| 57 | - } | |
| 58 | - $opts = get_option('mxchat_options'); | |
| 59 | - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') { | |
| 60 | - $opts['model'] = 'gemini-3.1-pro-preview'; | |
| 61 | - update_option('mxchat_options', $opts); | |
| 62 | - } | |
| 63 | - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') { | |
| 64 | - $opts['content_model'] = 'gemini-3.1-pro-preview'; | |
| 65 | - update_option('mxchat_options', $opts); | |
| 66 | - } | |
| 67 | - update_option('mxchat_gemini_3_remap_done', 1); | |
| 68 | -}); | |
| 69 | - | |
| 70 | -/** | |
| 71 | - * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212, | |
| 72 | - * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing | |
| 73 | - * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning | |
| 74 | - * (modern, fast, broadly available) the first time admin_init fires after update. | |
| 75 | - */ | |
| 76 | -add_action('admin_init', function () { | |
| 77 | - if (get_option('mxchat_grok_2_remap_done')) { | |
| 78 | - return; | |
| 79 | - } | |
| 80 | - $opts = get_option('mxchat_options'); | |
| 81 | - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') { | |
| 82 | - $opts['model'] = 'grok-4-1-fast-non-reasoning'; | |
| 83 | - update_option('mxchat_options', $opts); | |
| 84 | - } | |
| 85 | - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') { | |
| 86 | - $opts['content_model'] = 'grok-4-1-fast-non-reasoning'; | |
| 87 | - update_option('mxchat_options', $opts); | |
| 88 | - } | |
| 89 | - update_option('mxchat_grok_2_remap_done', 1); | |
| 90 | -}); | |
| 91 | - | |
| 92 | -/** | |
| 93 | - * Exclude MxChat assets from caching plugin optimizations | |
| 94 | - * | |
| 95 | - * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache, | |
| 96 | - * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by | |
| 97 | - * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery. | |
| 98 | - * | |
| 99 | - * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also | |
| 100 | - * be excluded from any optimization that changes load order or timing. | |
| 101 | - */ | |
| 102 | - | |
| 103 | -// ── WP Rocket ──────────────────────────────────────────────────────────────── | |
| 104 | - | |
| 105 | -// Exclude from Remove Unused CSS (RUCSS) | |
| 106 | -add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) { | |
| 107 | - if (!is_array($exclusions)) $exclusions = array(); | |
| 108 | - $exclusions[] = 'mxchat'; | |
| 109 | - return $exclusions; | |
| 110 | -}); | |
| 111 | - | |
| 112 | -// Exclude CSS from minification/combination | |
| 113 | -add_filter('rocket_exclude_css', function($excluded) { | |
| 114 | - if (!is_array($excluded)) $excluded = array(); | |
| 115 | - $excluded[] = '/plugins/mxchat-basic/css/chat-style.css'; | |
| 116 | - return $excluded; | |
| 117 | -}); | |
| 118 | - | |
| 119 | -// Exclude JS from minification/combination | |
| 120 | -add_filter('rocket_exclude_js', function($excluded) { | |
| 121 | - if (!is_array($excluded)) $excluded = array(); | |
| 122 | - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js'; | |
| 123 | - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js'; | |
| 124 | - $excluded[] = '/jquery-core'; | |
| 125 | - $excluded[] = '/jquery.min.js'; | |
| 126 | - $excluded[] = '/jquery.js'; | |
| 127 | - $excluded[] = '/jquery-migrate'; | |
| 128 | - return $excluded; | |
| 129 | -}); | |
| 130 | - | |
| 131 | -// Exclude JS from defer | |
| 132 | -add_filter('rocket_exclude_defer_js', function($excluded) { | |
| 133 | - if (!is_array($excluded)) $excluded = array(); | |
| 134 | - $excluded[] = '/plugins/mxchat-basic/js/chat-script.js'; | |
| 135 | - $excluded[] = '/plugins/mxchat-basic/js/floating-script.js'; | |
| 136 | - $excluded[] = '/jquery-core'; | |
| 137 | - $excluded[] = '/jquery.min.js'; | |
| 138 | - $excluded[] = '/jquery.js'; | |
| 139 | - $excluded[] = '/jquery-migrate'; | |
| 140 | - return $excluded; | |
| 141 | -}); | |
| 142 | - | |
| 143 | -// Exclude from delay JS execution | |
| 144 | -add_filter('rocket_delay_js_exclusions', function($excluded) { | |
| 145 | - if (!is_array($excluded)) $excluded = array(); | |
| 146 | - $excluded[] = 'mxchat'; | |
| 147 | - $excluded[] = 'chat-script'; | |
| 148 | - $excluded[] = 'floating-script'; | |
| 149 | - $excluded[] = '/jquery-core'; | |
| 150 | - $excluded[] = '/jquery.min.js'; | |
| 151 | - $excluded[] = '/jquery.js'; | |
| 152 | - $excluded[] = '/jquery-migrate'; | |
| 153 | - return $excluded; | |
| 154 | -}); | |
| 155 | - | |
| 156 | -// ── LiteSpeed Cache ────────────────────────────────────────────────────────── | |
| 157 | - | |
| 158 | -// Exclude CSS from optimization | |
| 159 | -add_filter('litespeed_optimize_css_excludes', function($excluded) { | |
| 160 | - if (!is_array($excluded)) $excluded = array(); | |
| 161 | - $excluded[] = 'chat-style.css'; | |
| 162 | - $excluded[] = 'mxchat'; | |
| 163 | - return $excluded; | |
| 164 | -}); | |
| 165 | - | |
| 166 | -// Exclude from UCSS (Unique CSS) - prevents LiteSpeed from stripping "unused" MxChat CSS | |
| 167 | -add_filter('litespeed_ucss_whitelist', function($whitelist) { | |
| 168 | - if (!is_array($whitelist)) $whitelist = array(); | |
| 169 | - $whitelist[] = '.mxchat-chatbot-wrapper'; | |
| 170 | - $whitelist[] = '.floating-chatbot'; | |
| 171 | - $whitelist[] = '.floating-chatbot-button'; | |
| 172 | - $whitelist[] = '.chatbot-top-bar'; | |
| 173 | - $whitelist[] = '.mxchat-chatbot'; | |
| 174 | - $whitelist[] = '.chat-container'; | |
| 175 | - $whitelist[] = '.chat-box'; | |
| 176 | - $whitelist[] = '.bot-message'; | |
| 177 | - $whitelist[] = '.input-container'; | |
| 178 | - $whitelist[] = '.chat-input'; | |
| 179 | - $whitelist[] = '.send-button'; | |
| 180 | - $whitelist[] = '.pre-chat-message'; | |
| 181 | - $whitelist[] = '.mxchat-popular-questions'; | |
| 182 | - $whitelist[] = '.chat-toolbar'; | |
| 183 | - $whitelist[] = '.exit-chat'; | |
| 184 | - $whitelist[] = '.email-blocker'; | |
| 185 | - return $whitelist; | |
| 186 | -}); | |
| 187 | - | |
| 188 | -// Exclude CSS from CCSS (Critical CSS) generation | |
| 189 | -add_filter('litespeed_optm_ccss_exc', function($excluded) { | |
| 190 | - if (!is_array($excluded)) $excluded = array(); | |
| 191 | - $excluded[] = 'chat-style.css'; | |
| 192 | - $excluded[] = 'mxchat'; | |
| 193 | - return $excluded; | |
| 194 | -}); | |
| 195 | - | |
| 196 | -// Exclude JS from defer | |
| 197 | -add_filter('litespeed_optm_js_defer_exc', function($excluded) { | |
| 198 | - if (!is_array($excluded)) $excluded = array(); | |
| 199 | - $excluded[] = 'chat-script.js'; | |
| 200 | - $excluded[] = 'floating-script.js'; | |
| 201 | - $excluded[] = 'mxchat'; | |
| 202 | - $excluded[] = 'jquery.min.js'; | |
| 203 | - $excluded[] = 'jquery.js'; | |
| 204 | - return $excluded; | |
| 205 | -}); | |
| 206 | - | |
| 207 | -// Exclude JS from combining | |
| 208 | -add_filter('litespeed_optm_js_exc', function($excluded) { | |
| 209 | - if (!is_array($excluded)) $excluded = array(); | |
| 210 | - $excluded[] = 'chat-script.js'; | |
| 211 | - $excluded[] = 'floating-script.js'; | |
| 212 | - $excluded[] = 'mxchat'; | |
| 213 | - $excluded[] = 'jquery.min.js'; | |
| 214 | - $excluded[] = 'jquery.js'; | |
| 215 | - return $excluded; | |
| 216 | -}); | |
| 217 | - | |
| 218 | -// Exclude JS from delayed execution | |
| 219 | -add_filter('litespeed_optm_js_delay_exc', function($excluded) { | |
| 220 | - if (!is_array($excluded)) $excluded = array(); | |
| 221 | - $excluded[] = 'chat-script.js'; | |
| 222 | - $excluded[] = 'floating-script.js'; | |
| 223 | - $excluded[] = 'mxchat'; | |
| 224 | - return $excluded; | |
| 225 | -}); | |
| 226 | - | |
| 227 | -// Exclude from Guest Mode optimization | |
| 228 | -add_filter('litespeed_guest_optm_exc', function($excluded) { | |
| 229 | - if (!is_array($excluded)) $excluded = array(); | |
| 230 | - $excluded[] = 'mxchat'; | |
| 231 | - $excluded[] = 'chat-style'; | |
| 232 | - $excluded[] = 'chat-script'; | |
| 233 | - $excluded[] = 'floating-script'; | |
| 234 | - return $excluded; | |
| 235 | -}); | |
| 236 | - | |
| 237 | -// ── Autoptimize ────────────────────────────────────────────────────────────── | |
| 238 | - | |
| 239 | -// Exclude CSS from optimization (comma-separated strings) | |
| 240 | -add_filter('autoptimize_filter_css_exclude', function($excluded) { | |
| 241 | - if (!is_string($excluded)) $excluded = ''; | |
| 242 | - return $excluded . ', mxchat, chat-style.css'; | |
| 243 | -}); | |
| 244 | - | |
| 245 | -// Exclude JS from optimization (comma-separated strings) | |
| 246 | -add_filter('autoptimize_filter_js_exclude', function($excluded) { | |
| 247 | - if (!is_string($excluded)) $excluded = ''; | |
| 248 | - return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js'; | |
| 249 | -}); | |
| 250 | - | |
| 251 | -// ── SG Optimizer (SiteGround) ──────────────────────────────────────────────── | |
| 252 | - | |
| 253 | -add_filter('sgo_js_minify_exclude', function($excluded) { | |
| 254 | - if (!is_array($excluded)) $excluded = array(); | |
| 255 | - $excluded[] = 'chat-script.js'; | |
| 256 | - $excluded[] = 'floating-script.js'; | |
| 257 | - $excluded[] = 'jquery.min.js'; | |
| 258 | - return $excluded; | |
| 259 | -}); | |
| 260 | - | |
| 261 | -add_filter('sgo_javascript_combine_exclude', function($excluded) { | |
| 262 | - if (!is_array($excluded)) $excluded = array(); | |
| 263 | - $excluded[] = 'chat-script.js'; | |
| 264 | - $excluded[] = 'floating-script.js'; | |
| 265 | - $excluded[] = 'jquery.min.js'; | |
| 266 | - return $excluded; | |
| 267 | -}); | |
| 268 | - | |
| 269 | -add_filter('sgo_js_async_exclude', function($excluded) { | |
| 270 | - if (!is_array($excluded)) $excluded = array(); | |
| 271 | - $excluded[] = 'chat-script.js'; | |
| 272 | - $excluded[] = 'floating-script.js'; | |
| 273 | - $excluded[] = 'jquery.min.js'; | |
| 274 | - return $excluded; | |
| 275 | -}); | |
| 276 | - | |
| 277 | -// ── W3 Total Cache ─────────────────────────────────────────────────────────── | |
| 278 | - | |
| 279 | -add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) { | |
| 280 | - if (strpos($file, 'chat-script.js') !== false || | |
| 281 | - strpos($file, 'floating-script.js') !== false || | |
| 282 | - strpos($file, 'jquery.min.js') !== false || | |
| 283 | - strpos($file, 'jquery.js') !== false) { | |
| 284 | - return false; | |
| 285 | - } | |
| 286 | - return $do_minify; | |
| 287 | -}, 10, 3); | |
| 288 | - | |
| 289 | -// ── WP Super Cache ────────────────────────────────────────────────────────── | |
| 290 | - | |
| 291 | -add_filter('wpsc_rejected_uri', function($rejected) { | |
| 292 | - if (!is_array($rejected)) $rejected = array(); | |
| 293 | - $rejected[] = 'wp-admin/admin-ajax.php'; | |
| 294 | - return $rejected; | |
| 295 | -}); | |
| 296 | - | |
| 297 | -// ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix) | |
| 298 | -// Each cache plugin gets its own filter export so that visitors hitting an | |
| 299 | -// edge-cached page never receive cached chat-AJAX responses. The chat send / | |
| 300 | -// stream send / file upload all POST to /wp-admin/admin-ajax.php with | |
| 301 | -// `action=mxchat_*`. Without these exports, a cache plugin can stale a response | |
| 302 | -// and break the per-session nonce flow on the first message. | |
| 303 | - | |
| 304 | -// WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings. | |
| 305 | -add_filter('rocket_cache_reject_uri', function($uris) { | |
| 306 | - if (!is_array($uris)) $uris = array(); | |
| 307 | - $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*'; | |
| 308 | - return $uris; | |
| 309 | -}); | |
| 310 | - | |
| 311 | -// LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits | |
| 312 | -// caching when the request matches our chat-AJAX pattern. | |
| 313 | -add_filter('litespeed_cache_no_cache_for_request', function($no_cache) { | |
| 314 | - if ($no_cache) return $no_cache; | |
| 315 | - if (!empty($_SERVER['REQUEST_URI']) && | |
| 316 | - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false && | |
| 317 | - !empty($_REQUEST['action']) && | |
| 318 | - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) { | |
| 319 | - return true; | |
| 320 | - } | |
| 321 | - return $no_cache; | |
| 322 | -}); | |
| 323 | - | |
| 324 | -// W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when | |
| 325 | -// the URI matches. | |
| 326 | -add_filter('w3tc_pgcache_request_skip_uri', function($skip) { | |
| 327 | - if ($skip) return $skip; | |
| 328 | - if (!empty($_SERVER['REQUEST_URI']) && | |
| 329 | - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false && | |
| 330 | - !empty($_REQUEST['action']) && | |
| 331 | - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) { | |
| 332 | - return true; | |
| 333 | - } | |
| 334 | - return $skip; | |
| 335 | -}); | |
| 336 | - | |
| 337 | -// FlyingPress — `flying_press_cacheable` takes a boolean and is run per | |
| 338 | -// request. Same pattern as LiteSpeed / W3TC. | |
| 339 | -add_filter('flying_press_cacheable', function($cacheable) { | |
| 340 | - if (!$cacheable) return $cacheable; | |
| 341 | - if (!empty($_SERVER['REQUEST_URI']) && | |
| 342 | - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false && | |
| 343 | - !empty($_REQUEST['action']) && | |
| 344 | - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) { | |
| 345 | - return false; | |
| 346 | - } | |
| 347 | - return $cacheable; | |
| 348 | -}); | |
| 349 | - | |
| 350 | -// Include classes with error handling | |
| 351 | -function mxchat_include_classes() { | |
| 352 | - $class_files = array( | |
| 353 | - 'includes/class-mxchat-integrator.php', | |
| 354 | - 'includes/class-mxchat-admin.php', | |
| 355 | - 'includes/class-mxchat-public.php', | |
| 356 | - 'includes/class-mxchat-utils.php', | |
| 357 | - 'includes/class-mxchat-user.php', | |
| 358 | - 'includes/class-mxchat-meta-box.php', | |
| 359 | - 'includes/class-mxchat-chunker.php', | |
| 360 | - 'includes/class-mxchat-word-handler.php', | |
| 361 | - 'includes/class-mxchat-content-generator.php', | |
| 362 | - 'includes/class-rest-api.php', | |
| 363 | - 'admin/class-ajax-handler.php', | |
| 364 | - 'admin/class-pinecone-manager.php', | |
| 365 | - 'admin/class-knowledge-manager.php' | |
| 366 | - ); | |
| 367 | - | |
| 368 | - foreach ($class_files as $file) { | |
| 369 | - $file_path = plugin_dir_path(__FILE__) . $file; | |
| 370 | - if (file_exists($file_path)) { | |
| 371 | - require_once $file_path; | |
| 372 | - } else { | |
| 373 | - //error_log('MxChat: Missing class file - ' . $file); | |
| 374 | - } | |
| 375 | - } | |
| 376 | - | |
| 377 | - // Admin pages that aren't classes (procedural include). | |
| 378 | - if (is_admin()) { | |
| 379 | - $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php'; | |
| 380 | - if (file_exists($admin_api_page)) { | |
| 381 | - require_once $admin_api_page; | |
| 382 | - } | |
| 383 | - // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php. | |
| 384 | - // The require MUST live here (admin bootstrap) and not just inside | |
| 385 | - // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT | |
| 386 | - // fire on admin-ajax.php requests, so the wizard's AJAX handlers | |
| 387 | - // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step / | |
| 388 | - // auto_graduate + the f7c7d4 dismiss handler) would never register. | |
| 389 | - $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php'; | |
| 390 | - if (file_exists($admin_onboarding_page)) { | |
| 391 | - require_once $admin_onboarding_page; | |
| 392 | - } | |
| 393 | - } | |
| 394 | -} | |
| 395 | - | |
| 396 | -/** | |
| 397 | - * Lazy-load the PDF parser library only when needed. | |
| 398 | - * Avoids loading 44 files on every page request. | |
| 399 | - */ | |
| 400 | -function mxchat_load_pdf_parser() { | |
| 401 | - if (class_exists('\Smalot\PdfParser\Parser')) { | |
| 402 | - return true; | |
| 403 | - } | |
| 404 | - $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php'; | |
| 405 | - if (file_exists($autoload_path)) { | |
| 406 | - require_once $autoload_path; | |
| 407 | - return true; | |
| 408 | - } | |
| 409 | - return false; | |
| 410 | -} | |
| 411 | - | |
| 412 | -/** | |
| 413 | - * Create URL click tracking table | |
| 414 | - */ | |
| 415 | -function mxchat_create_url_clicks_table() { | |
| 416 | - global $wpdb; | |
| 417 | - | |
| 418 | - $table_name = $wpdb->prefix . 'mxchat_url_clicks'; | |
| 419 | - | |
| 420 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 421 | - | |
| 422 | - $sql = "CREATE TABLE $table_name ( | |
| 423 | - id mediumint(9) NOT NULL AUTO_INCREMENT, | |
| 424 | - session_id varchar(100) NOT NULL, | |
| 425 | - clicked_url text NOT NULL, | |
| 426 | - message_context text, | |
| 427 | - click_timestamp datetime DEFAULT CURRENT_TIMESTAMP, | |
| 428 | - user_ip varchar(45), | |
| 429 | - user_agent text, | |
| 430 | - PRIMARY KEY (id), | |
| 431 | - KEY session_id (session_id), | |
| 432 | - KEY click_timestamp (click_timestamp) | |
| 433 | - ) $charset_collate;"; | |
| 434 | - | |
| 435 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 436 | - dbDelta($sql); | |
| 437 | -} | |
| 438 | - | |
| 439 | -/** | |
| 440 | - * FIXED: Robust table creation and column management | |
| 441 | - */ | |
| 442 | -function mxchat_create_chat_transcripts_table() { | |
| 443 | - global $wpdb; | |
| 444 | - | |
| 445 | - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 446 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 447 | - | |
| 448 | - // Create table with ALL columns including user_name from the start | |
| 449 | - $sql = "CREATE TABLE $table_name ( | |
| 450 | - id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, | |
| 451 | - user_id MEDIUMINT(9) DEFAULT 0, | |
| 452 | - session_id VARCHAR(255) NOT NULL, | |
| 453 | - role VARCHAR(255) NOT NULL, | |
| 454 | - message TEXT NOT NULL, | |
| 455 | - user_email VARCHAR(255) DEFAULT NULL, | |
| 456 | - user_name VARCHAR(100) DEFAULT NULL, | |
| 457 | - user_identifier VARCHAR(255) DEFAULT NULL, | |
| 458 | - originating_page_url TEXT DEFAULT NULL, | |
| 459 | - originating_page_title VARCHAR(500) DEFAULT NULL, | |
| 460 | - timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, | |
| 461 | - PRIMARY KEY (id), | |
| 462 | - KEY session_id (session_id), | |
| 463 | - KEY user_email (user_email), | |
| 464 | - KEY timestamp (timestamp) | |
| 465 | - ) $charset_collate;"; | |
| 466 | - | |
| 467 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 468 | - $result = dbDelta($sql); | |
| 469 | - | |
| 470 | - // Log the result for debugging | |
| 471 | - if (empty($result)) { | |
| 472 | - //error_log("MxChat: dbDelta returned empty result for chat transcripts table"); | |
| 473 | - } else { | |
| 474 | - //error_log("MxChat: dbDelta result: " . print_r($result, true)); | |
| 475 | - } | |
| 476 | - | |
| 477 | - // IMPORTANT: Ensure all columns exist for existing installations | |
| 478 | - mxchat_ensure_all_columns($table_name); | |
| 479 | -} | |
| 480 | - | |
| 481 | -/** | |
| 482 | - * Ensure all required columns exist (for upgrades) | |
| 483 | - */ | |
| 484 | -function mxchat_ensure_all_columns($table_name) { | |
| 485 | - global $wpdb; | |
| 486 | - | |
| 487 | - // First check if table exists | |
| 488 | - $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 489 | - if (!$table_exists) { | |
| 490 | - //error_log("MxChat: Table $table_name does not exist, cannot add columns"); | |
| 491 | - return; | |
| 492 | - } | |
| 493 | - | |
| 494 | - // Define all required columns and their types | |
| 495 | - $required_columns = [ | |
| 496 | - 'user_identifier' => 'VARCHAR(255) DEFAULT NULL', | |
| 497 | - 'user_email' => 'VARCHAR(255) DEFAULT NULL', | |
| 498 | - 'user_name' => 'VARCHAR(100) DEFAULT NULL', | |
| 499 | - 'originating_page_url' => 'TEXT DEFAULT NULL', | |
| 500 | - 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL', | |
| 501 | - 'rag_context' => 'LONGTEXT DEFAULT NULL' | |
| 502 | - ]; | |
| 503 | - | |
| 504 | - // Get existing columns | |
| 505 | - $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name"); | |
| 506 | - if (empty($existing_columns)) { | |
| 507 | - //error_log("MxChat: Could not get columns for table $table_name"); | |
| 508 | - return; | |
| 509 | - } | |
| 510 | - | |
| 511 | - $existing_column_names = array_column($existing_columns, 'Field'); | |
| 512 | - | |
| 513 | - // Add missing columns | |
| 514 | - foreach ($required_columns as $column_name => $column_definition) { | |
| 515 | - if (!in_array($column_name, $existing_column_names)) { | |
| 516 | - $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition"; | |
| 517 | - $result = $wpdb->query($alter_sql); | |
| 518 | - | |
| 519 | - if ($result === false) { | |
| 520 | - //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error); | |
| 521 | - } else { | |
| 522 | - //error_log("MxChat: Successfully added column $column_name to $table_name"); | |
| 523 | - } | |
| 524 | - } | |
| 525 | - } | |
| 526 | -} | |
| 527 | - | |
| 528 | -/** | |
| 529 | - * Add role restriction column to knowledge base table | |
| 530 | - */ | |
| 531 | -function mxchat_add_role_restriction_column() { | |
| 532 | - global $wpdb; | |
| 533 | - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 534 | - | |
| 535 | - // Check if table exists first | |
| 536 | - $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 537 | - if (!$table_exists) { | |
| 538 | - //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column"); | |
| 539 | - return; | |
| 540 | - } | |
| 541 | - | |
| 542 | - // Check if column already exists | |
| 543 | - $column_exists = $wpdb->get_results( | |
| 544 | - $wpdb->prepare( | |
| 545 | - "SHOW COLUMNS FROM {$table_name} LIKE %s", | |
| 546 | - 'role_restriction' | |
| 547 | - ) | |
| 548 | - ); | |
| 549 | - | |
| 550 | - if (empty($column_exists)) { | |
| 551 | - $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url"; | |
| 552 | - $result = $wpdb->query($alter_sql); | |
| 553 | - | |
| 554 | - if ($result === false) { | |
| 555 | - //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error); | |
| 556 | - } else { | |
| 557 | - //error_log("MxChat: Successfully added role_restriction column"); | |
| 558 | - | |
| 559 | - // Set all existing records to 'public' (everyone can access) | |
| 560 | - $update_result = $wpdb->query( | |
| 561 | - "UPDATE {$table_name} | |
| 562 | - SET role_restriction = 'public' | |
| 563 | - WHERE role_restriction IS NULL OR role_restriction = ''" | |
| 564 | - ); | |
| 565 | - | |
| 566 | - if ($update_result !== false) { | |
| 567 | - //error_log("MxChat: Updated {$update_result} existing records to public access"); | |
| 568 | - } | |
| 569 | - } | |
| 570 | - } | |
| 571 | -} | |
| 572 | - | |
| 573 | -/** | |
| 574 | - * Add enabled_bots column to intents table for multi-bot action filtering | |
| 575 | - */ | |
| 576 | -function mxchat_add_enabled_bots_column() { | |
| 577 | - global $wpdb; | |
| 578 | - $table_name = $wpdb->prefix . 'mxchat_intents'; | |
| 579 | - | |
| 580 | - // Check if table exists first | |
| 581 | - $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 582 | - if (!$table_exists) { | |
| 583 | - //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column"); | |
| 584 | - return; | |
| 585 | - } | |
| 586 | - | |
| 587 | - // Check if column already exists | |
| 588 | - $column_exists = $wpdb->get_results( | |
| 589 | - $wpdb->prepare( | |
| 590 | - "SHOW COLUMNS FROM {$table_name} LIKE %s", | |
| 591 | - 'enabled_bots' | |
| 592 | - ) | |
| 593 | - ); | |
| 594 | - | |
| 595 | - if (empty($column_exists)) { | |
| 596 | - $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled"; | |
| 597 | - $result = $wpdb->query($alter_sql); | |
| 598 | - | |
| 599 | - if ($result === false) { | |
| 600 | - //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error); | |
| 601 | - } else { | |
| 602 | - //error_log("MxChat: Successfully added enabled_bots column"); | |
| 603 | - | |
| 604 | - // Set all existing actions to work with 'default' bot for backward compatibility | |
| 605 | - $default_bots = json_encode(['default']); | |
| 606 | - $update_result = $wpdb->query( | |
| 607 | - $wpdb->prepare( | |
| 608 | - "UPDATE {$table_name} | |
| 609 | - SET enabled_bots = %s | |
| 610 | - WHERE enabled_bots IS NULL OR enabled_bots = ''", | |
| 611 | - $default_bots | |
| 612 | - ) | |
| 613 | - ); | |
| 614 | - | |
| 615 | - if ($update_result !== false) { | |
| 616 | - //error_log("MxChat: Updated {$update_result} existing actions to work with default bot"); | |
| 617 | - } | |
| 618 | - } | |
| 619 | - } | |
| 620 | -} | |
| 621 | - | |
| 622 | -/** | |
| 623 | - * Create Pinecone role restrictions table with multi-bot support | |
| 624 | - */ | |
| 625 | -function mxchat_create_pinecone_roles_table() { | |
| 626 | - global $wpdb; | |
| 627 | - | |
| 628 | - $table_name = $wpdb->prefix . 'mxchat_pinecone_roles'; | |
| 629 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 630 | - | |
| 631 | - $sql = "CREATE TABLE $table_name ( | |
| 632 | - id mediumint(9) NOT NULL AUTO_INCREMENT, | |
| 633 | - vector_id varchar(255) NOT NULL, | |
| 634 | - bot_id varchar(50) NOT NULL DEFAULT 'default', | |
| 635 | - source_url text, | |
| 636 | - role_restriction varchar(50) DEFAULT 'public', | |
| 637 | - updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, | |
| 638 | - PRIMARY KEY (id), | |
| 639 | - UNIQUE KEY vector_bot (vector_id, bot_id), | |
| 640 | - KEY role_restriction (role_restriction), | |
| 641 | - KEY bot_id (bot_id) | |
| 642 | - ) $charset_collate;"; | |
| 643 | - | |
| 644 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 645 | - dbDelta($sql); | |
| 646 | -} | |
| 647 | - | |
| 648 | -/** | |
| 649 | - * Add bot_id column to mxchat_pinecone_roles table for multi-bot support | |
| 650 | - * This migration runs once to update existing installations | |
| 651 | - */ | |
| 652 | -function mxchat_migrate_pinecone_roles_add_bot_id() { | |
| 653 | - global $wpdb; | |
| 654 | - | |
| 655 | - // Check if migration already ran | |
| 656 | - $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0'); | |
| 657 | - if (version_compare($migration_version, '2.5.2', '>=')) { | |
| 658 | - return; // Already migrated | |
| 659 | - } | |
| 660 | - | |
| 661 | - $table_name = $wpdb->prefix . 'mxchat_pinecone_roles'; | |
| 662 | - | |
| 663 | - // Check if table exists | |
| 664 | - if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) { | |
| 665 | - return; // Table doesn't exist yet | |
| 666 | - } | |
| 667 | - | |
| 668 | - // Check if bot_id column already exists | |
| 669 | - $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'"); | |
| 670 | - | |
| 671 | - if (empty($column_exists)) { | |
| 672 | - // Add bot_id column | |
| 673 | - $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id"); | |
| 674 | - | |
| 675 | - // Update the unique key to include bot_id | |
| 676 | - $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id"); | |
| 677 | - $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)"); | |
| 678 | - | |
| 679 | - // Add index for bot_id | |
| 680 | - $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)"); | |
| 681 | - | |
| 682 | - //error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table'); | |
| 683 | - } | |
| 684 | - | |
| 685 | - // Mark migration as complete | |
| 686 | - update_option('mxchat_pinecone_roles_migration_version', '2.5.2'); | |
| 687 | -} | |
| 688 | - | |
| 689 | -/** | |
| 690 | - * 2.5.6: Add content_type column to mxchat_system_prompt_content table | |
| 691 | - * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.) | |
| 692 | - */ | |
| 693 | -function mxchat_migrate_add_content_type_column() { | |
| 694 | - global $wpdb; | |
| 695 | - | |
| 696 | - // Check if migration already ran | |
| 697 | - $migration_version = get_option('mxchat_content_type_migration_version', '0'); | |
| 698 | - if (version_compare($migration_version, '2.5.6', '>=')) { | |
| 699 | - return; | |
| 700 | - } | |
| 701 | - | |
| 702 | - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 703 | - | |
| 704 | - // Check if table exists | |
| 705 | - if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) { | |
| 706 | - return; | |
| 707 | - } | |
| 708 | - | |
| 709 | - // Check if content_type column already exists | |
| 710 | - $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'"); | |
| 711 | - | |
| 712 | - if (empty($column_exists)) { | |
| 713 | - // Add content_type column with default value 'content' for backwards compatibility | |
| 714 | - $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction"); | |
| 715 | - | |
| 716 | - // Add index for better query performance | |
| 717 | - $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)"); | |
| 718 | - | |
| 719 | - //error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table'); | |
| 720 | - } | |
| 721 | - | |
| 722 | - // Mark migration as complete | |
| 723 | - update_option('mxchat_content_type_migration_version', '2.5.6'); | |
| 724 | -} | |
| 725 | - | |
| 726 | -/** | |
| 727 | - * 3.2.4: Backfill the active embedding model option for installs that already | |
| 728 | - * have KB content but no stamped model. The mismatch warning compares this | |
| 729 | - * against the user's currently selected model — no per-row column needed. | |
| 730 | - */ | |
| 731 | -function mxchat_backfill_active_embedding_model() { | |
| 732 | - global $wpdb; | |
| 733 | - | |
| 734 | - if (get_option('mxchat_active_embedding_model', '') !== '') { | |
| 735 | - return; | |
| 736 | - } | |
| 737 | - | |
| 738 | - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 739 | - if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) { | |
| 740 | - return; | |
| 741 | - } | |
| 742 | - | |
| 743 | - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}"); | |
| 744 | - if ($kb_count > 0) { | |
| 745 | - $options = get_option('mxchat_options', array()); | |
| 746 | - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002'; | |
| 747 | - update_option('mxchat_active_embedding_model', $current_model, false); | |
| 748 | - } | |
| 749 | -} | |
| 750 | - | |
| 751 | -/** | |
| 752 | - * 2.5.2: Create queue processing tables for reliable background processing | |
| 753 | - */ | |
| 754 | -function mxchat_create_queue_tables() { | |
| 755 | - global $wpdb; | |
| 756 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 757 | - | |
| 758 | - // Main queue table | |
| 759 | - $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 760 | - $sql_queue = "CREATE TABLE $queue_table ( | |
| 761 | - id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 762 | - queue_id varchar(64) NOT NULL, | |
| 763 | - item_type varchar(20) NOT NULL, | |
| 764 | - item_data longtext NOT NULL, | |
| 765 | - status varchar(20) NOT NULL DEFAULT 'pending', | |
| 766 | - bot_id varchar(50) NOT NULL DEFAULT 'default', | |
| 767 | - priority int(11) NOT NULL DEFAULT 0, | |
| 768 | - attempts int(11) NOT NULL DEFAULT 0, | |
| 769 | - max_attempts int(11) NOT NULL DEFAULT 3, | |
| 770 | - error_message text DEFAULT NULL, | |
| 771 | - created_at datetime NOT NULL, | |
| 772 | - started_at datetime DEFAULT NULL, | |
| 773 | - completed_at datetime DEFAULT NULL, | |
| 774 | - PRIMARY KEY (id), | |
| 775 | - KEY queue_id (queue_id), | |
| 776 | - KEY status (status), | |
| 777 | - KEY item_type (item_type), | |
| 778 | - KEY priority (priority) | |
| 779 | - ) $charset_collate;"; | |
| 780 | - | |
| 781 | - // Queue metadata table | |
| 782 | - $meta_table = $wpdb->prefix . 'mxchat_queue_meta'; | |
| 783 | - $sql_meta = "CREATE TABLE $meta_table ( | |
| 784 | - id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 785 | - queue_id varchar(64) NOT NULL, | |
| 786 | - meta_key varchar(255) NOT NULL, | |
| 787 | - meta_value longtext, | |
| 788 | - PRIMARY KEY (id), | |
| 789 | - KEY queue_id (queue_id), | |
| 790 | - KEY meta_key (meta_key) | |
| 791 | - ) $charset_collate;"; | |
| 792 | - | |
| 793 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 794 | - dbDelta($sql_queue); | |
| 795 | - dbDelta($sql_meta); | |
| 796 | - | |
| 797 | - //error_log("MxChat: Queue tables created/updated successfully"); | |
| 798 | -} | |
| 799 | - | |
| 800 | -/** | |
| 801 | - * Create transcript translations table for persisting translations | |
| 802 | - */ | |
| 803 | -function mxchat_create_translations_table() { | |
| 804 | - global $wpdb; | |
| 805 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 806 | - | |
| 807 | - $table_name = $wpdb->prefix . 'mxchat_transcript_translations'; | |
| 808 | - $sql = "CREATE TABLE $table_name ( | |
| 809 | - id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 810 | - session_id varchar(255) NOT NULL, | |
| 811 | - language_code varchar(10) NOT NULL, | |
| 812 | - translations longtext NOT NULL, | |
| 813 | - created_at datetime NOT NULL, | |
| 814 | - updated_at datetime NOT NULL, | |
| 815 | - PRIMARY KEY (id), | |
| 816 | - UNIQUE KEY session_lang (session_id, language_code), | |
| 817 | - KEY session_id (session_id) | |
| 818 | - ) $charset_collate;"; | |
| 819 | - | |
| 820 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 821 | - dbDelta($sql); | |
| 822 | -} | |
| 823 | - | |
| 824 | -/** | |
| 825 | - * Create per-session satisfaction ratings table (v3.2.6) | |
| 826 | - * Stores one 👍/👎 rating + optional feedback per chat session. | |
| 827 | - */ | |
| 828 | -function mxchat_create_session_ratings_table() { | |
| 829 | - global $wpdb; | |
| 830 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 831 | - | |
| 832 | - $table_name = $wpdb->prefix . 'mxchat_session_ratings'; | |
| 833 | - $sql = "CREATE TABLE $table_name ( | |
| 834 | - id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 835 | - session_id varchar(255) NOT NULL, | |
| 836 | - bot_id varchar(50) NOT NULL DEFAULT 'default', | |
| 837 | - rating_value tinyint(1) NOT NULL, | |
| 838 | - rating_feedback text DEFAULT NULL, | |
| 839 | - created_at datetime NOT NULL, | |
| 840 | - PRIMARY KEY (id), | |
| 841 | - UNIQUE KEY session_id (session_id), | |
| 842 | - KEY bot_id (bot_id), | |
| 843 | - KEY created_at (created_at) | |
| 844 | - ) $charset_collate;"; | |
| 845 | - | |
| 846 | - require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 847 | - dbDelta($sql); | |
| 848 | -} | |
| 849 | - | |
| 850 | -/** | |
| 851 | - * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding) | |
| 852 | - * This fixes "url, source_url. The supplied values may be too long" errors | |
| 853 | - */ | |
| 854 | -function mxchat_fix_url_column_size() { | |
| 855 | - global $wpdb; | |
| 856 | - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 857 | - | |
| 858 | - // Check if table exists | |
| 859 | - $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 860 | - if (!$table_exists) { | |
| 861 | - return; | |
| 862 | - } | |
| 863 | - | |
| 864 | - // Change url and source_url from VARCHAR to TEXT to handle long URLs | |
| 865 | - // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.) | |
| 866 | - $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT"); | |
| 867 | - $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT"); | |
| 868 | - | |
| 869 | - //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support"); | |
| 870 | -} | |
| 871 | - | |
| 872 | -/** | |
| 873 | - * Migrate deprecated AI models to their replacements | |
| 874 | - * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet | |
| 875 | - * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support | |
| 876 | - * Without utf8mb4, any bot response containing emojis silently fails to insert. | |
| 877 | - */ | |
| 878 | -function mxchat_migrate_transcripts_charset() { | |
| 879 | - global $wpdb; | |
| 880 | - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 881 | - $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); | |
| 882 | -} | |
| 883 | - | |
| 884 | -/** | |
| 885 | - * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series | |
| 886 | - */ | |
| 887 | -function mxchat_migrate_deprecated_models() { | |
| 888 | - $options = get_option('mxchat_options', array()); | |
| 889 | - $migrated = false; | |
| 890 | - $migration_message = ''; | |
| 891 | - | |
| 892 | - if (!isset($options['model'])) { | |
| 893 | - return; | |
| 894 | - } | |
| 895 | - | |
| 896 | - $current_model = $options['model']; | |
| 897 | - | |
| 898 | - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic) | |
| 899 | - $deprecated_claude_models = array( | |
| 900 | - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025 | |
| 901 | - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025 | |
| 902 | - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026 | |
| 903 | - 'claude-3-opus-20240229', // Retired Jan 5, 2026 | |
| 904 | - 'claude-3-sonnet-20240229', // Legacy | |
| 905 | - 'claude-3-haiku-20240307', // Legacy | |
| 906 | - ); | |
| 907 | - if (in_array($current_model, $deprecated_claude_models, true)) { | |
| 908 | - $options['model'] = 'claude-opus-4-6'; | |
| 909 | - $migrated = true; | |
| 910 | - $migration_message = sprintf( | |
| 911 | - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.', | |
| 912 | - $current_model | |
| 913 | - ); | |
| 914 | - } | |
| 915 | - | |
| 916 | - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5 | |
| 917 | - if ($current_model === 'claude-3-5-haiku-20241022') { | |
| 918 | - $options['model'] = 'claude-haiku-4-5-20251001'; | |
| 919 | - $migrated = true; | |
| 920 | - $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.'; | |
| 921 | - } | |
| 922 | - | |
| 923 | - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest | |
| 924 | - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) { | |
| 925 | - $options['model'] = 'gpt-5.1-chat-latest'; | |
| 926 | - $migrated = true; | |
| 927 | - $migration_message = sprintf( | |
| 928 | - 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.', | |
| 929 | - $current_model | |
| 930 | - ); | |
| 931 | - } | |
| 932 | - | |
| 933 | - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini | |
| 934 | - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) { | |
| 935 | - $options['model'] = 'gpt-5-mini'; | |
| 936 | - $migrated = true; | |
| 937 | - $migration_message = sprintf( | |
| 938 | - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.', | |
| 939 | - $current_model | |
| 940 | - ); | |
| 941 | - } | |
| 942 | - | |
| 943 | - if ($migrated) { | |
| 944 | - update_option('mxchat_options', $options); | |
| 945 | - update_option('mxchat_model_migrated_notice', true); | |
| 946 | - update_option('mxchat_model_migration_message', $migration_message); | |
| 947 | - } | |
| 948 | -} | |
| 949 | - | |
| 950 | -/** | |
| 951 | - * Show admin notice after model migration | |
| 952 | - */ | |
| 953 | -function mxchat_show_migration_notice() { | |
| 954 | - if (get_option('mxchat_model_migrated_notice')) { | |
| 955 | - $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat')); | |
| 956 | - ?> | |
| 957 | - <div class="notice notice-info is-dismissible"> | |
| 958 | - <p> | |
| 959 | - <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br> | |
| 960 | - <?php echo esc_html($migration_message); ?> | |
| 961 | - </p> | |
| 962 | - </div> | |
| 963 | - <?php | |
| 964 | - delete_option('mxchat_model_migrated_notice'); | |
| 965 | - delete_option('mxchat_model_migration_message'); | |
| 966 | - } | |
| 967 | -} | |
| 968 | - | |
| 969 | -function mxchat_activate() { | |
| 970 | - global $wpdb; | |
| 971 | - $charset_collate = $wpdb->get_charset_collate(); | |
| 972 | - | |
| 973 | - //error_log("MxChat: Running activation function"); | |
| 974 | - | |
| 975 | - // Create chat transcripts table with improved function | |
| 976 | - mxchat_create_chat_transcripts_table(); | |
| 977 | - | |
| 978 | - // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns | |
| 979 | - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 980 | - $sql_system_prompt = "CREATE TABLE $system_prompt_table ( | |
| 981 | - id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, | |
| 982 | - url TEXT NOT NULL, | |
| 983 | - article_content LONGTEXT NOT NULL, | |
| 984 | - embedding_vector LONGTEXT, | |
| 985 | - source_url TEXT DEFAULT NULL, | |
| 986 | - role_restriction VARCHAR(50) DEFAULT 'public', | |
| 987 | - content_type VARCHAR(50) DEFAULT 'content', | |
| 988 | - timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, | |
| 989 | - PRIMARY KEY (id), | |
| 990 | - KEY content_type (content_type) | |
| 991 | - ) $charset_collate;"; | |
| 992 | - | |
| 993 | - // Intents Table - NOW INCLUDES enabled_bots column from the start | |
| 994 | - $intents_table = $wpdb->prefix . 'mxchat_intents'; | |
| 995 | - $sql_intents_table = "CREATE TABLE $intents_table ( | |
| 996 | - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, | |
| 997 | - intent_label VARCHAR(255) NOT NULL, | |
| 998 | - phrases TEXT NOT NULL, | |
| 999 | - embedding_vector LONGTEXT NOT NULL, | |
| 1000 | - callback_function VARCHAR(255) NOT NULL, | |
| 1001 | - similarity_threshold FLOAT DEFAULT 0.85, | |
| 1002 | - enabled TINYINT(1) NOT NULL DEFAULT 1, | |
| 1003 | - enabled_bots LONGTEXT DEFAULT NULL, | |
| 1004 | - PRIMARY KEY (id) | |
| 1005 | - ) $charset_collate;"; | |
| 1006 | - | |
| 1007 | - // Individual Intent Phrases Table - each phrase gets its own embedding vector | |
| 1008 | - $intent_phrases_table = $wpdb->prefix . 'mxchat_intent_phrases'; | |
| 1009 | - $sql_intent_phrases_table = "CREATE TABLE $intent_phrases_table ( | |
| 1010 | - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, | |
| 1011 | - intent_id BIGINT(20) UNSIGNED NOT NULL, | |
| 1012 | - phrase TEXT NOT NULL, | |
| 1013 | - embedding_vector LONGTEXT NOT NULL, | |
| 1014 | - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, | |
| 1015 | - PRIMARY KEY (id), | |
| 1016 | - KEY intent_id (intent_id) | |
| 1017 | - ) $charset_collate;"; | |
| 1018 | - | |
| 1019 | - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; | |
| 1020 | - | |
| 1021 | - // Create other tables | |
| 1022 | - dbDelta($sql_system_prompt); | |
| 1023 | - dbDelta($sql_intents_table); | |
| 1024 | - dbDelta($sql_intent_phrases_table); | |
| 1025 | - | |
| 1026 | - // Create URL click tracking table | |
| 1027 | - mxchat_create_url_clicks_table(); | |
| 1028 | - | |
| 1029 | - // Create Pinecone roles table | |
| 1030 | - mxchat_create_pinecone_roles_table(); | |
| 1031 | - | |
| 1032 | - // NEW 2.5.2: Create queue processing tables | |
| 1033 | - mxchat_create_queue_tables(); | |
| 1034 | - | |
| 1035 | - // Create transcript translations table | |
| 1036 | - mxchat_create_translations_table(); | |
| 1037 | - | |
| 1038 | - // Create per-session satisfaction ratings table (v3.2.6) | |
| 1039 | - mxchat_create_session_ratings_table(); | |
| 1040 | - | |
| 1041 | - // Ensure additional columns in system prompt table | |
| 1042 | - $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table"); | |
| 1043 | - if (!empty($existing_system_columns)) { | |
| 1044 | - $existing_system_column_names = array_column($existing_system_columns, 'Field'); | |
| 1045 | - | |
| 1046 | - if (!in_array('embedding_vector', $existing_system_column_names)) { | |
| 1047 | - $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT"); | |
| 1048 | - } | |
| 1049 | - if (!in_array('source_url', $existing_system_column_names)) { | |
| 1050 | - $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL"); | |
| 1051 | - } | |
| 1052 | - if (!in_array('role_restriction', $existing_system_column_names)) { | |
| 1053 | - $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url"); | |
| 1054 | - } | |
| 1055 | - } | |
| 1056 | - | |
| 1057 | - // Set default thresholds for existing intents | |
| 1058 | - $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL"); | |
| 1059 | - | |
| 1060 | - // Ensure enabled column exists in intents table | |
| 1061 | - $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table"); | |
| 1062 | - if (!empty($existing_intent_columns)) { | |
| 1063 | - $existing_intent_column_names = array_column($existing_intent_columns, 'Field'); | |
| 1064 | - | |
| 1065 | - if (!in_array('enabled', $existing_intent_column_names)) { | |
| 1066 | - $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1"); | |
| 1067 | - } | |
| 1068 | - | |
| 1069 | - // Ensure enabled_bots column exists for existing installations | |
| 1070 | - if (!in_array('enabled_bots', $existing_intent_column_names)) { | |
| 1071 | - $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled"); | |
| 1072 | - | |
| 1073 | - // Set existing actions to work with default bot | |
| 1074 | - $default_bots = json_encode(['default']); | |
| 1075 | - $wpdb->query($wpdb->prepare( | |
| 1076 | - "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL", | |
| 1077 | - $default_bots | |
| 1078 | - )); | |
| 1079 | - } | |
| 1080 | - } | |
| 1081 | - | |
| 1082 | - // Run migration for existing installations | |
| 1083 | - mxchat_migrate_pinecone_roles_add_bot_id(); | |
| 1084 | - | |
| 1085 | - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking) | |
| 1086 | - mxchat_backfill_active_embedding_model(); | |
| 1087 | - | |
| 1088 | - // Setup cron jobs | |
| 1089 | - mxchat_setup_cron_jobs(); | |
| 1090 | - | |
| 1091 | - // Update version | |
| 1092 | - update_option('mxchat_plugin_version', MXCHAT_VERSION); | |
| 1093 | - | |
| 1094 | - //error_log("MxChat: Activation function completed"); | |
| 1095 | -} | |
| 1096 | - | |
| 1097 | -/** | |
| 1098 | - * Setup cron jobs on plugin activation | |
| 1099 | - */ | |
| 1100 | -function mxchat_setup_cron_jobs() { | |
| 1101 | - // Clear any existing cron jobs first | |
| 1102 | - wp_clear_scheduled_hook('mxchat_reset_rate_limits'); | |
| 1103 | - | |
| 1104 | - // Check if WordPress cron is disabled | |
| 1105 | - if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { | |
| 1106 | - // Set flag to use fallback system | |
| 1107 | - update_option('mxchat_use_fallback_rate_limits', true); | |
| 1108 | - update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 1109 | - return; | |
| 1110 | - } | |
| 1111 | - | |
| 1112 | - // Schedule the rate limit reset cron job | |
| 1113 | - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits'); | |
| 1114 | - | |
| 1115 | - if ($result === false) { | |
| 1116 | - // Fallback if scheduling fails | |
| 1117 | - update_option('mxchat_use_fallback_rate_limits', true); | |
| 1118 | - update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 1119 | - } else { | |
| 1120 | - // Clear fallback flags if cron scheduling succeeded | |
| 1121 | - delete_option('mxchat_use_fallback_rate_limits'); | |
| 1122 | - } | |
| 1123 | - | |
| 1124 | - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0) | |
| 1125 | - $transcript_options = get_option('mxchat_transcripts_options', array()); | |
| 1126 | - $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never'; | |
| 1127 | - $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0; | |
| 1128 | - | |
| 1129 | - if ($cleanup_interval !== 'never' || $custom_retention > 0) { | |
| 1130 | - // Check if not already scheduled | |
| 1131 | - if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) { | |
| 1132 | - // Schedule to run daily at 3 AM | |
| 1133 | - $next_run = strtotime('tomorrow 3:00 AM'); | |
| 1134 | - wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts'); | |
| 1135 | - } | |
| 1136 | - } | |
| 1137 | -} | |
| 1138 | - | |
| 1139 | -/** | |
| 1140 | - * Clean up on plugin deactivation | |
| 1141 | - */ | |
| 1142 | -function mxchat_deactivate() { | |
| 1143 | - // Clear scheduled cron jobs | |
| 1144 | - wp_clear_scheduled_hook('mxchat_reset_rate_limits'); | |
| 1145 | - wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts'); | |
| 1146 | - wp_clear_scheduled_hook('mxchat_send_delayed_transcript'); | |
| 1147 | - | |
| 1148 | - // Clear fallback options | |
| 1149 | - delete_option('mxchat_use_fallback_rate_limits'); | |
| 1150 | - delete_option('mxchat_next_rate_limit_check'); | |
| 1151 | - delete_option('mxchat_fallback_check_interval'); | |
| 1152 | - | |
| 1153 | - // NOTE: We do NOT delete queue tables on deactivation | |
| 1154 | - // This preserves data if user accidentally deactivates the plugin | |
| 1155 | -} | |
| 1156 | - | |
| 1157 | -/** | |
| 1158 | - * Check if fallback rate limit cleanup is needed | |
| 1159 | - */ | |
| 1160 | -function mxchat_check_fallback_rate_limits() { | |
| 1161 | - $use_fallback = get_option('mxchat_use_fallback_rate_limits', false); | |
| 1162 | - | |
| 1163 | - if (!$use_fallback) { | |
| 1164 | - return; | |
| 1165 | - } | |
| 1166 | - | |
| 1167 | - $next_check = get_option('mxchat_next_rate_limit_check', 0); | |
| 1168 | - | |
| 1169 | - if (time() >= $next_check) { | |
| 1170 | - // Only run reset if the MxChat_Integrator class exists | |
| 1171 | - if (class_exists('MxChat_Integrator')) { | |
| 1172 | - $integrator = new MxChat_Integrator(); | |
| 1173 | - if (method_exists($integrator, 'mxchat_reset_rate_limits')) { | |
| 1174 | - $integrator->mxchat_reset_rate_limits(); | |
| 1175 | - update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 1176 | - } | |
| 1177 | - } | |
| 1178 | - } | |
| 1179 | -} | |
| 1180 | - | |
| 1181 | -/** | |
| 1182 | - * Robust update checking with role restriction migration, model deprecation, and queue tables | |
| 1183 | - * CRITICAL: This runs on EVERY page load to ensure tables exist | |
| 1184 | - */ | |
| 1185 | -function mxchat_check_for_update() { | |
| 1186 | - global $wpdb; | |
| 1187 | - | |
| 1188 | - try { | |
| 1189 | - $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 1190 | - $plugin_version = MXCHAT_VERSION; | |
| 1191 | - | |
| 1192 | - // Always ensure critical tables exist (even if version matches) | |
| 1193 | - // This handles manual table deletion or fresh installs | |
| 1194 | - $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1195 | - $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 1196 | - | |
| 1197 | - $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table; | |
| 1198 | - $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; | |
| 1199 | - | |
| 1200 | - if (!$chat_exists || !$queue_exists) { | |
| 1201 | - //error_log("MxChat: Critical tables missing, running activation"); | |
| 1202 | - mxchat_activate(); | |
| 1203 | - } | |
| 1204 | - | |
| 1205 | - // Version-specific migrations | |
| 1206 | - if ($current_version !== $plugin_version) { | |
| 1207 | - //error_log("MxChat: Version change detected: $current_version -> $plugin_version"); | |
| 1208 | - | |
| 1209 | - // Run live agent update BEFORE updating the stored version | |
| 1210 | - mxchat_handle_live_agent_update(); | |
| 1211 | - | |
| 1212 | - // Run theme migration notice for 3.0.1 (AI theme CSS structure changes) | |
| 1213 | - mxchat_handle_theme_migration_notice(); | |
| 1214 | - | |
| 1215 | - // Run role restriction migration for 2.4.1 | |
| 1216 | - if (version_compare($current_version, '2.4.1', '<')) { | |
| 1217 | - mxchat_add_role_restriction_column(); | |
| 1218 | - } | |
| 1219 | - | |
| 1220 | - // Run enabled_bots column migration for 2.4.4 | |
| 1221 | - if (version_compare($current_version, '2.4.4', '<')) { | |
| 1222 | - mxchat_add_enabled_bots_column(); | |
| 1223 | - } | |
| 1224 | - | |
| 1225 | - // Run model migration for 2.5.1 (Claude deprecation) | |
| 1226 | - if (version_compare($current_version, '2.5.1', '<')) { | |
| 1227 | - mxchat_migrate_deprecated_models(); | |
| 1228 | - } | |
| 1229 | - | |
| 1230 | - // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2 | |
| 1231 | - if (version_compare($current_version, '2.5.2', '<')) { | |
| 1232 | - mxchat_create_queue_tables(); | |
| 1233 | - mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs | |
| 1234 | - //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2"); | |
| 1235 | - } | |
| 1236 | - | |
| 1237 | - // 2.6.0: Ensure rag_context column exists for retrieved documents feature | |
| 1238 | - if (version_compare($current_version, '2.6.0', '<')) { | |
| 1239 | - $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1240 | - mxchat_ensure_all_columns($chat_table); | |
| 1241 | - //error_log("MxChat: rag_context column migration for 2.6.0"); | |
| 1242 | - } | |
| 1243 | - | |
| 1244 | - // 3.0.5: Migrate deprecated Gemini embedding model | |
| 1245 | - if (version_compare($current_version, '3.0.5', '<')) { | |
| 1246 | - mxchat_migrate_gemini_embedding_model(); | |
| 1247 | - } | |
| 1248 | - | |
| 1249 | - // 3.0.6: Migrate deprecated OpenAI and Claude models | |
| 1250 | - if (version_compare($current_version, '3.0.6', '<')) { | |
| 1251 | - mxchat_migrate_deprecated_models(); | |
| 1252 | - } | |
| 1253 | - | |
| 1254 | - // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support | |
| 1255 | - if (version_compare($current_version, '3.1.2', '<')) { | |
| 1256 | - mxchat_migrate_transcripts_charset(); | |
| 1257 | - } | |
| 1258 | - | |
| 1259 | - // 3.1.7: Clean up stale shared session email/name entries | |
| 1260 | - if (version_compare($current_version, '3.1.7', '<')) { | |
| 1261 | - delete_option('mxchat_email_null'); | |
| 1262 | - delete_option('mxchat_name_null'); | |
| 1263 | - } | |
| 1264 | - | |
| 1265 | - // 3.2.4: Backfill active embedding model option for the warning UI | |
| 1266 | - // (replaces the per-row column tracking from 3.2.3, which was reverted) | |
| 1267 | - if (version_compare($current_version, '3.2.4', '<')) { | |
| 1268 | - mxchat_backfill_active_embedding_model(); | |
| 1269 | - } | |
| 1270 | - | |
| 1271 | - // Run full activation to ensure everything is up to date | |
| 1272 | - mxchat_activate(); | |
| 1273 | - | |
| 1274 | - // Run migration functions | |
| 1275 | - mxchat_migrate_live_agent_status(); | |
| 1276 | - | |
| 1277 | - // Add the cleanup function for version 2.1.8 | |
| 1278 | - if (version_compare($current_version, '2.1.8', '<')) { | |
| 1279 | - $deleted = mxchat_cleanup_orphaned_chat_history(); | |
| 1280 | - } | |
| 1281 | - | |
| 1282 | - // Update version LAST | |
| 1283 | - update_option('mxchat_plugin_version', $plugin_version); | |
| 1284 | - | |
| 1285 | - //error_log("MxChat: Updated from version $current_version to $plugin_version"); | |
| 1286 | - } | |
| 1287 | - | |
| 1288 | - } catch (Exception $e) { | |
| 1289 | - //error_log('MxChat update error: ' . $e->getMessage()); | |
| 1290 | - // Don't update version if there was an error | |
| 1291 | - } | |
| 1292 | -} | |
| 1293 | - | |
| 1294 | -/** | |
| 1295 | - * Ensure tables exist on every admin load for fresh installations | |
| 1296 | - * This is a safety net for cases where activation hook doesn't fire | |
| 1297 | - */ | |
| 1298 | -function mxchat_ensure_tables_exist() { | |
| 1299 | - global $wpdb; | |
| 1300 | - | |
| 1301 | - // Only run for admin users to avoid performance impact | |
| 1302 | - if (!current_user_can('administrator')) { | |
| 1303 | - return; | |
| 1304 | - } | |
| 1305 | - | |
| 1306 | - // Check if we've already verified tables in this session | |
| 1307 | - static $tables_checked = false; | |
| 1308 | - if ($tables_checked) { | |
| 1309 | - return; | |
| 1310 | - } | |
| 1311 | - $tables_checked = true; | |
| 1312 | - | |
| 1313 | - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1314 | - $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 1315 | - | |
| 1316 | - $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 1317 | - $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; | |
| 1318 | - | |
| 1319 | - if (!$chat_exists || !$queue_exists) { | |
| 1320 | - //error_log("MxChat: Tables missing on admin load, running activation"); | |
| 1321 | - mxchat_activate(); | |
| 1322 | - } | |
| 1323 | -} | |
| 1324 | - | |
| 1325 | -/** | |
| 1326 | - * Clean up orphaned chat history options from the wp_options table | |
| 1327 | - * @return int Number of options deleted | |
| 1328 | - */ | |
| 1329 | -function mxchat_cleanup_orphaned_chat_history() { | |
| 1330 | - global $wpdb; | |
| 1331 | - $count = 0; | |
| 1332 | - | |
| 1333 | - // Get all option keys that match our pattern | |
| 1334 | - $history_options = $wpdb->get_results( | |
| 1335 | - "SELECT option_name FROM {$wpdb->options} | |
| 1336 | - WHERE option_name LIKE 'mxchat_history_%'" | |
| 1337 | - ); | |
| 1338 | - | |
| 1339 | - if (!empty($history_options)) { | |
| 1340 | - foreach ($history_options as $option) { | |
| 1341 | - // Extract the session ID from the option name | |
| 1342 | - $session_id = str_replace('mxchat_history_', '', $option->option_name); | |
| 1343 | - | |
| 1344 | - // Check if this session still exists in the custom table | |
| 1345 | - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1346 | - $exists = $wpdb->get_var( | |
| 1347 | - $wpdb->prepare( | |
| 1348 | - "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", | |
| 1349 | - $session_id | |
| 1350 | - ) | |
| 1351 | - ); | |
| 1352 | - | |
| 1353 | - // If session doesn't exist in the main table, delete the option | |
| 1354 | - if ($exists == 0) { | |
| 1355 | - delete_option($option->option_name); | |
| 1356 | - // Also delete related metadata | |
| 1357 | - delete_option("mxchat_email_{$session_id}"); | |
| 1358 | - delete_option("mxchat_name_{$session_id}"); | |
| 1359 | - delete_option("mxchat_agent_name_{$session_id}"); | |
| 1360 | - $count++; | |
| 1361 | - } | |
| 1362 | - } | |
| 1363 | - } | |
| 1364 | - | |
| 1365 | - return $count; | |
| 1366 | -} | |
| 1367 | - | |
| 1368 | -function mxchat_migrate_live_agent_status() { | |
| 1369 | - $options = get_option('mxchat_options', []); | |
| 1370 | - | |
| 1371 | - // Check if live_agent_status exists | |
| 1372 | - if (isset($options['live_agent_status'])) { | |
| 1373 | - $current_status = $options['live_agent_status']; | |
| 1374 | - $needs_update = false; | |
| 1375 | - | |
| 1376 | - // Convert to new format if needed | |
| 1377 | - if ($current_status === 'online') { | |
| 1378 | - $options['live_agent_status'] = 'on'; | |
| 1379 | - $needs_update = true; | |
| 1380 | - } else if ($current_status === 'offline') { | |
| 1381 | - $options['live_agent_status'] = 'off'; | |
| 1382 | - $needs_update = true; | |
| 1383 | - } else if (!in_array($current_status, ['on', 'off'])) { | |
| 1384 | - // Default to off for any unexpected values | |
| 1385 | - $options['live_agent_status'] = 'off'; | |
| 1386 | - $needs_update = true; | |
| 1387 | - } | |
| 1388 | - | |
| 1389 | - // Only update if needed | |
| 1390 | - if ($needs_update) { | |
| 1391 | - update_option('mxchat_options', $options); | |
| 1392 | - } | |
| 1393 | - } else { | |
| 1394 | - // If status doesn't exist, set default to off | |
| 1395 | - $options['live_agent_status'] = 'off'; | |
| 1396 | - update_option('mxchat_options', $options); | |
| 1397 | - } | |
| 1398 | -} | |
| 1399 | - | |
| 1400 | -function mxchat_handle_live_agent_update() { | |
| 1401 | - // Get the CURRENT stored version (before it gets updated) | |
| 1402 | - $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 1403 | - $new_version = '2.2.2'; | |
| 1404 | - | |
| 1405 | - // Only run this once for the update to 2.2.2 | |
| 1406 | - $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false); | |
| 1407 | - | |
| 1408 | - // Check if we're upgrading TO 2.2.2 and haven't handled this yet | |
| 1409 | - if (version_compare($current_version, $new_version, '<') && !$update_handled) { | |
| 1410 | - $options = get_option('mxchat_options', array()); | |
| 1411 | - | |
| 1412 | - // Check if live agent was previously enabled | |
| 1413 | - if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') { | |
| 1414 | - // Disable live agent | |
| 1415 | - $options['live_agent_status'] = 'off'; | |
| 1416 | - update_option('mxchat_options', $options); | |
| 1417 | - | |
| 1418 | - // Set flag to show the notification banner | |
| 1419 | - update_option('mxchat_show_live_agent_disabled_notice', true); | |
| 1420 | - } | |
| 1421 | - | |
| 1422 | - // Mark this update as handled | |
| 1423 | - update_option('mxchat_live_agent_update_2_2_2_handled', true); | |
| 1424 | - } | |
| 1425 | -} | |
| 1426 | - | |
| 1427 | -/** | |
| 1428 | - * Handle theme migration notice for version 3.0.1 | |
| 1429 | - * Shows a dismissible notice to Pro users about migrating AI-generated themes | |
| 1430 | - */ | |
| 1431 | -function mxchat_handle_theme_migration_notice() { | |
| 1432 | - // Get the CURRENT stored version (before it gets updated) | |
| 1433 | - $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 1434 | - $target_version = '3.0.1'; | |
| 1435 | - | |
| 1436 | - // Only run this once for the update to 3.0.1 | |
| 1437 | - $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false); | |
| 1438 | - | |
| 1439 | - // Check if we're upgrading TO 3.0.1 and haven't handled this yet | |
| 1440 | - if (version_compare($current_version, $target_version, '<') && !$update_handled) { | |
| 1441 | - // Check if Pro is activated - only show to Pro users | |
| 1442 | - $license_status = get_option('mxchat_license_status', 'inactive'); | |
| 1443 | - $is_pro = ($license_status === 'active'); | |
| 1444 | - | |
| 1445 | - if ($is_pro) { | |
| 1446 | - // Set flag to show the theme migration notification banner | |
| 1447 | - update_option('mxchat_show_theme_migration_notice', true); | |
| 1448 | - } | |
| 1449 | - | |
| 1450 | - // Mark this update as handled (whether Pro or not) | |
| 1451 | - update_option('mxchat_theme_migration_update_3_0_1_handled', true); | |
| 1452 | - } | |
| 1453 | -} | |
| 1454 | - | |
| 1455 | -// Initialize plugin safely | |
| 1456 | -function mxchat_init() { | |
| 1457 | - // Include all class files first | |
| 1458 | - mxchat_include_classes(); | |
| 1459 | - | |
| 1460 | - // Run update check (this also ensures tables exist) | |
| 1461 | - mxchat_check_for_update(); | |
| 1462 | - | |
| 1463 | - // CRITICAL: Ensure tables exist on admin pages (safety net) | |
| 1464 | - add_action('admin_init', 'mxchat_ensure_tables_exist', 1); | |
| 1465 | - | |
| 1466 | - // Add fallback rate limit check | |
| 1467 | - add_action('init', 'mxchat_check_fallback_rate_limits', 5); | |
| 1468 | - | |
| 1469 | - // Add migration notice hook | |
| 1470 | - add_action('admin_notices', 'mxchat_show_migration_notice'); | |
| 1471 | - | |
| 1472 | - // Initialize classes with error handling | |
| 1473 | - try { | |
| 1474 | - // Initialize admin classes | |
| 1475 | - if (is_admin()) { | |
| 1476 | - if (class_exists('MxChat_Knowledge_Manager')) { | |
| 1477 | - $mxchat_knowledge_manager = new MxChat_Knowledge_Manager(); | |
| 1478 | - | |
| 1479 | - if (class_exists('MxChat_Admin')) { | |
| 1480 | - $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager); | |
| 1481 | - } | |
| 1482 | - } | |
| 1483 | - | |
| 1484 | - // Initialize meta box class | |
| 1485 | - if (class_exists('MxChat_Meta_Box')) { | |
| 1486 | - new MxChat_Meta_Box(); | |
| 1487 | - } | |
| 1488 | - | |
| 1489 | - } | |
| 1490 | - | |
| 1491 | - // Initialize content generator globally — it registers wp_head hook | |
| 1492 | - // for frontend CSS injection, plus wp_ajax_ hooks for admin. | |
| 1493 | - if (class_exists('MxChat_Content_Generator')) { | |
| 1494 | - new MxChat_Content_Generator(); | |
| 1495 | - } | |
| 1496 | - | |
| 1497 | - // Initialize REST API globally — endpoints must be registered on | |
| 1498 | - // every request (admin and frontend) so they're reachable via /wp-json/. | |
| 1499 | - // Endpoints are auth-gated and locked until the site owner generates | |
| 1500 | - // a token in MxChat → API Access. | |
| 1501 | - if (class_exists('MxChat_Rest_Api')) { | |
| 1502 | - new MxChat_Rest_Api(); | |
| 1503 | - } | |
| 1504 | - | |
| 1505 | - // Initialize public classes | |
| 1506 | - if (class_exists('MxChat_Public')) { | |
| 1507 | - $mxchat_public = new MxChat_Public(); | |
| 1508 | - } | |
| 1509 | - | |
| 1510 | - if (class_exists('MxChat_Integrator')) { | |
| 1511 | - global $mxchat_integrator; | |
| 1512 | - $mxchat_integrator = new MxChat_Integrator(); | |
| 1513 | - } | |
| 1514 | - | |
| 1515 | - } catch (Exception $e) { | |
| 1516 | - //error_log('MxChat initialization error: ' . $e->getMessage()); | |
| 1517 | - | |
| 1518 | - // Show admin notice if there's an error | |
| 1519 | - if (is_admin()) { | |
| 1520 | - add_action('admin_notices', function() use ($e) { | |
| 1521 | - echo '<div class="notice notice-error"><p>'; | |
| 1522 | - echo '<strong>MxChat Error:</strong> Plugin initialization failed. '; | |
| 1523 | - echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage()); | |
| 1524 | - echo '</p></div>'; | |
| 1525 | - }); | |
| 1526 | - } | |
| 1527 | - } | |
| 1528 | -} | |
| 1529 | - | |
| 1530 | -// Run initialization on plugins_loaded | |
| 1531 | -add_action('plugins_loaded', 'mxchat_init'); | |
| 1532 | - | |
| 1533 | -// Run migration check on admin init (for auto-updates without reactivation) | |
| 1534 | -add_action('admin_init', 'mxchat_check_and_run_migrations'); | |
| 1535 | - | |
| 1536 | -/** | |
| 1537 | - * Check and run migrations on admin init | |
| 1538 | - * This ensures migrations run even when plugin is auto-updated | |
| 1539 | - */ | |
| 1540 | -function mxchat_check_and_run_migrations() { | |
| 1541 | - // Only run in admin and not on every request | |
| 1542 | - static $checked = false; | |
| 1543 | - if ($checked) { | |
| 1544 | - return; | |
| 1545 | - } | |
| 1546 | - $checked = true; | |
| 1547 | - | |
| 1548 | - mxchat_migrate_pinecone_roles_add_bot_id(); | |
| 1549 | - mxchat_migrate_add_content_type_column(); | |
| 1550 | - mxchat_migrate_add_translations_table(); | |
| 1551 | - mxchat_migrate_add_session_ratings_table(); | |
| 1552 | -} | |
| 1553 | - | |
| 1554 | -/** | |
| 1555 | - * Migration: Create per-session satisfaction ratings table (v3.2.6) | |
| 1556 | - * For users upgrading from versions before 3.2.6 | |
| 1557 | - */ | |
| 1558 | -function mxchat_migrate_add_session_ratings_table() { | |
| 1559 | - $migration_key = 'mxchat_session_ratings_table_created'; | |
| 1560 | - if (get_option($migration_key)) { | |
| 1561 | - return; | |
| 1562 | - } | |
| 1563 | - mxchat_create_session_ratings_table(); | |
| 1564 | - update_option($migration_key, '3.2.6'); | |
| 1565 | -} | |
| 1566 | - | |
| 1567 | -/** | |
| 1568 | - * Migration: Create transcript translations table (v3.0.4) | |
| 1569 | - * For users upgrading from versions before 3.0.4 | |
| 1570 | - */ | |
| 1571 | -function mxchat_migrate_add_translations_table() { | |
| 1572 | - $migration_key = 'mxchat_translations_table_created'; | |
| 1573 | - | |
| 1574 | - // Check if migration already ran | |
| 1575 | - if (get_option($migration_key)) { | |
| 1576 | - return; | |
| 1577 | - } | |
| 1578 | - | |
| 1579 | - // Create the translations table | |
| 1580 | - mxchat_create_translations_table(); | |
| 1581 | - | |
| 1582 | - // Mark migration as complete | |
| 1583 | - update_option($migration_key, '3.0.4'); | |
| 1584 | -} | |
| 1585 | - | |
| 1586 | -/** | |
| 1587 | - * Migration: Update deprecated Gemini embedding model (v3.0.5) | |
| 1588 | - * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected | |
| 1589 | - */ | |
| 1590 | -function mxchat_migrate_gemini_embedding_model() { | |
| 1591 | - $options = get_option('mxchat_options', array()); | |
| 1592 | - | |
| 1593 | - if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') { | |
| 1594 | - $options['embedding_model'] = 'gemini-embedding-001'; | |
| 1595 | - update_option('mxchat_options', $options); | |
| 1596 | - } | |
| 1597 | -} | |
| 1598 | - | |
| 1599 | -// Register activation hook | |
| 1600 | -register_activation_hook(__FILE__, 'mxchat_activate'); | |
| 1601 | - | |
| 1602 | -// Add cron schedule | |
| 1603 | -add_filter('cron_schedules', function($schedules) { | |
| 1604 | - $schedules['one_minute'] = array( | |
| 1605 | - 'interval' => 60, | |
| 1606 | - 'display' => 'Every Minute' | |
| 1607 | - ); | |
| 1608 | - return $schedules; | |
| 1609 | -}); | |
| 1610 | - | |
| 1611 | -// Register deactivation hook | |
| 1612 | -register_deactivation_hook(__FILE__, 'mxchat_deactivate'); | |
| 1613 | - | |
| 1614 | -/** | |
| 1615 | - * Per-session satisfaction rating: AJAX save handler (v3.2.6). | |
| 1616 | - * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on | |
| 1617 | - * session_id makes this naturally idempotent — only the first rating per | |
| 1618 | - * session is stored; duplicate POSTs are silent no-ops. | |
| 1619 | - */ | |
| 1620 | -function mxchat_save_session_rating() { | |
| 1621 | - global $wpdb; | |
| 1622 | - | |
| 1623 | - $session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''; | |
| 1624 | - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default'; | |
| 1625 | - $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0; | |
| 1626 | - $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : ''; | |
| 1627 | - | |
| 1628 | - if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) { | |
| 1629 | - wp_send_json_error(array('message' => 'invalid_input'), 400); | |
| 1630 | - } | |
| 1631 | - | |
| 1632 | - if (strlen($feedback) > 1000) { | |
| 1633 | - $feedback = substr($feedback, 0, 1000); | |
| 1634 | - } | |
| 1635 | - | |
| 1636 | - $table_name = $wpdb->prefix . 'mxchat_session_ratings'; | |
| 1637 | - $existing = $wpdb->get_var($wpdb->prepare( | |
| 1638 | - "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1", | |
| 1639 | - $session_id | |
| 1640 | - )); | |
| 1641 | - | |
| 1642 | - if ($existing) { | |
| 1643 | - if ($feedback !== '') { | |
| 1644 | - $wpdb->update( | |
| 1645 | - $table_name, | |
| 1646 | - array('rating_feedback' => $feedback), | |
| 1647 | - array('id' => (int) $existing), | |
| 1648 | - array('%s'), | |
| 1649 | - array('%d') | |
| 1650 | - ); | |
| 1651 | - } | |
| 1652 | - wp_send_json_success(array('updated' => true)); | |
| 1653 | - } | |
| 1654 | - | |
| 1655 | - $inserted = $wpdb->insert( | |
| 1656 | - $table_name, | |
| 1657 | - array( | |
| 1658 | - 'session_id' => $session_id, | |
| 1659 | - 'bot_id' => $bot_id !== '' ? $bot_id : 'default', | |
| 1660 | - 'rating_value' => $rating_raw, | |
| 1661 | - 'rating_feedback' => $feedback !== '' ? $feedback : null, | |
| 1662 | - 'created_at' => current_time('mysql'), | |
| 1663 | - ), | |
| 1664 | - array('%s', '%s', '%d', '%s', '%s') | |
| 1665 | - ); | |
| 1666 | - | |
| 1667 | - if ($inserted === false) { | |
| 1668 | - wp_send_json_error(array('message' => 'db_insert_failed'), 500); | |
| 1669 | - } | |
| 1670 | - | |
| 1671 | - wp_send_json_success(array('saved' => true)); | |
| 1672 | -} | |
| 1673 | -add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating'); | |
| 1674 | -add_action('wp_ajax_nopriv_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.1.2 | |
| 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 | +// Define plugin version constant for asset versioning | |
| 20 | +// Reads version from plugin header automatically | |
| 21 | +if (!defined('MXCHAT_VERSION')) { | |
| 22 | + $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), 'plugin'); | |
| 23 | + define('MXCHAT_VERSION', $plugin_data['Version']); | |
| 24 | +} | |
| 25 | + | |
| 26 | +function mxchat_load_textdomain() { | |
| 27 | + $domain = 'mxchat'; | |
| 28 | + $locale = determine_locale(); | |
| 29 | + | |
| 30 | + // First, try to load from /wp-content/languages/plugins/ (preserved during updates) | |
| 31 | + $mo_file = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo'; | |
| 32 | + if (file_exists($mo_file)) { | |
| 33 | + load_textdomain($domain, $mo_file); | |
| 34 | + return; | |
| 35 | + } | |
| 36 | + | |
| 37 | + // Fallback to plugin's /languages directory | |
| 38 | + load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages'); | |
| 39 | +} | |
| 40 | +add_action('init', 'mxchat_load_textdomain'); | |
| 41 | + | |
| 42 | +/** | |
| 43 | + * Exclude MxChat assets from caching plugin optimizations | |
| 44 | + * | |
| 45 | + * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache, | |
| 46 | + * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by | |
| 47 | + * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery. | |
| 48 | + * | |
| 49 | + * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also | |
| 50 | + * be excluded from any optimization that changes load order or timing. | |
| 51 | + */ | |
| 52 | + | |
| 53 | +// ── WP Rocket ──────────────────────────────────────────────────────────────── | |
| 54 | + | |
| 55 | +// Exclude from Remove Unused CSS (RUCSS) | |
| 56 | +add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) { | |
| 57 | + if (!is_array($exclusions)) $exclusions = array(); | |
| 58 | + $exclusions[] = 'mxchat'; | |
| 59 | + return $exclusions; | |
| 60 | +}); | |
| 61 | + | |
| 62 | +// Exclude CSS from minification/combination | |
| 63 | +add_filter('rocket_exclude_css', function($excluded) { | |
| 64 | + if (!is_array($excluded)) $excluded = array(); | |
| 65 | + $excluded[] = '/plugins/mxchat-basic/css/chat-style.css'; | |
| 66 | + return $excluded; | |
| 67 | +}); | |
| 68 | + | |
| 69 | +// Exclude JS from minification/combination | |
| 70 | +add_filter('rocket_exclude_js', function($excluded) { | |
| 71 | + if (!is_array($excluded)) $excluded = array(); | |
| 72 | + $excluded[] = '/plugins/mxchat-basic/js/chat-script.js'; | |
| 73 | + $excluded[] = '/plugins/mxchat-basic/js/floating-script.js'; | |
| 74 | + $excluded[] = '/jquery-core'; | |
| 75 | + $excluded[] = '/jquery.min.js'; | |
| 76 | + $excluded[] = '/jquery.js'; | |
| 77 | + $excluded[] = '/jquery-migrate'; | |
| 78 | + return $excluded; | |
| 79 | +}); | |
| 80 | + | |
| 81 | +// Exclude JS from defer | |
| 82 | +add_filter('rocket_exclude_defer_js', function($excluded) { | |
| 83 | + if (!is_array($excluded)) $excluded = array(); | |
| 84 | + $excluded[] = '/plugins/mxchat-basic/js/chat-script.js'; | |
| 85 | + $excluded[] = '/plugins/mxchat-basic/js/floating-script.js'; | |
| 86 | + $excluded[] = '/jquery-core'; | |
| 87 | + $excluded[] = '/jquery.min.js'; | |
| 88 | + $excluded[] = '/jquery.js'; | |
| 89 | + $excluded[] = '/jquery-migrate'; | |
| 90 | + return $excluded; | |
| 91 | +}); | |
| 92 | + | |
| 93 | +// Exclude from delay JS execution | |
| 94 | +add_filter('rocket_delay_js_exclusions', function($excluded) { | |
| 95 | + if (!is_array($excluded)) $excluded = array(); | |
| 96 | + $excluded[] = 'mxchat'; | |
| 97 | + $excluded[] = 'chat-script'; | |
| 98 | + $excluded[] = 'floating-script'; | |
| 99 | + $excluded[] = '/jquery-core'; | |
| 100 | + $excluded[] = '/jquery.min.js'; | |
| 101 | + $excluded[] = '/jquery.js'; | |
| 102 | + $excluded[] = '/jquery-migrate'; | |
| 103 | + return $excluded; | |
| 104 | +}); | |
| 105 | + | |
| 106 | +// ── LiteSpeed Cache ────────────────────────────────────────────────────────── | |
| 107 | + | |
| 108 | +// Exclude CSS from optimization | |
| 109 | +add_filter('litespeed_optimize_css_excludes', function($excluded) { | |
| 110 | + if (!is_array($excluded)) $excluded = array(); | |
| 111 | + $excluded[] = 'chat-style.css'; | |
| 112 | + $excluded[] = 'mxchat'; | |
| 113 | + return $excluded; | |
| 114 | +}); | |
| 115 | + | |
| 116 | +// Exclude from UCSS (Unique CSS) - prevents LiteSpeed from stripping "unused" MxChat CSS | |
| 117 | +add_filter('litespeed_ucss_whitelist', function($whitelist) { | |
| 118 | + if (!is_array($whitelist)) $whitelist = array(); | |
| 119 | + $whitelist[] = '.mxchat-chatbot-wrapper'; | |
| 120 | + $whitelist[] = '.floating-chatbot'; | |
| 121 | + $whitelist[] = '.floating-chatbot-button'; | |
| 122 | + $whitelist[] = '.chatbot-top-bar'; | |
| 123 | + $whitelist[] = '.mxchat-chatbot'; | |
| 124 | + $whitelist[] = '.chat-container'; | |
| 125 | + $whitelist[] = '.chat-box'; | |
| 126 | + $whitelist[] = '.bot-message'; | |
| 127 | + $whitelist[] = '.input-container'; | |
| 128 | + $whitelist[] = '.chat-input'; | |
| 129 | + $whitelist[] = '.send-button'; | |
| 130 | + $whitelist[] = '.pre-chat-message'; | |
| 131 | + $whitelist[] = '.mxchat-popular-questions'; | |
| 132 | + $whitelist[] = '.chat-toolbar'; | |
| 133 | + $whitelist[] = '.exit-chat'; | |
| 134 | + $whitelist[] = '.email-blocker'; | |
| 135 | + return $whitelist; | |
| 136 | +}); | |
| 137 | + | |
| 138 | +// Exclude CSS from CCSS (Critical CSS) generation | |
| 139 | +add_filter('litespeed_optm_ccss_exc', function($excluded) { | |
| 140 | + if (!is_array($excluded)) $excluded = array(); | |
| 141 | + $excluded[] = 'chat-style.css'; | |
| 142 | + $excluded[] = 'mxchat'; | |
| 143 | + return $excluded; | |
| 144 | +}); | |
| 145 | + | |
| 146 | +// Exclude JS from defer | |
| 147 | +add_filter('litespeed_optm_js_defer_exc', function($excluded) { | |
| 148 | + if (!is_array($excluded)) $excluded = array(); | |
| 149 | + $excluded[] = 'chat-script.js'; | |
| 150 | + $excluded[] = 'floating-script.js'; | |
| 151 | + $excluded[] = 'mxchat'; | |
| 152 | + $excluded[] = 'jquery.min.js'; | |
| 153 | + $excluded[] = 'jquery.js'; | |
| 154 | + return $excluded; | |
| 155 | +}); | |
| 156 | + | |
| 157 | +// Exclude JS from combining | |
| 158 | +add_filter('litespeed_optm_js_exc', function($excluded) { | |
| 159 | + if (!is_array($excluded)) $excluded = array(); | |
| 160 | + $excluded[] = 'chat-script.js'; | |
| 161 | + $excluded[] = 'floating-script.js'; | |
| 162 | + $excluded[] = 'mxchat'; | |
| 163 | + $excluded[] = 'jquery.min.js'; | |
| 164 | + $excluded[] = 'jquery.js'; | |
| 165 | + return $excluded; | |
| 166 | +}); | |
| 167 | + | |
| 168 | +// Exclude JS from delayed execution | |
| 169 | +add_filter('litespeed_optm_js_delay_exc', function($excluded) { | |
| 170 | + if (!is_array($excluded)) $excluded = array(); | |
| 171 | + $excluded[] = 'chat-script.js'; | |
| 172 | + $excluded[] = 'floating-script.js'; | |
| 173 | + $excluded[] = 'mxchat'; | |
| 174 | + return $excluded; | |
| 175 | +}); | |
| 176 | + | |
| 177 | +// Exclude from Guest Mode optimization | |
| 178 | +add_filter('litespeed_guest_optm_exc', function($excluded) { | |
| 179 | + if (!is_array($excluded)) $excluded = array(); | |
| 180 | + $excluded[] = 'mxchat'; | |
| 181 | + $excluded[] = 'chat-style'; | |
| 182 | + $excluded[] = 'chat-script'; | |
| 183 | + $excluded[] = 'floating-script'; | |
| 184 | + return $excluded; | |
| 185 | +}); | |
| 186 | + | |
| 187 | +// ── Autoptimize ────────────────────────────────────────────────────────────── | |
| 188 | + | |
| 189 | +// Exclude CSS from optimization (comma-separated strings) | |
| 190 | +add_filter('autoptimize_filter_css_exclude', function($excluded) { | |
| 191 | + if (!is_string($excluded)) $excluded = ''; | |
| 192 | + return $excluded . ', mxchat, chat-style.css'; | |
| 193 | +}); | |
| 194 | + | |
| 195 | +// Exclude JS from optimization (comma-separated strings) | |
| 196 | +add_filter('autoptimize_filter_js_exclude', function($excluded) { | |
| 197 | + if (!is_string($excluded)) $excluded = ''; | |
| 198 | + return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js'; | |
| 199 | +}); | |
| 200 | + | |
| 201 | +// ── SG Optimizer (SiteGround) ──────────────────────────────────────────────── | |
| 202 | + | |
| 203 | +add_filter('sgo_js_minify_exclude', function($excluded) { | |
| 204 | + if (!is_array($excluded)) $excluded = array(); | |
| 205 | + $excluded[] = 'chat-script.js'; | |
| 206 | + $excluded[] = 'floating-script.js'; | |
| 207 | + $excluded[] = 'jquery.min.js'; | |
| 208 | + return $excluded; | |
| 209 | +}); | |
| 210 | + | |
| 211 | +add_filter('sgo_javascript_combine_exclude', function($excluded) { | |
| 212 | + if (!is_array($excluded)) $excluded = array(); | |
| 213 | + $excluded[] = 'chat-script.js'; | |
| 214 | + $excluded[] = 'floating-script.js'; | |
| 215 | + $excluded[] = 'jquery.min.js'; | |
| 216 | + return $excluded; | |
| 217 | +}); | |
| 218 | + | |
| 219 | +add_filter('sgo_js_async_exclude', function($excluded) { | |
| 220 | + if (!is_array($excluded)) $excluded = array(); | |
| 221 | + $excluded[] = 'chat-script.js'; | |
| 222 | + $excluded[] = 'floating-script.js'; | |
| 223 | + $excluded[] = 'jquery.min.js'; | |
| 224 | + return $excluded; | |
| 225 | +}); | |
| 226 | + | |
| 227 | +// ── W3 Total Cache ─────────────────────────────────────────────────────────── | |
| 228 | + | |
| 229 | +add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) { | |
| 230 | + if (strpos($file, 'chat-script.js') !== false || | |
| 231 | + strpos($file, 'floating-script.js') !== false || | |
| 232 | + strpos($file, 'jquery.min.js') !== false || | |
| 233 | + strpos($file, 'jquery.js') !== false) { | |
| 234 | + return false; | |
| 235 | + } | |
| 236 | + return $do_minify; | |
| 237 | +}, 10, 3); | |
| 238 | + | |
| 239 | +// ── WP Super Cache ────────────────────────────────────────────────────────── | |
| 240 | + | |
| 241 | +add_filter('wpsc_rejected_uri', function($rejected) { | |
| 242 | + if (!is_array($rejected)) $rejected = array(); | |
| 243 | + $rejected[] = 'wp-admin/admin-ajax.php'; | |
| 244 | + return $rejected; | |
| 245 | +}); | |
| 246 | + | |
| 247 | +// Include classes with error handling | |
| 248 | +function mxchat_include_classes() { | |
| 249 | + $class_files = array( | |
| 250 | + 'includes/class-mxchat-integrator.php', | |
| 251 | + 'includes/class-mxchat-admin.php', | |
| 252 | + 'includes/class-mxchat-public.php', | |
| 253 | + 'includes/class-mxchat-utils.php', | |
| 254 | + 'includes/class-mxchat-user.php', | |
| 255 | + 'includes/class-mxchat-meta-box.php', | |
| 256 | + 'includes/class-mxchat-chunker.php', | |
| 257 | + 'includes/class-mxchat-word-handler.php', | |
| 258 | + 'includes/class-mxchat-content-generator.php', | |
| 259 | + 'admin/class-ajax-handler.php', | |
| 260 | + 'admin/class-pinecone-manager.php', | |
| 261 | + 'admin/class-knowledge-manager.php' | |
| 262 | + ); | |
| 263 | + | |
| 264 | + foreach ($class_files as $file) { | |
| 265 | + $file_path = plugin_dir_path(__FILE__) . $file; | |
| 266 | + if (file_exists($file_path)) { | |
| 267 | + require_once $file_path; | |
| 268 | + } else { | |
| 269 | + //error_log('MxChat: Missing class file - ' . $file); | |
| 270 | + } | |
| 271 | + } | |
| 272 | +} | |
| 273 | + | |
| 274 | +/** | |
| 275 | + * Lazy-load the PDF parser library only when needed. | |
| 276 | + * Avoids loading 44 files on every page request. | |
| 277 | + */ | |
| 278 | +function mxchat_load_pdf_parser() { | |
| 279 | + if (class_exists('\Smalot\PdfParser\Parser')) { | |
| 280 | + return true; | |
| 281 | + } | |
| 282 | + $autoload_path = plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php'; | |
| 283 | + if (file_exists($autoload_path)) { | |
| 284 | + require_once $autoload_path; | |
| 285 | + return true; | |
| 286 | + } | |
| 287 | + return false; | |
| 288 | +} | |
| 289 | + | |
| 290 | +/** | |
| 291 | + * Create URL click tracking table | |
| 292 | + */ | |
| 293 | +function mxchat_create_url_clicks_table() { | |
| 294 | + global $wpdb; | |
| 295 | + | |
| 296 | + $table_name = $wpdb->prefix . 'mxchat_url_clicks'; | |
| 297 | + | |
| 298 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 299 | + | |
| 300 | + $sql = "CREATE TABLE $table_name ( | |
| 301 | + id mediumint(9) NOT NULL AUTO_INCREMENT, | |
| 302 | + session_id varchar(100) NOT NULL, | |
| 303 | + clicked_url text NOT NULL, | |
| 304 | + message_context text, | |
| 305 | + click_timestamp datetime DEFAULT CURRENT_TIMESTAMP, | |
| 306 | + user_ip varchar(45), | |
| 307 | + user_agent text, | |
| 308 | + PRIMARY KEY (id), | |
| 309 | + KEY session_id (session_id), | |
| 310 | + KEY click_timestamp (click_timestamp) | |
| 311 | + ) $charset_collate;"; | |
| 312 | + | |
| 313 | + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 314 | + dbDelta($sql); | |
| 315 | +} | |
| 316 | + | |
| 317 | +/** | |
| 318 | + * FIXED: Robust table creation and column management | |
| 319 | + */ | |
| 320 | +function mxchat_create_chat_transcripts_table() { | |
| 321 | + global $wpdb; | |
| 322 | + | |
| 323 | + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 324 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 325 | + | |
| 326 | + // Create table with ALL columns including user_name from the start | |
| 327 | + $sql = "CREATE TABLE $table_name ( | |
| 328 | + id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, | |
| 329 | + user_id MEDIUMINT(9) DEFAULT 0, | |
| 330 | + session_id VARCHAR(255) NOT NULL, | |
| 331 | + role VARCHAR(255) NOT NULL, | |
| 332 | + message TEXT NOT NULL, | |
| 333 | + user_email VARCHAR(255) DEFAULT NULL, | |
| 334 | + user_name VARCHAR(100) DEFAULT NULL, | |
| 335 | + user_identifier VARCHAR(255) DEFAULT NULL, | |
| 336 | + originating_page_url TEXT DEFAULT NULL, | |
| 337 | + originating_page_title VARCHAR(500) DEFAULT NULL, | |
| 338 | + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, | |
| 339 | + PRIMARY KEY (id), | |
| 340 | + KEY session_id (session_id), | |
| 341 | + KEY user_email (user_email), | |
| 342 | + KEY timestamp (timestamp) | |
| 343 | + ) $charset_collate;"; | |
| 344 | + | |
| 345 | + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 346 | + $result = dbDelta($sql); | |
| 347 | + | |
| 348 | + // Log the result for debugging | |
| 349 | + if (empty($result)) { | |
| 350 | + //error_log("MxChat: dbDelta returned empty result for chat transcripts table"); | |
| 351 | + } else { | |
| 352 | + //error_log("MxChat: dbDelta result: " . print_r($result, true)); | |
| 353 | + } | |
| 354 | + | |
| 355 | + // IMPORTANT: Ensure all columns exist for existing installations | |
| 356 | + mxchat_ensure_all_columns($table_name); | |
| 357 | +} | |
| 358 | + | |
| 359 | +/** | |
| 360 | + * Ensure all required columns exist (for upgrades) | |
| 361 | + */ | |
| 362 | +function mxchat_ensure_all_columns($table_name) { | |
| 363 | + global $wpdb; | |
| 364 | + | |
| 365 | + // First check if table exists | |
| 366 | + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 367 | + if (!$table_exists) { | |
| 368 | + //error_log("MxChat: Table $table_name does not exist, cannot add columns"); | |
| 369 | + return; | |
| 370 | + } | |
| 371 | + | |
| 372 | + // Define all required columns and their types | |
| 373 | + $required_columns = [ | |
| 374 | + 'user_identifier' => 'VARCHAR(255) DEFAULT NULL', | |
| 375 | + 'user_email' => 'VARCHAR(255) DEFAULT NULL', | |
| 376 | + 'user_name' => 'VARCHAR(100) DEFAULT NULL', | |
| 377 | + 'originating_page_url' => 'TEXT DEFAULT NULL', | |
| 378 | + 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL', | |
| 379 | + 'rag_context' => 'LONGTEXT DEFAULT NULL' | |
| 380 | + ]; | |
| 381 | + | |
| 382 | + // Get existing columns | |
| 383 | + $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name"); | |
| 384 | + if (empty($existing_columns)) { | |
| 385 | + //error_log("MxChat: Could not get columns for table $table_name"); | |
| 386 | + return; | |
| 387 | + } | |
| 388 | + | |
| 389 | + $existing_column_names = array_column($existing_columns, 'Field'); | |
| 390 | + | |
| 391 | + // Add missing columns | |
| 392 | + foreach ($required_columns as $column_name => $column_definition) { | |
| 393 | + if (!in_array($column_name, $existing_column_names)) { | |
| 394 | + $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition"; | |
| 395 | + $result = $wpdb->query($alter_sql); | |
| 396 | + | |
| 397 | + if ($result === false) { | |
| 398 | + //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error); | |
| 399 | + } else { | |
| 400 | + //error_log("MxChat: Successfully added column $column_name to $table_name"); | |
| 401 | + } | |
| 402 | + } | |
| 403 | + } | |
| 404 | +} | |
| 405 | + | |
| 406 | +/** | |
| 407 | + * Add role restriction column to knowledge base table | |
| 408 | + */ | |
| 409 | +function mxchat_add_role_restriction_column() { | |
| 410 | + global $wpdb; | |
| 411 | + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 412 | + | |
| 413 | + // Check if table exists first | |
| 414 | + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 415 | + if (!$table_exists) { | |
| 416 | + //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column"); | |
| 417 | + return; | |
| 418 | + } | |
| 419 | + | |
| 420 | + // Check if column already exists | |
| 421 | + $column_exists = $wpdb->get_results( | |
| 422 | + $wpdb->prepare( | |
| 423 | + "SHOW COLUMNS FROM {$table_name} LIKE %s", | |
| 424 | + 'role_restriction' | |
| 425 | + ) | |
| 426 | + ); | |
| 427 | + | |
| 428 | + if (empty($column_exists)) { | |
| 429 | + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url"; | |
| 430 | + $result = $wpdb->query($alter_sql); | |
| 431 | + | |
| 432 | + if ($result === false) { | |
| 433 | + //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error); | |
| 434 | + } else { | |
| 435 | + //error_log("MxChat: Successfully added role_restriction column"); | |
| 436 | + | |
| 437 | + // Set all existing records to 'public' (everyone can access) | |
| 438 | + $update_result = $wpdb->query( | |
| 439 | + "UPDATE {$table_name} | |
| 440 | + SET role_restriction = 'public' | |
| 441 | + WHERE role_restriction IS NULL OR role_restriction = ''" | |
| 442 | + ); | |
| 443 | + | |
| 444 | + if ($update_result !== false) { | |
| 445 | + //error_log("MxChat: Updated {$update_result} existing records to public access"); | |
| 446 | + } | |
| 447 | + } | |
| 448 | + } | |
| 449 | +} | |
| 450 | + | |
| 451 | +/** | |
| 452 | + * Add enabled_bots column to intents table for multi-bot action filtering | |
| 453 | + */ | |
| 454 | +function mxchat_add_enabled_bots_column() { | |
| 455 | + global $wpdb; | |
| 456 | + $table_name = $wpdb->prefix . 'mxchat_intents'; | |
| 457 | + | |
| 458 | + // Check if table exists first | |
| 459 | + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 460 | + if (!$table_exists) { | |
| 461 | + //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column"); | |
| 462 | + return; | |
| 463 | + } | |
| 464 | + | |
| 465 | + // Check if column already exists | |
| 466 | + $column_exists = $wpdb->get_results( | |
| 467 | + $wpdb->prepare( | |
| 468 | + "SHOW COLUMNS FROM {$table_name} LIKE %s", | |
| 469 | + 'enabled_bots' | |
| 470 | + ) | |
| 471 | + ); | |
| 472 | + | |
| 473 | + if (empty($column_exists)) { | |
| 474 | + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled"; | |
| 475 | + $result = $wpdb->query($alter_sql); | |
| 476 | + | |
| 477 | + if ($result === false) { | |
| 478 | + //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error); | |
| 479 | + } else { | |
| 480 | + //error_log("MxChat: Successfully added enabled_bots column"); | |
| 481 | + | |
| 482 | + // Set all existing actions to work with 'default' bot for backward compatibility | |
| 483 | + $default_bots = json_encode(['default']); | |
| 484 | + $update_result = $wpdb->query( | |
| 485 | + $wpdb->prepare( | |
| 486 | + "UPDATE {$table_name} | |
| 487 | + SET enabled_bots = %s | |
| 488 | + WHERE enabled_bots IS NULL OR enabled_bots = ''", | |
| 489 | + $default_bots | |
| 490 | + ) | |
| 491 | + ); | |
| 492 | + | |
| 493 | + if ($update_result !== false) { | |
| 494 | + //error_log("MxChat: Updated {$update_result} existing actions to work with default bot"); | |
| 495 | + } | |
| 496 | + } | |
| 497 | + } | |
| 498 | +} | |
| 499 | + | |
| 500 | +/** | |
| 501 | + * Create Pinecone role restrictions table with multi-bot support | |
| 502 | + */ | |
| 503 | +function mxchat_create_pinecone_roles_table() { | |
| 504 | + global $wpdb; | |
| 505 | + | |
| 506 | + $table_name = $wpdb->prefix . 'mxchat_pinecone_roles'; | |
| 507 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 508 | + | |
| 509 | + $sql = "CREATE TABLE $table_name ( | |
| 510 | + id mediumint(9) NOT NULL AUTO_INCREMENT, | |
| 511 | + vector_id varchar(255) NOT NULL, | |
| 512 | + bot_id varchar(50) NOT NULL DEFAULT 'default', | |
| 513 | + source_url text, | |
| 514 | + role_restriction varchar(50) DEFAULT 'public', | |
| 515 | + updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, | |
| 516 | + PRIMARY KEY (id), | |
| 517 | + UNIQUE KEY vector_bot (vector_id, bot_id), | |
| 518 | + KEY role_restriction (role_restriction), | |
| 519 | + KEY bot_id (bot_id) | |
| 520 | + ) $charset_collate;"; | |
| 521 | + | |
| 522 | + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 523 | + dbDelta($sql); | |
| 524 | +} | |
| 525 | + | |
| 526 | +/** | |
| 527 | + * Add bot_id column to mxchat_pinecone_roles table for multi-bot support | |
| 528 | + * This migration runs once to update existing installations | |
| 529 | + */ | |
| 530 | +function mxchat_migrate_pinecone_roles_add_bot_id() { | |
| 531 | + global $wpdb; | |
| 532 | + | |
| 533 | + // Check if migration already ran | |
| 534 | + $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0'); | |
| 535 | + if (version_compare($migration_version, '2.5.2', '>=')) { | |
| 536 | + return; // Already migrated | |
| 537 | + } | |
| 538 | + | |
| 539 | + $table_name = $wpdb->prefix . 'mxchat_pinecone_roles'; | |
| 540 | + | |
| 541 | + // Check if table exists | |
| 542 | + if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) { | |
| 543 | + return; // Table doesn't exist yet | |
| 544 | + } | |
| 545 | + | |
| 546 | + // Check if bot_id column already exists | |
| 547 | + $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'"); | |
| 548 | + | |
| 549 | + if (empty($column_exists)) { | |
| 550 | + // Add bot_id column | |
| 551 | + $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id"); | |
| 552 | + | |
| 553 | + // Update the unique key to include bot_id | |
| 554 | + $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id"); | |
| 555 | + $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)"); | |
| 556 | + | |
| 557 | + // Add index for bot_id | |
| 558 | + $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)"); | |
| 559 | + | |
| 560 | + error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table'); | |
| 561 | + } | |
| 562 | + | |
| 563 | + // Mark migration as complete | |
| 564 | + update_option('mxchat_pinecone_roles_migration_version', '2.5.2'); | |
| 565 | +} | |
| 566 | + | |
| 567 | +/** | |
| 568 | + * 2.5.6: Add content_type column to mxchat_system_prompt_content table | |
| 569 | + * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.) | |
| 570 | + */ | |
| 571 | +function mxchat_migrate_add_content_type_column() { | |
| 572 | + global $wpdb; | |
| 573 | + | |
| 574 | + // Check if migration already ran | |
| 575 | + $migration_version = get_option('mxchat_content_type_migration_version', '0'); | |
| 576 | + if (version_compare($migration_version, '2.5.6', '>=')) { | |
| 577 | + return; | |
| 578 | + } | |
| 579 | + | |
| 580 | + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 581 | + | |
| 582 | + // Check if table exists | |
| 583 | + if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) { | |
| 584 | + return; | |
| 585 | + } | |
| 586 | + | |
| 587 | + // Check if content_type column already exists | |
| 588 | + $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'"); | |
| 589 | + | |
| 590 | + if (empty($column_exists)) { | |
| 591 | + // Add content_type column with default value 'content' for backwards compatibility | |
| 592 | + $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction"); | |
| 593 | + | |
| 594 | + // Add index for better query performance | |
| 595 | + $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)"); | |
| 596 | + | |
| 597 | + error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table'); | |
| 598 | + } | |
| 599 | + | |
| 600 | + // Mark migration as complete | |
| 601 | + update_option('mxchat_content_type_migration_version', '2.5.6'); | |
| 602 | +} | |
| 603 | + | |
| 604 | +/** | |
| 605 | + * 2.5.2: Create queue processing tables for reliable background processing | |
| 606 | + */ | |
| 607 | +function mxchat_create_queue_tables() { | |
| 608 | + global $wpdb; | |
| 609 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 610 | + | |
| 611 | + // Main queue table | |
| 612 | + $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 613 | + $sql_queue = "CREATE TABLE $queue_table ( | |
| 614 | + id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 615 | + queue_id varchar(64) NOT NULL, | |
| 616 | + item_type varchar(20) NOT NULL, | |
| 617 | + item_data longtext NOT NULL, | |
| 618 | + status varchar(20) NOT NULL DEFAULT 'pending', | |
| 619 | + bot_id varchar(50) NOT NULL DEFAULT 'default', | |
| 620 | + priority int(11) NOT NULL DEFAULT 0, | |
| 621 | + attempts int(11) NOT NULL DEFAULT 0, | |
| 622 | + max_attempts int(11) NOT NULL DEFAULT 3, | |
| 623 | + error_message text DEFAULT NULL, | |
| 624 | + created_at datetime NOT NULL, | |
| 625 | + started_at datetime DEFAULT NULL, | |
| 626 | + completed_at datetime DEFAULT NULL, | |
| 627 | + PRIMARY KEY (id), | |
| 628 | + KEY queue_id (queue_id), | |
| 629 | + KEY status (status), | |
| 630 | + KEY item_type (item_type), | |
| 631 | + KEY priority (priority) | |
| 632 | + ) $charset_collate;"; | |
| 633 | + | |
| 634 | + // Queue metadata table | |
| 635 | + $meta_table = $wpdb->prefix . 'mxchat_queue_meta'; | |
| 636 | + $sql_meta = "CREATE TABLE $meta_table ( | |
| 637 | + id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 638 | + queue_id varchar(64) NOT NULL, | |
| 639 | + meta_key varchar(255) NOT NULL, | |
| 640 | + meta_value longtext, | |
| 641 | + PRIMARY KEY (id), | |
| 642 | + KEY queue_id (queue_id), | |
| 643 | + KEY meta_key (meta_key) | |
| 644 | + ) $charset_collate;"; | |
| 645 | + | |
| 646 | + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 647 | + dbDelta($sql_queue); | |
| 648 | + dbDelta($sql_meta); | |
| 649 | + | |
| 650 | + //error_log("MxChat: Queue tables created/updated successfully"); | |
| 651 | +} | |
| 652 | + | |
| 653 | +/** | |
| 654 | + * Create transcript translations table for persisting translations | |
| 655 | + */ | |
| 656 | +function mxchat_create_translations_table() { | |
| 657 | + global $wpdb; | |
| 658 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 659 | + | |
| 660 | + $table_name = $wpdb->prefix . 'mxchat_transcript_translations'; | |
| 661 | + $sql = "CREATE TABLE $table_name ( | |
| 662 | + id bigint(20) unsigned NOT NULL AUTO_INCREMENT, | |
| 663 | + session_id varchar(255) NOT NULL, | |
| 664 | + language_code varchar(10) NOT NULL, | |
| 665 | + translations longtext NOT NULL, | |
| 666 | + created_at datetime NOT NULL, | |
| 667 | + updated_at datetime NOT NULL, | |
| 668 | + PRIMARY KEY (id), | |
| 669 | + UNIQUE KEY session_lang (session_id, language_code), | |
| 670 | + KEY session_id (session_id) | |
| 671 | + ) $charset_collate;"; | |
| 672 | + | |
| 673 | + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
| 674 | + dbDelta($sql); | |
| 675 | +} | |
| 676 | + | |
| 677 | +/** | |
| 678 | + * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding) | |
| 679 | + * This fixes "url, source_url. The supplied values may be too long" errors | |
| 680 | + */ | |
| 681 | +function mxchat_fix_url_column_size() { | |
| 682 | + global $wpdb; | |
| 683 | + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 684 | + | |
| 685 | + // Check if table exists | |
| 686 | + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 687 | + if (!$table_exists) { | |
| 688 | + return; | |
| 689 | + } | |
| 690 | + | |
| 691 | + // Change url and source_url from VARCHAR to TEXT to handle long URLs | |
| 692 | + // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.) | |
| 693 | + $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT"); | |
| 694 | + $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT"); | |
| 695 | + | |
| 696 | + //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support"); | |
| 697 | +} | |
| 698 | + | |
| 699 | +/** | |
| 700 | + * Migrate deprecated AI models to their replacements | |
| 701 | + * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet | |
| 702 | + * Version 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support | |
| 703 | + * Without utf8mb4, any bot response containing emojis silently fails to insert. | |
| 704 | + */ | |
| 705 | +function mxchat_migrate_transcripts_charset() { | |
| 706 | + global $wpdb; | |
| 707 | + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 708 | + $wpdb->query("ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); | |
| 709 | +} | |
| 710 | + | |
| 711 | +/** | |
| 712 | + * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series | |
| 713 | + */ | |
| 714 | +function mxchat_migrate_deprecated_models() { | |
| 715 | + $options = get_option('mxchat_options', array()); | |
| 716 | + $migrated = false; | |
| 717 | + $migration_message = ''; | |
| 718 | + | |
| 719 | + if (!isset($options['model'])) { | |
| 720 | + return; | |
| 721 | + } | |
| 722 | + | |
| 723 | + $current_model = $options['model']; | |
| 724 | + | |
| 725 | + // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic) | |
| 726 | + $deprecated_claude_models = array( | |
| 727 | + 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025 | |
| 728 | + 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025 | |
| 729 | + 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026 | |
| 730 | + 'claude-3-opus-20240229', // Retired Jan 5, 2026 | |
| 731 | + 'claude-3-sonnet-20240229', // Legacy | |
| 732 | + 'claude-3-haiku-20240307', // Legacy | |
| 733 | + ); | |
| 734 | + if (in_array($current_model, $deprecated_claude_models, true)) { | |
| 735 | + $options['model'] = 'claude-opus-4-6'; | |
| 736 | + $migrated = true; | |
| 737 | + $migration_message = sprintf( | |
| 738 | + __('Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.', 'mxchat'), | |
| 739 | + $current_model | |
| 740 | + ); | |
| 741 | + } | |
| 742 | + | |
| 743 | + // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5 | |
| 744 | + if ($current_model === 'claude-3-5-haiku-20241022') { | |
| 745 | + $options['model'] = 'claude-haiku-4-5-20251001'; | |
| 746 | + $migrated = true; | |
| 747 | + $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.', 'mxchat'); | |
| 748 | + } | |
| 749 | + | |
| 750 | + // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest | |
| 751 | + if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) { | |
| 752 | + $options['model'] = 'gpt-5.1-chat-latest'; | |
| 753 | + $migrated = true; | |
| 754 | + $migration_message = sprintf( | |
| 755 | + __('Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.', 'mxchat'), | |
| 756 | + $current_model | |
| 757 | + ); | |
| 758 | + } | |
| 759 | + | |
| 760 | + // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini | |
| 761 | + if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) { | |
| 762 | + $options['model'] = 'gpt-5-mini'; | |
| 763 | + $migrated = true; | |
| 764 | + $migration_message = sprintf( | |
| 765 | + __('Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.', 'mxchat'), | |
| 766 | + $current_model | |
| 767 | + ); | |
| 768 | + } | |
| 769 | + | |
| 770 | + if ($migrated) { | |
| 771 | + update_option('mxchat_options', $options); | |
| 772 | + update_option('mxchat_model_migrated_notice', true); | |
| 773 | + update_option('mxchat_model_migration_message', $migration_message); | |
| 774 | + } | |
| 775 | +} | |
| 776 | + | |
| 777 | +/** | |
| 778 | + * Show admin notice after model migration | |
| 779 | + */ | |
| 780 | +function mxchat_show_migration_notice() { | |
| 781 | + if (get_option('mxchat_model_migrated_notice')) { | |
| 782 | + $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat')); | |
| 783 | + ?> | |
| 784 | + <div class="notice notice-info is-dismissible"> | |
| 785 | + <p> | |
| 786 | + <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br> | |
| 787 | + <?php echo esc_html($migration_message); ?> | |
| 788 | + </p> | |
| 789 | + </div> | |
| 790 | + <?php | |
| 791 | + delete_option('mxchat_model_migrated_notice'); | |
| 792 | + delete_option('mxchat_model_migration_message'); | |
| 793 | + } | |
| 794 | +} | |
| 795 | + | |
| 796 | +function mxchat_activate() { | |
| 797 | + global $wpdb; | |
| 798 | + $charset_collate = $wpdb->get_charset_collate(); | |
| 799 | + | |
| 800 | + //error_log("MxChat: Running activation function"); | |
| 801 | + | |
| 802 | + // Create chat transcripts table with improved function | |
| 803 | + mxchat_create_chat_transcripts_table(); | |
| 804 | + | |
| 805 | + // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns | |
| 806 | + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content'; | |
| 807 | + $sql_system_prompt = "CREATE TABLE $system_prompt_table ( | |
| 808 | + id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, | |
| 809 | + url TEXT NOT NULL, | |
| 810 | + article_content LONGTEXT NOT NULL, | |
| 811 | + embedding_vector LONGTEXT, | |
| 812 | + source_url TEXT DEFAULT NULL, | |
| 813 | + role_restriction VARCHAR(50) DEFAULT 'public', | |
| 814 | + content_type VARCHAR(50) DEFAULT 'content', | |
| 815 | + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, | |
| 816 | + PRIMARY KEY (id), | |
| 817 | + KEY content_type (content_type) | |
| 818 | + ) $charset_collate;"; | |
| 819 | + | |
| 820 | + // Intents Table - NOW INCLUDES enabled_bots column from the start | |
| 821 | + $intents_table = $wpdb->prefix . 'mxchat_intents'; | |
| 822 | + $sql_intents_table = "CREATE TABLE $intents_table ( | |
| 823 | + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, | |
| 824 | + intent_label VARCHAR(255) NOT NULL, | |
| 825 | + phrases TEXT NOT NULL, | |
| 826 | + embedding_vector LONGTEXT NOT NULL, | |
| 827 | + callback_function VARCHAR(255) NOT NULL, | |
| 828 | + similarity_threshold FLOAT DEFAULT 0.85, | |
| 829 | + enabled TINYINT(1) NOT NULL DEFAULT 1, | |
| 830 | + enabled_bots LONGTEXT DEFAULT NULL, | |
| 831 | + PRIMARY KEY (id) | |
| 832 | + ) $charset_collate;"; | |
| 833 | + | |
| 834 | + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; | |
| 835 | + | |
| 836 | + // Create other tables | |
| 837 | + dbDelta($sql_system_prompt); | |
| 838 | + dbDelta($sql_intents_table); | |
| 839 | + | |
| 840 | + // Create URL click tracking table | |
| 841 | + mxchat_create_url_clicks_table(); | |
| 842 | + | |
| 843 | + // Create Pinecone roles table | |
| 844 | + mxchat_create_pinecone_roles_table(); | |
| 845 | + | |
| 846 | + // NEW 2.5.2: Create queue processing tables | |
| 847 | + mxchat_create_queue_tables(); | |
| 848 | + | |
| 849 | + // Create transcript translations table | |
| 850 | + mxchat_create_translations_table(); | |
| 851 | + | |
| 852 | + // Ensure additional columns in system prompt table | |
| 853 | + $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table"); | |
| 854 | + if (!empty($existing_system_columns)) { | |
| 855 | + $existing_system_column_names = array_column($existing_system_columns, 'Field'); | |
| 856 | + | |
| 857 | + if (!in_array('embedding_vector', $existing_system_column_names)) { | |
| 858 | + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT"); | |
| 859 | + } | |
| 860 | + if (!in_array('source_url', $existing_system_column_names)) { | |
| 861 | + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL"); | |
| 862 | + } | |
| 863 | + if (!in_array('role_restriction', $existing_system_column_names)) { | |
| 864 | + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url"); | |
| 865 | + } | |
| 866 | + } | |
| 867 | + | |
| 868 | + // Set default thresholds for existing intents | |
| 869 | + $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL"); | |
| 870 | + | |
| 871 | + // Ensure enabled column exists in intents table | |
| 872 | + $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table"); | |
| 873 | + if (!empty($existing_intent_columns)) { | |
| 874 | + $existing_intent_column_names = array_column($existing_intent_columns, 'Field'); | |
| 875 | + | |
| 876 | + if (!in_array('enabled', $existing_intent_column_names)) { | |
| 877 | + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1"); | |
| 878 | + } | |
| 879 | + | |
| 880 | + // Ensure enabled_bots column exists for existing installations | |
| 881 | + if (!in_array('enabled_bots', $existing_intent_column_names)) { | |
| 882 | + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled"); | |
| 883 | + | |
| 884 | + // Set existing actions to work with default bot | |
| 885 | + $default_bots = json_encode(['default']); | |
| 886 | + $wpdb->query($wpdb->prepare( | |
| 887 | + "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL", | |
| 888 | + $default_bots | |
| 889 | + )); | |
| 890 | + } | |
| 891 | + } | |
| 892 | + | |
| 893 | + // Run migration for existing installations | |
| 894 | + mxchat_migrate_pinecone_roles_add_bot_id(); | |
| 895 | + | |
| 896 | + // Setup cron jobs | |
| 897 | + mxchat_setup_cron_jobs(); | |
| 898 | + | |
| 899 | + // Update version | |
| 900 | + update_option('mxchat_plugin_version', MXCHAT_VERSION); | |
| 901 | + | |
| 902 | + //error_log("MxChat: Activation function completed"); | |
| 903 | +} | |
| 904 | + | |
| 905 | +/** | |
| 906 | + * Setup cron jobs on plugin activation | |
| 907 | + */ | |
| 908 | +function mxchat_setup_cron_jobs() { | |
| 909 | + // Clear any existing cron jobs first | |
| 910 | + wp_clear_scheduled_hook('mxchat_reset_rate_limits'); | |
| 911 | + | |
| 912 | + // Check if WordPress cron is disabled | |
| 913 | + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { | |
| 914 | + // Set flag to use fallback system | |
| 915 | + update_option('mxchat_use_fallback_rate_limits', true); | |
| 916 | + update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 917 | + return; | |
| 918 | + } | |
| 919 | + | |
| 920 | + // Schedule the rate limit reset cron job | |
| 921 | + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits'); | |
| 922 | + | |
| 923 | + if ($result === false) { | |
| 924 | + // Fallback if scheduling fails | |
| 925 | + update_option('mxchat_use_fallback_rate_limits', true); | |
| 926 | + update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 927 | + } else { | |
| 928 | + // Clear fallback flags if cron scheduling succeeded | |
| 929 | + delete_option('mxchat_use_fallback_rate_limits'); | |
| 930 | + } | |
| 931 | + | |
| 932 | + // Schedule transcript cleanup if configured | |
| 933 | + $transcript_options = get_option('mxchat_transcripts_options', array()); | |
| 934 | + $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never'; | |
| 935 | + | |
| 936 | + if ($cleanup_interval !== 'never') { | |
| 937 | + // Check if not already scheduled | |
| 938 | + if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) { | |
| 939 | + // Schedule to run daily at 3 AM | |
| 940 | + $next_run = strtotime('tomorrow 3:00 AM'); | |
| 941 | + wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts'); | |
| 942 | + } | |
| 943 | + } | |
| 944 | +} | |
| 945 | + | |
| 946 | +/** | |
| 947 | + * Clean up on plugin deactivation | |
| 948 | + */ | |
| 949 | +function mxchat_deactivate() { | |
| 950 | + // Clear scheduled cron jobs | |
| 951 | + wp_clear_scheduled_hook('mxchat_reset_rate_limits'); | |
| 952 | + wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts'); | |
| 953 | + wp_clear_scheduled_hook('mxchat_send_delayed_transcript'); | |
| 954 | + | |
| 955 | + // Clear fallback options | |
| 956 | + delete_option('mxchat_use_fallback_rate_limits'); | |
| 957 | + delete_option('mxchat_next_rate_limit_check'); | |
| 958 | + delete_option('mxchat_fallback_check_interval'); | |
| 959 | + | |
| 960 | + // NOTE: We do NOT delete queue tables on deactivation | |
| 961 | + // This preserves data if user accidentally deactivates the plugin | |
| 962 | +} | |
| 963 | + | |
| 964 | +/** | |
| 965 | + * Check if fallback rate limit cleanup is needed | |
| 966 | + */ | |
| 967 | +function mxchat_check_fallback_rate_limits() { | |
| 968 | + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false); | |
| 969 | + | |
| 970 | + if (!$use_fallback) { | |
| 971 | + return; | |
| 972 | + } | |
| 973 | + | |
| 974 | + $next_check = get_option('mxchat_next_rate_limit_check', 0); | |
| 975 | + | |
| 976 | + if (time() >= $next_check) { | |
| 977 | + // Only run reset if the MxChat_Integrator class exists | |
| 978 | + if (class_exists('MxChat_Integrator')) { | |
| 979 | + $integrator = new MxChat_Integrator(); | |
| 980 | + if (method_exists($integrator, 'mxchat_reset_rate_limits')) { | |
| 981 | + $integrator->mxchat_reset_rate_limits(); | |
| 982 | + update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 983 | + } | |
| 984 | + } | |
| 985 | + } | |
| 986 | +} | |
| 987 | + | |
| 988 | +/** | |
| 989 | + * Robust update checking with role restriction migration, model deprecation, and queue tables | |
| 990 | + * CRITICAL: This runs on EVERY page load to ensure tables exist | |
| 991 | + */ | |
| 992 | +function mxchat_check_for_update() { | |
| 993 | + global $wpdb; | |
| 994 | + | |
| 995 | + try { | |
| 996 | + $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 997 | + $plugin_version = MXCHAT_VERSION; | |
| 998 | + | |
| 999 | + // Always ensure critical tables exist (even if version matches) | |
| 1000 | + // This handles manual table deletion or fresh installs | |
| 1001 | + $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1002 | + $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 1003 | + | |
| 1004 | + $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table; | |
| 1005 | + $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; | |
| 1006 | + | |
| 1007 | + if (!$chat_exists || !$queue_exists) { | |
| 1008 | + //error_log("MxChat: Critical tables missing, running activation"); | |
| 1009 | + mxchat_activate(); | |
| 1010 | + } | |
| 1011 | + | |
| 1012 | + // Version-specific migrations | |
| 1013 | + if ($current_version !== $plugin_version) { | |
| 1014 | + //error_log("MxChat: Version change detected: $current_version -> $plugin_version"); | |
| 1015 | + | |
| 1016 | + // Run live agent update BEFORE updating the stored version | |
| 1017 | + mxchat_handle_live_agent_update(); | |
| 1018 | + | |
| 1019 | + // Run theme migration notice for 3.0.1 (AI theme CSS structure changes) | |
| 1020 | + mxchat_handle_theme_migration_notice(); | |
| 1021 | + | |
| 1022 | + // Run role restriction migration for 2.4.1 | |
| 1023 | + if (version_compare($current_version, '2.4.1', '<')) { | |
| 1024 | + mxchat_add_role_restriction_column(); | |
| 1025 | + } | |
| 1026 | + | |
| 1027 | + // Run enabled_bots column migration for 2.4.4 | |
| 1028 | + if (version_compare($current_version, '2.4.4', '<')) { | |
| 1029 | + mxchat_add_enabled_bots_column(); | |
| 1030 | + } | |
| 1031 | + | |
| 1032 | + // Run model migration for 2.5.1 (Claude deprecation) | |
| 1033 | + if (version_compare($current_version, '2.5.1', '<')) { | |
| 1034 | + mxchat_migrate_deprecated_models(); | |
| 1035 | + } | |
| 1036 | + | |
| 1037 | + // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2 | |
| 1038 | + if (version_compare($current_version, '2.5.2', '<')) { | |
| 1039 | + mxchat_create_queue_tables(); | |
| 1040 | + mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs | |
| 1041 | + //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2"); | |
| 1042 | + } | |
| 1043 | + | |
| 1044 | + // 2.6.0: Ensure rag_context column exists for retrieved documents feature | |
| 1045 | + if (version_compare($current_version, '2.6.0', '<')) { | |
| 1046 | + $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1047 | + mxchat_ensure_all_columns($chat_table); | |
| 1048 | + //error_log("MxChat: rag_context column migration for 2.6.0"); | |
| 1049 | + } | |
| 1050 | + | |
| 1051 | + // 3.0.5: Migrate deprecated Gemini embedding model | |
| 1052 | + if (version_compare($current_version, '3.0.5', '<')) { | |
| 1053 | + mxchat_migrate_gemini_embedding_model(); | |
| 1054 | + } | |
| 1055 | + | |
| 1056 | + // 3.0.6: Migrate deprecated OpenAI and Claude models | |
| 1057 | + if (version_compare($current_version, '3.0.6', '<')) { | |
| 1058 | + mxchat_migrate_deprecated_models(); | |
| 1059 | + } | |
| 1060 | + | |
| 1061 | + // 3.1.2: Convert chat transcripts table to utf8mb4 for emoji support | |
| 1062 | + if (version_compare($current_version, '3.1.2', '<')) { | |
| 1063 | + mxchat_migrate_transcripts_charset(); | |
| 1064 | + } | |
| 1065 | + | |
| 1066 | + // Run full activation to ensure everything is up to date | |
| 1067 | + mxchat_activate(); | |
| 1068 | + | |
| 1069 | + // Run migration functions | |
| 1070 | + mxchat_migrate_live_agent_status(); | |
| 1071 | + | |
| 1072 | + // Add the cleanup function for version 2.1.8 | |
| 1073 | + if (version_compare($current_version, '2.1.8', '<')) { | |
| 1074 | + $deleted = mxchat_cleanup_orphaned_chat_history(); | |
| 1075 | + } | |
| 1076 | + | |
| 1077 | + // Update version LAST | |
| 1078 | + update_option('mxchat_plugin_version', $plugin_version); | |
| 1079 | + | |
| 1080 | + //error_log("MxChat: Updated from version $current_version to $plugin_version"); | |
| 1081 | + } | |
| 1082 | + | |
| 1083 | + } catch (Exception $e) { | |
| 1084 | + //error_log('MxChat update error: ' . $e->getMessage()); | |
| 1085 | + // Don't update version if there was an error | |
| 1086 | + } | |
| 1087 | +} | |
| 1088 | + | |
| 1089 | +/** | |
| 1090 | + * Ensure tables exist on every admin load for fresh installations | |
| 1091 | + * This is a safety net for cases where activation hook doesn't fire | |
| 1092 | + */ | |
| 1093 | +function mxchat_ensure_tables_exist() { | |
| 1094 | + global $wpdb; | |
| 1095 | + | |
| 1096 | + // Only run for admin users to avoid performance impact | |
| 1097 | + if (!current_user_can('administrator')) { | |
| 1098 | + return; | |
| 1099 | + } | |
| 1100 | + | |
| 1101 | + // Check if we've already verified tables in this session | |
| 1102 | + static $tables_checked = false; | |
| 1103 | + if ($tables_checked) { | |
| 1104 | + return; | |
| 1105 | + } | |
| 1106 | + $tables_checked = true; | |
| 1107 | + | |
| 1108 | + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1109 | + $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; | |
| 1110 | + | |
| 1111 | + $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; | |
| 1112 | + $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; | |
| 1113 | + | |
| 1114 | + if (!$chat_exists || !$queue_exists) { | |
| 1115 | + //error_log("MxChat: Tables missing on admin load, running activation"); | |
| 1116 | + mxchat_activate(); | |
| 1117 | + } | |
| 1118 | +} | |
| 1119 | + | |
| 1120 | +/** | |
| 1121 | + * Clean up orphaned chat history options from the wp_options table | |
| 1122 | + * @return int Number of options deleted | |
| 1123 | + */ | |
| 1124 | +function mxchat_cleanup_orphaned_chat_history() { | |
| 1125 | + global $wpdb; | |
| 1126 | + $count = 0; | |
| 1127 | + | |
| 1128 | + // Get all option keys that match our pattern | |
| 1129 | + $history_options = $wpdb->get_results( | |
| 1130 | + "SELECT option_name FROM {$wpdb->options} | |
| 1131 | + WHERE option_name LIKE 'mxchat_history_%'" | |
| 1132 | + ); | |
| 1133 | + | |
| 1134 | + if (!empty($history_options)) { | |
| 1135 | + foreach ($history_options as $option) { | |
| 1136 | + // Extract the session ID from the option name | |
| 1137 | + $session_id = str_replace('mxchat_history_', '', $option->option_name); | |
| 1138 | + | |
| 1139 | + // Check if this session still exists in the custom table | |
| 1140 | + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1141 | + $exists = $wpdb->get_var( | |
| 1142 | + $wpdb->prepare( | |
| 1143 | + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", | |
| 1144 | + $session_id | |
| 1145 | + ) | |
| 1146 | + ); | |
| 1147 | + | |
| 1148 | + // If session doesn't exist in the main table, delete the option | |
| 1149 | + if ($exists == 0) { | |
| 1150 | + delete_option($option->option_name); | |
| 1151 | + // Also delete related metadata | |
| 1152 | + delete_option("mxchat_email_{$session_id}"); | |
| 1153 | + delete_option("mxchat_name_{$session_id}"); | |
| 1154 | + delete_option("mxchat_agent_name_{$session_id}"); | |
| 1155 | + $count++; | |
| 1156 | + } | |
| 1157 | + } | |
| 1158 | + } | |
| 1159 | + | |
| 1160 | + return $count; | |
| 1161 | +} | |
| 1162 | + | |
| 1163 | +function mxchat_migrate_live_agent_status() { | |
| 1164 | + $options = get_option('mxchat_options', []); | |
| 1165 | + | |
| 1166 | + // Check if live_agent_status exists | |
| 1167 | + if (isset($options['live_agent_status'])) { | |
| 1168 | + $current_status = $options['live_agent_status']; | |
| 1169 | + $needs_update = false; | |
| 1170 | + | |
| 1171 | + // Convert to new format if needed | |
| 1172 | + if ($current_status === 'online') { | |
| 1173 | + $options['live_agent_status'] = 'on'; | |
| 1174 | + $needs_update = true; | |
| 1175 | + } else if ($current_status === 'offline') { | |
| 1176 | + $options['live_agent_status'] = 'off'; | |
| 1177 | + $needs_update = true; | |
| 1178 | + } else if (!in_array($current_status, ['on', 'off'])) { | |
| 1179 | + // Default to off for any unexpected values | |
| 1180 | + $options['live_agent_status'] = 'off'; | |
| 1181 | + $needs_update = true; | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | + // Only update if needed | |
| 1185 | + if ($needs_update) { | |
| 1186 | + update_option('mxchat_options', $options); | |
| 1187 | + } | |
| 1188 | + } else { | |
| 1189 | + // If status doesn't exist, set default to off | |
| 1190 | + $options['live_agent_status'] = 'off'; | |
| 1191 | + update_option('mxchat_options', $options); | |
| 1192 | + } | |
| 1193 | +} | |
| 1194 | + | |
| 1195 | +function mxchat_handle_live_agent_update() { | |
| 1196 | + // Get the CURRENT stored version (before it gets updated) | |
| 1197 | + $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 1198 | + $new_version = '2.2.2'; | |
| 1199 | + | |
| 1200 | + // Only run this once for the update to 2.2.2 | |
| 1201 | + $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false); | |
| 1202 | + | |
| 1203 | + // Check if we're upgrading TO 2.2.2 and haven't handled this yet | |
| 1204 | + if (version_compare($current_version, $new_version, '<') && !$update_handled) { | |
| 1205 | + $options = get_option('mxchat_options', array()); | |
| 1206 | + | |
| 1207 | + // Check if live agent was previously enabled | |
| 1208 | + if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') { | |
| 1209 | + // Disable live agent | |
| 1210 | + $options['live_agent_status'] = 'off'; | |
| 1211 | + update_option('mxchat_options', $options); | |
| 1212 | + | |
| 1213 | + // Set flag to show the notification banner | |
| 1214 | + update_option('mxchat_show_live_agent_disabled_notice', true); | |
| 1215 | + } | |
| 1216 | + | |
| 1217 | + // Mark this update as handled | |
| 1218 | + update_option('mxchat_live_agent_update_2_2_2_handled', true); | |
| 1219 | + } | |
| 1220 | +} | |
| 1221 | + | |
| 1222 | +/** | |
| 1223 | + * Handle theme migration notice for version 3.0.1 | |
| 1224 | + * Shows a dismissible notice to Pro users about migrating AI-generated themes | |
| 1225 | + */ | |
| 1226 | +function mxchat_handle_theme_migration_notice() { | |
| 1227 | + // Get the CURRENT stored version (before it gets updated) | |
| 1228 | + $current_version = get_option('mxchat_plugin_version', '0.0.0'); | |
| 1229 | + $target_version = '3.0.1'; | |
| 1230 | + | |
| 1231 | + // Only run this once for the update to 3.0.1 | |
| 1232 | + $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false); | |
| 1233 | + | |
| 1234 | + // Check if we're upgrading TO 3.0.1 and haven't handled this yet | |
| 1235 | + if (version_compare($current_version, $target_version, '<') && !$update_handled) { | |
| 1236 | + // Check if Pro is activated - only show to Pro users | |
| 1237 | + $license_status = get_option('mxchat_license_status', 'inactive'); | |
| 1238 | + $is_pro = ($license_status === 'active' || $license_status === esc_html__('active', 'mxchat')); | |
| 1239 | + | |
| 1240 | + if ($is_pro) { | |
| 1241 | + // Set flag to show the theme migration notification banner | |
| 1242 | + update_option('mxchat_show_theme_migration_notice', true); | |
| 1243 | + } | |
| 1244 | + | |
| 1245 | + // Mark this update as handled (whether Pro or not) | |
| 1246 | + update_option('mxchat_theme_migration_update_3_0_1_handled', true); | |
| 1247 | + } | |
| 1248 | +} | |
| 1249 | + | |
| 1250 | +// Initialize plugin safely | |
| 1251 | +function mxchat_init() { | |
| 1252 | + // Include all class files first | |
| 1253 | + mxchat_include_classes(); | |
| 1254 | + | |
| 1255 | + // Run update check (this also ensures tables exist) | |
| 1256 | + mxchat_check_for_update(); | |
| 1257 | + | |
| 1258 | + // CRITICAL: Ensure tables exist on admin pages (safety net) | |
| 1259 | + add_action('admin_init', 'mxchat_ensure_tables_exist', 1); | |
| 1260 | + | |
| 1261 | + // Add fallback rate limit check | |
| 1262 | + add_action('init', 'mxchat_check_fallback_rate_limits', 5); | |
| 1263 | + | |
| 1264 | + // Add migration notice hook | |
| 1265 | + add_action('admin_notices', 'mxchat_show_migration_notice'); | |
| 1266 | + | |
| 1267 | + // Initialize classes with error handling | |
| 1268 | + try { | |
| 1269 | + // Initialize admin classes | |
| 1270 | + if (is_admin()) { | |
| 1271 | + if (class_exists('MxChat_Knowledge_Manager')) { | |
| 1272 | + $mxchat_knowledge_manager = new MxChat_Knowledge_Manager(); | |
| 1273 | + | |
| 1274 | + if (class_exists('MxChat_Admin')) { | |
| 1275 | + $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager); | |
| 1276 | + } | |
| 1277 | + } | |
| 1278 | + | |
| 1279 | + // Initialize meta box class | |
| 1280 | + if (class_exists('MxChat_Meta_Box')) { | |
| 1281 | + new MxChat_Meta_Box(); | |
| 1282 | + } | |
| 1283 | + | |
| 1284 | + } | |
| 1285 | + | |
| 1286 | + // Initialize content generator globally — it registers wp_head hook | |
| 1287 | + // for frontend CSS injection, plus wp_ajax_ hooks for admin. | |
| 1288 | + if (class_exists('MxChat_Content_Generator')) { | |
| 1289 | + new MxChat_Content_Generator(); | |
| 1290 | + } | |
| 1291 | + | |
| 1292 | + // Initialize public classes | |
| 1293 | + if (class_exists('MxChat_Public')) { | |
| 1294 | + $mxchat_public = new MxChat_Public(); | |
| 1295 | + } | |
| 1296 | + | |
| 1297 | + if (class_exists('MxChat_Integrator')) { | |
| 1298 | + global $mxchat_integrator; | |
| 1299 | + $mxchat_integrator = new MxChat_Integrator(); | |
| 1300 | + } | |
| 1301 | + | |
| 1302 | + } catch (Exception $e) { | |
| 1303 | + //error_log('MxChat initialization error: ' . $e->getMessage()); | |
| 1304 | + | |
| 1305 | + // Show admin notice if there's an error | |
| 1306 | + if (is_admin()) { | |
| 1307 | + add_action('admin_notices', function() use ($e) { | |
| 1308 | + echo '<div class="notice notice-error"><p>'; | |
| 1309 | + echo '<strong>MxChat Error:</strong> Plugin initialization failed. '; | |
| 1310 | + echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage()); | |
| 1311 | + echo '</p></div>'; | |
| 1312 | + }); | |
| 1313 | + } | |
| 1314 | + } | |
| 1315 | +} | |
| 1316 | + | |
| 1317 | +// Run initialization on plugins_loaded | |
| 1318 | +add_action('plugins_loaded', 'mxchat_init'); | |
| 1319 | + | |
| 1320 | +// Run migration check on admin init (for auto-updates without reactivation) | |
| 1321 | +add_action('admin_init', 'mxchat_check_and_run_migrations'); | |
| 1322 | + | |
| 1323 | +/** | |
| 1324 | + * Check and run migrations on admin init | |
| 1325 | + * This ensures migrations run even when plugin is auto-updated | |
| 1326 | + */ | |
| 1327 | +function mxchat_check_and_run_migrations() { | |
| 1328 | + // Only run in admin and not on every request | |
| 1329 | + static $checked = false; | |
| 1330 | + if ($checked) { | |
| 1331 | + return; | |
| 1332 | + } | |
| 1333 | + $checked = true; | |
| 1334 | + | |
| 1335 | + mxchat_migrate_pinecone_roles_add_bot_id(); | |
| 1336 | + mxchat_migrate_add_content_type_column(); | |
| 1337 | + mxchat_migrate_add_translations_table(); | |
| 1338 | +} | |
| 1339 | + | |
| 1340 | +/** | |
| 1341 | + * Migration: Create transcript translations table (v3.0.4) | |
| 1342 | + * For users upgrading from versions before 3.0.4 | |
| 1343 | + */ | |
| 1344 | +function mxchat_migrate_add_translations_table() { | |
| 1345 | + $migration_key = 'mxchat_translations_table_created'; | |
| 1346 | + | |
| 1347 | + // Check if migration already ran | |
| 1348 | + if (get_option($migration_key)) { | |
| 1349 | + return; | |
| 1350 | + } | |
| 1351 | + | |
| 1352 | + // Create the translations table | |
| 1353 | + mxchat_create_translations_table(); | |
| 1354 | + | |
| 1355 | + // Mark migration as complete | |
| 1356 | + update_option($migration_key, '3.0.4'); | |
| 1357 | +} | |
| 1358 | + | |
| 1359 | +/** | |
| 1360 | + * Migration: Update deprecated Gemini embedding model (v3.0.5) | |
| 1361 | + * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected | |
| 1362 | + */ | |
| 1363 | +function mxchat_migrate_gemini_embedding_model() { | |
| 1364 | + $options = get_option('mxchat_options', array()); | |
| 1365 | + | |
| 1366 | + if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') { | |
| 1367 | + $options['embedding_model'] = 'gemini-embedding-001'; | |
| 1368 | + update_option('mxchat_options', $options); | |
| 1369 | + } | |
| 1370 | +} | |
| 1371 | + | |
| 1372 | +// Register activation hook | |
| 1373 | +register_activation_hook(__FILE__, 'mxchat_activate'); | |
| 1374 | + | |
| 1375 | +// Add cron schedule | |
| 1376 | +add_filter('cron_schedules', function($schedules) { | |
| 1377 | + $schedules['one_minute'] = array( | |
| 1378 | + 'interval' => 60, | |
| 1379 | + 'display' => 'Every Minute' | |
| 1380 | + ); | |
| 1381 | + return $schedules; | |
| 1382 | +}); | |
| 1383 | + | |
| 1384 | +// Register deactivation hook | |
| 1385 | +register_deactivation_hook(__FILE__, 'mxchat_deactivate'); | |