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