is_activated; } /** * Get plugin options * @return array */ public function get_options() { return $this->options; } public function __construct($knowledge_manager = null) { $this->options = get_option('mxchat_options'); $this->chat_count = get_option('mxchat_chat_count', 0); $this->is_activated = $this->is_license_active(); $this->knowledge_manager = $knowledge_manager; // Seed defaults on init, not here — the constructor runs on // plugins_loaded, before the mxchat textdomain loads (init, priority 10), // so translating the default strings here both triggers WP 6.7's // _load_textdomain_just_in_time notice and stores the untranslated // English fallbacks. Priority 20 lands after mxchat_load_textdomain(). if (!$this->options) { add_action('init', array($this, 'initialize_default_options'), 20); } // Add admin menu and initialize settings add_action('admin_menu', array($this, 'mxchat_add_plugin_page')); // Pro & Extensions registers at priority 30 so it always lands last in // the sidebar — below API Access (priority 20) and below any other // submenu that hooks at default priority 10. add_action('admin_menu', array($this, 'mxchat_add_pro_extensions_page'), 30); // Onboarding visibility — runs LAST so it can remove the submenu after every // other add_submenu_page() call. The page stays reachable by direct URL. add_action('admin_menu', array($this, 'mxchat_apply_onboarding_visibility'), 999); add_action('admin_init', array($this, 'mxchat_page_init')); add_action('admin_init', array($this, 'mxchat_prompts_page_init')); add_action('admin_enqueue_scripts', array($this, 'mxchat_enqueue_admin_assets')); // Add body class for the Onboarding wizard (plan-905439) so the // chrome-surgery CSS in admin-onboarding-wizard.css can scope its // WP-sidebar collapse to this page only. add_filter('admin_body_class', array($this, 'mxchat_add_onboarding_body_class')); add_action('wp_ajax_mxchat_delete_chat_history', array($this, 'mxchat_delete_chat_history')); add_action('admin_post_mxchat_delete_prompt', array($this, 'mxchat_handle_delete_prompt')); add_action('wp_ajax_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history')); add_action('wp_ajax_nopriv_mxchat_fetch_chat_history', array($this, 'mxchat_fetch_chat_history')); add_action('wp_ajax_mxchat_fetch_conversation', array($this, 'mxchat_fetch_conversation')); add_action('wp_footer', array($this, 'mxchat_append_chatbot_to_body')); add_action('admin_head-mxchat-prompts', array($this, 'mxchat_enqueue_admin_assets')); add_action('admin_head-toplevel_page_mxchat-max', array($this, 'mxchat_enqueue_admin_assets')); add_action('admin_notices', array($this, 'mxchat_display_admin_notice')); add_action('admin_post_mxchat_delete_all_prompts', array($this, 'mxchat_handle_delete_all_prompts')); add_action('admin_post_mxchat_add_intent', array($this, 'mxchat_handle_add_intent')); add_action('admin_post_mxchat_delete_intent', array($this, 'mxchat_handle_delete_intent')); add_action('admin_post_mxchat_edit_intent', array($this, 'mxchat_handle_edit_intent')); add_action('wp_ajax_mxchat_export_transcripts', array($this, 'export_chat_transcripts')); // Leads tab (inside Transcripts) add_action('wp_ajax_mxchat_fetch_leads', array($this, 'mxchat_fetch_leads')); add_action('wp_ajax_mxchat_delete_leads', array($this, 'mxchat_delete_leads')); add_action('wp_ajax_mxchat_export_leads', array($this, 'mxchat_export_leads')); add_action('admin_init', array($this, 'mxchat_transcripts_page_init')); add_action('wp_ajax_dismiss_live_agent_notice', array($this, 'dismiss_live_agent_notice')); add_action('wp_ajax_dismiss_theme_migration_notice', array($this, 'dismiss_theme_migration_notice')); add_action('mxchat_cleanup_old_transcripts', array($this, 'cleanup_old_transcripts')); // Self-heal: the cleanup event is otherwise only scheduled at activation or // when the retention setting CHANGES — if it is ever lost (deactivate cycle, // cron-option wipe, DB restore) nothing re-registers it and retention goes // silently inert while the UI still says it is on (plan-bc08a6). add_action('admin_init', array($this, 'ensure_transcript_cleanup_scheduled')); add_action('admin_init', array($this, 'register_pinecone_settings')); add_action('admin_init', array($this, 'register_openai_vectorstore_settings')); add_action('admin_notices', array($this, 'display_admin_notices')); add_action('wp_ajax_mxchat_test_streaming_actual', [$this, 'mxchat_handle_test_streaming_actual']); add_action('wp_ajax_mxchat_test_streaming', [$this, 'mxchat_handle_test_streaming']); // Keep existing as fallback add_action('wp_ajax_mxchat_test_vectorstore_connection', array($this, 'mxchat_test_vectorstore_connection')); // wp_ajax_mxchat_save_selected_bot is registered (and handled) in // admin/class-ajax-handler.php — a duplicate registration here pointed // at a method this class never defined, a load-order-dependent fatal // waiting to fire (plan 52bcad). add_action('wp_ajax_mxchat_fetch_openrouter_models', array($this, 'fetch_openrouter_models')); add_action('wp_ajax_mxchat_get_rag_context', array($this, 'mxchat_get_rag_context')); // Actions page AJAX handlers add_action('wp_ajax_mxchat_fetch_actions_list', array($this, 'mxchat_fetch_actions_list')); add_action('wp_ajax_mxchat_toggle_action_status', array($this, 'mxchat_toggle_action_status')); add_action('wp_ajax_mxchat_bulk_delete_actions', array($this, 'mxchat_bulk_delete_actions')); add_action('wp_ajax_mxchat_add_intent_ajax', array($this, 'mxchat_add_intent_ajax')); add_action('wp_ajax_mxchat_edit_intent_ajax', array($this, 'mxchat_edit_intent_ajax')); add_action('wp_ajax_mxchat_delete_intent_ajax', array($this, 'mxchat_delete_intent_ajax')); add_action('wp_ajax_mxchat_add_phrase', array($this, 'mxchat_add_phrase_ajax')); add_action('wp_ajax_mxchat_delete_phrase', array($this, 'mxchat_delete_phrase_ajax')); add_action('wp_ajax_mxchat_get_phrases', array($this, 'mxchat_get_phrases_ajax')); add_action('wp_ajax_mxchat_delete_legacy_phrases', array($this, 'mxchat_delete_legacy_phrases_ajax')); // Slack test connection add_action('wp_ajax_mxchat_test_slack_connection', array($this, 'mxchat_test_slack_connection')); // Translation handlers add_action('wp_ajax_mxchat_translate_messages', array($this, 'mxchat_translate_messages')); add_action('wp_ajax_mxchat_get_transcript_translation', array($this, 'mxchat_get_transcript_translation')); // 3.2.3: Embedding model switch protection add_action('wp_ajax_mxchat_check_embedding_switch', array($this, 'mxchat_check_embedding_switch_ajax')); add_action('wp_ajax_mxchat_dismiss_embedding_mismatch', array($this, 'mxchat_dismiss_embedding_mismatch_ajax')); add_action('wp_ajax_mxchat_dismiss_telegram_secret_notice', array($this, 'mxchat_dismiss_telegram_secret_notice_ajax')); add_action('admin_notices', array($this, 'mxchat_embedding_mismatch_notice')); add_action('admin_notices', array($this, 'mxchat_telegram_secret_notice')); } /** * Nudge admins to configure a Telegram webhook secret (plan-0c17b5). * * Shown only when a Telegram bot token is configured (integration active) * AND no webhook secret is set. Without a secret the webhook falls back to a * Telegram source-IP check — safer than the old fail-open, but a real secret * is the recommended protection. Dismissible; does not block anything. */ public function mxchat_telegram_secret_notice() { if (!current_user_can('manage_options')) { return; } $options = get_option('mxchat_options', array()); $has_token = !empty($options['telegram_bot_token']); $has_secret = !empty($options['telegram_webhook_secret']); if (!$has_token) { return; } // Inbound rejections recorded by verify_telegram_request() (plan 30398e). // When the webhook is actually being rejected this stops being a hardening // suggestion and becomes an outage report: it shows even when a secret IS // set (a wrong or unregistered secret rejects just as hard as none), and it // ignores the dismissal flag, because a nudge someone dismissed in July // must not silence live breakage. It self-clears on the first accepted // request, so a fixed install stops nagging without anyone touching it. $rejects = get_option('mxchat_telegram_webhook_rejects', array()); $reject_count = (is_array($rejects) && !empty($rejects['count'])) ? (int) $rejects['count'] : 0; if ($reject_count < 1) { // Nothing is failing — the original advisory, unchanged. if ($has_secret) { return; } if (get_option('mxchat_dismissed_telegram_secret_notice', '') === '1') { return; } } $settings_url = admin_url('admin.php?page=mxchat-settings#integrations-telegram'); ?> 0) : ?>
$is_mismatch, 'active_model' => $active_model, 'active_label' => MxChat_Utils::embedding_model_label($active_model), 'new_model' => $new_model, 'new_label' => MxChat_Utils::embedding_model_label($new_model), 'dims_differ' => ($active_dims > 0 && $new_dims > 0 && $active_dims !== $new_dims), 'active_dims' => $active_dims, 'new_dims' => $new_dims, )); } /** * 3.2.3: Dismiss the persistent mismatch banner. Tied to the active+selected * pair so the banner reappears on the next switch event. */ public function mxchat_dismiss_embedding_mismatch_ajax() { check_ajax_referer('mxchat_admin_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(__('Unauthorized', 'mxchat')); } $options = get_option('mxchat_options', array()); $selected = MxChat_Utils::get_selected_embedding_model($options); $active = MxChat_Utils::get_active_embedding_model(); update_option('mxchat_dismissed_embedding_mismatch', $active . '|' . $selected, false); wp_send_json_success(); } /** * 3.2.3: Persistent admin banner shown whenever the active embedding model * (last used to actually embed something) differs from the currently * selected model. Pure option comparison — no DB queries on every page * load. The banner auto-clears once both match again, i.e. after a delete * + re-embed cycle. */ public function mxchat_embedding_mismatch_notice() { if (!current_user_can('manage_options')) { return; } $options = get_option('mxchat_options', array()); $selected = MxChat_Utils::get_selected_embedding_model($options); $active = MxChat_Utils::get_active_embedding_model(); if (empty($active) || empty($selected) || $active === $selected) { return; } $dismissed = get_option('mxchat_dismissed_embedding_mismatch', ''); if ($dismissed === $active . '|' . $selected) { return; } $active_label = MxChat_Utils::embedding_model_label($active); $selected_label = MxChat_Utils::embedding_model_label($selected); $active_dims = MxChat_Utils::embedding_model_dimensions($active); $selected_dims = MxChat_Utils::embedding_model_dimensions($selected); $dims_differ = ($active_dims > 0 && $selected_dims > 0 && $active_dims !== $selected_dims); $kb_url = admin_url('admin.php?page=mxchat-prompts'); $actions_url = admin_url('admin.php?page=mxchat-actions'); ?> '', 'xai_api_key' => '', 'claude_api_key' => '', 'deepseek_api_key' => '', 'voyage_api_key' => '', 'gemini_api_key' => '', 'enable_streaming_toggle' => 'off', 'enable_web_search' => 'off', 'embedding_model' => 'text-embedding-ada-002', 'system_prompt_instructions' => 'You are an AI Chatbot assistant for this website. Your main goal is to assist visitors with questions and provide helpful information. Here are your key guidelines: # Response Style - CRITICALLY IMPORTANT - MAXIMUM LENGTH: 1-3 short sentences per response - Ultra-concise: Get straight to the answer with no filler - No introductions like "Sure!" or "I\'d be happy to help" - No phrases like "based on my knowledge" or "according to information" - No explanatory text before giving the answer - No summaries or repetition - Hyperlink all URLs - Respond in user\'s language - Minor chit chat or conversation is okay, but try to keep it focused on [insert topic] # Knowledge Base Requirements - PREVENT HALLUCINATIONS - ONLY answer questions using information explicitly provided in OFFICIAL KNOWLEDGE DATABASE CONTENT sections marked with ===== delimiters - If required information is NOT in the knowledge database: "I don\'t have enough information in my knowledge base to answer that question accurately." - NEVER invent or hallucinate URLs, links, product specs, procedures, dates, statistics, names, contacts, or company information - When knowledge base information is unclear or contradictory, acknowledge the limitation rather than guessing - Better to admit insufficient information than provide inaccurate answers', 'model' => 'gpt-5.6-sol', 'rate_limit_logged_out' => '100', 'role_rate_limits' => array(), 'rate_limit_message' => esc_html__('Rate limit exceeded. Please try again later.', 'mxchat'), 'enable_email_block' => '', 'email_blocker_header_content' => __("Let's get started. Enter your email to begin chatting with us.
", 'mxchat'), 'email_blocker_button_text' => esc_html__('Start Chat', 'mxchat'), 'enable_name_field' => 'off', // NEW 'name_field_placeholder' => esc_html__('Enter your name', 'mxchat'), // NEW 'enable_consent_checkbox' => 'off', // b062c4 — default OFF: changes an existing form on every install 'consent_checkbox_label' => __('I agree to the Privacy Policy.', 'mxchat'), 'consent_checkbox_required' => 'off', // Lead capture options (c0cfaf). Both default to today's behaviour: // the form is hidden from logged-in visitors, and email is required. 'lead_capture_logged_in_toggle' => 'off', 'lead_capture_require_email_toggle' => 'on', 'top_bar_title' => esc_html__('MxChat', 'mxchat'), 'intro_message' => __('Hello! How can I assist you today?', 'mxchat'), 'ai_agent_text' => esc_html__('AI Agent', 'mxchat'), 'input_copy' => esc_html__('How can I assist?', 'mxchat'), 'append_to_body' => 'off', 'post_type_visibility_mode' => 'all', // 'all', 'include', 'exclude' 'post_type_visibility_list' => array(), // Array of post type slugs 'contextual_awareness_toggle' => 'off', 'citation_links_toggle' => 'on', 'satisfaction_rating_enabled' => 'off', 'satisfaction_rating_idle_seconds' => 60, 'satisfaction_rating_question' => '', 'satisfaction_rating_thanks' => '', 'satisfaction_rating_placeholder' => '', 'satisfaction_rating_saved' => '', 'close_button_color' => '#fff', 'chatbot_bg_color' => '#fff', 'user_message_bg_color' => '#fff', 'user_message_font_color' => '#212121', 'bot_message_bg_color' => '#212121', 'bot_message_font_color' => '#fff', 'top_bar_bg_color' => '#212121', 'send_button_font_color' => '#212121', 'chat_input_font_color' => '#212121', 'chatbot_background_color' => '#212121', 'icon_color' => '#fff', 'enable_woocommerce_integration' => '0', 'link_target_toggle' => 'off', 'pre_chat_message' => esc_html__('Hey there! Ask me anything!', 'mxchat'), // New fields for Loops Integration 'loops_api_key' => '', 'loops_mailing_list' => '', 'triggered_phrase_response' => __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'), 'email_capture_response' => __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'), 'popular_question_1' => '', 'popular_question_2' => '', 'popular_question_3' => '', 'pdf_intent_trigger_text' => __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'), 'pdf_intent_success_text' => __("I've processed the PDF. What questions do you have about it?", 'mxchat'), 'pdf_intent_error_text' => __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'), 'pdf_max_pages' => 69, 'show_pdf_upload_button' => 'on', 'show_word_upload_button' => 'on', // Live Agent Integration (Slack) 'live_agent_webhook_url' => '', 'live_agent_secret_key' => '', 'live_agent_bot_token' => '', 'live_agent_message_bg_color' => '#ffffff', 'live_agent_message_font_color' => '#333333', // Telegram Integration 'telegram_status' => 'off', 'telegram_bot_token' => '', 'telegram_group_id' => '', 'telegram_webhook_secret' => '', 'telegram_notification_message' => __("I've notified a support agent. Please allow a moment for them to respond. If you'd like to continue with AI, just type \"Switch to AI\" at any time.", 'mxchat'), 'telegram_away_message' => __("I just checked, and it looks like our support team isn't personally available at the moment. If you'd like, you can leave your email address, and they'll get back to you as soon as possible. In the meantime, you can keep chatting with me — just let me know how I can help!", 'mxchat'), // Webhook handoff destination (plan d88e22, outbound-only) 'webhook_handoff_status' => 'off', 'webhook_handoff_url' => '', 'webhook_handoff_secret' => '', 'webhook_handoff_notification_message' => __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat'), 'webhook_handoff_away_message' => __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'), 'chat_toolbar_toggle' => 'off', 'mode_indicator_bg_color' => '#767676', 'mode_indicator_font_color' => '#ffffff', 'toolbar_icon_color' => '#212121', // Optimization settings 'script_loading_strategy' => 'default', // Debug settings 'debug_mode' => 'off', ); // Merge existing options with defaults $existing_options = get_option('mxchat_options', array()); $merged_options = wp_parse_args($existing_options, $default_options); // Update the options if they have changed if ($existing_options !== $merged_options) { update_option('mxchat_options', $merged_options); } // Add default limits for each role $roles = wp_roles()->get_names(); foreach ($roles as $role_id => $role_name) { $default_options['role_rate_limits'][$role_id] = '100'; } return $default_options; // Update the $this->options property $this->options = $merged_options; } public function mxchat_add_plugin_page() { // Onboarding lifecycle helpers (admin_init redirect + ajax handlers live in the file). require_once plugin_dir_path(__FILE__) . 'admin-onboarding-page.php'; // Main menu page — `mxchat-max` remains the parent slug for every MxChat submenu // (Settings, Knowledge, Transcripts, …). Hitting `?page=mxchat-max` directly now // dispatches to the Onboarding page (or Settings if the user has dismissed onboarding). add_menu_page( esc_html__('MxChat', 'mxchat'), esc_html__('MxChat', 'mxchat'), 'manage_options', 'mxchat-max', array($this, 'mxchat_create_dashboard_page'), 'dashicons-testimonial', 6 ); // Onboarding submenu — first child under MxChat (plan-d14e89). // First registration uses menu_slug === parent slug 'mxchat-max' → // WP-canonical override of the auto-duplicate "MxChat" entry. Result: the // first child shows as "Onboarding" instead of a redundant pair. add_submenu_page( 'mxchat-max', esc_html__('MxChat Onboarding', 'mxchat'), esc_html__('Onboarding', 'mxchat'), 'manage_options', 'mxchat-max', array($this, 'mxchat_create_dashboard_page') ); // Hidden route for `?page=mxchat-onboarding` (Settings "Show again" link // + legacy redirects still target this slug). Parent === null keeps it // out of the menu while remaining accessible by URL. add_submenu_page( null, esc_html__('MxChat Onboarding', 'mxchat'), esc_html__('Onboarding', 'mxchat'), 'manage_options', 'mxchat-onboarding', array($this, 'mxchat_create_dashboard_page') ); // Settings submenu — same callback as before, just at a new slug. add_submenu_page( 'mxchat-max', esc_html__('MxChat Settings', 'mxchat'), esc_html__('Settings', 'mxchat'), 'manage_options', 'mxchat-settings', array($this, 'mxchat_create_admin_page') ); // Submenu page for Knowledge add_submenu_page( 'mxchat-max', esc_html__('Prompts', 'mxchat'), esc_html__('Knowledge', 'mxchat'), 'manage_options', 'mxchat-prompts', array($this, 'mxchat_create_prompts_page') ); add_submenu_page( 'mxchat-max', esc_html__('Chat Transcripts', 'mxchat'), esc_html__('Transcripts', 'mxchat'), 'manage_options', 'mxchat-transcripts', array($this, 'mxchat_create_transcripts_page') ); add_submenu_page( 'mxchat-max', esc_html__('MxChat Actions', 'mxchat'), esc_html__('Actions', 'mxchat'), 'manage_options', 'mxchat-actions', array($this, 'mxchat_actions_page_html') ); // Content Generator page add_submenu_page( 'mxchat-max', esc_html__('Content', 'mxchat'), esc_html__('Content', 'mxchat'), 'manage_options', 'mxchat-content', array($this, 'mxchat_create_content_page') ); } /** * Register the Pro & Extensions submenu on a later admin_menu priority so it * always renders as the bottom-most item in the MxChat sidebar — below * configuration pages like API Access (priority 20). */ public function mxchat_add_pro_extensions_page() { add_submenu_page( 'mxchat-max', esc_html__('Pro & Extensions', 'mxchat'), esc_html__('Pro & Extensions', 'mxchat'), 'manage_options', 'mxchat-activation', array($this, 'mxchat_create_activation_page') ); } public function mxchat_create_addons_page() { require_once plugin_dir_path(__FILE__) . 'class-mxchat-addons.php'; $addons_page = new MxChat_Addons(); $addons_page->render_page(); } /** * Render the Content Generator admin page */ public function mxchat_create_content_page() { require_once plugin_dir_path(__FILE__) . 'admin-content-page.php'; // The Editor Assistant toggle on the Settings tab renders through // mxchat_render_field_wrapper(), which lives in admin-settings-page.php // (plan-f7df40 relocation) — load it the same way the settings page does. require_once plugin_dir_path(__FILE__) . 'admin-settings-page.php'; mxchat_render_content_page($this); } /** * Test actual streaming functionality in the WordPress environment */ public function mxchat_handle_test_streaming_actual() { check_ajax_referer('mxchat_test_streaming_nonce', 'nonce'); // A nonce is not authorization (plan-mxchat-20260731-c63fb6). This handler // reads the site's provider keys and spends them on an outbound call, so it // is billable abuse for any logged-in user who obtained the nonce. if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403); } // Check if headers have already been sent if (headers_sent()) { wp_send_json_error(['message' => 'Headers already sent - streaming not possible']); return; } // Check for required functions if (!function_exists('curl_init')) { wp_send_json_error(['message' => 'cURL not available - streaming requires cURL']); return; } // Get user's selected model and API key $options = get_option('mxchat_options', []); $selected_model = $options['model'] ?? 'gpt-5.6-sol'; // Get the provider from the model $model_parts = explode('-', $selected_model); $provider = strtolower($model_parts[0]); // Get the appropriate API key $api_key = ''; switch ($provider) { case 'gpt': case 'o1': $api_key = $options['api_key'] ?? ''; break; case 'claude': $api_key = $options['claude_api_key'] ?? ''; break; case 'grok': $api_key = $options['xai_api_key'] ?? ''; break; case 'deepseek': $api_key = $options['deepseek_api_key'] ?? ''; break; case 'gemini': $api_key = $options['gemini_api_key'] ?? ''; break; default: // Default to OpenAI for unknown models $api_key = $options['api_key'] ?? ''; $provider = 'gpt'; break; } if (empty($api_key)) { wp_send_json_error(['message' => "API key not configured for {$provider} provider"]); return; } // Test streaming with the selected model and provider try { $this->perform_streaming_test($provider, $selected_model, $api_key); } catch (Exception $e) { wp_send_json_error(['message' => 'Streaming test exception: ' . $e->getMessage()]); } } /** * Perform the actual streaming test */ private function perform_streaming_test($provider, $model, $api_key) { // Set streaming headers header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('X-Accel-Buffering: no'); // Disable nginx buffering // Prepare test message $test_message = "Please respond with exactly: 'Streaming test successful!' - send this as a short response for testing."; // Configure API request based on provider $url = ''; $headers = []; $body = []; switch ($provider) { case 'gpt': case 'o1': $url = 'https://api.openai.com/v1/chat/completions'; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]; $body = [ 'model' => $model, 'messages' => [['role' => 'user', 'content' => $test_message]], 'max_tokens' => 50, 'temperature' => 0.3, 'stream' => true ]; break; case 'claude': $url = 'https://api.anthropic.com/v1/messages'; $headers = [ 'Content-Type: application/json', 'x-api-key: ' . $api_key, 'anthropic-version: 2023-06-01' ]; $body = [ 'model' => $model, 'messages' => [['role' => 'user', 'content' => $test_message]], 'max_tokens' => 50, 'temperature' => 0.3, 'stream' => true ]; // Claude flagships from Opus 4.7 onward reject the temperature // param outright (400). Reuse the catalog's decision — this path // previously sent temperature unconditionally, so the streaming // test was broken for Opus 4.7/4.8, Fable 5 and Sonnet 5. if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'supports_temperature') && !MxChat_Model_Catalog::supports_temperature($model)) { unset($body['temperature']); } break; case 'grok': $url = 'https://api.x.ai/v1/chat/completions'; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]; $body = [ 'model' => $model, 'messages' => [['role' => 'user', 'content' => $test_message]], 'max_tokens' => 50, 'temperature' => 0.3, 'stream' => true ]; break; case 'deepseek': $url = 'https://api.deepseek.com/v1/chat/completions'; $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]; $body = [ 'model' => $model, 'messages' => [['role' => 'user', 'content' => $test_message]], 'max_tokens' => 50, 'temperature' => 0.3, 'stream' => true, // DeepSeek V4 defaults to thinking mode ON — reasoning would // consume the 50-token test budget and return no visible text. 'thinking' => ['type' => 'disabled'] ]; break; default: echo "data: " . json_encode(['error' => 'Unsupported provider for streaming test: ' . $provider]) . "\n\n"; flush(); return; } // Initialize cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use ($provider) { return $this->process_streaming_test_data($data, $provider); }); // Send initial test message echo "data: " . json_encode(['content' => '[Starting streaming test...]']) . "\n\n"; flush(); $result = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error = curl_error($ch); curl_close($ch); if ($curl_error) { echo "data: " . json_encode(['error' => 'cURL Error: ' . $curl_error]) . "\n\n"; flush(); return; } if ($http_code !== 200) { echo "data: " . json_encode(['error' => 'API returned HTTP ' . $http_code]) . "\n\n"; flush(); return; } // Send completion signal echo "data: [DONE]\n\n"; flush(); } /** * Process streaming data for the test */ private function process_streaming_test_data($data, $provider) { static $chunk_count = 0; $lines = explode("\n", $data); foreach ($lines as $line) { if (trim($line) === '') { continue; } // Handle different provider formats if ($provider === 'claude') { // Claude uses event: and data: format if (strpos($line, 'data: ') === 0) { $json_str = substr($line, 6); $json = json_decode($json_str, true); if (isset($json['type']) && $json['type'] === 'content_block_delta') { if (isset($json['delta']['text'])) { $chunk_count++; echo "data: " . json_encode([ 'content' => $json['delta']['text'], 'test_chunk' => $chunk_count ]) . "\n\n"; flush(); } } } } else { // OpenAI, X.AI, DeepSeek format if (strpos($line, 'data: ') === 0) { $json_str = substr($line, 6); if ($json_str === '[DONE]') { // Don't echo [DONE] here, let the main function handle it continue; } $json = json_decode($json_str, true); if (isset($json['choices'][0]['delta']['content'])) { $chunk_count++; echo "data: " . json_encode([ 'content' => $json['choices'][0]['delta']['content'], 'test_chunk' => $chunk_count ]) . "\n\n"; flush(); } } } } return strlen($data); } /** * Updated version of your existing test method (keep this as a fallback) */ public function mxchat_handle_test_streaming() { check_ajax_referer('mxchat_test_streaming_nonce', 'nonce'); // plan-mxchat-20260731-c63fb6 — the delegate below checks this too, but // fail here so the alias never becomes a bypass if that call is refactored. if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')], 403); } // Use the actual streaming test instead $this->mxchat_handle_test_streaming_actual(); } public function register_pinecone_settings() { register_setting( 'mxchat_pinecone_addon_options', 'mxchat_pinecone_addon_options', array( 'type' => 'array', 'sanitize_callback' => array($this, 'sanitize_pinecone_settings'), 'default' => array( 'mxchat_use_pinecone' => '0', 'mxchat_pinecone_api_key' => '', 'mxchat_pinecone_host' => '', 'mxchat_pinecone_index' => '', 'mxchat_pinecone_environment' => '', 'mxchat_pinecone_top_k' => '50' ) ) ); } public function sanitize_pinecone_settings($input) { $sanitized = array(); $sanitized['mxchat_use_pinecone'] = isset($input['mxchat_use_pinecone']) ? '1' : '0'; $sanitized['mxchat_pinecone_api_key'] = sanitize_text_field($input['mxchat_pinecone_api_key'] ?? ''); $sanitized['mxchat_pinecone_host'] = sanitize_text_field($input['mxchat_pinecone_host'] ?? ''); $sanitized['mxchat_pinecone_index'] = sanitize_text_field($input['mxchat_pinecone_index'] ?? ''); $sanitized['mxchat_pinecone_environment'] = sanitize_text_field($input['mxchat_pinecone_environment'] ?? ''); // d0cae1: this function REBUILDS the array, so the topK key must be // carried here or any form save strips it. Clamp mirrors the read site. $top_k = absint($input['mxchat_pinecone_top_k'] ?? 50); $sanitized['mxchat_pinecone_top_k'] = (string) (($top_k >= 1 && $top_k <= 1000) ? $top_k : 50); // Remove https:// from host if present $sanitized['mxchat_pinecone_host'] = str_replace(['https://', 'http://'], '', $sanitized['mxchat_pinecone_host']); // Index type (plan 362c31). The document index is opt-in, and its host // must have passed Check index (or come from Create index for me) before // the choice sticks — a classic host routed through the documents API // answers 400 on every query. The verified host is carried from the // stored option; only the AJAX handlers set it, never the form. $existing = get_option('mxchat_pinecone_addon_options', array()); $existing = is_array($existing) ? $existing : array(); $verified_host = (string) ($existing['mxchat_pinecone_docs_verified_host'] ?? ''); $index_type = (($input['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector'; $host_for_check = strtolower(trim($sanitized['mxchat_pinecone_host'], '/')); if ($index_type === 'document' && ($host_for_check === '' || $host_for_check !== strtolower($verified_host))) { $index_type = 'vector'; if (function_exists('add_settings_error')) { add_settings_error('mxchat_pinecone_addon_options', 'mxchat_pinecone_docs_unverified', __('The document index host has not been checked, so the index type stayed on Vector index. Click Check index (or Create index for me) and save again.', 'mxchat')); } } // 3e83e4: never point the live chatbot at a document index whose copy is // still running — the save keeps the previous type unless the owner // ticked Switch anyway. Only a vector → document switch is gated. $existing_type = (($existing['mxchat_pinecone_index_type'] ?? 'vector') === 'document') ? 'document' : 'vector'; if ($index_type === 'document' && $existing_type !== 'document' && class_exists('MxChat_Pinecone_Documents') && empty($input['mxchat_pinecone_docs_switch_anyway'])) { $running = MxChat_Pinecone_Documents::migration_blocks_switch($host_for_check); if ($running !== null) { $index_type = 'vector'; if (function_exists('add_settings_error')) { add_settings_error('mxchat_pinecone_addon_options', 'mxchat_pinecone_docs_copy_running', MxChat_Pinecone_Documents::switch_blocked_message($running)); } } } $sanitized['mxchat_pinecone_index_type'] = $index_type; $sanitized['mxchat_pinecone_docs_verified_host'] = $verified_host; $vector_host = str_replace(['https://', 'http://'], '', sanitize_text_field($input['mxchat_pinecone_vector_host'] ?? ($existing['mxchat_pinecone_vector_host'] ?? ''))); $sanitized['mxchat_pinecone_vector_host'] = trim($vector_host, '/'); $sanitized['mxchat_pinecone_vector_index'] = sanitize_text_field($input['mxchat_pinecone_vector_index'] ?? ($existing['mxchat_pinecone_vector_index'] ?? '')); $docs_cloud = sanitize_key($input['mxchat_pinecone_docs_cloud'] ?? ($existing['mxchat_pinecone_docs_cloud'] ?? 'aws')); $sanitized['mxchat_pinecone_docs_cloud'] = in_array($docs_cloud, array('aws', 'gcp', 'azure'), true) ? $docs_cloud : 'aws'; $docs_region = sanitize_text_field($input['mxchat_pinecone_docs_region'] ?? ($existing['mxchat_pinecone_docs_region'] ?? 'us-east-1')); $sanitized['mxchat_pinecone_docs_region'] = $docs_region !== '' ? $docs_region : 'us-east-1'; $docs_language = sanitize_key($input['mxchat_pinecone_docs_language'] ?? ($existing['mxchat_pinecone_docs_language'] ?? 'en')); $sanitized['mxchat_pinecone_docs_language'] = (class_exists('MxChat_Pinecone_Documents') && array_key_exists($docs_language, MxChat_Pinecone_Documents::languages())) ? $docs_language : 'en'; // The namespace has no form field; carry the stored value so a form save cannot drop it. if (isset($existing['mxchat_pinecone_namespace'])) { $sanitized['mxchat_pinecone_namespace'] = sanitize_text_field($existing['mxchat_pinecone_namespace']); } return $sanitized; } public function register_openai_vectorstore_settings() { register_setting( 'mxchat_openai_vectorstore_options', 'mxchat_openai_vectorstore_options', array( 'type' => 'array', 'sanitize_callback' => array($this, 'sanitize_openai_vectorstore_settings'), 'default' => array( 'mxchat_use_openai_vectorstore' => '0', 'mxchat_vectorstore_ids' => '', 'mxchat_vectorstore_max_results' => 5, 'mxchat_vectorstore_sync_enabled' => '0', 'mxchat_vectorstore_sync_store_id' => '' ) ) ); } public function sanitize_openai_vectorstore_settings($input) { $sanitized = array(); $sanitized['mxchat_use_openai_vectorstore'] = isset($input['mxchat_use_openai_vectorstore']) ? '1' : '0'; $sanitized['mxchat_vectorstore_ids'] = sanitize_text_field($input['mxchat_vectorstore_ids'] ?? ''); $sanitized['mxchat_vectorstore_max_results'] = absint($input['mxchat_vectorstore_max_results'] ?? 5); // Knowledge-base sync (write path, plan 15b5c6). Store ID may be blank — // the sync falls back to the first retrieval ID above. $sanitized['mxchat_vectorstore_sync_enabled'] = isset($input['mxchat_vectorstore_sync_enabled']) ? '1' : '0'; $sanitized['mxchat_vectorstore_sync_store_id'] = sanitize_text_field($input['mxchat_vectorstore_sync_store_id'] ?? ''); // Ensure max results is within reasonable range if ($sanitized['mxchat_vectorstore_max_results'] < 1) { $sanitized['mxchat_vectorstore_max_results'] = 1; } if ($sanitized['mxchat_vectorstore_max_results'] > 20) { $sanitized['mxchat_vectorstore_max_results'] = 20; } return $sanitized; } /** * AJAX handler to test OpenAI Vector Store connection */ public function mxchat_test_vectorstore_connection() { check_ajax_referer('mxchat_admin_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied.', 'mxchat'))); return; } $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array()); $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? ''; $mxchat_options = get_option('mxchat_options', array()); $api_key = $mxchat_options['api_key'] ?? ''; if (empty($api_key)) { wp_send_json_error(array('message' => __('OpenAI API key is not configured.', 'mxchat'))); return; } if (empty($vectorstore_ids)) { wp_send_json_error(array('message' => __('No Vector Store ID configured.', 'mxchat'))); return; } // Get the first Vector Store ID for testing $ids_array = array_map('trim', explode(',', $vectorstore_ids)); $test_id = $ids_array[0]; // Test by retrieving the Vector Store info $response = wp_remote_get( 'https://api.openai.com/v1/vector_stores/' . $test_id, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'OpenAI-Beta' => 'assistants=v2' ), 'timeout' => 30 ) ); if (is_wp_error($response)) { wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $response->get_error_message())); return; } $status_code = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($status_code === 200 && isset($body['id'])) { $file_count = $body['file_counts']['completed'] ?? 0; $name = $body['name'] ?? $test_id; wp_send_json_success(array( 'message' => sprintf( __('Connected successfully! Vector Store: %s (%d files)', 'mxchat'), esc_html($name), $file_count ) )); } elseif ($status_code === 404) { wp_send_json_error(array('message' => __('Vector Store not found. Please check the ID.', 'mxchat'))); } elseif ($status_code === 401) { wp_send_json_error(array('message' => __('Invalid API key.', 'mxchat'))); } else { $error_message = $body['error']['message'] ?? __('Unknown error occurred.', 'mxchat'); wp_send_json_error(array('message' => $error_message)); } } /** * AJAX handler to test Slack connection and validate scopes */ public function mxchat_test_slack_connection() { check_ajax_referer('mxchat_admin_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied.', 'mxchat'))); return; } $bot_token = $this->options['live_agent_bot_token'] ?? ''; if (empty($bot_token)) { wp_send_json_error(array('message' => __('Slack Bot Token is not configured. Please enter your token and save settings first.', 'mxchat'))); return; } // Test 1: Validate bot token with auth.test $auth_response = wp_remote_post('https://slack.com/api/auth.test', array( 'headers' => array( 'Authorization' => 'Bearer ' . $bot_token, 'Content-Type' => 'application/json' ), 'timeout' => 15 )); if (is_wp_error($auth_response)) { wp_send_json_error(array('message' => __('Connection failed: ', 'mxchat') . $auth_response->get_error_message())); return; } $auth_body = json_decode(wp_remote_retrieve_body($auth_response), true); if (!isset($auth_body['ok']) || !$auth_body['ok']) { $error = $auth_body['error'] ?? 'unknown_error'; $error_messages = array( 'invalid_auth' => __('Invalid bot token. Please check your token starts with xoxb-', 'mxchat'), 'not_authed' => __('No authentication token provided.', 'mxchat'), 'account_inactive' => __('The Slack workspace has been deactivated.', 'mxchat'), 'token_revoked' => __('The bot token has been revoked. Please generate a new one.', 'mxchat'), ); $message = $error_messages[$error] ?? sprintf(__('Authentication failed: %s', 'mxchat'), $error); wp_send_json_error(array('message' => $message)); return; } $team_name = $auth_body['team'] ?? 'Unknown Workspace'; $bot_name = $auth_body['user'] ?? 'Unknown Bot'; // Test 2: Check if we can list channels (tests channels:read scope) $channels_response = wp_remote_post('https://slack.com/api/conversations.list', array( 'headers' => array( 'Authorization' => 'Bearer ' . $bot_token, 'Content-Type' => 'application/json' ), 'body' => json_encode(array('limit' => 1)), 'timeout' => 15 )); $channels_body = json_decode(wp_remote_retrieve_body($channels_response), true); $can_read_channels = isset($channels_body['ok']) && $channels_body['ok']; // Test 3: Check if we can create channels (tests channels:manage scope) // We'll just check the error message without actually creating $create_response = wp_remote_post('https://slack.com/api/conversations.create', array( 'headers' => array( 'Authorization' => 'Bearer ' . $bot_token, 'Content-Type' => 'application/json' ), 'body' => json_encode(array('name' => 'mxchat-test-' . time(), 'is_private' => false)), 'timeout' => 15 )); $create_body = json_decode(wp_remote_retrieve_body($create_response), true); // If channel was created, delete it immediately if (isset($create_body['ok']) && $create_body['ok'] && isset($create_body['channel']['id'])) { wp_remote_post('https://slack.com/api/conversations.archive', array( 'headers' => array( 'Authorization' => 'Bearer ' . $bot_token, 'Content-Type' => 'application/json' ), 'body' => json_encode(array('channel' => $create_body['channel']['id'])), 'timeout' => 15 )); $can_create_channels = true; } else { $create_error = $create_body['error'] ?? ''; // name_taken means we have permission but channel exists $can_create_channels = ($create_error === 'name_taken' || (isset($create_body['ok']) && $create_body['ok'])); // Check for missing scope errors if ($create_error === 'missing_scope') { $can_create_channels = false; } } // Build result message $results = array(); $results[] = sprintf(__('Workspace: %s', 'mxchat'), esc_html($team_name)); $results[] = sprintf(__('Bot: %s', 'mxchat'), esc_html($bot_name)); $results[] = ''; $results[] = ($can_read_channels ? '✓' : '✗') . ' ' . __('channels:read - List channels', 'mxchat'); $results[] = ($can_create_channels ? '✓' : '✗') . ' ' . __('channels:manage - Create channels', 'mxchat'); $missing_scopes = array(); if (!$can_read_channels) $missing_scopes[] = 'channels:read'; if (!$can_create_channels) $missing_scopes[] = 'channels:manage'; if (!empty($missing_scopes)) { wp_send_json_error(array( 'message' => implode("\n", $results), 'missing_scopes' => $missing_scopes, 'partial' => true )); } else { wp_send_json_success(array( 'message' => implode("\n", $results) )); } } public function mxchat_display_admin_notice() { // Success notice if ($message = get_transient('mxchat_admin_notice_success')) { ?>We've temporarily disabled your Live Agent integration due to recent enhancements that have made it much better! You can easily turn it back on by going to Settings → Integrations → Toolbar and reviewing the new configuration options.
If you're using an AI-generated chatbot theme, you'll need to migrate it to match the new CSS structure. Go to Theme Settings, select your theme from the sidebar, and click the Migrate button.
' . esc_html__('Configure email notifications for new chat transcripts. You will receive an email notification when a new chat session begins.', 'mxchat') . '
'; } public function mxchat_enable_notifications_callback() { $options = get_option('mxchat_transcripts_options', array()); $enabled = isset($options['mxchat_enable_notifications']) ? $options['mxchat_enable_notifications'] : 0; ?>
0 it overrides the bucket dropdown above * and deletes transcripts older than the given number of days. Set to 0 to fall * back to the dropdown (or "Never" if the dropdown is also Never). * * Devs can override the final day count via the `mxchat_transcript_retention_days` * filter — runs in `cleanup_old_transcripts()` after this option is read. * * (plan-mxchat-20260509-9b80b1) */ public function mxchat_retention_days_callback() { $options = get_option('mxchat_transcripts_options', array()); $days = isset($options['mxchat_retention_days']) ? (int) $options['mxchat_retention_days'] : 0; ?>
apply_filters( 'mxchat_transcript_retention_days', $days )
' . esc_html__('All knowledge has been deleted successfully.', 'mxchat') . '
{$code}";
}, $text);
// Process inline code with single backticks
$text = preg_replace('/`([^`]+)`/', '$1', $text);
// Process bold text **text** or __text__
$text = preg_replace('/\*\*(.+?)\*\*/', '$1', $text);
$text = preg_replace('/__(.+?)__/', '$1', $text);
// Process italic text *text* or _text_ (but not if part of URL)
$text = preg_replace('/(?$1', $text);
$text = preg_replace('/(?$1', $text);
// Process markdown links [text](url)
$text = preg_replace_callback('/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/', function($matches) {
$link_text = esc_html($matches[1]);
$url = esc_url($matches[2]);
return "{$link_text}";
}, $text);
// Process citation-style brackets [URL]
$text = preg_replace_callback('/\[(https?:\/\/[^\]]+)\]/', function($matches) {
$url = esc_url($matches[1]);
return "{$url}";
}, $text);
// Process standalone URLs (not already in links or img src)
$text = preg_replace_callback(
'/(?)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/',
function($matches) {
$url = esc_url($matches[1]);
// Truncate display URL if too long
$display = strlen($matches[1]) > 50 ? substr($matches[1], 0, 47) . '...' : $matches[1];
return "{$display}";
},
$text
);
// Process mailto links
$text = preg_replace_callback('/\[([^\]]+)\]\((mailto:[^)]+)\)/', function($matches) {
$link_text = esc_html($matches[1]);
$mailto = esc_url($matches[2]);
return "{$link_text}";
}, $text);
// Convert paragraphs: split by double newlines, wrap in tags
// This creates proper paragraph structure instead of excessive
tags
$paragraphs = preg_split('/\n\n+/', $text);
// Filter out empty paragraphs but preserve content like "0"
$paragraphs = array_values(array_filter(array_map('trim', $paragraphs), function($p) {
return $p !== '';
}));
if (empty($paragraphs)) {
// No content after filtering
return '';
} elseif (count($paragraphs) > 1) {
// Multiple paragraphs - wrap each in
tags, convert single newlines to
$formatted_paragraphs = array_map(function($p) {
return nl2br($p);
}, $paragraphs);
$text = '
' . implode('
', $formatted_paragraphs) . '
'; } else { // Single paragraph - just convert newlines to' . wp_kses_post($error_notice) . '
' . $dismiss_button . '' . wp_kses_post($success_notice) . '
' . $dismiss_button . '' . wp_kses_post($info_notice) . '
' . $dismiss_button . '
' . esc_html__('Set message limits for each user role and customize the experience when users reach those limits. You can use {limit}, {timeframe}, {count}, and {remaining} as placeholders.', 'mxchat') . '
'; // Add markdown link documentation echo '' . esc_html__('Markdown Links Supported:', 'mxchat') . '
'; echo '' . esc_html__('You can include clickable links in your custom messages using markdown syntax:', 'mxchat') . '
'; echo '[Link text](https://example.com) - Creates a clickable link[Visit our pricing](https://example.com/pricing) - Link with custom textPlain URLs like https://example.com will also become clickable' . esc_html__('Manage all your API keys in one place. Add the API keys for the services you want to use with your chatbot.', 'mxchat') . '
'; } // OpenAI API Key public function api_key_callback() { $apiKey = isset($this->options['api_key']) ? esc_attr($this->options['api_key']) : ''; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Required for OpenAI GPT models and OpenAI embeddings. Get your API key from OpenAI Platform.', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('openai', 'api_key'); echo '' . esc_html__('Required for X.AI Grok models. Get your API key from X.AI Console.', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('xai', 'xai_api_key'); echo '' . esc_html__('Required for Anthropic Claude models. Get your API key from Anthropic Console.', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('claude', 'claude_api_key'); echo '' . esc_html__('Required for DeepSeek models. Get your API key from DeepSeek Platform.', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('deepseek', 'deepseek_api_key'); echo '' . esc_html__('Required for Google Gemini models and embeddings. Get your API key from Google AI Studio.', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('gemini', 'gemini_api_key'); echo '' . esc_html__('Required for OpenRouter models. Get your API key from OpenRouter.ai', 'mxchat') . '
'; echo $this->mxchat_provider_key_test_button('openrouter', 'openrouter_api_key'); echo '' . esc_html__('Point MxChat at any OpenAI-compatible /v1/chat/completions endpoint: Ollama, LM Studio, vLLM, llama.cpp, LocalAI, Azure OpenAI, etc. Then select "Custom (OpenAI-compatible)" in the model picker.', 'mxchat') . '
'; // Azure OpenAI quick start — consolidates the 4-field Azure recipe in one scannable callout // so admins can configure Azure without piecing it together from each field's hint. echo 'https://<resource>.openai.azure.com/openai/deployments/<deployment>', 'mxchat'), array('strong' => array(), 'code' => array())) . 'api-key header (Azure OpenAI)', 'mxchat'), array('strong' => array(), 'code' => array())) . '2024-08-01-preview', 'mxchat'), array('strong' => array(), 'code' => array())) . '' . esc_html__('Examples: Ollama http://localhost:11434/v1 · LM Studio http://localhost:1234/v1 · vLLM http://gpu:8000/v1 · Azure https://
' . esc_html__('Leave empty for unauthenticated local servers. Required for Azure / vLLM / hosted endpoints.', 'mxchat') . '
'; echo '' . esc_html__('The model identifier the upstream server expects (e.g. llama3.2, mistral, gpt-oss). For Azure this is the deployment ID — leave empty if the Base URL already includes /deployments/
' . esc_html__('Most OpenAI-compatible servers use Bearer. Azure OpenAI uses the api-key header.', 'mxchat') . '
'; echo '' . esc_html__('Appended as ?api-version=... on the request URL. Required for Azure OpenAI; leave empty for non-Azure providers.', 'mxchat') . '
'; echo '' . esc_html__('When off, embeddings and image generation continue to use OpenAI (current behavior). Turn on only if your endpoint exposes OpenAI-compatible /embeddings or /images/generations routes (e.g. Ollama, vLLM, LocalAI).', 'mxchat') . '
'; echo '' . esc_html__('Only used when "Use custom provider for embeddings" is on. The embedding model name is separate from the chat model name above (e.g. Ollama embedding models: nomic-embed-text, mxbai-embed-large). Leave blank to fall back to the chat model name.', 'mxchat') . '
'; echo '' . esc_html__('Required for Voyage AI embedding models. Get your API key from Voyage AI.', 'mxchat') . '
'; echo '' . wp_kses( sprintf( /* translators: %s: link to the Loops integration tab. */ __('Required for Loops email integration. Get your API key from Loops.so, then choose your mailing list under %s.', 'mxchat'), '' . esc_html__('Integrations, Loops', 'mxchat') . '' ), self::mxchat_loops_pointer_allowed_html() ) . '
'; } public function mxchat_loops_mailing_list_callback() { // Add error handling and type checking $loops_api_key = ''; $selected_list = ''; $nonce = wp_create_nonce('mxchat_autosave_nonce'); // Safely get the API key if (isset($this->options['loops_api_key']) && is_string($this->options['loops_api_key'])) { $loops_api_key = $this->options['loops_api_key']; } // Safely get the selected list if (isset($this->options['loops_mailing_list']) && is_string($this->options['loops_mailing_list'])) { $selected_list = $this->options['loops_mailing_list']; } if (!empty($loops_api_key)) { $lists = $this->mxchat_fetch_loops_mailing_lists($loops_api_key); if (is_array($lists) && !empty($lists)) { echo '' . esc_html__('Please select a mailing list to use with Loops.', 'mxchat') . '
'; } else { echo '' . wp_kses( self::mxchat_loops_api_key_pointer( /* translators: %s: link to the API Keys tab. */ __('No lists found. Please check your Loops API key under %s.', 'mxchat') ), self::mxchat_loops_pointer_allowed_html() ) . '
'; } } else { echo '' . wp_kses( self::mxchat_loops_api_key_pointer( /* translators: %s: link to the API Keys tab. */ __('Enter your Loops API key under %s to load mailing lists.', 'mxchat') ), self::mxchat_loops_pointer_allowed_html() ) . '
'; } } /** * Build the "API Keys" pointer used by the Loops mailing-list field. * * plan-mxchat-20260802-907a63. The Loops API key field was moved to the API * Keys tab, but this field's copy still read as though the input were beside * it, so users had nowhere to go. Both live on the SAME screen * (admin.php?page=mxchat-settings) — the key is under the API Keys tab, this * dropdown under Integrations > Loops — so the pointer is an in-page tab * switch, not a cross-page link. * * A plain href="#api-keys" is all it takes: the shared admin shell * (js/admin-sidebar.js) honours section-naming hashes on load AND on * hashchange (plan 4ede16), so ordinary anchors switch tabs — the old * data-target workaround on these pointer anchors is gone. * * @param string $template Translatable string containing one %s placeholder. * @return string */ private static function mxchat_loops_api_key_pointer($template) { return sprintf( $template, '' . esc_html__('API Keys', 'mxchat') . '' ); } /** * Allowed HTML for the Loops pointer — anchor plus the shell's tab-switch hook. */ private static function mxchat_loops_pointer_allowed_html() { return array( 'a' => array( 'href' => array(), 'data-target' => array(), ), ); } public function mxchat_triggered_phrase_response_callback() { $default_response = __('Would you like to join our mailing list? Please provide your email below.', 'mxchat'); $triggered_response = isset($this->options['triggered_phrase_response']) ? $this->options['triggered_phrase_response'] : $default_response; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Enter the instruction for the AI when a trigger keyword is detected. The AI will use this as guidance to naturally ask for the user\'s email in a conversational way.', 'mxchat') . '
'; } public function mxchat_email_capture_response_callback() { $default_response = __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat'); $email_capture_response = isset($this->options['email_capture_response']) ? $this->options['email_capture_response'] : $default_response; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Enter the instruction for the AI when a user provides their email. The AI will use this as guidance to naturally confirm the email capture in a conversational way.', 'mxchat') . '
'; } public function mxchat_pre_chat_message_callback() { // Load the entire 'mxchat_options' array $all_options = get_option('mxchat_options', []); // Retrieve the saved message or use the default value $default_message = __('Hey there! Ask me anything!', 'mxchat'); $pre_chat_message = isset($all_options['pre_chat_message']) ? $all_options['pre_chat_message'] : $default_message; // Output the textarea printf( '', esc_textarea($pre_chat_message) ); } // Callback for AI Instructions textarea public function system_prompt_instructions_callback() { // Retrieve the current value of the system prompt instructions $instructions = isset($this->options['system_prompt_instructions']) ? esc_textarea($this->options['system_prompt_instructions']) : ''; // Render the textarea field printf( '', $instructions ); // Personalization hint echo '';
echo esc_html__('Use {visitor_name} to personalize AI responses when lead capture is enabled.', 'mxchat') . '
';
echo '' . esc_html__('Example: The visitor\'s name is {visitor_name}. Address them by name.', 'mxchat') . '';
echo '
'; echo esc_html__('The chatbot is told the current date and time in your site\'s timezone with every message, so it can tell past events from upcoming ones. You can also place {current_date} or {current_datetime} in the instructions above. Note: a placeholder changes the prompt once a day (date) or every minute (date and time), which reduces how much of it your AI provider can cache; the automatic line has no such cost, so most sites do not need one.', 'mxchat'); echo '
'; // Sample instructions button echo '
' . __('Required for Brave Search integration. Get your API key from Brave Search API.', 'mxchat') . '
'; } public function mxchat_brave_image_count_callback() { $brave_image_count = isset($this->options['brave_image_count']) ? intval($this->options['brave_image_count']) : 4; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . __('Select the number of images to return (1-6).', 'mxchat') . '
'; } public function mxchat_brave_safe_search_callback() { $brave_safe_search = isset($this->options['brave_safe_search']) ? esc_attr($this->options['brave_safe_search']) : 'strict'; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Set the Safe Search level for image searches. Brave Search only supports "Strict" and "Off" options.', 'mxchat') . '
'; } public function mxchat_brave_news_count_callback() { $brave_news_count = isset($this->options['brave_news_count']) ? intval($this->options['brave_news_count']) : 3; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Select the number of news articles to retrieve (1-10).', 'mxchat') . '
'; } public function mxchat_brave_country_callback() { $brave_country = isset($this->options['brave_country']) ? esc_attr($this->options['brave_country']) : 'us'; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Enter the country code (e.g., "us" for United States).', 'mxchat') . '
'; } public function mxchat_brave_language_callback() { $brave_language = isset($this->options['brave_language']) ? esc_attr($this->options['brave_language']) : 'en'; $nonce = wp_create_nonce('mxchat_autosave_nonce'); echo '' . esc_html__('Enter the language code (e.g., "en" for English).', 'mxchat') . '
'; } // Section Callback public function mxchat_pdf_intent_section_callback() { echo '' . esc_html__('Configure the intent settings for the Chat with PDF feature.', 'mxchat') . '
'; } public function mxchat_chat_toolbar_toggle_callback() { // Get chat toolbar toggle value with fallback $chat_toolbar_toggle = isset($this->options['chat_toolbar_toggle']) ? $this->options['chat_toolbar_toggle'] : 'off'; $checked = ($chat_toolbar_toggle === 'on') ? 'checked' : ''; // Output the toggle switch echo ''; echo '' . esc_html__('Enable to display the chat toolbar, adding two icons below the chatbot input field for uploading PDF and Word documents (default is hidden).', 'mxchat') . '
'; } /** * Callback for PDF upload button toggle setting */ public function mxchat_show_pdf_upload_button_callback() { // Get toggle value with fallback $show_pdf_button = isset($this->options['show_pdf_upload_button']) ? $this->options['show_pdf_upload_button'] : 'on'; $checked = ($show_pdf_button === 'on') ? 'checked' : ''; // Output the toggle switch echo ''; echo '' . esc_html__('Enable to show the PDF upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '
'; } /** * Callback for Word upload button toggle setting */ public function mxchat_show_word_upload_button_callback() { // Get toggle value with fallback $show_word_button = isset($this->options['show_word_upload_button']) ? $this->options['show_word_upload_button'] : 'on'; $checked = ($show_word_button === 'on') ? 'checked' : ''; // Output the toggle switch echo ''; echo '' . esc_html__('Enable to show the Word document upload button in the chatbot toolbar. Disable to hide it.', 'mxchat') . '
'; } public function mxchat_pdf_intent_trigger_text_callback() { $default_text = __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat'); echo sprintf( '', esc_attr__('Enter trigger text', 'mxchat'), isset($this->options['pdf_intent_trigger_text']) ? esc_textarea($this->options['pdf_intent_trigger_text']) : esc_textarea($default_text) ); echo '' . esc_html__('Text displayed when the intent is triggered.', 'mxchat') . '
'; } public function mxchat_pdf_intent_success_text_callback() { $default_text = __("I've processed the PDF. What questions do you have about it?", 'mxchat'); echo sprintf( '', esc_attr__('Enter success text', 'mxchat'), isset($this->options['pdf_intent_success_text']) ? esc_textarea($this->options['pdf_intent_success_text']) : esc_textarea($default_text) ); echo '' . esc_html__('Text displayed when the intent is successful.', 'mxchat') . '
'; } public function mxchat_pdf_intent_error_text_callback() { $default_text = __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat'); echo sprintf( '', esc_attr__('Enter error text', 'mxchat'), isset($this->options['pdf_intent_error_text']) ? esc_textarea($this->options['pdf_intent_error_text']) : esc_textarea($default_text) ); echo '' . esc_html__('Text displayed when an error occurs during the intent.', 'mxchat') . '
'; } public function mxchat_pdf_max_pages_callback() { $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69; echo sprintf( '', esc_attr($max_pages) ); echo '' . esc_html($max_pages) . ''; echo '' . esc_html__('Set the maximum number of document pages users can upload for processing. (1-69 pages)', 'mxchat') . '
'; } public function mxchat_live_agent_status_callback() { // Always get fresh options instead of using cached $this->options $fresh_options = get_option('mxchat_options'); $status = isset($fresh_options['live_agent_status']) ? $fresh_options['live_agent_status'] : 'off'; echo ''; echo ''; } /** * Availability-schedule editor (plans 8ccaa2 + 99d7a4). * * ONE callback, parameterized by channel ('slack' | 'telegram' via the * add_settings_field $args) — the markup and CSS are shared, only the bound * option and the helper text differ. Each channel's editor renders under its * own Integrations tab and governs ONLY that channel's handoff. While the * master toggle is off the day grid is inert and handoff availability stays * governed solely by that channel's manual status toggle. * * The day inputs carry NO name attribute and are marked .mxchat-la-field so the * generic autosave skips them; the editor JS folds them into the channel's * hidden live_agent_schedule_' . esc_html($channel_label) . '', '' . esc_html($tz) . '' ); ?>
options['live_agent_away_message']) ? $this->options['live_agent_away_message'] : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '
'; } public function mxchat_live_agent_notification_message_callback() { $message = isset($this->options['live_agent_notification_message']) ? $this->options['live_agent_notification_message'] : __('Live agent has been notified.', 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '
'; } public function mxchat_live_agent_webhook_url_callback() { $webhook_url = isset($this->options['live_agent_webhook_url']) ? esc_url($this->options['live_agent_webhook_url']) : esc_url(get_option('live_agent_webhook_url', '')); printf( '', $webhook_url ); echo ''; echo '' . esc_html__('Enter your Slack webhook URL for live agent notifications.', 'mxchat') . '
'; } public function mxchat_live_agent_secret_key_callback() { printf( '', isset($this->options['live_agent_secret_key']) ? esc_attr($this->options['live_agent_secret_key']) : '' ); echo ''; echo '' . esc_html__('Secret key for validating Slack requests. Keep this secure.', 'mxchat') . '
'; } public function mxchat_live_agent_bot_token_callback() { printf( '', isset($this->options['live_agent_bot_token']) ? esc_attr($this->options['live_agent_bot_token']) : '' ); echo ''; echo '' . esc_html__('Your Slack Bot OAuth Token (starts with xoxb-). Keep this secure.', 'mxchat') . '
'; } public function mxchat_live_agent_user_ids_callback() { $user_ids = isset($this->options['live_agent_user_ids']) ? esc_textarea($this->options['live_agent_user_ids']) : ''; printf( '', $user_ids ); echo '' . esc_html__('Enter Slack User IDs of agents who should be automatically invited to chat channels (one per line). Find user IDs in Slack profiles under "More" → "Copy member ID". Example: U1234567890', 'mxchat') . '
'; } public function mxchat_live_agent_shared_channel_callback() { $value = isset($this->options['live_agent_shared_channel']) ? $this->options['live_agent_shared_channel'] : ''; printf( '', esc_attr($value) ); echo '' . esc_html__('Optional. Route ALL live agent handoffs into this one existing Slack channel — each conversation becomes its own thread there. Enter a channel ID (starts with C) or a #channel-name, and invite your bot to the channel first (/invite @YourBot). Agents reply inside a conversation\'s thread; !endchat inside the thread ends that chat. Leave blank to keep creating a separate chat- channel per conversation.', 'mxchat') . '
'; // Surface the last failed handoff so a wrong name / missing invite is // visible right where it gets fixed. A successful handoff clears this. $shared_error = get_option('mxchat_slack_shared_channel_error'); if (!empty($shared_error['error']) && trim((string) $value) !== '' && ($shared_error['configured'] ?? '') === trim((string) $value)) { echo '' . esc_html__('⚠ Last handoff could not reach this channel', 'mxchat') . ' — ' . esc_html(sprintf( /* translators: %s: Slack API error code */ __('Slack said "%s". Handoffs are falling back to per-conversation channels until this is fixed. Check the channel name or ID and make sure the bot has been invited to it.', 'mxchat'), $shared_error['error'] )) . '
'; } // Private-channel warning (plan 1a2666), recorded by the privacy probe at // configuration time or when the channel id first resolves. Posting INTO // a private channel works once the bot is a member, so everything looks // configured — but Slack delivers inbound replies from private channels // as message.groups events, which the documented app setup never // subscribes to, and agent replies silently never reach the visitor. $shared_privacy = get_option('mxchat_slack_shared_channel_privacy'); if (!empty($shared_privacy['is_private']) && trim((string) $value) !== '' && ($shared_privacy['configured'] ?? '') === trim((string) $value)) { echo '' . esc_html__('⚠ This is a private channel', 'mxchat') . ' — ' . esc_html__('Slack sends replies from private channels as message.groups events. In your Slack app, add the groups:history scope and subscribe to the message.groups bot event (alongside message.channels), then reinstall the app — otherwise agent replies posted here never reach your visitors.', 'mxchat') . '
'; } } public function mxchat_live_agent_archive_on_end_callback() { $value = isset($this->options['live_agent_archive_on_end_toggle']) ? $this->options['live_agent_archive_on_end_toggle'] : 'off'; printf( '', checked('on', $value, false) ); echo ''; echo '' . esc_html__('Keeps your Slack sidebar tidy on busy sites — each ended conversation\'s channel is archived instead of living forever. Archived channels stay searchable in Slack, so the record is never lost. Only applies to per-conversation chat- channels; a Shared Handoff Channel is never archived. If a returning visitor requests an agent again, a fresh channel is created automatically.', 'mxchat') . '
'; } /** * Telegram Integration Callbacks */ public function mxchat_telegram_section_callback() { echo '' . esc_html__('Configure Telegram integration for live agent support.', 'mxchat') . '
'; } public function mxchat_telegram_status_callback() { $fresh_options = get_option('mxchat_options'); $status = isset($fresh_options['telegram_status']) ? $fresh_options['telegram_status'] : 'off'; echo ''; echo ''; } public function mxchat_telegram_notification_message_callback() { $message = isset($this->options['telegram_notification_message']) ? $this->options['telegram_notification_message'] : __("I've notified a support agent. Please allow a moment for them to respond.", 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown when live transfer activated.', 'mxchat') . '
'; } public function mxchat_telegram_away_message_callback() { $message = isset($this->options['telegram_away_message']) ? $this->options['telegram_away_message'] : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown when live agents are offline.', 'mxchat') . '
'; } public function mxchat_telegram_bot_token_callback() { printf( '', isset($this->options['telegram_bot_token']) ? esc_attr($this->options['telegram_bot_token']) : '' ); echo ''; echo '' . esc_html__('Your Telegram Bot Token from @BotFather (e.g., 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ).', 'mxchat') . '
'; } public function mxchat_telegram_group_id_callback() { printf( '', isset($this->options['telegram_group_id']) ? esc_attr($this->options['telegram_group_id']) : '' ); echo '' . esc_html__('Your Telegram supergroup ID (starts with -100). The group must have forum topics enabled.', 'mxchat') . '
'; // Surface the last failed Telegram API call right where it gets fixed // (plan 1aeee3). Before this existed every Telegram response was // discarded — a wrong group id, a closed topic, or an oversized handoff // all failed with no trace anywhere. Kept until the next failure // overwrites it; the timestamp shows how stale it is. $tg_error = get_option('mxchat_telegram_last_error'); if (!empty($tg_error['error'])) { echo '' . esc_html__('⚠ Last Telegram API failure', 'mxchat') . ' — ' . esc_html(sprintf( /* translators: 1: Telegram API method name, 2: Telegram's error description, 3: local date and time of the failure */ __('%1$s failed with "%2$s" (%3$s). If live agent chat is working now, this may be from an earlier misconfiguration.', 'mxchat'), $tg_error['method'] ?? 'sendMessage', $tg_error['error'], !empty($tg_error['time']) ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $tg_error['time']) : __('unknown time', 'mxchat') )) . '
'; } // The inbound counterpart of the line above (plan 30398e): outbound tells you // MxChat could not reach Telegram, this one tells you Telegram reached MxChat // and was turned away. That failure previously left nothing behind but a // single error_log() line, so a Cloudflare-fronted install with no secret set // dropped every agent reply with no admin-side trace at all. Cleared // automatically by the first accepted request. $tg_rejects = get_option('mxchat_telegram_webhook_rejects'); if (is_array($tg_rejects) && !empty($tg_rejects['count'])) { $reject_count = (int) $tg_rejects['count']; echo '' . esc_html__('⚠ Incoming Telegram webhook requests are being rejected', 'mxchat') . ' — ' . esc_html(sprintf( /* translators: 1: number of rejected requests, 2: local date and time of the most recent rejection */ _n( '%1$s request rejected, most recently %2$s. Agent replies are not reaching visitors.', '%1$s requests rejected, most recently %2$s. Agent replies are not reaching visitors.', $reject_count, 'mxchat' ), number_format_i18n($reject_count), !empty($tg_rejects['last_ts']) ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $tg_rejects['last_ts']) : __('unknown time', 'mxchat') )) . ' ' . esc_html($this->mxchat_telegram_reject_advice($tg_rejects['last_reason'] ?? '')) . '
'; } } public function mxchat_telegram_webhook_secret_callback() { $secret = isset($this->options['telegram_webhook_secret']) ? $this->options['telegram_webhook_secret'] : ''; // Auto-generate secret if empty if (empty($secret)) { $secret = wp_generate_password(64, false, false); $options = get_option('mxchat_options', []); $options['telegram_webhook_secret'] = $secret; update_option('mxchat_options', $options); $this->options['telegram_webhook_secret'] = $secret; } printf( '', esc_attr($secret) ); echo ''; echo '' . esc_html__('Secret token for webhook verification. Use this when setting up your Telegram webhook with the secret_token parameter.', 'mxchat') . '
'; } /** * Webhook Handoff Callbacks (plan d88e22) */ public function mxchat_webhook_handoff_section_callback() { echo '' . esc_html__('Send live-agent handoffs to any URL you choose — your helpdesk, an automation flow, a CRM.', 'mxchat') . '
'; } public function mxchat_webhook_handoff_status_callback() { $fresh_options = get_option('mxchat_options'); $status = isset($fresh_options['webhook_handoff_status']) ? $fresh_options['webhook_handoff_status'] : 'off'; echo ''; echo ''; } public function mxchat_webhook_handoff_notification_message_callback() { $message = isset($this->options['webhook_handoff_notification_message']) ? $this->options['webhook_handoff_notification_message'] : __("I've notified our support team — they'll follow up with you soon. Meanwhile, I'm happy to keep helping.", 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown after the handoff is delivered. The chat stays in AI mode — your team follows up separately, so let the visitor know what to expect.', 'mxchat') . '
'; } public function mxchat_webhook_handoff_away_message_callback() { $message = isset($this->options['webhook_handoff_away_message']) ? $this->options['webhook_handoff_away_message'] : __('Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.', 'mxchat'); printf( '', esc_textarea($message) ); echo '' . esc_html__('Message shown when this destination is offline or outside its scheduled hours.', 'mxchat') . '
'; } public function mxchat_webhook_handoff_url_callback() { $value = isset($this->options['webhook_handoff_url']) ? $this->options['webhook_handoff_url'] : ''; printf( '', esc_attr($value) ); echo '' . esc_html__('Where handoffs are sent as a JSON POST. Must be https and publicly reachable (localhost and private-network hosts are rejected).', 'mxchat') . '
'; // Surface the last failed delivery right where it gets fixed — a handoff // that silently 404s is worse than no handoff. A successful one clears this. $webhook_error = get_option('mxchat_webhook_handoff_error'); if (!empty($webhook_error['error']) && trim((string) $value) !== '' && ($webhook_error['configured'] ?? '') === trim((string) $value)) { echo '' . esc_html__('⚠ Last handoff could not reach this URL', 'mxchat') . ' — ' . esc_html(sprintf( /* translators: %s: the delivery failure, e.g. an HTTP status or a transport error */ __('the request failed with "%s". Until this is fixed, the chatbot answers these conversations itself instead of telling visitors a human was notified.', 'mxchat'), $webhook_error['error'] )) . '
'; } } public function mxchat_webhook_handoff_secret_callback() { printf( '', isset($this->options['webhook_handoff_secret']) ? esc_attr($this->options['webhook_handoff_secret']) : '' ); echo ''; echo '' . esc_html__('Optional. When set, each POST carries an X-MxChat-Signature header (sha256 HMAC of the body) so your endpoint can verify the sender. The secret itself is never sent.', 'mxchat') . '
'; } public function mxchat_similarity_threshold_callback() { // Load from mxchat_options array $options = get_option('mxchat_options', []); // Get value from options array with default of 35 $threshold = isset($options['similarity_threshold']) ? $options['similarity_threshold'] : 35; echo ''; } public function mxchat_max_input_length_callback() { // Load from mxchat_options array (plan a3fae2 part C). $options = get_option('mxchat_options', []); // 0 = unlimited (default — preserves current behavior, no cap). $max_input_length = isset($options['max_input_length']) ? intval($options['max_input_length']) : 0; echo sprintf( '', esc_attr($max_input_length) ); } public function mxchat_rag_sources_limit_callback() { // Load from mxchat_options array $options = get_option('mxchat_options', []); // Get value from options array with default of 3 $rag_sources_limit = isset($options['rag_sources_limit']) ? intval($options['rag_sources_limit']) : 3; echo ''; } public function mxchat_rag_chunks_limit_callback() { // Load from mxchat_options array $options = get_option('mxchat_options', []); // Get value from options array with default of 15 $rag_chunks_limit = isset($options['rag_chunks_limit']) ? intval($options['rag_chunks_limit']) : 15; echo ''; } /** * Add body class on the Onboarding wizard page so CSS-only chrome surgery * (collapsing the WP admin sidebar) only applies on this page. * Plan: plan-mxchat-20260527-905439. */ public function mxchat_add_onboarding_body_class($classes) { if (isset($_GET['page']) && $_GET['page'] === 'mxchat-onboarding') { $classes .= ' mxchat-onboarding-focused'; } return $classes; } public function mxchat_enqueue_admin_assets($hook_suffix = '') { // Authorization gate (plan-mxchat-20260731-c63fb6). Previously the ONLY // guard here was the strpos() on $_GET['page'] below — which is // attacker-controlled — so ANY logged-in user (Subscriber included) could // load a page they are legitimately allowed to see, e.g. // /wp-admin/profile.php?page=mxchat, and receive every nonce this method // localizes. Three of the handlers behind those nonces verified the nonce // but checked no capability. Every MxChat menu page is registered // 'manage_options' (see mxchat_add_admin_menu), so this is a no-op for // legitimate users. if (!current_user_can('manage_options')) { return; } // Get plugin version $version = MXCHAT_VERSION; // Use file modification time for development (remove in production) if (defined('WP_DEBUG') && WP_DEBUG) { $version = filemtime(plugin_dir_path(__FILE__) . '../mxchat-basic.php'); } $current_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; $plugin_url = plugin_dir_url(__FILE__) . '../'; // Only load on MxChat pages. Prefer the server-derived $hook_suffix that // admin_enqueue_scripts passes us — unlike $_GET['page'] it cannot be // forged onto a screen MxChat does not own. Falls back to the legacy // $_GET check only when the hook is unavailable (direct/legacy callers). if ($hook_suffix !== '') { if (strpos($hook_suffix, 'mxchat') === false) { return; } } elseif (strpos($current_page, 'mxchat') === false) { return; } // Always load these on all MxChat pages $this->enqueue_core_admin_assets($plugin_url, $version); $this->enqueue_page_specific_assets($current_page, $plugin_url, $version); $this->localize_admin_scripts($current_page); } private function enqueue_core_admin_assets($plugin_url, $version) { // Core admin styles wp_enqueue_style('mxchat-admin-css', $plugin_url . 'css/admin-style.css', array(), $version); wp_enqueue_style('mxchat-knowledge-css', $plugin_url . 'css/knowledge-style.css', array(), $version); // New sidebar navigation styles (for main settings page) wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); // Core admin scripts wp_enqueue_script('mxchat-admin-js', $plugin_url . 'js/mxchat-admin.js', array('jquery'), $version, true); } private function enqueue_page_specific_assets($current_page, $plugin_url, $version) { switch ($current_page) { case 'mxchat-prompts': // Shared shell JS: tab switching, deep-linking and the mobile menu // for this page's flat nav (inline copies removed by plan c192a4). wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true); wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array( 'copied' => __('Copied', 'mxchat'), )); // Knowledge processing page assets wp_enqueue_style('mxchat-content-selector-css', $plugin_url . 'css/content-selector.css', array(), $version); wp_enqueue_script('mxchat-content-selector-js', $plugin_url . 'js/content-selector.js', array('jquery'), $version, true); // Add the knowledge processing script (common script needed for WordPress dismiss functionality) wp_enqueue_script('mxchat-knowledge-processing', $plugin_url . 'js/knowledge-processing.js', array('jquery', 'common'), $version, true); // Per-entry "View indexed content" inspector (plan-d8cb4b) reuses the // Testing tab's match-card / chunk-detail components, which are scoped // under .mxch-testing-results. Load that stylesheet here so the inspector // modal renders identically to the Testing tab. wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css'), $version); break; case 'mxchat-transcripts': // Load admin sidebar CSS first (shared styles for sidebar navigation) wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); // Load transcripts-specific styles wp_enqueue_style('mxchat-chat-transcripts-css', $plugin_url . 'css/chat-transcripts.css', array('mxchat-admin-sidebar-css'), $version); wp_enqueue_script('mxchat-transcripts-js', $plugin_url . 'js/mxchat_transcripts.js', array('jquery'), $version, true); break; case 'mxchat-actions': // Load admin sidebar CSS first (shared styles for sidebar navigation) wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); // Load actions-specific styles wp_enqueue_style('mxchat-actions-css', $plugin_url . 'css/actions.css', array('mxchat-admin-sidebar-css'), $version); wp_enqueue_script('mxchat-actions-js', $plugin_url . 'js/mxchat_actions.js', array('jquery'), $version, true); // Localize script data for actions page $is_activated = get_option('mxchat_pro_license_status') === 'active'; wp_localize_script('mxchat-actions-js', 'mxchActionsData', array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_actions_nonce'), 'addNonce' => wp_create_nonce('mxchat_add_intent_nonce'), 'editNonce' => wp_create_nonce('mxchat_edit_intent'), 'deleteNonce' => wp_create_nonce('mxchat_delete_intent_nonce'), 'toggleNonce' => wp_create_nonce('mxchat_actions_nonce'), 'addPhraseNonce' => wp_create_nonce('mxchat_add_phrase_nonce'), 'deletePhraseNonce' => wp_create_nonce('mxchat_delete_phrase_nonce'), 'getPhrasesNonce' => wp_create_nonce('mxchat_get_phrases_nonce'), 'deleteLegacyNonce' => wp_create_nonce('mxchat_delete_legacy_nonce'), 'isActivated' => $is_activated, 'i18n' => array( 'confirmDelete' => __('Are you sure you want to delete this trigger phrase?', 'mxchat'), 'confirmBulkDelete' => __('Are you sure you want to delete the selected trigger phrases?', 'mxchat'), 'saving' => __('Saving...', 'mxchat'), 'saved' => __('Saved successfully!', 'mxchat'), 'error' => __('An error occurred. Please try again.', 'mxchat'), 'proRequired' => __('This feature requires MxChat Pro.', 'mxchat'), 'addonRequired' => __('This feature requires an add-on.', 'mxchat') ) )); break; case 'mxchat-activation': // Load admin sidebar CSS first (shared styles for sidebar navigation) wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); // Load pro page-specific styles wp_enqueue_style('mxchat-pro-css', $plugin_url . 'css/admin-pro.css', array('mxchat-admin-sidebar-css'), $version); // Load pro page JavaScript wp_enqueue_script('mxchat-pro-js', $plugin_url . 'js/mxchat_pro.js', array('jquery'), $version, true); // Load activation script for license activation/deactivation wp_enqueue_script('mxchat-activation-js', $plugin_url . 'js/activation-script.js', array('jquery'), $version, true); break; case 'mxchat-content': // Load admin sidebar CSS (shared styles for sidebar navigation) wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); // Load content page-specific styles wp_enqueue_style('mxchat-content-css', $plugin_url . 'css/admin-content.css', array('mxchat-admin-sidebar-css'), $version); // Load content page JavaScript wp_enqueue_script('mxchat-content-js', $plugin_url . 'js/mxchat-content.js', array('jquery'), $version, true); break; case 'mxchat-api-access': // Shared sidebar shell (CSS + JS for tab switching / mobile menu / copy buttons). wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true); wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array( 'copied' => __('Copied', 'mxchat'), )); break; case 'mxchat-max': case 'mxchat-onboarding': // Onboarding page — uses the shared admin shell PLUS the wizard // overlay (plan-905439). admin-onboarding-wizard.css scopes the // WP-chrome surgery to body.mxchat-onboarding-focused so it only // applies on THIS page. The body class is added below via the // admin_body_class filter. wp_enqueue_style('mxchat-admin-sidebar-css', $plugin_url . 'css/admin-sidebar.css', array(), $version); wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true); wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array( 'copied' => __('Copied', 'mxchat'), )); // admin-style.css provides the .mxchat-instructions-modal-* classes // the new Behavior step's "View Sample Instructions" modal needs. // Enqueued AFTER admin-sidebar.css but BEFORE the wizard overlay // so the wizard's own rules win where they collide. plan-a2e4d6. wp_enqueue_style('mxchat-admin-style-css', $plugin_url . 'css/admin-style.css', array('mxchat-admin-sidebar-css'), $version); wp_enqueue_style('mxchat-admin-onboarding-wizard-css', $plugin_url . 'css/admin-onboarding-wizard.css', array('mxchat-admin-sidebar-css', 'mxchat-admin-style-css'), $version); wp_enqueue_script('mxchat-admin-onboarding-wizard-js', $plugin_url . 'js/admin-onboarding-wizard.js', array(), $version, true); break; default: // Settings page: load the shared shell JS for #hash deep-linking // to tabs (plan 4ede16). The page's own inline nav script owns // clicks/accordion behaviour; the shell script adds load + // hashchange activation and replaceState so plain href="#tab" // anchors and shared URLs land on the right tab. Kept inside the // default case because the settings page also needs everything // below (Testing tab chatbot + streaming assets). if ($current_page === 'mxchat-settings') { wp_enqueue_script('mxchat-admin-sidebar-js', $plugin_url . 'js/admin-sidebar.js', array(), $version, true); wp_localize_script('mxchat-admin-sidebar-js', 'MxChatAdminSidebarI18n', array( 'copied' => __('Copied', 'mxchat'), )); } wp_enqueue_script( 'mxchat-test-streaming-js', $plugin_url . 'js/mxchat-test-streaming.js', ['jquery'], $version, true ); wp_localize_script('mxchat-test-streaming-js', 'mxchatTestStreamingAjax', [ 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_test_streaming_nonce'), 'settings_nonce' => wp_create_nonce('mxchat_save_setting_nonce') ]); // Testing Tab: Load chatbot assets for the embedded testing chatbot wp_enqueue_style('mxchat-chat-css', $plugin_url . 'css/chat-style.css', array(), $version); wp_enqueue_style('mxchat-admin-testing-css', $plugin_url . 'css/admin-testing-tab.css', array('mxchat-admin-sidebar-css', 'mxchat-chat-css'), $version); wp_enqueue_script('mxchat-chat-js', $plugin_url . 'js/chat-script.js', array('jquery'), $version, true); wp_enqueue_script('mxchat-admin-testing-js', $plugin_url . 'js/admin-testing-tab.js', array('jquery', 'mxchat-chat-js'), $version, true); // Allow add-ons to enqueue their public CSS/JS for the testing chatbot do_action('mxchat_enqueue_testing_tab_assets'); // Localize mxchatChat for the chatbot JS (same settings as frontend) $options = get_option('mxchat_options', array()); $prompts_options = get_option('mxchat_prompts_options', array()); $theme_options = get_option('mxchat_theme_options', array()); $ai_theme_active = !empty($theme_options['active_ai_theme_css']); $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']); $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments; wp_localize_script('mxchat-chat-js', 'mxchatChat', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_chat_nonce'), 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol', 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on', 'contextual_awareness_toggle' => isset($options['contextual_awareness_toggle']) ? $options['contextual_awareness_toggle'] : 'off', 'link_target_toggle' => $options['link_target_toggle'] ?? 'off', 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.', 'complianz_toggle' => isset($options['complianz_toggle']) && $options['complianz_toggle'] === 'on', 'user_message_bg_color' => $options['user_message_bg_color'] ?? '#fff', 'user_message_font_color' => $options['user_message_font_color'] ?? '#212121', 'bot_message_bg_color' => $options['bot_message_bg_color'] ?? '#212121', 'bot_message_font_color' => $options['bot_message_font_color'] ?? '#fff', 'top_bar_bg_color' => $options['top_bar_bg_color'] ?? '#212121', 'send_button_font_color' => $options['send_button_font_color'] ?? '#212121', 'close_button_color' => $options['close_button_color'] ?? '#fff', 'chatbot_background_color' => $options['chatbot_background_color'] ?? '#212121', 'chatbot_bg_color' => $options['chatbot_bg_color'] ?? '#fff', 'icon_color' => $options['icon_color'] ?? '#fff', 'chat_input_font_color' => $options['chat_input_font_color'] ?? '#212121', 'chat_persistence_toggle' => 'off', // Always off for testing chatbot 'appendWidgetToBody' => 'off', 'live_agent_message_bg_color' => $options['live_agent_message_bg_color'] ?? '#ffffff', 'live_agent_message_font_color' => $options['live_agent_message_font_color'] ?? '#333333', 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off', 'mode_indicator_bg_color' => $options['mode_indicator_bg_color'] ?? '#767676', 'mode_indicator_font_color' => $options['mode_indicator_font_color'] ?? '#ffffff', 'toolbar_icon_color' => $options['toolbar_icon_color'] ?? '#212121', 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0', 'email_collection_enabled' => 'off', // No email collection in testing 'initial_email_state' => null, 'skip_email_check' => true, 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1', 'skip_inline_colors' => $skip_inline_colors, 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array() )); // Localize testing tab script data wp_localize_script('mxchat-admin-testing-js', 'mxchatAdminTestData', array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_test_nonce'), 'isAdmin' => true, 'testingEnabled' => true )); // Add testing enabled flag for the chatbot to return debug data add_action('admin_footer', function() { echo ''; }); break; } } /** * The base mxchatAdmin payload shared by every MxChat admin page. * * Extracted (plan c192a4) so page-specific re-localizations of the SAME * global — the knowledge page prints a second `var mxchatAdmin` via the * mxchat-knowledge-processing handle, and last-printed wins — can merge * their extra keys on top of this instead of silently narrowing the object * that mxchat-admin.js also reads on that page. */ private function mxchat_get_admin_base_localization() { return array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_admin_nonce'), 'admin_url' => admin_url(), 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce'), 'inline_edit_nonce' => wp_create_nonce('mxchat_save_inline_nonce'), 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'), 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'), 'actions_nonce' => wp_create_nonce('mxchat_actions_nonce'), 'add_intent_nonce' => wp_create_nonce('mxchat_add_intent_nonce'), 'edit_intent_nonce' => wp_create_nonce('mxchat_edit_intent'), 'add_phrase_nonce' => wp_create_nonce('mxchat_add_phrase_nonce'), 'delete_phrase_nonce' => wp_create_nonce('mxchat_delete_phrase_nonce'), 'get_phrases_nonce' => wp_create_nonce('mxchat_get_phrases_nonce'), 'delete_legacy_nonce' => wp_create_nonce('mxchat_delete_legacy_nonce'), 'toggle_action_nonce' => wp_create_nonce('mxchat_actions_nonce'), 'fetch_openrouter_models_nonce' => wp_create_nonce('mxchat_fetch_openrouter_models'), 'is_activated' => $this->is_activated ? '1' : '0', 'status_refresh_interval' => 5000, 'discard_changes_confirm' => __('Discard your unsaved changes?', 'mxchat'), 'unsaved_label' => __('Unsaved', 'mxchat'), // Live-agent schedule status text (plan 8ccaa2). 'i18n_scheduled_hours' => __('Scheduled hours', 'mxchat'), 'i18n_always_available' => __('Always available', 'mxchat'), 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'), 'ajaxurl' => admin_url('admin-ajax.php') ); } private function localize_admin_scripts($current_page) { // Base localization data for main admin script $base_data = $this->mxchat_get_admin_base_localization(); // Localize main admin script with base data wp_localize_script('mxchat-admin-js', 'mxchatAdmin', $base_data); // Canonical chat-model catalog for the modal picker grid // (plan-d14e89). Adding a model in class-mxchat-model-catalog.php // automatically appears here. if (!class_exists('MxChat_Model_Catalog')) { require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php'; } wp_localize_script('mxchat-admin-js', 'mxchatChatModelCatalog', MxChat_Model_Catalog::js_picker_shape()); // Page-specific localizations $this->localize_page_specific_scripts($current_page); } private function localize_page_specific_scripts($current_page) { switch ($current_page) { case 'mxchat-prompts': // Status updater localization wp_localize_script('mxchat-status-updater', 'mxchat_status_data', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_status_nonce') )); // Content selector localization wp_localize_script('mxchat-content-selector-js', 'mxchatSelector', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_content_selector_nonce'), 'i18n' => array( 'searchPlaceholder' => __('Search posts and pages...', 'mxchat'), 'selectAll' => __('Select All', 'mxchat'), 'process' => __('Process Selected', 'mxchat'), 'cancel' => __('Cancel', 'mxchat'), 'noResults' => __('No content found.', 'mxchat'), 'extractingPdfs' => __('extracting %d PDF(s)...', 'mxchat'), 'pdfExtractedSuffix' => __(' (%d PDF(s) extracted)', 'mxchat') ) )); // This prints a SECOND `var mxchatAdmin` (after mxchat-admin-js's // base one) and last-printed wins — so it must carry the FULL base // payload plus the knowledge-page extras, or every mxchatAdmin.* // key mxchat-admin.js reads on this page comes up undefined // (plan c192a4). Extras merge last: status_refresh_interval stays // at this page's faster 2000ms cadence. wp_localize_script('mxchat-knowledge-processing', 'mxchatAdmin', array_merge( $this->mxchat_get_admin_base_localization(), array( 'status_nonce' => wp_create_nonce('mxchat_status_nonce'), 'queue_nonce' => wp_create_nonce('mxchat_queue_nonce'), 'stop_nonce' => wp_create_nonce('mxchat_stop_processing_action'), 'settings_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'), 'entries_nonce' => wp_create_nonce('mxchat_entries_nonce'), 'status_refresh_interval' => 2000, 'bot_id' => isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default' ) )); break; case 'mxchat-activation': // Same last-printed-wins clobber as the knowledge page (plan c192a4, // fixed here by a5b297): this second `var mxchatAdmin` must carry // the full base payload plus the page extras. wp_localize_script('mxchat-activation-js', 'mxchatAdmin', array_merge( $this->mxchat_get_admin_base_localization(), array( 'license_nonce' => wp_create_nonce('mxchat_activate_license_nonce') ) )); break; case 'mxchat-content': wp_localize_script('mxchat-content-js', 'mxchatContent', array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mxchat_content_nonce'), 'settingNonce' => wp_create_nonce('mxchat_save_setting_nonce'), 'previewUrl' => home_url('/?p='), 'isActivated' => $this->is_activated(), 'hasAdvancedContent' => apply_filters('mxchat_content_pro_feature', false, 'seo_readability'), 'hasGSC' => apply_filters('mxchat_content_pro_feature', false, 'gsc_integration'), // Whether Search Console is actually LINKED — distinct from hasGSC // (add-on active). Reads the same option the add-on's settings // card keys off; harmless false when the add-on is absent. 'gscLinked' => (bool) get_option('mxchat_gsc_connected', false), 'seoOptimize' => array( 'meta_description' => ($options['seo_optimize_meta_desc'] ?? 'on') === 'on', 'seo_title' => ($options['seo_optimize_seo_title'] ?? 'on') === 'on', 'slug' => ($options['seo_optimize_slug'] ?? 'on') === 'on', 'readability' => ($options['seo_optimize_readability'] ?? 'on') === 'on', 'internal_links' => ($options['seo_optimize_internal_links'] ?? 'on') === 'on', 'img_alt' => ($options['seo_optimize_img_alt'] ?? 'on') === 'on', 'featured_img' => ($options['seo_optimize_featured_img'] ?? 'on') === 'on', ), 'i18n' => array( 'generating' => __('Generating...', 'mxchat'), 'planning' => __('Planning content structure...', 'mxchat'), 'images' => __('Generating images...', 'mxchat'), 'writing' => __('Writing full content...', 'mxchat'), 'creating' => __('Creating WordPress post...', 'mxchat'), 'done' => __('Content generated successfully!', 'mxchat'), 'error' => __('An error occurred. Please try again.', 'mxchat'), 'editSuccess' => __('Content updated successfully.', 'mxchat'), 'promptEmpty' => __('Please enter a prompt.', 'mxchat'), ) )); break; case 'mxchat-transcripts': // Get chart data for localization $chart_data = $this->get_transcripts_chart_data(); // Same last-printed-wins clobber as the knowledge page (plan c192a4, // fixed here by a5b297): merge the base payload under the page keys. // export_nonce/setting_nonce/ajax_url duplicate base values identically; // delete_nonce and translate_nonce are the page-specific adds. wp_localize_script('mxchat-transcripts-js', 'mxchatAdmin', array_merge( $this->mxchat_get_admin_base_localization(), array( 'export_nonce' => wp_create_nonce('mxchat_export_transcripts'), 'delete_nonce' => wp_create_nonce('mxchat_delete_chat_history'), 'setting_nonce' => wp_create_nonce('mxchat_save_setting_nonce'), 'translate_nonce' => wp_create_nonce('mxchat_translate_messages') ) )); // Localize chart data separately - use array_values to ensure proper JSON array encoding wp_localize_script('mxchat-transcripts-js', 'mxchatChartData', array( 'labels' => array_values($chart_data['labels']), 'chats' => array_values($chart_data['chats']), 'messages' => array_values($chart_data['messages']) )); break; case 'mxchat-settings': default: // The 'mxchatStyleSettings' localize that used to live here was // REMOVED by plan-mxchat-20260731-c63fb6. // // It targeted the script handle 'mxchat-color-picker', which is // registered/enqueued NOWHERE in the plugin — so wp_localize_script() // returned false and printed nothing. That accident was the only // thing keeping it from being a live secret disclosure: the payload // carried loops_api_key, live_agent_secret_key and // live_agent_bot_token in full, and this whole method ran for any // logged-in user (see the capability gate added to // mxchat_enqueue_admin_assets). One future // wp_enqueue_script('mxchat-color-picker', ...) would have printed // three secrets into page HTML for Subscribers. // // Nothing consumed the object: a tree-wide grep for // 'mxchatStyleSettings' returns only this call site, and js/ names // loops_api_key only at mxchat-admin.js:572, as a field-NAME string // in an autosave allowlist — not a value read. Removed entirely // rather than deleting just the three secret keys, so there is no // dead payload left for someone to re-arm. break; } // Additional localization that was in the original code wp_localize_script('mxchat-admin-js', 'mxchatPromptsAdmin', array( 'ajax_url' => admin_url('admin-ajax.php'), 'prompts_setting_nonce' => wp_create_nonce('mxchat_prompts_setting_nonce'), )); } public function mxchat_sanitize($input) { $new_input = array(); if (isset($input['api_key'])) { $new_input['api_key'] = sanitize_text_field($input['api_key']); } if (isset($input['similarity_threshold'])) { $new_input['similarity_threshold'] = absint($input['similarity_threshold']); // Ensure it's an integer $new_input['similarity_threshold'] = min(max($new_input['similarity_threshold'], 20), 85); // Enforce range } if (isset($input['rag_sources_limit'])) { $new_input['rag_sources_limit'] = absint($input['rag_sources_limit']); // Ensure it's an integer $new_input['rag_sources_limit'] = min(max($new_input['rag_sources_limit'], 3), 10); // Enforce range 3-10 } if (isset($input['rag_chunks_limit'])) { $new_input['rag_chunks_limit'] = absint($input['rag_chunks_limit']); // Ensure it's an integer $new_input['rag_chunks_limit'] = min(max($new_input['rag_chunks_limit'], 8), 20); // Enforce range 8-20 } if (isset($input['xai_api_key'])) { $new_input['xai_api_key'] = sanitize_text_field($input['xai_api_key']); } if (isset($input['claude_api_key'])) { $new_input['claude_api_key'] = sanitize_text_field($input['claude_api_key']); } if (isset($input['enable_streaming_toggle'])) { $new_input['enable_streaming_toggle'] = ($input['enable_streaming_toggle'] === 'on') ? 'on' : 'off'; } else { // If checkbox not checked, it won't be in $input, so set to 'off' $new_input['enable_streaming_toggle'] = 'off'; } if (isset($input['enable_web_search'])) { $new_input['enable_web_search'] = ($input['enable_web_search'] === 'on') ? 'on' : 'off'; } else { // If checkbox not checked, it won't be in $input, so set to 'off' $new_input['enable_web_search'] = 'off'; } if (isset($input['deepseek_api_key'])) { $new_input['deepseek_api_key'] = sanitize_text_field($input['deepseek_api_key']); } if (isset($input['gemini_api_key'])) { $new_input['gemini_api_key'] = sanitize_text_field($input['gemini_api_key']); } if (isset($input['enable_woocommerce_integration'])) { $new_input['enable_woocommerce_integration'] = $input['enable_woocommerce_integration'] === 'on' ? 'on' : 'off'; } if (isset($input['privacy_toggle'])) { $new_input['privacy_toggle'] = $input['privacy_toggle']; } if (isset($input['complianz_toggle'])) { $new_input['complianz_toggle'] = $input['complianz_toggle']; } // Handle custom privacy text input if (isset($input['privacy_text'])) { // Allow basic HTML for links $new_input['privacy_text'] = wp_kses_post($input['privacy_text']); } if (isset($input['system_prompt_instructions'])) { $new_input['system_prompt_instructions'] = sanitize_textarea_field($input['system_prompt_instructions']); } if (isset($input['mxchat_pro_email'])) { $new_input['mxchat_pro_email'] = sanitize_email($input['mxchat_pro_email']); } if (isset($input['mxchat_activation_key'])) { $new_input['mxchat_activation_key'] = sanitize_text_field($input['mxchat_activation_key']); } if (isset($input['append_to_body'])) { $new_input['append_to_body'] = $input['append_to_body'] === 'on' ? 'on' : 'off'; } // Post type visibility settings if (isset($input['post_type_visibility_mode'])) { $allowed_modes = array('all', 'include', 'exclude'); $new_input['post_type_visibility_mode'] = in_array($input['post_type_visibility_mode'], $allowed_modes) ? $input['post_type_visibility_mode'] : 'all'; } if (isset($input['post_type_visibility_list'])) { if (is_array($input['post_type_visibility_list'])) { $new_input['post_type_visibility_list'] = array_map('sanitize_key', $input['post_type_visibility_list']); } else { $new_input['post_type_visibility_list'] = array(); } } if (isset($input['contextual_awareness_toggle'])) { $new_input['contextual_awareness_toggle'] = $input['contextual_awareness_toggle'] === 'on' ? 'on' : 'off'; } if (isset($input['citation_links_toggle'])) { $new_input['citation_links_toggle'] = $input['citation_links_toggle'] === 'on' ? 'on' : 'off'; } if (isset($input['strip_unapproved_links_toggle'])) { $new_input['strip_unapproved_links_toggle'] = $input['strip_unapproved_links_toggle'] === 'on' ? 'on' : 'off'; } // Satisfaction rating prompt — defaults ON when unchecked (so first save // doesn't accidentally disable it). The form posts 'on' when checked; // unchecked checkboxes don't post a value at all, so we infer 'off' only // when the autosave/PHP request explicitly clears it via empty string. if (array_key_exists('satisfaction_rating_enabled', $input)) { $new_input['satisfaction_rating_enabled'] = $input['satisfaction_rating_enabled'] === 'on' ? 'on' : 'off'; } // Satisfaction rating customization (plan-141a12). Idle is clamped 5-600; // the 4 text strings are sanitized + capped server-side. Blank values are // preserved so the integrator falls back to translated defaults. if (array_key_exists('satisfaction_rating_idle_seconds', $input)) { $new_input['satisfaction_rating_idle_seconds'] = max(5, min(600, intval($input['satisfaction_rating_idle_seconds']))); } // Max input length in characters (plan a3fae2 part C). 0 = unlimited (default, // preserves current behavior). Clamp to a sane ceiling so a typo can't lock out // all input. REQUIRED here — mxchat_sanitize() rebuilds the array from a whitelist, // so without this isset-handler the key is stripped on the next save of ANY field // (the 2c02ea global-rate-limit footgun). if (array_key_exists('max_input_length', $input)) { $new_input['max_input_length'] = max(0, min(100000, intval($input['max_input_length']))); } if (array_key_exists('satisfaction_rating_question', $input)) { $new_input['satisfaction_rating_question'] = mb_substr(sanitize_text_field($input['satisfaction_rating_question']), 0, 200); } if (array_key_exists('satisfaction_rating_thanks', $input)) { $new_input['satisfaction_rating_thanks'] = mb_substr(sanitize_text_field($input['satisfaction_rating_thanks']), 0, 300); } if (array_key_exists('satisfaction_rating_placeholder', $input)) { $new_input['satisfaction_rating_placeholder'] = mb_substr(sanitize_text_field($input['satisfaction_rating_placeholder']), 0, 200); } if (array_key_exists('satisfaction_rating_saved', $input)) { $new_input['satisfaction_rating_saved'] = mb_substr(sanitize_text_field($input['satisfaction_rating_saved']), 0, 200); } if (isset($input['top_bar_title'])) { $new_input['top_bar_title'] = sanitize_text_field($input['top_bar_title']); } if (isset($input['ai_agent_text'])) { $new_input['ai_agent_text'] = sanitize_text_field($input['ai_agent_text']); } if (isset($input['enable_email_block'])) { $new_input['enable_email_block'] = sanitize_text_field($input['enable_email_block']); } if (isset($input['email_blocker_header_content'])) { // wp_kses_post() allows standard HTML tags permitted by WordPress $new_input['email_blocker_header_content'] = wp_kses_post($input['email_blocker_header_content']); } if (isset($input['email_blocker_button_text'])) { $new_input['email_blocker_button_text'] = sanitize_text_field($input['email_blocker_button_text']); } // Sanitize name field toggle if (isset($input['enable_name_field'])) { $new_input['enable_name_field'] = ($input['enable_name_field'] === 'on') ? 'on' : 'off'; } else { $new_input['enable_name_field'] = 'off'; } // Sanitize name field placeholder if (isset($input['name_field_placeholder'])) { $new_input['name_field_placeholder'] = sanitize_text_field($input['name_field_placeholder']); } // Consent checkbox (b062c4). Both toggles default off — an unchecked box // posts nothing, so the else-branch is what makes unticking stick. if (isset($input['enable_consent_checkbox'])) { $new_input['enable_consent_checkbox'] = ($input['enable_consent_checkbox'] === 'on') ? 'on' : 'off'; } else { $new_input['enable_consent_checkbox'] = 'off'; } if (isset($input['consent_checkbox_label'])) { // Shared allowlist with the render path — see MxChat_Utils::sanitize_consent_label(). $new_input['consent_checkbox_label'] = MxChat_Utils::sanitize_consent_label($input['consent_checkbox_label']); } if (isset($input['consent_checkbox_required'])) { $new_input['consent_checkbox_required'] = ($input['consent_checkbox_required'] === 'on') ? 'on' : 'off'; } else { $new_input['consent_checkbox_required'] = 'off'; } // Lead capture options (c0cfaf). Default OFF gets the else-branch so // unticking sticks; default ON deliberately has NO else — an absent key // must stay absent so the reader's ?? 'on' default applies, otherwise // every autosave of an unrelated field would silently flip the setting // off on installs that never touched it (the 2c02ea bug class). if (isset($input['lead_capture_logged_in_toggle'])) { $new_input['lead_capture_logged_in_toggle'] = ($input['lead_capture_logged_in_toggle'] === 'on') ? 'on' : 'off'; } else { $new_input['lead_capture_logged_in_toggle'] = 'off'; } if (isset($input['lead_capture_require_email_toggle'])) { $new_input['lead_capture_require_email_toggle'] = ($input['lead_capture_require_email_toggle'] === 'on') ? 'on' : 'off'; } if (isset($input['intro_message'])) { $new_input['intro_message'] = wp_kses_post($input['intro_message']); // Use wp_kses_post instead } if (isset($input['input_copy'])) { $new_input['input_copy'] = sanitize_text_field($input['input_copy']); } if (isset($input['rate_limit_message'])) { $new_input['rate_limit_message'] = sanitize_text_field($input['rate_limit_message']); } // Handle the new rate limits format if (isset($input['rate_limits']) && is_array($input['rate_limits'])) { $new_input['rate_limits'] = array(); $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited'); $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly'); foreach ($input['rate_limits'] as $role_id => $settings) { $new_input['rate_limits'][$role_id] = array(); // Sanitize limit if (isset($settings['limit'])) { $limit = sanitize_text_field($settings['limit']); // Accept presets, 'unlimited', the '__custom__' sentinel, OR any positive // integer (custom value) — mirrors the global branch (plan-2c02ea). Without // the custom path the per-role custom input was dropped and reset to the role // default on every save (plan-7e23e7). if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) { $new_input['rate_limits'][$role_id]['limit'] = $limit; } else { $new_input['rate_limits'][$role_id]['limit'] = ($role_id === 'logged_out') ? '10' : '100'; // Default } } // Preserve the per-role custom value (mirrors the global branch's limit_custom). if (isset($settings['limit_custom'])) { $new_input['rate_limits'][$role_id]['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $settings['limit_custom']); } // Sanitize timeframe if (isset($settings['timeframe'])) { $timeframe = sanitize_text_field($settings['timeframe']); if (in_array($timeframe, $allowed_timeframes, true)) { $new_input['rate_limits'][$role_id]['timeframe'] = $timeframe; } else { $new_input['rate_limits'][$role_id]['timeframe'] = 'daily'; // Default } } // Sanitize message if (isset($settings['message'])) { $new_input['rate_limits'][$role_id]['message'] = sanitize_textarea_field($settings['message']); } } } // Handle the whole-chatbot global rate limit (plan-mxchat-20260603-2c02ea). // Mirrors the per-role block above, adapted to the single global shape. Without // this branch the whitelist-rebuild dropped rate_limits_global entirely on every // save, so the global cap silently fell back to its 'unlimited' default. // MUST accept arbitrary positive integers so the custom-value path (d55f65) is not regressed. if (isset($input['rate_limits_global']) && is_array($input['rate_limits_global'])) { $g = $input['rate_limits_global']; $allowed_limits = array('1', '3', '5', '10', '15', '20', '50', '100', 'unlimited'); $allowed_timeframes = array('hourly', 'daily', 'weekly', 'monthly'); $global_out = array(); if (isset($g['limit'])) { $limit = sanitize_text_field($g['limit']); // Accept presets, 'unlimited', the '__custom__' sentinel (resolved by the // autosave handler / renderer), OR any positive integer (custom value). if (in_array($limit, $allowed_limits, true) || $limit === '__custom__' || (ctype_digit($limit) && (int) $limit >= 1)) { $global_out['limit'] = $limit; } else { $global_out['limit'] = 'unlimited'; } } if (isset($g['limit_custom'])) { $global_out['limit_custom'] = preg_replace('/[^0-9]/', '', (string) $g['limit_custom']); } if (isset($g['timeframe'])) { $timeframe = sanitize_text_field($g['timeframe']); $global_out['timeframe'] = in_array($timeframe, $allowed_timeframes, true) ? $timeframe : 'daily'; } if (isset($g['message'])) { $global_out['message'] = sanitize_textarea_field($g['message']); } $new_input['rate_limits_global'] = $global_out; } if (isset($input['pre_chat_message'])) { $new_input['pre_chat_message'] = sanitize_textarea_field($input['pre_chat_message']); } if (isset($input['voyage_api_key'])) { $new_input['voyage_api_key'] = sanitize_text_field($input['voyage_api_key']); } // Add to your sanitize function if (isset($input['embedding_model'])) { // Catalog refactor (plan-d14e89): allowlist derived from the canonical // catalog in includes/class-mxchat-model-catalog.php. if (!class_exists('MxChat_Model_Catalog')) { require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php'; } $allowed_models = MxChat_Model_Catalog::embedding_model_ids(); if (in_array($input['embedding_model'], $allowed_models)) { $new_input['embedding_model'] = sanitize_text_field($input['embedding_model']); } } if (isset($input['model'])) { if ($input['model'] === 'openrouter') { $new_input['model'] = 'openrouter'; } else { if (!class_exists('MxChat_Model_Catalog')) { require_once plugin_dir_path(__FILE__) . 'class-mxchat-model-catalog.php'; } $allowed_models = MxChat_Model_Catalog::chat_model_ids(); if (in_array($input['model'], $allowed_models)) { $new_input['model'] = sanitize_text_field($input['model']); } else { // Fallback for any deprecated model $new_input['model'] = 'gpt-5.6-sol'; } } } if (isset($input['openrouter_selected_model'])) { // Just sanitize it, don't validate against a whitelist $new_input['openrouter_selected_model'] = sanitize_text_field($input['openrouter_selected_model']); } // ADD THIS: if (isset($input['openrouter_selected_model_name'])) { $new_input['openrouter_selected_model_name'] = sanitize_text_field($input['openrouter_selected_model_name']); } if (isset($input['openrouter_api_key'])) { $new_input['openrouter_api_key'] = sanitize_text_field($input['openrouter_api_key']); } // Custom (OpenAI-compatible) Provider — Ollama, LM Studio, vLLM, Azure OpenAI, etc. if (isset($input['custom_provider_base_url'])) { $new_input['custom_provider_base_url'] = esc_url_raw(rtrim(trim((string) $input['custom_provider_base_url']), '/')); } if (isset($input['custom_provider_api_key'])) { $new_input['custom_provider_api_key'] = sanitize_text_field($input['custom_provider_api_key']); } if (isset($input['custom_provider_model'])) { $new_input['custom_provider_model'] = sanitize_text_field($input['custom_provider_model']); } if (isset($input['custom_provider_auth_scheme'])) { $scheme = sanitize_text_field($input['custom_provider_auth_scheme']); $new_input['custom_provider_auth_scheme'] = in_array($scheme, array('bearer', 'api-key'), true) ? $scheme : 'bearer'; } if (isset($input['custom_provider_for_embeddings'])) { $new_input['custom_provider_for_embeddings'] = ($input['custom_provider_for_embeddings'] === 'on') ? 'on' : 'off'; } if (isset($input['custom_provider_for_images'])) { $new_input['custom_provider_for_images'] = ($input['custom_provider_for_images'] === 'on') ? 'on' : 'off'; } if (isset($input['custom_provider_embedding_model'])) { $new_input['custom_provider_embedding_model'] = sanitize_text_field($input['custom_provider_embedding_model']); } if (isset($input['custom_provider_api_version'])) { $new_input['custom_provider_api_version'] = sanitize_text_field($input['custom_provider_api_version']); } if (isset($input['woocommerce_consumer_key'])) { $new_input['woocommerce_consumer_key'] = sanitize_text_field($input['woocommerce_consumer_key']); } if (isset($input['woocommerce_consumer_secret'])) { $new_input['woocommerce_consumer_secret'] = sanitize_text_field($input['woocommerce_consumer_secret']); } // Sanitize link_target_toggle if (isset($input['link_target_toggle'])) { $new_input['link_target_toggle'] = $input['link_target_toggle'] === 'on' ? 'on' : 'off'; } // Sanitize Loops API Key if (isset($input['loops_api_key'])) { $new_input['loops_api_key'] = sanitize_text_field($input['loops_api_key']); } if (isset($input['chat_persistence_toggle'])) { $new_input['chat_persistence_toggle'] = $input['chat_persistence_toggle'] === 'on' ? 'on' : 'off'; } // No else clause: an absent key stays absent, so the front-end default ('on') applies // and the rebuild never strips a saved 'off' (autosave passes the full options array back through here). if (isset($input['print_button_enabled'])) { $new_input['print_button_enabled'] = $input['print_button_enabled'] === 'on' ? 'on' : 'off'; } // plan ac2e81 — "Start new chat" toggle (default OFF) + editable label. // No else on the toggle: an absent key stays absent so the front-end '?? off' // default applies, and the full-array autosave rebuild preserves a saved value. if (isset($input['reset_chat_enabled'])) { $new_input['reset_chat_enabled'] = $input['reset_chat_enabled'] === 'on' ? 'on' : 'off'; } if (isset($input['reset_chat_label'])) { $new_input['reset_chat_label'] = sanitize_text_field($input['reset_chat_label']); } if (isset($input['popular_question_1'])) { $new_input['popular_question_1'] = sanitize_text_field($input['popular_question_1']); } if (isset($input['popular_question_2'])) { $new_input['popular_question_2'] = sanitize_text_field($input['popular_question_2']); } if (isset($input['popular_question_3'])) { $new_input['popular_question_3'] = sanitize_text_field($input['popular_question_3']); } if (isset($input['additional_popular_questions']) && is_array($input['additional_popular_questions'])) { $new_input['additional_popular_questions'] = array_map('sanitize_text_field', $input['additional_popular_questions']); } // Sanitize Loops Mailing List if (isset($input['loops_mailing_list'])) { $new_input['loops_mailing_list'] = sanitize_text_field($input['loops_mailing_list']); } // Sanitize Triggered Phrase Response if (isset($input['triggered_phrase_response'])) { $new_input['triggered_phrase_response'] = wp_kses_post($input['triggered_phrase_response']); } if (isset($input['email_capture_response'])) { $new_input['email_capture_response'] = wp_kses_post($input['email_capture_response']); } // Sanitize Brave Search Settings if (isset($input['brave_api_key'])) { $new_input['brave_api_key'] = sanitize_text_field($input['brave_api_key']); } if (isset($input['brave_image_count'])) { $image_count = intval($input['brave_image_count']); $new_input['brave_image_count'] = ($image_count >=1 && $image_count <=6) ? $image_count : 4; } if (isset($input['brave_safe_search'])) { $allowed = array('strict', 'off'); $new_input['brave_safe_search'] = in_array($input['brave_safe_search'], $allowed, true) ? $input['brave_safe_search'] : 'strict'; } if (isset($input['brave_news_count'])) { $news_count = intval($input['brave_news_count']); $new_input['brave_news_count'] = ($news_count >=1 && $news_count <=10) ? $news_count : 3; } if (isset($input['brave_country'])) { $new_input['brave_country'] = sanitize_text_field($input['brave_country']); } if (isset($input['brave_language'])) { $new_input['brave_language'] = sanitize_text_field($input['brave_language']); } if (isset($input['chat_toolbar_toggle'])) { $new_input['chat_toolbar_toggle'] = $input['chat_toolbar_toggle'] === 'on' ? 'on' : 'off'; } // Sanitize PDF upload button toggle if (isset($input['show_pdf_upload_button'])) { $new_input['show_pdf_upload_button'] = $input['show_pdf_upload_button'] === 'on' ? 'on' : 'off'; } else { $new_input['show_pdf_upload_button'] = 'off'; // If checkbox is unchecked } // Sanitize Word upload button toggle if (isset($input['show_word_upload_button'])) { $new_input['show_word_upload_button'] = $input['show_word_upload_button'] === 'on' ? 'on' : 'off'; } else { $new_input['show_word_upload_button'] = 'off'; // If checkbox is unchecked } if (isset($input['pdf_intent_trigger_text'])) { $new_input['pdf_intent_trigger_text'] = sanitize_text_field($input['pdf_intent_trigger_text']); } if (isset($input['pdf_intent_success_text'])) { $new_input['pdf_intent_success_text'] = sanitize_text_field($input['pdf_intent_success_text']); } if (isset($input['pdf_intent_error_text'])) { $new_input['pdf_intent_error_text'] = sanitize_text_field($input['pdf_intent_error_text']); } if (isset($input['pdf_max_pages'])) { $new_input['pdf_max_pages'] = intval($input['pdf_max_pages']); if ($new_input['pdf_max_pages'] < 1 || $new_input['pdf_max_pages'] > 69) { $new_input['pdf_max_pages'] = 69; // Default to 69 if out of range } } if (isset($input['live_agent_webhook_url'])) { $new_input['live_agent_webhook_url'] = esc_url_raw($input['live_agent_webhook_url']); } if (isset($input['live_agent_secret_key'])) { $new_input['live_agent_secret_key'] = sanitize_text_field($input['live_agent_secret_key']); } // Live Agent Integration if (isset($input['live_agent_bot_token'])) { $new_input['live_agent_bot_token'] = sanitize_text_field($input['live_agent_bot_token']); } if (isset($input['live_agent_shared_channel'])) { $new_input['live_agent_shared_channel'] = sanitize_text_field($input['live_agent_shared_channel']); } // Default-OFF toggle: absent key stays absent (unchecked box = off). if (isset($input['live_agent_archive_on_end_toggle'])) { $new_input['live_agent_archive_on_end_toggle'] = ($input['live_agent_archive_on_end_toggle'] === 'on') ? 'on' : 'off'; } if (isset($input['live_agent_user_ids'])) { $new_input['live_agent_user_ids'] = sanitize_textarea_field($input['live_agent_user_ids']); } if (isset($input['live_agent_status'])) { $new_input['live_agent_status'] = ($input['live_agent_status'] === 'on') ? 'on' : 'off'; } if (isset($input['live_agent_away_message'])) { $new_input['live_agent_away_message'] = sanitize_textarea_field($input['live_agent_away_message']); } if (isset($input['live_agent_notification_message'])) { $new_input['live_agent_notification_message'] = sanitize_textarea_field($input['live_agent_notification_message']); } // Telegram Integration if (isset($input['telegram_status'])) { $new_input['telegram_status'] = ($input['telegram_status'] === 'on') ? 'on' : 'off'; } if (isset($input['telegram_bot_token'])) { $new_input['telegram_bot_token'] = sanitize_text_field($input['telegram_bot_token']); } if (isset($input['telegram_group_id'])) { $new_input['telegram_group_id'] = sanitize_text_field($input['telegram_group_id']); } if (isset($input['telegram_webhook_secret'])) { $new_input['telegram_webhook_secret'] = sanitize_text_field($input['telegram_webhook_secret']); } if (isset($input['telegram_notification_message'])) { $new_input['telegram_notification_message'] = sanitize_textarea_field($input['telegram_notification_message']); } if (isset($input['telegram_away_message'])) { $new_input['telegram_away_message'] = sanitize_textarea_field($input['telegram_away_message']); } // Webhook Handoff (plan d88e22) if (isset($input['webhook_handoff_status'])) { $new_input['webhook_handoff_status'] = ($input['webhook_handoff_status'] === 'on') ? 'on' : 'off'; } if (isset($input['webhook_handoff_url'])) { // https only — esc_url_raw with an https-only protocol list stores '' // for anything else, so a non-https URL can never persist. $new_input['webhook_handoff_url'] = esc_url_raw(trim((string) $input['webhook_handoff_url']), array('https')); } if (isset($input['webhook_handoff_secret'])) { $new_input['webhook_handoff_secret'] = sanitize_text_field($input['webhook_handoff_secret']); } if (isset($input['webhook_handoff_notification_message'])) { $new_input['webhook_handoff_notification_message'] = sanitize_textarea_field($input['webhook_handoff_notification_message']); } if (isset($input['webhook_handoff_away_message'])) { $new_input['webhook_handoff_away_message'] = sanitize_textarea_field($input['webhook_handoff_away_message']); } // Sanitize script loading strategy if (isset($input['script_loading_strategy'])) { $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction'); $new_input['script_loading_strategy'] = in_array($input['script_loading_strategy'], $allowed_strategies) ? $input['script_loading_strategy'] : 'default'; } // Sanitize debug mode if (isset($input['debug_mode'])) { $new_input['debug_mode'] = ($input['debug_mode'] === 'on') ? 'on' : 'off'; } // Content Generator Settings if (isset($input['content_model'])) { $new_input['content_model'] = sanitize_text_field($input['content_model']); } if (isset($input['content_image_model'])) { $new_input['content_image_model'] = sanitize_text_field($input['content_image_model']); } if (isset($input['content_image_quality'])) { $q = sanitize_text_field($input['content_image_quality']); $new_input['content_image_quality'] = in_array($q, array('auto', 'low', 'medium', 'high'), true) ? $q : 'auto'; } if (isset($input['content_enable_images'])) { $new_input['content_enable_images'] = ($input['content_enable_images'] === 'on') ? 'on' : 'off'; } if (isset($input['content_use_placeholders'])) { $new_input['content_use_placeholders'] = ($input['content_use_placeholders'] === 'on') ? 'on' : 'off'; } if (isset($input['content_internal_linking'])) { $new_input['content_internal_linking'] = ($input['content_internal_linking'] === 'on') ? 'on' : 'off'; } if (isset($input['content_tool_use'])) { $new_input['content_tool_use'] = ($input['content_tool_use'] === 'on') ? 'on' : 'off'; } if (isset($input['content_image_count'])) { $new_input['content_image_count'] = (string) max(1, min(5, (int) $input['content_image_count'])); } // SEO Optimize toggle fields foreach (array('seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $seo_key) { if (isset($input[$seo_key])) { $new_input[$seo_key] = ($input[$seo_key] === 'on') ? 'on' : 'off'; } } // Preserve content generator settings when saving from main settings page // (where content fields are not in the form submission) $existing = get_option('mxchat_options', array()); foreach (array('content_model', 'content_image_model', 'content_image_quality', 'content_image_count', 'content_enable_images', 'content_use_placeholders', 'content_internal_linking', 'content_tool_use', 'seo_optimize_meta_desc', 'seo_optimize_seo_title', 'seo_optimize_slug', 'seo_optimize_readability', 'seo_optimize_internal_links', 'seo_optimize_img_alt', 'seo_optimize_featured_img') as $key) { if (!isset($new_input[$key]) && isset($existing[$key])) { $new_input[$key] = $existing[$key]; } } return $new_input; } /** * Log a debug message if debug mode is enabled * * @param string $type The type of log entry (settings_save, api_error, activation, etc.) * @param string $message The log message * @param array $data Optional additional data to log * @return bool Whether the message was logged */ public static function mxchat_log_debug( $type, $message, $data = array() ) { $options = get_option( 'mxchat_options', array() ); // Check if debug mode is enabled if ( ! isset( $options['debug_mode'] ) || $options['debug_mode'] !== 'on' ) { return false; } // Get current log $log = get_option( 'mxchat_debug_log', array() ); if ( ! is_array( $log ) ) { $log = array(); } // Add new entry $entry = array( 'time' => current_time( 'Y-m-d H:i:s' ), 'type' => sanitize_key( $type ), 'message' => sanitize_text_field( $message ), ); if ( ! empty( $data ) ) { $entry['data'] = $data; } // Add to beginning of array (newest first) array_unshift( $log, $entry ); // Keep only last 100 entries if ( count( $log ) > 100 ) { $log = array_slice( $log, 0, 100 ); } // Save log update_option( 'mxchat_debug_log', $log, false ); return true; } /** * Get the debug log entries * * @return array The debug log entries */ public static function mxchat_get_debug_log() { $log = get_option( 'mxchat_debug_log', array() ); return is_array( $log ) ? $log : array(); } /** * Clear the debug log * * @return bool Whether the log was cleared */ public static function mxchat_clear_debug_log() { return delete_option( 'mxchat_debug_log' ); } /** * Export settings as JSON with masked API keys * * @return array The sanitized settings array */ public static function mxchat_export_settings() { $options = get_option( 'mxchat_options', array() ); if ( ! is_array( $options ) ) { return array(); } // List of API key fields to mask $api_key_fields = array( 'api_key', 'xai_api_key', 'claude_api_key', 'deepseek_api_key', 'voyage_api_key', 'gemini_api_key', 'openrouter_api_key', 'loops_api_key', 'brave_api_key', 'live_agent_secret_key', 'live_agent_bot_token', 'telegram_bot_token', 'telegram_webhook_secret', 'woocommerce_consumer_key', 'woocommerce_consumer_secret', ); // Mask API keys (show only last 4 characters) foreach ( $api_key_fields as $field ) { if ( isset( $options[ $field ] ) && ! empty( $options[ $field ] ) ) { $value = $options[ $field ]; if ( strlen( $value ) > 4 ) { $options[ $field ] = str_repeat( '*', strlen( $value ) - 4 ) . substr( $value, -4 ); } else { $options[ $field ] = '****'; } } } // Add metadata $export = array( 'plugin_version' => defined( 'MXCHAT_VERSION' ) ? MXCHAT_VERSION : 'unknown', 'export_date' => current_time( 'Y-m-d H:i:s' ), 'wordpress_version' => get_bloginfo( 'version' ), 'php_version' => phpversion(), 'settings' => $options, ); return $export; } /** * Reset all settings to defaults * * @return bool Whether the reset was successful */ public static function mxchat_reset_all_settings() { // Delete main options $deleted = delete_option( 'mxchat_options' ); // Also clear the debug log delete_option( 'mxchat_debug_log' ); // Log the reset (will create new log since we just cleared it) // We need to temporarily enable debug mode to log this $temp_options = array( 'debug_mode' => 'on' ); update_option( 'mxchat_options', $temp_options ); self::mxchat_log_debug( 'reset', 'All settings have been reset to defaults' ); // Now delete again to trigger re-initialization delete_option( 'mxchat_options' ); return $deleted; } // Method to append the chatbot to the body public function mxchat_append_chatbot_to_body() { $options = get_option('mxchat_options'); if (isset($options['append_to_body']) && $options['append_to_body'] === 'on') { echo do_shortcode('[mxchat_chatbot floating="yes"]'); } } private function mxchat_fetch_loops_mailing_lists($api_key) { $url = 'https://app.loops.so/api/v1/lists'; $response = wp_remote_get($url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json' ) )); if (is_wp_error($response)) { return array(); } $body = wp_remote_retrieve_body($response); $lists = json_decode($body, true); return isset($lists) && is_array($lists) ? $lists : array(); } function mxchat_calculate_cosine_similarity($vec1, $vec2) { if (empty($vec1) || empty($vec2)) { return 0.0; } $dot_product = 0.0; $norm_a = 0.0; $norm_b = 0.0; for ($i = 0; $i < count($vec1); $i++) { $dot_product += $vec1[$i] * $vec2[$i]; $norm_a += pow($vec1[$i], 2); $norm_b += pow($vec2[$i], 2); } if ($norm_a == 0.0 || $norm_b == 0.0) { return 0.0; } else { return $dot_product / (sqrt($norm_a) * sqrt($norm_b)); } } /** * Validates nonce and deletes all chat prompts */ public function mxchat_handle_delete_all_prompts() { //error_log('=== DELETE ALL DEBUG START ==='); // Verify nonce if (!isset($_POST['mxchat_delete_all_prompts_nonce']) || !wp_verify_nonce($_POST['mxchat_delete_all_prompts_nonce'], 'mxchat_delete_all_prompts_action')) { //error_log('DEBUG: Nonce verification failed'); wp_die(__('Nonce verification failed.', 'mxchat')); } // Check permissions if (!current_user_can('manage_options')) { //error_log('DEBUG: Permission check failed'); wp_die(__('You do not have sufficient permissions to delete all prompts.', 'mxchat')); } // Get bot_id and content type filter from POST data $bot_id = isset($_POST['bot_id']) ? sanitize_text_field($_POST['bot_id']) : 'default'; $content_type_filter = isset($_POST['content_type_filter']) ? sanitize_text_field($_POST['content_type_filter']) : ''; $success = true; $error_messages = array(); // Get bot-specific Pinecone configuration $pinecone_manager = MxChat_Pinecone_Manager::get_instance(); $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id); $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1'; if ($use_pinecone && !empty($pinecone_options['mxchat_pinecone_api_key'])) { // Delete from Pinecone (with optional content type filter) $result = $pinecone_manager->mxchat_delete_all_from_pinecone($pinecone_options, $content_type_filter); if (!$result['success']) { $success = false; $error_messages[] = $result['message']; } } else { // Delete from WordPress database global $wpdb; $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; // Build WHERE conditions $where_clauses = array(); $where_values = array(); // Bot filter if ($bot_id !== 'default' && class_exists('MxChat_Multi_Bot_Manager')) { $where_clauses[] = 'bot_id = %s'; $where_values[] = $bot_id; } // Content type filter if (!empty($content_type_filter)) { $where_clauses[] = 'content_type = %s'; $where_values[] = $content_type_filter; } if (!empty($where_clauses)) { $where_sql = implode(' AND ', $where_clauses); $result = $wpdb->query($wpdb->prepare("DELETE FROM {$table_name} WHERE {$where_sql}", $where_values)); } else { // No filters — delete all $result = $wpdb->query("DELETE FROM {$table_name}"); } if ($result === false) { $success = false; $error_messages[] = 'Failed to delete from WordPress database'; } } // Redirect back with a success message and bot_id $redirect_url = add_query_arg(array( 'page' => 'mxchat-prompts', 'bot_id' => $bot_id, 'all_deleted' => $success ? 'true' : 'false' ), admin_url('admin.php')); wp_safe_redirect($redirect_url); exit; } /** * Handles deletion prompt with nonce validation */ public function mxchat_handle_delete_prompt() { // Sanitize and validate nonce $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : ''; if (empty($nonce) || !wp_verify_nonce($nonce, 'mxchat_delete_prompt_nonce')) { wp_die(esc_html__('Nonce verification failed.', 'mxchat')); } // Check permissions if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to delete prompts.', 'mxchat')); } // Get ID and source parameters $id = isset($_GET['id']) ? sanitize_text_field($_GET['id']) : ''; $source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : ''; if (empty($id)) { wp_die(esc_html__('Invalid prompt ID.', 'mxchat')); } $success = false; $error_message = ''; // Resolve per-bot Pinecone settings — the global option is the wrong // index entirely when the row belongs to a bot with its own host $bot_id = isset($_GET['bot_id']) ? sanitize_text_field($_GET['bot_id']) : 'default'; $pinecone_manager = MxChat_Pinecone_Manager::get_instance(); $pinecone_options = $pinecone_manager->mxchat_get_bot_pinecone_options($bot_id); $use_pinecone = ($pinecone_options['mxchat_use_pinecone'] ?? '0') === '1'; // If source is not specified, determine based on Pinecone configuration if (empty($source)) { $source = $use_pinecone ? 'pinecone' : 'wordpress'; } if ($source === 'pinecone' || $use_pinecone) { //error_log('[MXCHAT-DELETE] Deleting from Pinecone, ID: ' . $id); // Handle Pinecone deletion if (empty($pinecone_options['mxchat_pinecone_host']) || empty($pinecone_options['mxchat_pinecone_api_key'])) { wp_die(esc_html__('Pinecone configuration is missing.', 'mxchat')); } // Delete from Pinecone using the vector ID directly $result = $pinecone_manager->mxchat_delete_from_pinecone_by_vector_id( $id, $pinecone_options['mxchat_pinecone_api_key'], $pinecone_options['mxchat_pinecone_host'], $pinecone_options['mxchat_pinecone_namespace'] ?? '' ); if ($result['success']) { $success = true; // Remove from vector cache $pinecone_manager->mxchat_remove_from_pinecone_vector_cache($id); $pinecone_manager->mxchat_remove_from_processed_content_caches($id); set_transient('mxchat_admin_notice_success', esc_html__('Vector deleted successfully from Pinecone.', 'mxchat'), 30); } else { $error_message = $result['message']; set_transient('mxchat_admin_notice_error', esc_html__('Failed to delete from Pinecone: ', 'mxchat') . esc_html($error_message), 30); } } else { //error_log('[MXCHAT-DELETE] Deleting from WordPress database, ID: ' . $id); // Handle WordPress database deletion global $wpdb; $table_name = $wpdb->prefix . 'mxchat_system_prompt_content'; // Clear cache and delete prompt wp_cache_delete('prompt_' . $id, 'mxchat_prompts'); $result = $wpdb->delete( $table_name, array('id' => intval($id)), array('%d') ); if ($result !== false) { $success = true; set_transient('mxchat_admin_notice_success', esc_html__('Entry deleted successfully.', 'mxchat'), 30); } else { set_transient('mxchat_admin_notice_error', esc_html__('Failed to delete entry from database.', 'mxchat'), 30); } } // Redirect back to the prompts page wp_safe_redirect(add_query_arg( array( 'page' => 'mxchat-prompts', 'deleted' => $success ? 'true' : 'false' ), admin_url('admin.php') )); exit; } /** * Averages multiple vectors into a single vector */ private function mxchat_average_vectors($vectors) { $vector_length = count($vectors[0]); $sum_vector = array_fill(0, $vector_length, 0); foreach ($vectors as $vector) { for ($i = 0; $i < $vector_length; $i++) { $sum_vector[$i] += $vector[$i]; } } // Divide each component by the number of vectors to get the average $num_vectors = count($vectors); for ($i = 0; $i < $vector_length; $i++) { $sum_vector[$i] /= $num_vectors; } return $sum_vector; } /** * Generates embeddings from input text for MXChat */ public function mxchat_generate_embedding($text) { // Enable detailed logging for debugging //error_log('[MXCHAT-EMBED] Starting embedding generation. Text length: ' . strlen($text) . ' bytes'); //error_log('[MXCHAT-EMBED] Text preview: ' . substr($text, 0, 100) . '...'); $options = get_option('mxchat_options'); $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002'; //error_log('[MXCHAT-EMBED] Selected embedding model: ' . $selected_model); // Determine provider and endpoint if (strpos($selected_model, 'voyage') === 0) { $api_key = $options['voyage_api_key'] ?? ''; $endpoint = 'https://api.voyageai.com/v1/embeddings'; $provider_name = 'Voyage AI'; //error_log('[MXCHAT-EMBED] Using Voyage AI API'); } elseif (strpos($selected_model, 'gemini-embedding') === 0) { $api_key = $options['gemini_api_key'] ?? ''; $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent'; $provider_name = 'Google Gemini'; //error_log('[MXCHAT-EMBED] Using Google Gemini API'); } else { $api_key = $options['api_key'] ?? ''; $endpoint = 'https://api.openai.com/v1/embeddings'; $provider_name = 'OpenAI'; //error_log('[MXCHAT-EMBED] Using OpenAI API'); } //error_log('[MXCHAT-EMBED] Using endpoint: ' . $endpoint); if (empty($api_key)) { $error_message = sprintf('Missing %s API key. Please configure your API key in the MxChat settings.', $provider_name); //error_log('[MXCHAT-EMBED] Error: ' . $error_message); return $error_message; } // Check if text is too long (for OpenAI, roughly estimate tokens as words/0.75) $estimated_tokens = ceil(str_word_count($text) / 0.75); //error_log('[MXCHAT-EMBED] Estimated token count: ~' . $estimated_tokens); if ($estimated_tokens > 8000 && strpos($selected_model, 'voyage') === false && strpos($selected_model, 'gemini-embedding') === false) { //error_log('[MXCHAT-EMBED] Warning: Text may exceed OpenAI token limits (8K for most models)'); // Consider truncating text here } // Prepare request body based on provider if (strpos($selected_model, 'gemini-embedding') === 0) { // Gemini API format $request_body = array( 'model' => 'models/' . $selected_model, 'content' => array( 'parts' => array( array('text' => $text) ) ) ); // Set output dimensionality to 1536 for consistency with other models $request_body['outputDimensionality'] = 1536; } else { // OpenAI/Voyage API format $request_body = array( 'model' => $selected_model, 'input' => $text ); // Add output_dimension for voyage-3-large model if ($selected_model === 'voyage-3-large') { $request_body['output_dimension'] = 2048; } } //error_log('[MXCHAT-EMBED] Request prepared with model: ' . $selected_model); // Prepare headers based on provider if (strpos($selected_model, 'gemini-embedding') === 0) { // Gemini uses API key as query parameter $endpoint .= '?key=' . $api_key; $headers = array( 'Content-Type' => 'application/json' ); } else { // OpenAI/Voyage use Bearer token $headers = array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json' ); } // Make API request //error_log('[MXCHAT-EMBED] Sending API request to: ' . $endpoint); $response = wp_remote_post($endpoint, array( 'body' => wp_json_encode($request_body), 'headers' => $headers, 'timeout' => 60 // Increased timeout for large inputs )); // Handle wp_remote_post errors if (is_wp_error($response)) { $error_message = $response->get_error_message(); //error_log('[MXCHAT-EMBED] WP Remote Post Error: ' . $error_message); return 'Connection error: ' . $error_message; } // Get and check HTTP response code $http_code = wp_remote_retrieve_response_code($response); //error_log('[MXCHAT-EMBED] API Response Code: ' . $http_code); if ($http_code !== 200) { $error_body = wp_remote_retrieve_body($response); //error_log('[MXCHAT-EMBED] API Error Response Body: ' . $error_body); // Try to parse error for more details $error_json = json_decode($error_body, true); if (json_last_error() === JSON_ERROR_NONE && isset($error_json['error'])) { $error_type = $error_json['error']['type'] ?? 'unknown'; $error_message = $error_json['error']['message'] ?? 'No message'; //error_log('[MXCHAT-EMBED] API Error Type: ' . $error_type); //error_log('[MXCHAT-EMBED] API Error Message: ' . $error_message); // Customize error message for common API errors if ($error_type === 'invalid_request_error' && strpos($error_message, 'API key') !== false) { $error_message = sprintf('Invalid %s API key. Please check your API key in the MxChat settings.', $provider_name); } elseif ($error_type === 'authentication_error') { $error_message = sprintf('%s authentication failed. Please verify your API key in the MxChat settings.', $provider_name); } //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message); return $error_message; } $error_message = sprintf("API Error (HTTP %d): Unable to generate embedding", $http_code); //error_log('[MXCHAT-EMBED] Returning error: ' . $error_message); return $error_message; } // Parse response body $response_body = wp_remote_retrieve_body($response); //error_log('[MXCHAT-EMBED] Received response length: ' . strlen($response_body) . ' bytes'); $response_data = json_decode($response_body, true); if (json_last_error() !== JSON_ERROR_NONE) { $error = json_last_error_msg(); //error_log('[MXCHAT-EMBED] JSON Parse Error: ' . $error); //error_log('[MXCHAT-EMBED] Response preview: ' . substr($response_body, 0, 200)); return "Failed to parse API response: $error"; } // Handle different response formats based on provider if (strpos($selected_model, 'gemini-embedding') === 0) { // Gemini API response format if (isset($response_data['embedding']['values'])) { $embedding_dimensions = count($response_data['embedding']['values']); //error_log('[MXCHAT-EMBED] Successfully extracted Gemini embedding with ' . $embedding_dimensions . ' dimensions'); // Check if embedding dimensions are as expected (should be 1536) if ($embedding_dimensions !== 1536) { //error_log('[MXCHAT-EMBED] Warning: Unexpected Gemini embedding dimensions: ' . $embedding_dimensions); } MxChat_Utils::stamp_active_embedding_model($selected_model); return $response_data['embedding']['values']; } else { //error_log('[MXCHAT-EMBED] Error: No embedding found in Gemini response'); //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data))); if (isset($response_data['error'])) { $error_message = "Gemini API Error in response: " . wp_json_encode($response_data['error']); //error_log('[MXCHAT-EMBED] ' . $error_message); return $error_message; } $error_message = "Invalid Gemini API response format: No embedding found"; //error_log('[MXCHAT-EMBED] ' . $error_message); return $error_message; } } else { // OpenAI/Voyage API response format if (isset($response_data['data'][0]['embedding'])) { $embedding_dimensions = count($response_data['data'][0]['embedding']); //error_log('[MXCHAT-EMBED] Successfully extracted embedding with ' . $embedding_dimensions . ' dimensions'); // Check if embedding dimensions are as expected if (($selected_model === 'text-embedding-ada-002' && $embedding_dimensions !== 1536) || ($selected_model === 'voyage-3-large' && $embedding_dimensions !== 2048)) { //error_log('[MXCHAT-EMBED] Warning: Unexpected embedding dimensions'); } MxChat_Utils::stamp_active_embedding_model($selected_model); return $response_data['data'][0]['embedding']; } else { //error_log('[MXCHAT-EMBED] Error: No embedding found in response'); //error_log('[MXCHAT-EMBED] Response structure: ' . wp_json_encode(array_keys($response_data))); if (isset($response_data['error'])) { $error_message = "API Error in response: " . wp_json_encode($response_data['error']); //error_log('[MXCHAT-EMBED] ' . $error_message); return $error_message; } $error_message = "Invalid API response format: No embedding found"; //error_log('[MXCHAT-EMBED] ' . $error_message); return $error_message; } } } } ?>