| @@ -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.8 | |
| 6 | + * Version: 3.2.21 | |
| 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,8 +23,16 @@ | ||
| 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); | |
| 27 | 35 | if (MXCHAT_DEV_MODE) { |
| 28 | 36 | $version .= '.' . time(); |
| 29 | 37 | } |
| 30 | 38 | define('MXCHAT_VERSION', $version); |
| @@ -29,8 +37,84 @@ | ||
| 29 | 37 | } |
| 30 | 38 | define('MXCHAT_VERSION', $version); |
| 31 | 39 | } |
| 32 | 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 | + | |
| 33 | 117 | function mxchat_load_textdomain() { |
| 34 | 118 | $domain = 'mxchat'; |
| 35 | 119 | $locale = determine_locale(); |
| 36 | 120 | |
| @@ -89,8 +173,41 @@ | ||
| 89 | 173 | update_option('mxchat_grok_2_remap_done', 1); |
| 90 | 174 | }); |
| 91 | 175 | |
| 92 | 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 | +/** | |
| 93 | 210 | * Exclude MxChat assets from caching plugin optimizations |
| 94 | 211 | * |
| 95 | 212 | * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache, |
| 96 | 213 | * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by |
| @@ -349,21 +466,32 @@ | ||
| 349 | 466 | |
| 350 | 467 | // Include classes with error handling |
| 351 | 468 | function mxchat_include_classes() { |
| 352 | 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', | |
| 353 | 475 | 'includes/class-mxchat-integrator.php', |
| 354 | 476 | 'includes/class-mxchat-admin.php', |
| 355 | 477 | 'includes/class-mxchat-public.php', |
| 478 | + 'includes/class-mxchat-block.php', | |
| 479 | + 'includes/class-mxchat-elementor.php', | |
| 356 | 480 | 'includes/class-mxchat-utils.php', |
| 357 | 481 | 'includes/class-mxchat-user.php', |
| 482 | + 'includes/class-mxchat-privacy.php', | |
| 358 | 483 | 'includes/class-mxchat-meta-box.php', |
| 359 | 484 | 'includes/class-mxchat-chunker.php', |
| 360 | 485 | 'includes/class-mxchat-word-handler.php', |
| 361 | 486 | 'includes/class-mxchat-content-generator.php', |
| 487 | + 'includes/class-mxchat-cache-purge.php', | |
| 488 | + 'includes/class-mxchat-editor-assistant.php', | |
| 362 | 489 | 'includes/class-rest-api.php', |
| 363 | 490 | 'admin/class-ajax-handler.php', |
| 364 | 491 | 'admin/class-pinecone-manager.php', |
| 365 | - 'admin/class-knowledge-manager.php' | |
| 492 | + 'admin/class-knowledge-manager.php', | |
| 493 | + 'admin/class-vectorstore-manager.php' | |
| 366 | 494 | ); |
| 367 | 495 | |
| 368 | 496 | foreach ($class_files as $file) { |
| 369 | 497 | $file_path = plugin_dir_path(__FILE__) . $file; |
| @@ -373,8 +501,59 @@ | ||
| 373 | 501 | //error_log('MxChat: Missing class file - ' . $file); |
| 374 | 502 | } |
| 375 | 503 | } |
| 376 | 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 | + | |
| 377 | 556 | // Admin pages that aren't classes (procedural include). |
| 378 | 557 | if (is_admin()) { |
| 379 | 558 | $admin_api_page = plugin_dir_path(__FILE__) . 'includes/admin-api-page.php'; |
| 380 | 559 | if (file_exists($admin_api_page)) { |
| @@ -436,8 +615,26 @@ | ||
| 436 | 615 | dbDelta($sql); |
| 437 | 616 | } |
| 438 | 617 | |
| 439 | 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 | +/** | |
| 440 | 637 | * FIXED: Robust table creation and column management |
| 441 | 638 | */ |
| 442 | 639 | function mxchat_create_chat_transcripts_table() { |
| 443 | 640 | global $wpdb; |
| @@ -748,8 +945,66 @@ | ||
| 748 | 945 | } |
| 749 | 946 | } |
| 750 | 947 | |
| 751 | 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 | +/** | |
| 752 | 1007 | * 2.5.2: Create queue processing tables for reliable background processing |
| 753 | 1008 | */ |
| 754 | 1009 | function mxchat_create_queue_tables() { |
| 755 | 1010 | global $wpdb; |
| @@ -847,8 +1102,41 @@ | ||
| 847 | 1102 | dbDelta($sql); |
| 848 | 1103 | } |
| 849 | 1104 | |
| 850 | 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 | +/** | |
| 851 | 1139 | * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding) |
| 852 | 1140 | * This fixes "url, source_url. The supplied values may be too long" errors |
| 853 | 1141 | */ |
| 854 | 1142 | function mxchat_fix_url_column_size() { |
| @@ -892,53 +1180,45 @@ | ||
| 892 | 1180 | if (!isset($options['model'])) { |
| 893 | 1181 | return; |
| 894 | 1182 | } |
| 895 | 1183 | |
| 896 | - $current_model = $options['model']; | |
| 897 | - | |
| 898 | - // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic) | |
| 899 | - $deprecated_claude_models = array( | |
| 900 | - 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025 | |
| 901 | - 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025 | |
| 902 | - 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026 | |
| 903 | - 'claude-3-opus-20240229', // Retired Jan 5, 2026 | |
| 904 | - 'claude-3-sonnet-20240229', // Legacy | |
| 905 | - 'claude-3-haiku-20240307', // Legacy | |
| 906 | - ); | |
| 907 | - if (in_array($current_model, $deprecated_claude_models, true)) { | |
| 908 | - $options['model'] = 'claude-opus-4-6'; | |
| 909 | - $migrated = true; | |
| 910 | - $migration_message = sprintf( | |
| 911 | - 'Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.', | |
| 912 | - $current_model | |
| 913 | - ); | |
| 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 | |
| 914 | 1190 | } |
| 1191 | + $map = MxChat_Model_Catalog::retired_model_map(); | |
| 915 | 1192 | |
| 916 | - // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5 | |
| 917 | - if ($current_model === 'claude-3-5-haiku-20241022') { | |
| 918 | - $options['model'] = 'claude-haiku-4-5-20251001'; | |
| 1193 | + $current_model = $options['model']; | |
| 1194 | + if (isset($map[$current_model])) { | |
| 1195 | + $entry = $map[$current_model]; | |
| 1196 | + $options['model'] = $entry['to']; | |
| 919 | 1197 | $migrated = true; |
| 920 | - $migration_message = 'Your chatbot model has been automatically updated from Claude Haiku 3.5 to Claude Haiku 4.5 due to Anthropic deprecating the older model.'; | |
| 921 | - } | |
| 922 | - | |
| 923 | - // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest | |
| 924 | - if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) { | |
| 925 | - $options['model'] = 'gpt-5.1-chat-latest'; | |
| 926 | - $migrated = true; | |
| 927 | 1198 | $migration_message = sprintf( |
| 928 | - 'Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.', | |
| 929 | - $current_model | |
| 1199 | + 'Your chatbot model has been automatically updated from %s to %s %s.', | |
| 1200 | + $current_model, | |
| 1201 | + $entry['label'], | |
| 1202 | + $entry['reason'] | |
| 930 | 1203 | ); |
| 931 | 1204 | } |
| 932 | 1205 | |
| 933 | - // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini | |
| 934 | - if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) { | |
| 935 | - $options['model'] = 'gpt-5-mini'; | |
| 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']; | |
| 936 | 1214 | $migrated = true; |
| 937 | - $migration_message = sprintf( | |
| 938 | - 'Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.', | |
| 939 | - $current_model | |
| 940 | - ); | |
| 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 | + )); | |
| 941 | 1221 | } |
| 942 | 1222 | |
| 943 | 1223 | if ($migrated) { |
| 944 | 1224 | update_option('mxchat_options', $options); |
| @@ -965,8 +1245,100 @@ | ||
| 965 | 1245 | delete_option('mxchat_model_migration_message'); |
| 966 | 1246 | } |
| 967 | 1247 | } |
| 968 | 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 | + | |
| 969 | 1341 | function mxchat_activate() { |
| 970 | 1342 | global $wpdb; |
| 971 | 1343 | $charset_collate = $wpdb->get_charset_collate(); |
| 972 | 1344 | |
| @@ -974,8 +1346,12 @@ | ||
| 974 | 1346 | |
| 975 | 1347 | // Create chat transcripts table with improved function |
| 976 | 1348 | mxchat_create_chat_transcripts_table(); |
| 977 | 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 | + | |
| 978 | 1354 | // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns |
| 979 | 1355 | $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content'; |
| 980 | 1356 | $sql_system_prompt = "CREATE TABLE $system_prompt_table ( |
| 981 | 1357 | id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, |
| @@ -1037,8 +1413,11 @@ | ||
| 1037 | 1413 | |
| 1038 | 1414 | // Create per-session satisfaction ratings table (v3.2.6) |
| 1039 | 1415 | mxchat_create_session_ratings_table(); |
| 1040 | 1416 | |
| 1417 | + // Create Vector Store file-mapping table (v3.2.20, plan 15b5c6) | |
| 1418 | + mxchat_create_vectorstore_files_table(); | |
| 1419 | + | |
| 1041 | 1420 | // Ensure additional columns in system prompt table |
| 1042 | 1421 | $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table"); |
| 1043 | 1422 | if (!empty($existing_system_columns)) { |
| 1044 | 1423 | $existing_system_column_names = array_column($existing_system_columns, 'Field'); |
| @@ -1087,10 +1466,11 @@ | ||
| 1087 | 1466 | |
| 1088 | 1467 | // Setup cron jobs |
| 1089 | 1468 | mxchat_setup_cron_jobs(); |
| 1090 | 1469 | |
| 1091 | - // Update version | |
| 1092 | - update_option('mxchat_plugin_version', MXCHAT_VERSION); | |
| 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); | |
| 1093 | 1473 | |
| 1094 | 1474 | //error_log("MxChat: Activation function completed"); |
| 1095 | 1475 | } |
| 1096 | 1476 | |
| @@ -1105,23 +1485,29 @@ | ||
| 1105 | 1485 | if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { |
| 1106 | 1486 | // Set flag to use fallback system |
| 1107 | 1487 | update_option('mxchat_use_fallback_rate_limits', true); |
| 1108 | 1488 | update_option('mxchat_next_rate_limit_check', time() + 3600); |
| 1109 | - return; | |
| 1110 | - } | |
| 1111 | - | |
| 1112 | - // Schedule the rate limit reset cron job | |
| 1113 | - $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits'); | |
| 1114 | - | |
| 1115 | - if ($result === false) { | |
| 1116 | - // Fallback if scheduling fails | |
| 1117 | - update_option('mxchat_use_fallback_rate_limits', true); | |
| 1118 | - update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 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. | |
| 1119 | 1496 | } else { |
| 1120 | - // Clear fallback flags if cron scheduling succeeded | |
| 1121 | - delete_option('mxchat_use_fallback_rate_limits'); | |
| 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 | + } | |
| 1122 | 1508 | } |
| 1123 | - | |
| 1509 | + | |
| 1124 | 1510 | // Schedule transcript cleanup if configured (bucket dropdown OR custom retention-days > 0) |
| 1125 | 1511 | $transcript_options = get_option('mxchat_transcripts_options', array()); |
| 1126 | 1512 | $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never'; |
| 1127 | 1513 | $custom_retention = isset($transcript_options['mxchat_retention_days']) ? (int) $transcript_options['mxchat_retention_days'] : 0; |
| @@ -1143,8 +1529,9 @@ | ||
| 1143 | 1529 | // Clear scheduled cron jobs |
| 1144 | 1530 | wp_clear_scheduled_hook('mxchat_reset_rate_limits'); |
| 1145 | 1531 | wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts'); |
| 1146 | 1532 | wp_clear_scheduled_hook('mxchat_send_delayed_transcript'); |
| 1533 | + wp_clear_scheduled_hook('mxchat_model_liveness_check'); | |
| 1147 | 1534 | |
| 1148 | 1535 | // Clear fallback options |
| 1149 | 1536 | delete_option('mxchat_use_fallback_rate_limits'); |
| 1150 | 1537 | delete_option('mxchat_next_rate_limit_check'); |
| @@ -1164,17 +1551,25 @@ | ||
| 1164 | 1551 | return; |
| 1165 | 1552 | } |
| 1166 | 1553 | |
| 1167 | 1554 | $next_check = get_option('mxchat_next_rate_limit_check', 0); |
| 1168 | - | |
| 1555 | + | |
| 1169 | 1556 | if (time() >= $next_check) { |
| 1170 | - // Only run reset if the MxChat_Integrator class exists | |
| 1171 | - if (class_exists('MxChat_Integrator')) { | |
| 1172 | - $integrator = new MxChat_Integrator(); | |
| 1173 | - if (method_exists($integrator, 'mxchat_reset_rate_limits')) { | |
| 1174 | - $integrator->mxchat_reset_rate_limits(); | |
| 1175 | - update_option('mxchat_next_rate_limit_check', time() + 3600); | |
| 1176 | - } | |
| 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); | |
| 1177 | 1572 | } |
| 1178 | 1573 | } |
| 1179 | 1574 | } |
| 1180 | 1575 | |
| @@ -1186,9 +1581,9 @@ | ||
| 1186 | 1581 | global $wpdb; |
| 1187 | 1582 | |
| 1188 | 1583 | try { |
| 1189 | 1584 | $current_version = get_option('mxchat_plugin_version', '0.0.0'); |
| 1190 | - $plugin_version = MXCHAT_VERSION; | |
| 1585 | + $plugin_version = MXCHAT_BASE_VERSION; | |
| 1191 | 1586 | |
| 1192 | 1587 | // Always ensure critical tables exist (even if version matches) |
| 1193 | 1588 | // This handles manual table deletion or fresh installs |
| 1194 | 1589 | $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; |
| @@ -1193,12 +1588,16 @@ | ||
| 1193 | 1588 | // This handles manual table deletion or fresh installs |
| 1194 | 1589 | $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts'; |
| 1195 | 1590 | $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; |
| 1196 | 1591 | |
| 1592 | + $sessions_table = $wpdb->prefix . 'mxchat_sessions'; | |
| 1593 | + | |
| 1197 | 1594 | $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table; |
| 1198 | 1595 | $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; |
| 1199 | - | |
| 1200 | - if (!$chat_exists || !$queue_exists) { | |
| 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) { | |
| 1201 | 1600 | //error_log("MxChat: Critical tables missing, running activation"); |
| 1202 | 1601 | mxchat_activate(); |
| 1203 | 1602 | } |
| 1204 | 1603 | |
| @@ -1267,8 +1666,55 @@ | ||
| 1267 | 1666 | if (version_compare($current_version, '3.2.4', '<')) { |
| 1268 | 1667 | mxchat_backfill_active_embedding_model(); |
| 1269 | 1668 | } |
| 1270 | 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 | + | |
| 1271 | 1717 | // Run full activation to ensure everything is up to date |
| 1272 | 1718 | mxchat_activate(); |
| 1273 | 1719 | |
| 1274 | 1720 | // Run migration functions |
| @@ -1273,12 +1719,11 @@ | ||
| 1273 | 1719 | |
| 1274 | 1720 | // Run migration functions |
| 1275 | 1721 | mxchat_migrate_live_agent_status(); |
| 1276 | 1722 | |
| 1277 | - // Add the cleanup function for version 2.1.8 | |
| 1278 | - if (version_compare($current_version, '2.1.8', '<')) { | |
| 1279 | - $deleted = mxchat_cleanup_orphaned_chat_history(); | |
| 1280 | - } | |
| 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.) | |
| 1281 | 1726 | |
| 1282 | 1727 | // Update version LAST |
| 1283 | 1728 | update_option('mxchat_plugin_version', $plugin_version); |
| 1284 | 1729 | |
| @@ -1291,8 +1736,170 @@ | ||
| 1291 | 1736 | } |
| 1292 | 1737 | } |
| 1293 | 1738 | |
| 1294 | 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 | +/** | |
| 1295 | 1902 | * Ensure tables exist on every admin load for fresh installations |
| 1296 | 1903 | * This is a safety net for cases where activation hook doesn't fire |
| 1297 | 1904 | */ |
| 1298 | 1905 | function mxchat_ensure_tables_exist() { |
| @@ -1312,12 +1919,16 @@ | ||
| 1312 | 1919 | |
| 1313 | 1920 | $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; |
| 1314 | 1921 | $queue_table = $wpdb->prefix . 'mxchat_processing_queue'; |
| 1315 | 1922 | |
| 1923 | + $sessions_table = $wpdb->prefix . 'mxchat_sessions'; | |
| 1924 | + | |
| 1316 | 1925 | $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name; |
| 1317 | 1926 | $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table; |
| 1318 | - | |
| 1319 | - if (!$chat_exists || !$queue_exists) { | |
| 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) { | |
| 1320 | 1931 | //error_log("MxChat: Tables missing on admin load, running activation"); |
| 1321 | 1932 | mxchat_activate(); |
| 1322 | 1933 | } |
| 1323 | 1934 | } |
| @@ -1322,49 +1933,116 @@ | ||
| 1322 | 1933 | } |
| 1323 | 1934 | } |
| 1324 | 1935 | |
| 1325 | 1936 | /** |
| 1326 | - * Clean up orphaned chat history options from the wp_options table | |
| 1327 | - * @return int Number of options deleted | |
| 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. | |
| 1328 | 1953 | */ |
| 1329 | -function mxchat_cleanup_orphaned_chat_history() { | |
| 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) { | |
| 1330 | 1979 | global $wpdb; |
| 1331 | - $count = 0; | |
| 1332 | 1980 | |
| 1333 | - // Get all option keys that match our pattern | |
| 1334 | - $history_options = $wpdb->get_results( | |
| 1335 | - "SELECT option_name FROM {$wpdb->options} | |
| 1336 | - WHERE option_name LIKE 'mxchat_history_%'" | |
| 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 | |
| 1337 | 1998 | ); |
| 1338 | 1999 | |
| 1339 | - if (!empty($history_options)) { | |
| 1340 | - foreach ($history_options as $option) { | |
| 1341 | - // Extract the session ID from the option name | |
| 1342 | - $session_id = str_replace('mxchat_history_', '', $option->option_name); | |
| 2000 | + if (empty($rows)) { | |
| 2001 | + $state['done'] = true; | |
| 2002 | + update_option('mxchat_legacy_history_cleanup', $state, 'no'); | |
| 2003 | + return 0; | |
| 2004 | + } | |
| 1343 | 2005 | |
| 1344 | - // Check if this session still exists in the custom table | |
| 1345 | - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts'; | |
| 1346 | - $exists = $wpdb->get_var( | |
| 1347 | - $wpdb->prepare( | |
| 1348 | - "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", | |
| 1349 | - $session_id | |
| 1350 | - ) | |
| 1351 | - ); | |
| 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 | + } | |
| 1352 | 2011 | |
| 1353 | - // If session doesn't exist in the main table, delete the option | |
| 1354 | - if ($exists == 0) { | |
| 1355 | - delete_option($option->option_name); | |
| 1356 | - // Also delete related metadata | |
| 1357 | - delete_option("mxchat_email_{$session_id}"); | |
| 1358 | - delete_option("mxchat_name_{$session_id}"); | |
| 1359 | - delete_option("mxchat_agent_name_{$session_id}"); | |
| 1360 | - $count++; | |
| 1361 | - } | |
| 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; | |
| 1362 | 2031 | } |
| 1363 | 2032 | } |
| 2033 | +} | |
| 1364 | 2034 | |
| 1365 | - return $count; | |
| 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); | |
| 1366 | 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'); | |
| 1367 | 2045 | |
| 1368 | 2046 | function mxchat_migrate_live_agent_status() { |
| 1369 | 2047 | $options = get_option('mxchat_options', []); |
| 1370 | 2048 | |
| @@ -1467,8 +2145,9 @@ | ||
| 1467 | 2145 | add_action('init', 'mxchat_check_fallback_rate_limits', 5); |
| 1468 | 2146 | |
| 1469 | 2147 | // Add migration notice hook |
| 1470 | 2148 | add_action('admin_notices', 'mxchat_show_migration_notice'); |
| 2149 | + add_action('admin_notices', 'mxchat_show_model_access_notice'); | |
| 1471 | 2150 | |
| 1472 | 2151 | // Initialize classes with error handling |
| 1473 | 2152 | try { |
| 1474 | 2153 | // Initialize admin classes |
| @@ -1493,8 +2172,15 @@ | ||
| 1493 | 2172 | if (class_exists('MxChat_Content_Generator')) { |
| 1494 | 2173 | new MxChat_Content_Generator(); |
| 1495 | 2174 | } |
| 1496 | 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 | + | |
| 1497 | 2183 | // Initialize REST API globally — endpoints must be registered on |
| 1498 | 2184 | // every request (admin and frontend) so they're reachable via /wp-json/. |
| 1499 | 2185 | // Endpoints are auth-gated and locked until the site owner generates |
| 1500 | 2186 | // a token in MxChat → API Access. |
| @@ -1619,9 +2305,9 @@ | ||
| 1619 | 2305 | */ |
| 1620 | 2306 | function mxchat_save_session_rating() { |
| 1621 | 2307 | global $wpdb; |
| 1622 | 2308 | |
| 1623 | - $session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''; | |
| 2309 | + $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : ''; | |
| 1624 | 2310 | $bot_id = isset($_POST['bot_id']) ? sanitize_text_field(wp_unslash($_POST['bot_id'])) : 'default'; |
| 1625 | 2311 | $rating_raw = isset($_POST['rating']) ? (int) $_POST['rating'] : 0; |
| 1626 | 2312 | $feedback = isset($_POST['feedback']) ? sanitize_textarea_field(wp_unslash($_POST['feedback'])) : ''; |
| 1627 | 2313 | |