PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.1.8
MxChat – AI Chatbot & Content Generation for WordPress v3.1.8
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | mxchat-basic.php +36 -601 3.2.183.1.8 View file →
@@ -2,9 +2,9 @@
2 2 /**
3 3 * Plugin Name: MxChat
4 4 * Plugin URI: https://mxchat.ai/
5 5 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
6 - * Version: 3.2.18
6 + * Version: 3.1.8
7 7 * Author: MxChat
8 8 * Author URI: https://mxchat.ai
9 9 * License: GPLv2 or later
10 10 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -23,16 +23,8 @@
23 23
24 24 if (!defined('MXCHAT_VERSION')) {
25 25 $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), 'plugin');
26 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 27 if (MXCHAT_DEV_MODE) {
36 28 $version .= '.' . time();
37 29 }
38 30 define('MXCHAT_VERSION', $version);
@@ -37,27 +29,8 @@
37 29 }
38 30 define('MXCHAT_VERSION', $version);
39 31 }
40 32
41 -/**
42 - * Honest, versioned User-Agent for MXChat remote-content ingestion fetches
43 - * (Knowledge Base PDF import, URL import, sitemap / website crawl).
44 - *
45 - * WAF rulesets (SiteGround/ModSecurity, Wordfence, Cloudflare managed rules)
46 - * flag stale spoofed-browser UAs as scrapers and return 403 — which silently
47 - * broke the single most common KB source: self-hosted media on the site's own
48 - * domain. A truthful crawler identifier is the industry norm for well-behaved
49 - * bots and lets a site owner allowlist "MXChatBot" in their WAF. Filterable so
50 - * a locked-down host can supply a different string without a code change.
51 - */
52 -if (!function_exists('mxchat_ingest_user_agent')) {
53 - function mxchat_ingest_user_agent() {
54 - $version = defined('MXCHAT_VERSION') ? MXCHAT_VERSION : '1.0';
55 - $ua = 'MXChatBot/' . $version . ' (+https://mxchat.ai/bot)';
56 - return apply_filters('mxchat_ingest_user_agent', $ua);
57 - }
58 -}
59 -
60 33 function mxchat_load_textdomain() {
61 34 $domain = 'mxchat';
62 35 $locale = determine_locale();
63 36
@@ -73,84 +46,8 @@
73 46 }
74 47 add_action('init', 'mxchat_load_textdomain');
75 48
76 49 /**
77 - * One-time migration: gemini-3-pro-preview was shut down by Google on March 9, 2026.
78 - * Existing installs with the dead ID get auto-remapped to gemini-3.1-pro-preview
79 - * (Google's official migration target) the first time admin_init fires after update.
80 - */
81 -add_action('admin_init', function () {
82 - if (get_option('mxchat_gemini_3_remap_done')) {
83 - return;
84 - }
85 - $opts = get_option('mxchat_options');
86 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'gemini-3-pro-preview') {
87 - $opts['model'] = 'gemini-3.1-pro-preview';
88 - update_option('mxchat_options', $opts);
89 - }
90 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'gemini-3-pro-preview') {
91 - $opts['content_model'] = 'gemini-3.1-pro-preview';
92 - update_option('mxchat_options', $opts);
93 - }
94 - update_option('mxchat_gemini_3_remap_done', 1);
95 -});
96 -
97 -/**
98 - * One-time migration: the Grok 2 family was retired by xAI (grok-2, grok-2-1212,
99 - * grok-2-latest, grok-2-vision-1212 all return 400 "Model not found"). Existing
100 - * installs with the dead ID get auto-remapped to grok-4-1-fast-non-reasoning
101 - * (modern, fast, broadly available) the first time admin_init fires after update.
102 - */
103 -add_action('admin_init', function () {
104 - if (get_option('mxchat_grok_2_remap_done')) {
105 - return;
106 - }
107 - $opts = get_option('mxchat_options');
108 - if (is_array($opts) && isset($opts['model']) && $opts['model'] === 'grok-2') {
109 - $opts['model'] = 'grok-4-1-fast-non-reasoning';
110 - update_option('mxchat_options', $opts);
111 - }
112 - if (is_array($opts) && isset($opts['content_model']) && $opts['content_model'] === 'grok-2') {
113 - $opts['content_model'] = 'grok-4-1-fast-non-reasoning';
114 - update_option('mxchat_options', $opts);
115 - }
116 - update_option('mxchat_grok_2_remap_done', 1);
117 -});
118 -
119 -/**
120 - * One-time migration: Anthropic retired the Claude 4 (2025-05-14) snapshots on
121 - * June 15, 2026 — claude-opus-4-20250514 and claude-sonnet-4-20250514 now return
122 - * an API error. Existing installs with a dead ID get auto-remapped to the current
123 - * equivalents Anthropic recommends (Opus 4.8 / Sonnet 4.6) the first time admin_init
124 - * fires after update. Mirrors the gemini-3-pro-preview / grok-2 rescues above.
125 - */
126 -add_action('admin_init', function () {
127 - if (get_option('mxchat_claude_4_retire_remap_done')) {
128 - return;
129 - }
130 - $map = array(
131 - 'claude-opus-4-20250514' => 'claude-opus-4-8',
132 - 'claude-sonnet-4-20250514' => 'claude-sonnet-4-6',
133 - );
134 - $opts = get_option('mxchat_options');
135 - if (is_array($opts)) {
136 - $changed = false;
137 - if (isset($opts['model']) && isset($map[$opts['model']])) {
138 - $opts['model'] = $map[$opts['model']];
139 - $changed = true;
140 - }
141 - if (isset($opts['content_model']) && isset($map[$opts['content_model']])) {
142 - $opts['content_model'] = $map[$opts['content_model']];
143 - $changed = true;
144 - }
145 - if ($changed) {
146 - update_option('mxchat_options', $opts);
147 - }
148 - }
149 - update_option('mxchat_claude_4_retire_remap_done', 1);
150 -});
151 -
152 -/**
153 50 * Exclude MxChat assets from caching plugin optimizations
154 51 *
155 52 * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
156 53 * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
@@ -353,81 +250,20 @@
353 250 $rejected[] = 'wp-admin/admin-ajax.php';
354 251 return $rejected;
355 252 });
356 253
357 -// ── Page-cache bypass for chat AJAX (companion to the 3.2.6 nonce-race hotfix)
358 -// Each cache plugin gets its own filter export so that visitors hitting an
359 -// edge-cached page never receive cached chat-AJAX responses. The chat send /
360 -// stream send / file upload all POST to /wp-admin/admin-ajax.php with
361 -// `action=mxchat_*`. Without these exports, a cache plugin can stale a response
362 -// and break the per-session nonce flow on the first message.
363 -
364 -// WP Rocket — `rocket_cache_reject_uri` takes a flat array of regex strings.
365 -add_filter('rocket_cache_reject_uri', function($uris) {
366 - if (!is_array($uris)) $uris = array();
367 - $uris[] = '/wp-admin/admin-ajax\.php\?action=mxchat_.*';
368 - return $uris;
369 -});
370 -
371 -// LiteSpeed Cache — `litespeed_cache_no_cache_for_request` short-circuits
372 -// caching when the request matches our chat-AJAX pattern.
373 -add_filter('litespeed_cache_no_cache_for_request', function($no_cache) {
374 - if ($no_cache) return $no_cache;
375 - if (!empty($_SERVER['REQUEST_URI']) &&
376 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
377 - !empty($_REQUEST['action']) &&
378 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
379 - return true;
380 - }
381 - return $no_cache;
382 -});
383 -
384 -// W3 Total Cache — `w3tc_pgcache_request_skip_uri` flips page-cache off when
385 -// the URI matches.
386 -add_filter('w3tc_pgcache_request_skip_uri', function($skip) {
387 - if ($skip) return $skip;
388 - if (!empty($_SERVER['REQUEST_URI']) &&
389 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
390 - !empty($_REQUEST['action']) &&
391 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
392 - return true;
393 - }
394 - return $skip;
395 -});
396 -
397 -// FlyingPress — `flying_press_cacheable` takes a boolean and is run per
398 -// request. Same pattern as LiteSpeed / W3TC.
399 -add_filter('flying_press_cacheable', function($cacheable) {
400 - if (!$cacheable) return $cacheable;
401 - if (!empty($_SERVER['REQUEST_URI']) &&
402 - strpos($_SERVER['REQUEST_URI'], '/wp-admin/admin-ajax.php') !== false &&
403 - !empty($_REQUEST['action']) &&
404 - strpos((string) $_REQUEST['action'], 'mxchat_') === 0) {
405 - return false;
406 - }
407 - return $cacheable;
408 -});
409 -
410 254 // Include classes with error handling
411 255 function mxchat_include_classes() {
412 256 $class_files = array(
413 - 'includes/class-mxchat-model-catalog.php',
414 - 'includes/class-mxchat-session-store.php',
415 - 'includes/class-mxchat-live-agent-schedule.php',
416 - 'includes/class-mxchat-tool-registry.php',
417 257 'includes/class-mxchat-integrator.php',
418 258 'includes/class-mxchat-admin.php',
419 259 'includes/class-mxchat-public.php',
420 260 'includes/class-mxchat-utils.php',
421 261 'includes/class-mxchat-user.php',
422 - 'includes/class-mxchat-privacy.php',
423 262 'includes/class-mxchat-meta-box.php',
424 263 'includes/class-mxchat-chunker.php',
425 264 'includes/class-mxchat-word-handler.php',
426 265 'includes/class-mxchat-content-generator.php',
427 - 'includes/class-mxchat-cache-purge.php',
428 - 'includes/class-mxchat-editor-assistant.php',
429 - 'includes/class-rest-api.php',
430 266 'admin/class-ajax-handler.php',
431 267 'admin/class-pinecone-manager.php',
432 268 'admin/class-knowledge-manager.php'
433 269 );
@@ -439,49 +275,8 @@
439 275 } else {
440 276 //error_log('MxChat: Missing class file - ' . $file);
441 277 }
442 278 }
443 -
444 - // Register the native function-calling admin-post save handler (a41dee).
445 - if (class_exists('MxChat_Tool_Registry')) {
446 - MxChat_Tool_Registry::init();
447 - }
448 -
449 - // GDPR: register with WP's personal-data export/erase tools (b81e42).
450 - if (class_exists('MxChat_Privacy')) {
451 - MxChat_Privacy::init();
452 - }
453 -
454 - // Per-session state store: retention cron + the cron-independent
455 - // migration drain off admin_init (b64b77).
456 - if (class_exists('MxChat_Session_Store')) {
457 - MxChat_Session_Store::init();
458 - }
459 -
460 - // Editor Assistant — free, OFF-by-default block-editor AI actions (plan-8cb0cb).
461 - // init() wires REST + streaming AJAX + sidebar enqueue ONLY when the
462 - // mxchat_editor_assistant_enabled option is 'on'; otherwise zero footprint.
463 - if (class_exists('MxChat_Editor_Assistant')) {
464 - MxChat_Editor_Assistant::init();
465 - }
466 -
467 - // Admin pages that aren't classes (procedural include).
468 - if (is_admin()) {
469 - $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php';
470 - if (file_exists($admin_api_page)) {
471 - require_once $admin_api_page;
472 - }
473 - // f7c7d4 renamed this file admin-dashboard-page.php → admin-onboarding-page.php.
474 - // The require MUST live here (admin bootstrap) and not just inside
475 - // mxchat_add_plugin_page() on the admin_menu hook — admin_menu does NOT
476 - // fire on admin-ajax.php requests, so the wizard's AJAX handlers
477 - // (plan-905439: mxchat_onboarding_kb_status / save_step / mark_step /
478 - // auto_graduate + the f7c7d4 dismiss handler) would never register.
479 - $admin_onboarding_page = plugin_dir_path(__FILE__) . 'includes/admin-onboarding-page.php';
480 - if (file_exists($admin_onboarding_page)) {
481 - require_once $admin_onboarding_page;
482 - }
483 - }
484 279 }
485 280
486 281 /**
487 282 * Lazy-load the PDF parser library only when needed.
@@ -526,26 +321,8 @@
526 321 dbDelta($sql);
527 322 }
528 323
529 324 /**
530 - * Create the per-session state table (b64b77).
531 - *
532 - * Callable from the activation hook, which can run before plugins_loaded has
533 - * included the class files — so it loads the class itself when needed.
534 - */
535 -function mxchat_create_sessions_table() {
536 - if (!class_exists('MxChat_Session_Store')) {
537 - $path = plugin_dir_path(__FILE__) . 'includes/class-mxchat-session-store.php';
538 - if (!file_exists($path)) {
539 - return false;
540 - }
541 - require_once $path;
542 - }
543 -
544 - return MxChat_Session_Store::create_table();
545 -}
546 -
547 -/**
548 325 * FIXED: Robust table creation and column management
549 326 */
550 327 function mxchat_create_chat_transcripts_table() {
551 328 global $wpdb;
@@ -831,33 +608,8 @@
831 608 update_option('mxchat_content_type_migration_version', '2.5.6');
832 609 }
833 610
834 611 /**
835 - * 3.2.4: Backfill the active embedding model option for installs that already
836 - * have KB content but no stamped model. The mismatch warning compares this
837 - * against the user's currently selected model — no per-row column needed.
838 - */
839 -function mxchat_backfill_active_embedding_model() {
840 - global $wpdb;
841 -
842 - if (get_option('mxchat_active_embedding_model', '') !== '') {
843 - return;
844 - }
845 -
846 - $kb_table = $wpdb->prefix . 'mxchat_system_prompt_content';
847 - if ($wpdb->get_var("SHOW TABLES LIKE '{$kb_table}'") !== $kb_table) {
848 - return;
849 - }
850 -
851 - $kb_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$kb_table}");
852 - if ($kb_count > 0) {
853 - $options = get_option('mxchat_options', array());
854 - $current_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
855 - update_option('mxchat_active_embedding_model', $current_model, false);
856 - }
857 -}
858 -
859 -/**
860 612 * 2.5.2: Create queue processing tables for reliable background processing
861 613 */
862 614 function mxchat_create_queue_tables() {
863 615 global $wpdb;
@@ -929,34 +681,8 @@
929 681 dbDelta($sql);
930 682 }
931 683
932 684 /**
933 - * Create per-session satisfaction ratings table (v3.2.6)
934 - * Stores one 👍/👎 rating + optional feedback per chat session.
935 - */
936 -function mxchat_create_session_ratings_table() {
937 - global $wpdb;
938 - $charset_collate = $wpdb->get_charset_collate();
939 -
940 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
941 - $sql = "CREATE TABLE $table_name (
942 - id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
943 - session_id varchar(255) NOT NULL,
944 - bot_id varchar(50) NOT NULL DEFAULT 'default',
945 - rating_value tinyint(1) NOT NULL,
946 - rating_feedback text DEFAULT NULL,
947 - created_at datetime NOT NULL,
948 - PRIMARY KEY (id),
949 - UNIQUE KEY session_id (session_id),
950 - KEY bot_id (bot_id),
951 - KEY created_at (created_at)
952 - ) $charset_collate;";
953 -
954 - require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
955 - dbDelta($sql);
956 -}
957 -
958 -/**
959 685 * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
960 686 * This fixes "url, source_url. The supplied values may be too long" errors
961 687 */
962 688 function mxchat_fix_url_column_size() {
@@ -1027,43 +753,18 @@
1027 753 $migrated = true;
1028 754 $migration_message = 'Your chatbot model has been automatically updated from Claude Haiku 3.5 to Claude Haiku 4.5 due to Anthropic deprecating the older model.';
1029 755 }
1030 756
1031 - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.6 Sol.
1032 - // (Previous target gpt-5.1-chat-latest itself retires 2026-08-10 — never
1033 - // migrate onto a model that is already on a deprecation list.)
757 + // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
1034 758 if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
1035 - $options['model'] = 'gpt-5.6-sol';
759 + $options['model'] = 'gpt-5.1-chat-latest';
1036 760 $migrated = true;
1037 761 $migration_message = sprintf(
1038 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol due to OpenAI deprecating older models.',
762 + 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.',
1039 763 $current_model
1040 764 );
1041 765 }
1042 766
1043 - // Migrate the gpt-5.x-chat-latest aliases OpenAI retires on August 10, 2026.
1044 - // Replacement per OpenAI's deprecations page: gpt-5.6-sol (plan e46b8f).
1045 - if (in_array($current_model, array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1046 - $options['model'] = 'gpt-5.6-sol';
1047 - $migrated = true;
1048 - $migration_message = sprintf(
1049 - 'Your chatbot model has been automatically updated from %s to GPT-5.6 Sol because OpenAI retires the GPT-5.x Chat Latest models on August 10, 2026.',
1050 - $current_model
1051 - );
1052 - }
1053 -
1054 - // The content generator has its own model option — same retirement applies.
1055 - if (isset($options['content_model'])
1056 - && in_array($options['content_model'], array('gpt-5.1-chat-latest', 'gpt-5.3-chat-latest'), true)) {
1057 - $old_content_model = $options['content_model'];
1058 - $options['content_model'] = 'gpt-5.6-sol';
1059 - $migrated = true;
1060 - $migration_message = trim($migration_message . ' ' . sprintf(
1061 - 'Your content generation model has also been updated from %s to GPT-5.6 Sol for the same OpenAI retirement.',
1062 - $old_content_model
1063 - ));
1064 - }
1065 -
1066 767 // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
1067 768 if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
1068 769 $options['model'] = 'gpt-5-mini';
1069 770 $migrated = true;
@@ -1072,21 +773,8 @@
1072 773 $current_model
1073 774 );
1074 775 }
1075 776
1076 - // Migrate retired DeepSeek ids to DeepSeek V4 Flash — the vendor removed
1077 - // deepseek-chat and deepseek-reasoner on 2026-07-24 (hard cutoff, every
1078 - // request 400s). V4 Flash is DeepSeek's designated successor for the
1079 - // legacy deepseek-chat alias.
1080 - if (in_array($current_model, array('deepseek-chat', 'deepseek-reasoner'), true)) {
1081 - $options['model'] = 'deepseek-v4-flash';
1082 - $migrated = true;
1083 - $migration_message = sprintf(
1084 - 'Your chatbot model has been automatically updated from %s to DeepSeek V4 Flash because DeepSeek retired its older API models on July 24, 2026.',
1085 - $current_model
1086 - );
1087 - }
1088 -
1089 777 if ($migrated) {
1090 778 update_option('mxchat_options', $options);
1091 779 update_option('mxchat_model_migrated_notice', true);
1092 780 update_option('mxchat_model_migration_message', $migration_message);
@@ -1111,46 +799,8 @@
1111 799 delete_option('mxchat_model_migration_message');
1112 800 }
1113 801 }
1114 802
1115 -/**
1116 - * Persistent admin notice when the provider rejected the configured model
1117 - * (model_not_found / no access). Set by mxchat_friendly_chat_error() in the
1118 - * integrator whenever a chat request fails on a model-access error — including
1119 - * requests from anonymous visitors, which is the case that otherwise stays
1120 - * invisible to the site owner for weeks (plan e46b8f).
1121 - *
1122 - * Deleted after render so it re-arms on the next failed chat: the notice keeps
1123 - * reappearing until the model is fixed, then stops on its own.
1124 - */
1125 -function mxchat_show_model_access_notice() {
1126 - if (!current_user_can('manage_options')) {
1127 - return;
1128 - }
1129 - $notice = get_option('mxchat_model_access_notice');
1130 - if (!is_array($notice) || empty($notice['model'])) {
1131 - return;
1132 - }
1133 - $settings_url = admin_url('admin.php?page=mxchat-max');
1134 - ?>
1135 - <div class="notice notice-error is-dismissible">
1136 - <p>
1137 - <strong><?php esc_html_e('MxChat: your AI model is being rejected by the provider', 'mxchat'); ?></strong><br>
1138 - <?php
1139 - printf(
1140 - /* translators: 1: model id, 2: provider name */
1141 - esc_html__('Chat requests using the model "%1$s" are failing because %2$s reports it as unavailable on your API key (it may have been retired). Visitors may be seeing errors instead of replies.', 'mxchat'),
1142 - esc_html($notice['model']),
1143 - esc_html(!empty($notice['provider']) ? $notice['provider'] : __('the AI provider', 'mxchat'))
1144 - );
1145 - ?>
1146 - <a href="<?php echo esc_url($settings_url); ?>"><?php esc_html_e('Choose a different model in MxChat Settings', 'mxchat'); ?></a>
1147 - </p>
1148 - </div>
1149 - <?php
1150 - delete_option('mxchat_model_access_notice');
1151 -}
1152 -
1153 803 function mxchat_activate() {
1154 804 global $wpdb;
1155 805 $charset_collate = $wpdb->get_charset_collate();
1156 806
@@ -1158,12 +808,8 @@
1158 808
1159 809 // Create chat transcripts table with improved function
1160 810 mxchat_create_chat_transcripts_table();
1161 811
1162 - // Per-session state table (b64b77). Activation can run before
1163 - // plugins_loaded has included the class files, so require it directly.
1164 - mxchat_create_sessions_table();
1165 -
1166 812 // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
1167 813 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
1168 814 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
1169 815 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -1222,11 +868,8 @@
1222 868
1223 869 // Create transcript translations table
1224 870 mxchat_create_translations_table();
1225 871
1226 - // Create per-session satisfaction ratings table (v3.2.6)
1227 - mxchat_create_session_ratings_table();
1228 -
1229 872 // Ensure additional columns in system prompt table
1230 873 $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
1231 874 if (!empty($existing_system_columns)) {
1232 875 $existing_system_column_names = array_column($existing_system_columns, 'Field');
@@ -1269,17 +912,13 @@
1269 912
1270 913 // Run migration for existing installations
1271 914 mxchat_migrate_pinecone_roles_add_bot_id();
1272 915
1273 - // 3.2.4: Backfill active embedding model option (replaces 3.2.3 column-based tracking)
1274 - mxchat_backfill_active_embedding_model();
1275 -
1276 916 // Setup cron jobs
1277 917 mxchat_setup_cron_jobs();
1278 918
1279 - // Update version (stable base version — never the dev time()-suffixed one,
1280 - // or the check_for_update comparison would churn every request)
1281 - update_option('mxchat_plugin_version', MXCHAT_BASE_VERSION);
919 + // Update version
920 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
1282 921
1283 922 //error_log("MxChat: Activation function completed");
1284 923 }
1285 924
@@ -1294,35 +933,28 @@
1294 933 if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
1295 934 // Set flag to use fallback system
1296 935 update_option('mxchat_use_fallback_rate_limits', true);
1297 936 update_option('mxchat_next_rate_limit_check', time() + 3600);
1298 - // Deliberately NO early return (plan-bc08a6): transcript cleanup below
1299 - // must still be scheduled. DISABLE_WP_CRON only changes HOW cron events
1300 - // execute (a server-side runner hitting wp-cron.php instead of loopback
1301 - // spawns) — scheduling still just writes the cron option. The old early
1302 - // return here meant a deactivate/reactivate cycle on a DISABLE_WP_CRON
1303 - // site permanently lost the transcript cleanup event while the retention
1304 - // setting still claimed to be active.
937 + return;
938 + }
939 +
940 + // Schedule the rate limit reset cron job
941 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
942 +
943 + if ($result === false) {
944 + // Fallback if scheduling fails
945 + update_option('mxchat_use_fallback_rate_limits', true);
946 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1305 947 } else {
1306 - // Schedule the rate limit reset cron job
1307 - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
1308 -
1309 - if ($result === false) {
1310 - // Fallback if scheduling fails
1311 - update_option('mxchat_use_fallback_rate_limits', true);
1312 - update_option('mxchat_next_rate_limit_check', time() + 3600);
1313 - } else {
1314 - // Clear fallback flags if cron scheduling succeeded
1315 - delete_option('mxchat_use_fallback_rate_limits');
1316 - }
948 + // Clear fallback flags if cron scheduling succeeded
949 + delete_option('mxchat_use_fallback_rate_limits');
1317 950 }
1318 -
1319 - // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0)
951 +
952 + // Schedule transcript cleanup if configured
1320 953 $transcript_options = get_option('mxchat_transcripts_options', array());
1321 954 $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
1322 - $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0;
1323 -
1324 - if ($cleanup_interval !== 'never' || $custom_retention > 0) {
955 +
956 + if ($cleanup_interval !== 'never') {
1325 957 // Check if not already scheduled
1326 958 if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
1327 959 // Schedule to run daily at 3 AM
1328 960 $next_run = strtotime('tomorrow 3:00 AM');
@@ -1359,25 +991,17 @@
1359 991 return;
1360 992 }
1361 993
1362 994 $next_check = get_option('mxchat_next_rate_limit_check', 0);
1363 -
995 +
1364 996 if (time() >= $next_check) {
1365 - // Reuse the bootstrap's integrator — mxchat_init() creates the global on
1366 - // plugins_loaded (before this init-priority-5 callback), so it's always set
1367 - // here. Constructing a second MxChat_Integrator just to call one method
1368 - // re-registers every hook the plugin has (ajax pairs, wp_footer loader,
1369 - // rest_api_init, admin_init guard) on a duplicate instance for the rest of
1370 - // the request. Defensive construction only if the global is somehow unset.
1371 - // NOTE: MxChat_Integrator::check_fallback_rate_limits() is a second
1372 - // implementation of this same check — if either changes, change both.
1373 - global $mxchat_integrator;
1374 - $integrator = ($mxchat_integrator instanceof MxChat_Integrator)
1375 - ? $mxchat_integrator
1376 - : (class_exists('MxChat_Integrator') ? new MxChat_Integrator() : null);
1377 - if ($integrator && method_exists($integrator, 'mxchat_reset_rate_limits')) {
1378 - $integrator->mxchat_reset_rate_limits();
1379 - update_option('mxchat_next_rate_limit_check', time() + 3600);
997 + // Only run reset if the MxChat_Integrator class exists
998 + if (class_exists('MxChat_Integrator')) {
999 + $integrator = new MxChat_Integrator();
1000 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
1001 + $integrator->mxchat_reset_rate_limits();
1002 + update_option('mxchat_next_rate_limit_check', time() + 3600);
1003 + }
1380 1004 }
1381 1005 }
1382 1006 }
1383 1007
@@ -1389,9 +1013,9 @@
1389 1013 global $wpdb;
1390 1014
1391 1015 try {
1392 1016 $current_version = get_option('mxchat_plugin_version', '0.0.0');
1393 - $plugin_version = MXCHAT_BASE_VERSION;
1017 + $plugin_version = MXCHAT_VERSION;
1394 1018
1395 1019 // Always ensure critical tables exist (even if version matches)
1396 1020 // This handles manual table deletion or fresh installs
1397 1021 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
@@ -1396,16 +1020,12 @@
1396 1020 // This handles manual table deletion or fresh installs
1397 1021 $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
1398 1022 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1399 1023
1400 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1401 -
1402 1024 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
1403 1025 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1404 - $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1405 - || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1406 -
1407 - if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1026 +
1027 + if (!$chat_exists || !$queue_exists) {
1408 1028 //error_log("MxChat: Critical tables missing, running activation");
1409 1029 mxchat_activate();
1410 1030 }
1411 1031
@@ -1468,38 +1088,8 @@
1468 1088 delete_option('mxchat_email_null');
1469 1089 delete_option('mxchat_name_null');
1470 1090 }
1471 1091
1472 - // 3.2.4: Backfill active embedding model option for the warning UI
1473 - // (replaces the per-row column tracking from 3.2.3, which was reverted)
1474 - if (version_compare($current_version, '3.2.4', '<')) {
1475 - mxchat_backfill_active_embedding_model();
1476 - }
1477 -
1478 - // 3.2.15: Migrate retired DeepSeek ids (deepseek-chat / deepseek-reasoner
1479 - // were shut off at the vendor on 2026-07-24). The function is idempotent —
1480 - // it only rewrites models on its deprecation lists.
1481 - if (version_compare($current_version, '3.2.15', '<')) {
1482 - mxchat_migrate_deprecated_models();
1483 - }
1484 -
1485 - // 3.2.16: Migrate OpenAI ids retiring 2026-08-10 (gpt-5.1-chat-latest /
1486 - // gpt-5.3-chat-latest → gpt-5.6-sol per OpenAI's deprecations page).
1487 - // Idempotent — only rewrites models on the deprecation lists (e46b8f).
1488 - if (version_compare($current_version, '3.2.16', '<')) {
1489 - mxchat_migrate_deprecated_models();
1490 - }
1491 -
1492 - // 3.2.17: Credential options must not autoload (af2400) — the two
1493 - // Pinecone-secret-holding rows were in alloptions, i.e. read into
1494 - // memory on every request including anonymous page views. Idempotent.
1495 - // Also carry the import modal's remembered ACF→PDF checkbox state
1496 - // into the new install-level option (11720c).
1497 - if (version_compare($current_version, '3.2.17', '<')) {
1498 - mxchat_fix_credential_option_autoload();
1499 - mxchat_migrate_acf_pdf_extraction_option();
1500 - }
1501 -
1502 1092 // Run full activation to ensure everything is up to date
1503 1093 mxchat_activate();
1504 1094
1505 1095 // Run migration functions
@@ -1522,67 +1112,8 @@
1522 1112 }
1523 1113 }
1524 1114
1525 1115 /**
1526 - * Credential options must never enter the autoloaded alloptions set.
1527 - * mxchat_prompts_options and mxchat_pinecone_addon_options can hold the
1528 - * Pinecone API secret; mxchat_options already stores its keys with autoload
1529 - * off and these two must match it. The filter covers every future
1530 - * add_option()/update_option() that creates the row — Settings API saves
1531 - * through options.php and WP-CLI included — on WP 6.6+; older cores are
1532 - * covered by the explicit autoload arguments at the plugin's own write
1533 - * sites plus the one-time migration below.
1534 - */
1535 -add_filter('wp_default_autoload_value', 'mxchat_credential_option_autoload_value', 10, 2);
1536 -function mxchat_credential_option_autoload_value($autoload, $option) {
1537 - if (in_array($option, array('mxchat_prompts_options', 'mxchat_pinecone_addon_options'), true)) {
1538 - return false;
1539 - }
1540 - return $autoload;
1541 -}
1542 -
1543 -/**
1544 - * One-time upgrade migration: flip the autoload flag on credential option
1545 - * rows that existing installs are already carrying autoloaded. Includes
1546 - * mxchat_adv_api_token (Advanced Content bearer token) — harmless no-op
1547 - * when that add-on is not installed, since missing rows simply don't match.
1548 - */
1549 -function mxchat_fix_credential_option_autoload() {
1550 - $keys = array('mxchat_prompts_options', 'mxchat_pinecone_addon_options', 'mxchat_adv_api_token');
1551 - if (function_exists('wp_set_option_autoload_values')) {
1552 - wp_set_option_autoload_values(array_fill_keys($keys, false));
1553 - return;
1554 - }
1555 - // Pre-WP-6.4 fallback: direct flip + cache invalidation.
1556 - global $wpdb;
1557 - $placeholders = implode(',', array_fill(0, count($keys), '%s'));
1558 - $wpdb->query($wpdb->prepare("UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ($placeholders)", $keys));
1559 - wp_cache_delete('alloptions', 'options');
1560 - foreach ($keys as $key) {
1561 - wp_cache_delete($key, 'options');
1562 - }
1563 -}
1564 -
1565 -/**
1566 - * One-time carry of the import modal's remembered ACF→PDF checkbox state
1567 - * (mxchat_options['acf_pdf_extract_default'], written per-import until 3.2.16)
1568 - * into the new install-level option mxchat_acf_pdf_extraction (plan 11720c).
1569 - * Fresh installs and installs that never touched the checkbox default OFF,
1570 - * matching the setting's own "recommended only if…" guidance.
1571 - */
1572 -function mxchat_migrate_acf_pdf_extraction_option() {
1573 - if (get_option('mxchat_acf_pdf_extraction', null) !== null) {
1574 - return; // already set — never overwrite an owner's choice
1575 - }
1576 - $mxchat_options = get_option('mxchat_options', array());
1577 - if (is_array($mxchat_options) && array_key_exists('acf_pdf_extract_default', $mxchat_options)) {
1578 - update_option('mxchat_acf_pdf_extraction', !empty($mxchat_options['acf_pdf_extract_default']) ? '1' : '0', false);
1579 - unset($mxchat_options['acf_pdf_extract_default']);
1580 - update_option('mxchat_options', $mxchat_options);
1581 - }
1582 -}
1583 -
1584 -/**
1585 1116 * Ensure tables exist on every admin load for fresh installations
1586 1117 * This is a safety net for cases where activation hook doesn't fire
1587 1118 */
1588 1119 function mxchat_ensure_tables_exist() {
@@ -1602,16 +1133,12 @@
1602 1133
1603 1134 $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1604 1135 $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1605 1136
1606 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1607 -
1608 1137 $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1609 1138 $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1610 - $sessions_exists = get_option('mxchat_session_store_ready') === '1'
1611 - || $wpdb->get_var("SHOW TABLES LIKE '$sessions_table'") === $sessions_table;
1612 -
1613 - if (!$chat_exists || !$queue_exists || !$sessions_exists) {
1139 +
1140 + if (!$chat_exists || !$queue_exists) {
1614 1141 //error_log("MxChat: Tables missing on admin load, running activation");
1615 1142 mxchat_activate();
1616 1143 }
1617 1144 }
@@ -1761,9 +1288,8 @@
1761 1288 add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1762 1289
1763 1290 // Add migration notice hook
1764 1291 add_action('admin_notices', 'mxchat_show_migration_notice');
1765 - add_action('admin_notices', 'mxchat_show_model_access_notice');
1766 1292
1767 1293 // Initialize classes with error handling
1768 1294 try {
1769 1295 // Initialize admin classes
@@ -1788,23 +1314,8 @@
1788 1314 if (class_exists('MxChat_Content_Generator')) {
1789 1315 new MxChat_Content_Generator();
1790 1316 }
1791 1317
1792 - // Initialize cache purge globally — settings writes can happen on any
1793 - // request type (admin screens, admin-ajax autosave, wp-cli), and the
1794 - // deferred-purge cron event fires on front-end requests.
1795 - if (class_exists('MxChat_Cache_Purge')) {
1796 - MxChat_Cache_Purge::init();
1797 - }
1798 -
1799 - // Initialize REST API globally — endpoints must be registered on
1800 - // every request (admin and frontend) so they're reachable via /wp-json/.
1801 - // Endpoints are auth-gated and locked until the site owner generates
1802 - // a token in MxChat → API Access.
1803 - if (class_exists('MxChat_Rest_Api')) {
1804 - new MxChat_Rest_Api();
1805 - }
1806 -
1807 1318 // Initialize public classes
1808 1319 if (class_exists('MxChat_Public')) {
1809 1320 $mxchat_public = new MxChat_Public();
1810 1321 }
@@ -1849,25 +1360,11 @@
1849 1360
1850 1361 mxchat_migrate_pinecone_roles_add_bot_id();
1851 1362 mxchat_migrate_add_content_type_column();
1852 1363 mxchat_migrate_add_translations_table();
1853 - mxchat_migrate_add_session_ratings_table();
1854 1364 }
1855 1365
1856 1366 /**
1857 - * Migration: Create per-session satisfaction ratings table (v3.2.6)
1858 - * For users upgrading from versions before 3.2.6
1859 - */
1860 -function mxchat_migrate_add_session_ratings_table() {
1861 - $migration_key = 'mxchat_session_ratings_table_created';
1862 - if (get_option($migration_key)) {
1863 - return;
1864 - }
1865 - mxchat_create_session_ratings_table();
1866 - update_option($migration_key, '3.2.6');
1867 -}
1868 -
1869 -/**
1870 1367 * Migration: Create transcript translations table (v3.0.4)
1871 1368 * For users upgrading from versions before 3.0.4
1872 1369 */
1873 1370 function mxchat_migrate_add_translations_table() {
@@ -1910,67 +1407,5 @@
1910 1407 return $schedules;
1911 1408 });
1912 1409
1913 1410 // Register deactivation hook
1914 -register_deactivation_hook(__FILE__, 'mxchat_deactivate');
1915 -
1916 -/**
1917 - * Per-session satisfaction rating: AJAX save handler (v3.2.6).
1918 - * Records one 👍/👎 + optional feedback per chat session. The UNIQUE KEY on
1919 - * session_id makes this naturally idempotent — only the first rating per
1920 - * session is stored; duplicate POSTs are silent no-ops.
1921 - */
1922 -function mxchat_save_session_rating() {
1923 - global $wpdb;
1924 -
1925 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1926 - $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default';
1927 - $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0;
1928 - $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : '';
1929 -
1930 - if ($session_id === '' || ($rating_raw !== 1 && $rating_raw !== -1)) {
1931 - wp_send_json_error(array('message' => 'invalid_input'), 400);
1932 - }
1933 -
1934 - if (strlen($feedback) > 1000) {
1935 - $feedback = substr($feedback, 0, 1000);
1936 - }
1937 -
1938 - $table_name = $wpdb->prefix . 'mxchat_session_ratings';
1939 - $existing = $wpdb->get_var($wpdb->prepare(
1940 - "SELECT id FROM $table_name WHERE session_id = %s LIMIT 1",
1941 - $session_id
1942 - ));
1943 -
1944 - if ($existing) {
1945 - if ($feedback !== '') {
1946 - $wpdb->update(
1947 - $table_name,
1948 - array('rating_feedback' => $feedback),
1949 - array('id' => (int) $existing),
1950 - array('%s'),
1951 - array('%d')
1952 - );
1953 - }
1954 - wp_send_json_success(array('updated' => true));
1955 - }
1956 -
1957 - $inserted = $wpdb->insert(
1958 - $table_name,
1959 - array(
1960 - 'session_id' => $session_id,
1961 - 'bot_id' => $bot_id !== '' ? $bot_id : 'default',
1962 - 'rating_value' => $rating_raw,
1963 - 'rating_feedback' => $feedback !== '' ? $feedback : null,
1964 - 'created_at' => current_time('mysql'),
1965 - ),
1966 - array('%s', '%s', '%d', '%s', '%s')
1967 - );
1968 -
1969 - if ($inserted === false) {
1970 - wp_send_json_error(array('message' => 'db_insert_failed'), 500);
1971 - }
1972 -
1973 - wp_send_json_success(array('saved' => true));
1974 -}
1975 -add_action('wp_ajax_mxchat_save_rating', 'mxchat_save_session_rating');
1976 -add_action('wp_ajax_nopriv_mxchat_save_rating', 'mxchat_save_session_rating');
1411 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');