api_handler = $api_handler; // API testing endpoint add_action('wp_ajax_ai_botkit_test_api_connection', array($this, 'handle_test_api')); // Chatbot management endpoints add_action('wp_ajax_ai_botkit_save_chatbot', array($this, 'handle_save_chatbot')); add_action('wp_ajax_ai_botkit_get_chatbot', array($this, 'handle_get_chatbot')); add_action('wp_ajax_ai_botkit_delete_chatbot', array($this, 'handle_delete_chatbot')); // Fallback order management endpoint add_action('wp_ajax_ai_botkit_update_fallback_order', array($this, 'handle_update_fallback_order')); // Rate limit management endpoints add_action('wp_ajax_ai_botkit_set_rate_limits', array($this, 'handle_set_rate_limits')); add_action('wp_ajax_ai_botkit_reset_rate_limits', array($this, 'handle_reset_rate_limits')); // Preview content endpoint add_action('wp_ajax_ai_botkit_preview_content', array($this, 'ai_botkit_preview_content')); // Document import endpoints add_action('wp_ajax_ai_botkit_upload_file', array($this, 'handle_file_upload')); add_action('wp_ajax_ai_botkit_import_url', array($this, 'handle_url_import')); add_action('wp_ajax_ai_botkit_import_wp_content', array($this, 'handle_wp_content_import')); add_action('wp_ajax_ai_botkit_delete_document', array($this, 'handle_delete_document')); // Chatbot document management endpoints add_action('wp_ajax_ai_botkit_add_chatbot_documents', array($this, 'handle_add_chatbot_documents')); add_action('wp_ajax_ai_botkit_remove_chatbot_document', array($this, 'handle_remove_chatbot_document')); add_action('wp_ajax_ai_botkit_get_chatbot_documents', array($this, 'handle_get_chatbot_documents')); // New endpoint for getting available documents for selection add_action('wp_ajax_ai_botkit_get_available_documents', array($this, 'handle_get_available_documents')); // Avatar upload endpoint add_action('wp_ajax_ai_botkit_upload_avatar', array($this, 'handle_upload_avatar')); add_action('wp_ajax_ai_botkit_upload_background_image', array($this, 'handle_upload_background_image')); // Conversations & Leads AJAX endpoints add_action('wp_ajax_ai_botkit_get_conversations', array($this, 'handle_get_conversations')); add_action('wp_ajax_ai_botkit_get_conversation_detail', array($this, 'handle_get_conversation_detail')); add_action('wp_ajax_ai_botkit_get_leads', array($this, 'handle_get_leads')); // SaaS connect-token claim (WP pulls the token outbound — see // docs/wordpress-token-claim/EXECUTION-PLAN.md) add_action('wp_ajax_ai_botkit_claim_token', array($this, 'handle_claim_token')); // Agent card and Deploy dialog: the shared chat widget switch, and // placement on this site (plan U12) add_action('wp_ajax_ai_botkit_get_deploy_state', array($this, 'handle_get_deploy_state')); add_action('wp_ajax_ai_botkit_set_widget_status', array($this, 'handle_set_widget_status')); add_action('wp_ajax_ai_botkit_save_placement', array($this, 'handle_save_placement')); add_action('wp_ajax_ai_botkit_search_items', array($this, 'handle_search_items')); } /** * The chat widget switch and this site's placement for each agent. * * Reads the agent list from AI BotKit every time, so the card and dialog * always show the current switch (R7), and fills each placement record's * numeric id on the way (KTD9). POST `namespace` narrows to one agent. */ public function handle_get_deploy_state() { $this->guard(); $namespace = isset($_POST['namespace']) ? sanitize_text_field(wp_unslash($_POST['namespace'])) : ''; $result = $this->api()->get_agents(); if (!$result['ok']) { wp_send_json_error(['message' => $result['error']]); } $agents = []; foreach ($result['agents'] as $agent) { if ('' !== $namespace && $agent['namespace'] !== $namespace) { continue; } $placement = '' === $agent['namespace'] ? null : $this->fill_placement_id($agent['namespace'], $agent['id']); $agents[] = $agent + [ 'deployed' => null !== $placement, 'placement' => $placement, ]; } if ('' === $namespace) { wp_send_json_success(['agents' => $agents]); } if (!$agents) { wp_send_json_error(['message' => __('This agent is not available to this site.', 'ai-botkit-for-lead-generation')]); } wp_send_json_success(['agents' => $agents, 'agent' => $agents[0]]); } /** * Turns the agent's chat widget on or off in AI BotKit and answers with * the value AI BotKit stored (R15, KTD6). Nothing is kept on this site, so * a failure leaves the dialog's previous value standing. * * POST `chatbot_id` (int), `enabled` ('1'/'0'/'true'/'false'). */ public function handle_set_widget_status() { $this->guard(); $chatbot_id = isset($_POST['chatbot_id']) && is_numeric($_POST['chatbot_id']) ? intval($_POST['chatbot_id']) : 0; $enabled = isset($_POST['enabled']) ? $this->parse_switch(sanitize_text_field(wp_unslash($_POST['enabled']))) : null; if ($chatbot_id <= 0) { wp_send_json_error(['message' => __('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]); } if (null === $enabled) { wp_send_json_error(['message' => __('Choose whether the chat widget is on or off.', 'ai-botkit-for-lead-generation')]); } $result = $this->api()->set_widget_enabled($chatbot_id, $enabled); if (!$result['ok']) { wp_send_json_error(['message' => $result['error']]); } wp_send_json_success($result['agent'] + [ 'message' => $result['agent']['widget_enabled'] ? __('The chat widget is on.', 'ai-botkit-for-lead-generation') : __('The chat widget is off.', 'ai-botkit-for-lead-generation'), ]); } /** * Saves where an agent shows on this site. Placement stays on the site; * AI BotKit is not told (R18, KTD7). * * POST `namespace`, `mode` ('entire_site'|'selected'), `show` and `hide` * (each {home, post_types[], items[]}, as form arrays or a JSON string), * optional `chatbot_id`. `deploy=1` is the first Deploy: after placement * is saved, the chat widget is switched on (R13). `widget_enabled=0` says * the dialog shows the switch off, so the reply can say it still is (R14). */ public function handle_save_placement() { $this->guard(); $namespace = isset($_POST['namespace']) ? sanitize_text_field(wp_unslash($_POST['namespace'])) : ''; $mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : ''; $chatbot_id = isset($_POST['chatbot_id']) && is_numeric($_POST['chatbot_id']) ? intval($_POST['chatbot_id']) : 0; $deploy = isset($_POST['deploy']) && '1' === sanitize_text_field(wp_unslash($_POST['deploy'])); $switch_off = isset($_POST['widget_enabled']) && false === $this->parse_switch(sanitize_text_field(wp_unslash($_POST['widget_enabled']))); if ('' === $namespace) { wp_send_json_error(['message' => __('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]); } if (!in_array($mode, ['entire_site', 'selected'], true)) { wp_send_json_error(['message' => __('Choose where the agent shows.', 'ai-botkit-for-lead-generation')]); } if ($deploy && $chatbot_id <= 0) { wp_send_json_error(['message' => __('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]); } // Until the placement migration completes, visitors still get the old placement, // and a later run rebuilds the store from the old options. Finish it first, or refuse. if (!\AI_BotKit\Placement\Placement_Migration::is_complete()) { \AI_BotKit\Placement\Placement_Migration::maybe_run(); if (!\AI_BotKit\Placement\Placement_Migration::is_complete()) { wp_send_json_error([ 'message' => __('Your placement settings are still being updated. Reload this page in a minute and try again.', 'ai-botkit-for-lead-generation'), ]); } } $show = $this->read_rules('show'); $hide = $this->read_rules('hide'); if (null === $show || null === $hide) { wp_send_json_error([ /* translators: %d: the most items one list may hold */ 'message' => sprintf(__('Each list can hold up to %d items. Remove some and save again.', 'ai-botkit-for-lead-generation'), self::MAX_RULE_ITEMS), ]); } $existing = \AI_BotKit\Placement\Placement_Store::get($namespace); // deploy=1 on an agent that already has a placement is Save changes switching it back on. $was_deployed = null !== $existing; if ($chatbot_id <= 0) { $chatbot_id = null !== $existing && null !== $existing['id'] ? $existing['id'] : 0; } $placement = \AI_BotKit\Placement\Placement_Store::save([ 'namespace' => $namespace, 'id' => $chatbot_id, 'mode' => $mode, 'show' => $show, 'hide' => $hide, ]); if (!$deploy) { wp_send_json_success([ 'placement' => $placement, 'message' => $switch_off ? __('Saved. The chat widget is still inactive, so visitors won\'t see this agent until you switch it on.', 'ai-botkit-for-lead-generation') : __('Saved.', 'ai-botkit-for-lead-generation'), ]); } $result = $this->api()->set_widget_enabled($chatbot_id, true); if (!$result['ok']) { wp_send_json_error([ 'placement_saved' => true, 'placement' => $placement, 'widget_enabled' => false, 'message' => __('Where it shows is saved, but the agent is still inactive.', 'ai-botkit-for-lead-generation') . ' ' . $result['error'], ]); } wp_send_json_success([ 'placement' => $placement, 'widget_enabled' => $result['agent']['widget_enabled'], 'live' => $result['agent']['live'], 'message' => $result['agent']['widget_enabled'] ? ($was_deployed ? __('Saved. The agent is active again.', 'ai-botkit-for-lead-generation') : __('Deployed. The agent is live on this site.', 'ai-botkit-for-lead-generation')) : __('Where it shows is saved, but the agent is still inactive.', 'ai-botkit-for-lead-generation'), ]); } /** * Search for the "Specific items" picker: published items of public post * types, matching `search`, 20 per page. POST `search`, `page` (from 1), * optional `post_type`. * * Titles are returned as plain text and links only when http(s); the * dialog inserts both as text. */ public function handle_search_items() { $this->guard(); $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : ''; $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1; $post_type = isset($_POST['post_type']) ? sanitize_key(wp_unslash($_POST['post_type'])) : ''; $types = $this->placement_post_types(); if ('' !== $post_type) { if (!isset($types[$post_type])) { wp_send_json_error(['message' => __('Invalid post type.', 'ai-botkit-for-lead-generation')]); } $query_types = [$post_type]; } else { $query_types = array_keys($types); } $args = [ 'post_type' => $query_types, 'post_status' => 'publish', 'posts_per_page' => self::SEARCH_PER_PAGE, 'paged' => $page, 'orderby' => '' === $search ? 'title' : 'relevance', 'order' => 'ASC', 'ignore_sticky_posts' => true, ]; if ('' !== $search) { $args['s'] = $search; } $query = new \WP_Query($args); $items = []; foreach ($query->posts as $post) { $title = trim((string) $post->post_title); $type = isset($types[$post->post_type]) ? $types[$post->post_type] : null; $items[] = [ 'id' => (int) $post->ID, 'title' => '' === $title ? __('(no title)', 'ai-botkit-for-lead-generation') : $title, 'type' => (string) $post->post_type, 'type_label' => $type ? (isset($type->labels->singular_name) ? (string) $type->labels->singular_name : (string) $type->label) : (string) $post->post_type, 'url' => $this->http_url(get_permalink($post)), ]; } $total = (int) $query->found_posts; $total_pages = (int) ceil($total / self::SEARCH_PER_PAGE); wp_send_json_success([ 'items' => $items, 'page' => $page, 'per_page' => self::SEARCH_PER_PAGE, 'total' => $total, 'total_pages' => $total_pages, 'has_more' => $page < $total_pages, ]); } /** * Nonce, then manage_options. Ends the request on failure, before any * input is read, option written or request sent. */ private function guard(): void { check_ajax_referer('ai_botkit_admin', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(['message' => __('Insufficient permissions.', 'ai-botkit-for-lead-generation')], 403); } } private function api(): \AI_BotKit\Integration\API_Handler { if (null === $this->api_handler) { $this->api_handler = new \AI_BotKit\Integration\API_Handler(); } return $this->api_handler; } /** * true, false, or null when the value is neither. * * @return bool|null */ private function parse_switch(string $value) { $value = strtolower($value); if (in_array($value, ['1', 'true', 'on'], true)) { return true; } if (in_array($value, ['0', 'false', 'off'], true)) { return false; } return null; } /** * Writes the agent's numeric id into its placement record, if it has one, * without touching its rules or its place in the order. * * @return array|null The record, or null when the agent is not placed here. */ private function fill_placement_id(string $namespace, int $chatbot_id) { $record = \AI_BotKit\Placement\Placement_Store::get($namespace); if (null === $record || $chatbot_id <= 0 || $record['id'] === $chatbot_id) { return $record; } $record['id'] = $chatbot_id; return \AI_BotKit\Placement\Placement_Store::write_record($record); } /** * One Show on or Hide on list from the request, sanitised. * * Only public post types are kept, and only positive item ids: anything * else, a `javascript:` string included, is dropped. Item entries may be * ids or {id, ...} objects; only the id is kept. * * @return array|null The rules, or null when a list is over the item cap. */ private function read_rules(string $key) { $raw = isset($_POST[$key]) ? wp_unslash($_POST[$key]) : []; if (is_string($raw)) { $raw = '' === trim($raw) ? [] : json_decode($raw, true); } if (!is_array($raw)) { $raw = []; } $raw_items = isset($raw['items']) && is_array($raw['items']) ? $raw['items'] : []; if (count($raw_items) > self::MAX_RULE_ITEMS) { return null; } // Placement_Store::normalize() keeps only positive numeric ids. $items = []; foreach ($raw_items as $item) { if (is_array($item)) { $item = isset($item['id']) ? $item['id'] : null; } if (is_scalar($item)) { $items[] = $item; } } $types = $this->placement_post_types(); $post_types = []; foreach (isset($raw['post_types']) && is_array($raw['post_types']) ? $raw['post_types'] : [] as $post_type) { if (!is_scalar($post_type)) { continue; } $post_type = sanitize_key((string) $post_type); if (isset($types[$post_type])) { $post_types[] = $post_type; } } $home = false; if (isset($raw['home'])) { $home = is_bool($raw['home']) ? $raw['home'] : (is_scalar($raw['home']) && true === $this->parse_switch((string) $raw['home'])); } return [ 'home' => $home, 'post_types' => $post_types, 'items' => $items, ]; } /** * Public post types that can be placement targets, keyed by name. * * @return object[] */ private function placement_post_types(): array { $types = []; foreach ((array) get_post_types(['public' => true], 'objects') as $name => $type) { if (!in_array((string) $name, self::EXCLUDED_POST_TYPES, true)) { $types[(string) $name] = $type; } } return $types; } /** * The URL when it is http(s), otherwise ''. */ private function http_url($url): string { if (!is_string($url) || '' === $url) { return ''; } $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME)); if ('http' !== $scheme && 'https' !== $scheme) { return ''; } return esc_url_raw($url, ['http', 'https']); } /** * Claim the SaaS connect token via an outbound (WP -> SaaS) request. * * Triggered by admin.js after the SaaS popup posts `ai-botkit:connect:success`. The * postMessage only signals that authentication succeeded; the token itself is pulled * here. Pulling it outbound sidesteps the inbound WAF / Cloudflare / security-plugin * blocking that made the legacy /wp-json/ai-botkit/v1/setToken push unreliable. */ public function handle_claim_token() { check_ajax_referer('ai_botkit_admin', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]); } $connect_nonce = get_transient('ai_botkit_onboarding_nonce'); if (empty($connect_nonce)) { wp_send_json_error(['expired' => true, 'message' => esc_html__('Connection expired. Please try logging in again.', 'ai-botkit-for-lead-generation')]); } global $ai_botkit_url; $response = wp_remote_post($ai_botkit_url . '/api/wordpress/claim-token', [ 'headers' => ['Content-Type' => 'application/json'], 'body' => wp_json_encode([ 'siteUrl' => home_url(), 'nonce' => $connect_nonce, ]), 'timeout' => 30, ]); if (is_wp_error($response)) { wp_send_json_error(['message' => $response->get_error_message()]); } $code = wp_remote_retrieve_response_code($response); $data = json_decode(wp_remote_retrieve_body($response), true); if ($code === 200 && !empty($data['token'])) { update_option('ai_botkit_saas_connect_token', $data['token'], false); delete_transient('ai_botkit_onboarding_nonce'); wp_send_json_success(['connected' => true]); } // Claim record not committed yet — let the client retry. if ($code === 404 || (is_array($data) && !empty($data['pending']))) { wp_send_json_error(['pending' => true]); } // 410 (expired/already claimed) or any other failure. wp_send_json_error(['expired' => true]); } /** * Handle AJAX request for fetching conversations list */ public function handle_get_conversations() { check_ajax_referer('ai_botkit_admin', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]); } $bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0; $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1; $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 20; $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : ''; if ($bot_id <= 0) { wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]); } $api_handler = new \AI_BotKit\Integration\API_Handler(); $params = [ 'page' => $page, 'limit' => $limit, ]; if (!empty($search)) { $params['search'] = $search; } $response = $api_handler->send_get_request('chatbots/' . $bot_id . '/conversations', $params); wp_send_json($response); } /** * Handle AJAX request for fetching a single conversation's detail */ public function handle_get_conversation_detail() { check_ajax_referer('ai_botkit_admin', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]); } $conversation_id = isset($_POST['conversation_id']) ? intval($_POST['conversation_id']) : 0; if ($conversation_id <= 0) { wp_send_json_error(['message' => esc_html__('Invalid conversation ID.', 'ai-botkit-for-lead-generation')]); } $api_handler = new \AI_BotKit\Integration\API_Handler(); $response = $api_handler->send_get_request('conversations/' . $conversation_id); wp_send_json($response); } /** * Handle AJAX request for fetching leads */ public function handle_get_leads() { check_ajax_referer('ai_botkit_admin', 'nonce'); if (!current_user_can('manage_options')) { wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'ai-botkit-for-lead-generation')]); } $bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0; $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1; $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 10; if ($bot_id <= 0) { wp_send_json_error(['message' => esc_html__('Invalid chatbot ID.', 'ai-botkit-for-lead-generation')]); } $api_handler = new \AI_BotKit\Integration\API_Handler(); $response = $api_handler->send_get_request('chatbots/' . $bot_id . '/leads', [ 'page' => $page, 'limit' => $limit, ]); wp_send_json($response); } }