*/ class A1AI_Public { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * The data manager instance. * * @since 1.0.0 * @access private * @var A1AI_Data_Manager $data_manager Handles database operations. */ private $data_manager; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. * @param A1AI_Data_Manager $data_manager The data manager instance. */ public function __construct($plugin_name = 'a1ai', $version = '1.3.0', $data_manager = null) { $this->plugin_name = $plugin_name; $this->version = $version; $this->data_manager = $data_manager; // If data manager wasn't passed, create one if (null === $this->data_manager) { require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-data-manager.php'; $this->data_manager = new A1AI_Data_Manager(); } // Add defer to main script for Plugin Check NonBlockingScripts compliance. add_filter( 'script_loader_tag', array( $this, 'add_defer_to_public_script' ), 10, 3 ); } /** * Add defer attribute to the main public script for non-blocking loading. * * @param string $tag Script tag. * @param string $handle Handle. * @param string $src Source. * @return string */ public function add_defer_to_public_script( $tag, $handle, $src ) { if ( $this->plugin_name !== $handle ) { return $tag; } if ( false !== strpos( $tag, ' defer' ) || false !== strpos( $tag, ' async' ) ) { return $tag; } return str_replace( ' src', ' defer src', $tag ); } /** * Whether public assets (CSS/JS) should be enqueued on this request. * Only enqueue when a chatbot is shown: global widget enabled or shortcode in content. * * @return bool */ private function should_enqueue_public_assets() { if ( (bool) get_option( 'a1ai_global_chatbot_enabled', false ) && (int) get_option( 'a1ai_global_chatbot_id', 0 ) > 0 ) { return true; } if ( is_singular() ) { $post = get_queried_object(); if ( $post instanceof \WP_Post && has_shortcode( $post->post_content, 'a1ai_chatbot' ) ) { return true; } } return false; } /** * Register the stylesheets for the public-facing side of the site. * * @since 1.0.0 */ public function enqueue_styles() { if ( ! $this->should_enqueue_public_assets() ) { return; } wp_enqueue_style( $this->plugin_name, plugin_dir_url(__FILE__) . 'css/a1ai-public.css', array(), $this->version, 'all' ); } /** * Register the JavaScript for the public-facing side of the site. * * @since 1.0.0 */ public function enqueue_scripts() { if ( ! $this->should_enqueue_public_assets() ) { return; } $recaptcha_enabled = (bool) get_option('a1ai_recaptcha_enabled', false); $recaptcha_site_key = get_option('a1ai_recaptcha_site_key', ''); $script_deps = array('jquery'); if ($recaptcha_enabled && !empty($recaptcha_site_key)) { wp_enqueue_script( 'a1ai-recaptcha', 'https://www.google.com/recaptcha/api.js?render=' . esc_attr($recaptcha_site_key), array(), $this->version, true ); $script_deps[] = 'a1ai-recaptcha'; } wp_enqueue_script( $this->plugin_name, plugin_dir_url(__FILE__) . 'js/a1ai-public.js', $script_deps, $this->version, true ); wp_script_add_data( $this->plugin_name, 'strategy', 'defer' ); // Localize script with necessary data wp_localize_script( $this->plugin_name, 'a1ai_public_params', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('a1ai_public_nonce'), 'review_nonce' => wp_create_nonce('a1ai_submit_review'), 'error_message' => esc_html__('I apologize, but I\'m having a little trouble right now. Could you try your question again? If this continues, please reach out to us directly and we\'ll be happy to help!', 'a1ai-chatbot'), 'recaptcha_enabled' => $recaptcha_enabled, 'recaptcha_site_key' => $recaptcha_site_key, ) ); } /** * Register the shortcodes. * * @since 1.0.0 */ public function register_shortcodes() { add_shortcode('a1ai_chatbot', array($this, 'render_chatbot_shortcode')); } /** * Render the chatbot shortcode. * * @since 1.0.0 * @param array $atts Shortcode attributes. * @return string Shortcode output. */ public function render_chatbot_shortcode($atts) { $atts = shortcode_atts( array( 'id' => 0, ), $atts, 'a1ai_chatbot' ); // Sanitize attributes $chatbot_id = intval($atts['id']); if ($chatbot_id <= 0) { return '
' . esc_html__('Invalid chatbot ID.', 'a1ai-chatbot') . '
'; } // Get chatbot data $chatbot = $this->data_manager->get_chatbot($chatbot_id); if (empty($chatbot)) { return '
' . esc_html__('Chatbot not found.', 'a1ai-chatbot') . '
'; } // Get session ID for user $session_id = $this->get_session_id(); // Pass Public instance to template $public_instance = $this; // Start output buffering ob_start(); // Include template $template_path = plugin_dir_path(__FILE__) . 'partials/a1ai-shortcode-chatbot.php'; if (file_exists($template_path)) { include $template_path; } else { return '
' . esc_html__('Chatbot template not found.', 'a1ai-chatbot') . '
'; } // Get the buffered content $output = ob_get_clean(); // Apply filter to allow other plugins to modify the chatbot output $output = apply_filters('a1ai_chatbot_output', $output, $chatbot_id); return $output; } /** * Render the global chatbot. * * @since 1.0.0 */ public function render_global_chatbot() { // Simple test output echo ''; // Check if global chatbot is enabled $enabled = get_option('a1ai_global_chatbot_enabled', false); // Debug: Global chatbot enabled status if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } if (!$enabled) { if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } return; } // Get global chatbot ID $chatbot_id = intval(get_option('a1ai_global_chatbot_id', 0)); if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } if ($chatbot_id <= 0) { if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } return; } // Get chatbot data $chatbot = $this->data_manager->get_chatbot($chatbot_id); if (empty($chatbot)) { if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } return; } if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } // Get global position setting $global_position = get_option('a1ai_global_chatbot_position', 'bottom-right'); // Get session ID for user $session_id = $this->get_session_id(); // Pass Public instance to template $public_instance = $this; // Include template $template_path = plugin_dir_path(__FILE__) . 'partials/a1ai-global-chatbot.php'; if (file_exists($template_path)) { include $template_path; } else { if (defined('WP_DEBUG') && WP_DEBUG) { echo ''; } } } /** * Inject conversion tracking pixels into wp_head. * Reads from the a1ai_conversion_tracking option set in the Settings page. * Scripts are enqueued via wp_enqueue_script / wp_add_inline_script for Plugin Check compliance. */ public function inject_conversion_tracking_head() { $ct = get_option( 'a1ai_conversion_tracking', array() ); if ( empty( $ct['enabled'] ) ) { return; } $has_google = ! empty( $ct['google_ads_id'] ) || ! empty( $ct['ga4_id'] ); // Google Ads / GA4 — enqueue gtag.js and inline config if ( $has_google ) { $gtag_id = ! empty( $ct['ga4_id'] ) ? $ct['ga4_id'] : $ct['google_ads_id']; $gtag_url = 'https://www.googletagmanager.com/gtag/js?id=' . esc_attr( $gtag_id ); $gtag_inline = "window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\n"; if ( ! empty( $ct['ga4_id'] ) ) { $gtag_inline .= "gtag('config', '" . esc_js( $ct['ga4_id'] ) . "');\n"; } if ( ! empty( $ct['google_ads_id'] ) ) { $gtag_inline .= "gtag('config', '" . esc_js( $ct['google_ads_id'] ) . "');\n"; } wp_enqueue_script( 'a1ai-gtag', $gtag_url, array(), $this->version, false ); wp_script_add_data( 'a1ai-gtag', 'async', true ); wp_add_inline_script( 'a1ai-gtag', $gtag_inline ); } // Facebook Pixel — enqueue as inline script (no external URL for the snippet) if ( ! empty( $ct['facebook_pixel_id'] ) ) { $fb_id = esc_js( $ct['facebook_pixel_id'] ); $fb_inline = "!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');\nfbq('init', '" . $fb_id . "');\nfbq('track', 'PageView');\n"; wp_register_script( 'a1ai-fb-pixel', false, $has_google ? array( 'a1ai-gtag' ) : array(), $this->version, false ); wp_add_inline_script( 'a1ai-fb-pixel', $fb_inline ); wp_enqueue_script( 'a1ai-fb-pixel' ); echo '' . "\n"; } // Conversion config for JS event firing — inline on a dedicated handle if ( $has_google || ! empty( $ct['facebook_pixel_id'] ) ) { $config_inline = 'window.a1aiConversionTracking = ' . wp_json_encode( array( 'enabled' => true, 'google_ads_id' => $ct['google_ads_id'] ?? '', 'google_ads_label' => $ct['google_ads_label'] ?? '', 'ga4_id' => $ct['ga4_id'] ?? '', 'facebook_pixel_id' => $ct['facebook_pixel_id'] ?? '', ) ) . ";\n"; $deps = array(); if ( $has_google ) { $deps[] = 'a1ai-gtag'; } if ( ! empty( $ct['facebook_pixel_id'] ) ) { $deps[] = 'a1ai-fb-pixel'; } wp_register_script( 'a1ai-conversion-config', false, $deps, $this->version, false ); wp_add_inline_script( 'a1ai-conversion-config', $config_inline ); wp_enqueue_script( 'a1ai-conversion-config' ); } } /** * Verify reCAPTCHA token with Google. * * @since 1.0.0 * @param string $token The reCAPTCHA response token from the client. * @return bool True if verification passed or reCAPTCHA is disabled; false otherwise. */ private function verify_recaptcha($token) { if (!get_option('a1ai_recaptcha_enabled', false)) { return true; } $secret = get_option('a1ai_recaptcha_secret_key', ''); if (empty($secret) || empty($token)) { return false; } $user_ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''; $response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array( 'timeout' => 10, 'body' => array( 'secret' => $secret, 'response' => $token, 'remoteip' => $user_ip, ), ) ); if (is_wp_error($response)) { return false; } $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); return (200 === $code && !empty($data['success'])); } /** * Check if text looks like spam using simple heuristics. * * @since 1.0.0 * @param string $text The text to check. * @param string $context Optional. 'message' or 'review'. * @return bool True if spam-like; false otherwise. */ private function is_heuristic_spam($text, $context = 'message') { if (!get_option('a1ai_spam_heuristic_enabled', false)) { return false; } $text = is_string($text) ? $text : ''; $len = strlen($text); $max_length = ('review' === $context) ? 2000 : 2000; if ($len > $max_length) { return true; } $link_count = preg_match_all('#https?://[^\s]+#i', $text); $max_links = ('review' === $context) ? 1 : 3; if ($link_count > $max_links) { return true; } if (preg_match('#(.)\1{9,}#', $text)) { return true; } return false; } /** * Classify text as spam using OpenAI (when option is enabled). * * @since 1.0.0 * @param string $text The text to classify. * @return bool True if classified as spam; false otherwise. */ private function is_ai_spam($text) { if (!get_option('a1ai_spam_ai_enabled', false)) { return false; } $api_key = get_option('a1ai_openai_api_key', ''); if (empty($api_key) || !is_string($text) || '' === trim($text)) { return false; } $model = get_option('a1ai_default_model', 'gpt-4o'); if (strpos($model, 'gpt-4o') !== false || strpos($model, 'gpt-4') !== false) { $model = 'gpt-4o-mini'; } $messages = array( array( 'role' => 'system', 'content' => 'Reply with exactly one word: spam or ok. Classify the following user message. Only output that one word.', ), array( 'role' => 'user', 'content' => substr($text, 0, 2000), ), ); $body = wp_json_encode(array( 'model' => $model, 'messages' => $messages, 'max_tokens' => 5, 'temperature' => 0, )); $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array( 'timeout' => 15, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => $body, ) ); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return false; } $res_body = wp_remote_retrieve_body($response); $data = json_decode($res_body, true); $reply = isset($data['choices'][0]['message']['content']) ? trim(strtolower($data['choices'][0]['message']['content'])) : ''; return (strpos($reply, 'spam') !== false); } /** * Handle AJAX request to send a message. * * @since 1.0.0 */ public function handle_send_message() { // Basic debug logging if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI: handle_send_message called at " . gmdate('Y-m-d H:i:s')); } // Check nonce for security if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_key(wp_unslash($_POST['nonce'])), 'a1ai_public_nonce')) { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI: Nonce check failed"); } wp_send_json_error(array('error' => 'Security check failed.')); } // Rate limiting: Prevent API abuse $user_ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''; $rate_limit_key = 'a1ai_rate_limit_' . md5($user_ip); $request_count = get_transient($rate_limit_key); $rate_limit = apply_filters('a1ai_rate_limit_messages_per_minute', 60); // Allow filtering if ($request_count && $request_count >= $rate_limit) { wp_send_json_error(array('error' => 'Rate limit exceeded. Please wait before sending more messages.')); } // Increment request count set_transient($rate_limit_key, ($request_count ? $request_count + 1 : 1), MINUTE_IN_SECONDS); // reCAPTCHA verification if (get_option('a1ai_recaptcha_enabled', false)) { $recaptcha_token = isset($_POST['g-recaptcha-response']) ? sanitize_text_field(wp_unslash($_POST['g-recaptcha-response'])) : ''; if (!$this->verify_recaptcha($recaptcha_token)) { wp_send_json_error(array('error' => __('Security check failed. Please try again.', 'a1ai-chatbot'))); return; } } // Check required parameters if (!isset($_POST['chatbot_id']) || !isset($_POST['session_id']) || !isset($_POST['message'])) { wp_send_json_error(array('error' => 'Missing required parameters.')); } // Sanitize inputs $chatbot_id = intval($_POST['chatbot_id']); $session_id = sanitize_text_field(wp_unslash($_POST['session_id'])); $message = sanitize_textarea_field(wp_unslash($_POST['message'])); $current_url = isset($_POST['current_url']) ? esc_url_raw(wp_unslash($_POST['current_url'])) : ''; $page_title = isset($_POST['page_title']) ? sanitize_text_field(wp_unslash($_POST['page_title'])) : ''; if (empty($message)) { wp_send_json_error(array('error' => 'Message cannot be empty.')); } // Heuristic spam check if ($this->is_heuristic_spam($message, 'message')) { wp_send_json_error(array('error' => __('Your message could not be sent.', 'a1ai-chatbot'))); return; } // AI spam check if ($this->is_ai_spam($message)) { wp_send_json_error(array('error' => __('Your message could not be sent.', 'a1ai-chatbot'))); return; } // Get chatbot $chatbot = $this->data_manager->get_chatbot($chatbot_id); if (empty($chatbot)) { wp_send_json_error(array('error' => 'Chatbot not found.')); } // Get or create conversation $conversation = $this->data_manager->get_conversation_by_session($session_id, $chatbot_id); if (empty($conversation)) { $user_id = is_user_logged_in() ? get_current_user_id() : 0; // Fix: correct parameter order (chatbot_id, session_id, user_id) $conversation_id = $this->data_manager->create_conversation($chatbot_id, $session_id, $user_id); $conversation = $this->data_manager->get_conversation($conversation_id); // Send email notification for new chat if (!empty($conversation)) { $this->data_manager->send_new_chat_notification($chatbot_id, $session_id, $message); } } if (empty($conversation)) { wp_send_json_error(array('error' => 'Failed to create conversation.')); } // Store user message (ID used by frontend poll cursor for agent messages). $user_message_id = $this->data_manager->add_message($conversation['id'], 'user', $message); // Check if this is the review chatbot $review_chatbot_id = get_option('a1ai_review_chatbot_id', 0); $is_review_chatbot = ($chatbot_id == $review_chatbot_id && $review_chatbot_id > 0); if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: chatbot_id=$chatbot_id, review_chatbot_id=$review_chatbot_id, is_review_chatbot=" . ($is_review_chatbot ? 'true' : 'false')); } // Process with AI and get response try { $settings = maybe_unserialize($chatbot['settings']); $settings['_current_url'] = $current_url; $settings['_page_title'] = $page_title; $settings['chatbot_id'] = $chatbot_id; $settings['conversation_id'] = $conversation['id']; $settings = apply_filters('a1ai_chatbot_settings_before_ai', $settings, $chatbot_id); // Allow premium plugins to block AI response (e.g. human agent takeover). if ( apply_filters( 'a1ai_pre_ai_response_blocked', false, $conversation['id'] ) ) { wp_send_json_success( array( 'message' => '', 'taken_over' => true, 'tokens_used' => 0, 'conversation_id' => (int) $conversation['id'], 'last_message_id' => $user_message_id ? (int) $user_message_id : 0, ) ); return; } $ai_response_data = $this->process_ai_message($message, $conversation['id'], $settings, $chatbot_id); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Error in AI processing: " . $e->getMessage()); } wp_send_json_error( array( 'error' => 'AI processing failed.', 'conversation_id' => (int) $conversation['id'], 'last_message_id' => $user_message_id ? (int) $user_message_id : 0, ) ); return; } // Store AI response with token usage $tokens_used = isset($ai_response_data['tokens_used']) ? intval($ai_response_data['tokens_used']) : 0; $assistant_message_id = $this->data_manager->add_message($conversation['id'], 'assistant', $ai_response_data['message'], $tokens_used); // Allow upgrade to schedule inactivity email X minutes after this message (premium feature) do_action('a1ai_message_added', $conversation['id'], $chatbot_id); // Answer-quality telemetry (adjustment hits, abstentions, retrieval tier). // Single hook point covers both the adjustment and LLM paths. if (!empty($ai_response_data['quality']) && is_array($ai_response_data['quality'])) { $quality = $ai_response_data['quality']; $this->data_manager->add_quality_event(array( 'chatbot_id' => $chatbot_id, 'conversation_id' => (int) $conversation['id'], 'message_id' => $assistant_message_id ? (int) $assistant_message_id : 0, 'event_type' => $quality['event_type'], 'retrieval_tier' => $quality['retrieval_tier'], 'result_count' => $quality['result_count'], 'semantic_used' => $quality['semantic_used'], 'user_message' => $message, // For failures store WHY it failed (the visitor-facing text is // just a generic apology and tells the owner nothing). 'assistant_excerpt' => 'error' === $quality['event_type'] ? (isset($quality['error_message']) ? $quality['error_message'] : 'Unknown error') : (in_array($quality['event_type'], array('abstention', 'no_context'), true) ? $ai_response_data['message'] : ''), 'tokens_used' => $tokens_used, )); } // Check for conversation inactivity and send full conversation email if needed (premium feature) if (class_exists('A1AI_Upgrade_Helper') && A1AI_Upgrade_Helper::is_upgrade_active()) { // Load email manager if not already loaded $email_manager_path = defined('A1AI_UPGRADE_PLUGIN_DIR') ? A1AI_UPGRADE_PLUGIN_DIR . 'includes/class-a1ai-email-manager.php' : WP_PLUGIN_DIR . '/a1ai-chatbot-upgrade/includes/class-a1ai-email-manager.php'; if (file_exists($email_manager_path) && !class_exists('A1AI_Email_Manager')) { require_once $email_manager_path; } if (class_exists('A1AI_Email_Manager')) { $email_manager = new A1AI_Email_Manager(); if (method_exists($email_manager, 'check_and_send_inactivity_email')) { $email_manager->check_and_send_inactivity_email($conversation['id'], $chatbot_id); } } } // Fire chat_started conversion event on first exchange (upgrade plugin feature) if (class_exists('A1AI_Upgrade_Helper') && A1AI_Upgrade_Helper::is_upgrade_active()) { $messages = $this->data_manager->get_messages($conversation['id']); if (count($messages) <= 2) { // 1 user + 1 AI = first exchange do_action('a1ai_conversion_event', 'chat_started', array( 'chatbot_id' => $chatbot_id, 'session_id' => $session_id, 'page_url' => $current_url, )); } } // Check if we should show review form after this conversation $response_data = array( 'message' => $ai_response_data['message'], 'conversation_id' => (int) $conversation['id'], 'last_message_id' => $assistant_message_id ? (int) $assistant_message_id : 0, ); // Check if upgrade plugin is active (reviews are a premium feature) $upgrade_active = class_exists('A1AI_Upgrade_Helper') && A1AI_Upgrade_Helper::is_upgrade_active(); // Only show review forms if upgrade plugin is active if ($upgrade_active) { // Check if user is explicitly asking for a review (works on any chatbot) $is_review_request = $this->is_review_request($message, $session_id); // Show review confirmation only when user explicitly asks to leave a review if ($is_review_request) { $response_data['show_review_confirmation'] = true; $response_data['review_confirmation_html'] = '
' . '

' . esc_html__('Would you like to leave us a review? We\'d love to hear about your experience!', 'a1ai-chatbot') . '

' . '
'; $response_data['review_form_html'] = $this->generate_review_form($chatbot_id); } } // Send response wp_send_json_success($response_data); } /** * Process message with AI. * * @since 1.0.0 * @param string $message The user message. * @param int $conversation_id The conversation ID. * @param array $settings The chatbot settings. * @param int $chatbot_id The chatbot ID. * @return string The AI response. */ private function process_ai_message($message, $conversation_id, $settings, $chatbot_id = 0) { // Load OpenAI integration class require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-openai.php'; $openai = new A1AI_OpenAI($this->data_manager); // Add chatbot ID to settings $settings['chatbot_id'] = $chatbot_id; // Process with OpenAI $response = $openai->process_conversation($conversation_id, $message, $settings); // Check if successful if ($response['success']) { return array( 'message' => $response['message'], 'tokens_used' => isset($response['tokens_used']) ? intval($response['tokens_used']) : 0, 'quality' => isset($response['quality']) ? $response['quality'] : null, ); } else { // Log error for admin using WordPress debug logging if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // Only log when debugging is enabled // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log('A1AI OpenAI Error: ' . $response['error']); } // Return friendly error message to user. The quality payload rides // along so the failure is recorded for the site owner even though // the visitor only ever sees the generic apology. return array( 'message' => esc_html__('I apologize, but I\'m having a little trouble right now. Could you try your question again? If this continues, please reach out to us directly and we\'ll be happy to help!', 'a1ai-chatbot'), 'tokens_used' => 0, 'quality' => isset($response['quality']) ? $response['quality'] : null, ); } } /** * Generate a unique session ID for the user. * * @since 1.0.0 * @return string Unique session ID. */ private function get_session_id() { if (is_user_logged_in()) { $user_id = get_current_user_id(); $cookie_name = 'a1ai_session_id_user'; if ( ! isset( $_COOKIE[ $cookie_name ] ) ) { $session_id = 'user_' . $user_id . '_' . wp_generate_uuid4(); $this->remember_session_cookie( $cookie_name, $session_id ); } else { $session_id = sanitize_text_field( wp_unslash( $_COOKIE[ $cookie_name ] ) ); // Verify this session belongs to the current user (handles account switches) if ( strpos( $session_id, 'user_' . $user_id . '_' ) !== 0 ) { $session_id = 'user_' . $user_id . '_' . wp_generate_uuid4(); $this->remember_session_cookie( $cookie_name, $session_id ); } } } else { // For guests, use cookies to track sessions if ( ! isset( $_COOKIE['a1ai_session_id'] ) ) { $session_id = 'guest_' . wp_generate_uuid4(); $this->remember_session_cookie( 'a1ai_session_id', $session_id ); } else { $session_id = sanitize_text_field( wp_unslash( $_COOKIE['a1ai_session_id'] ) ); } } return $session_id; } /** * Persist a session id to a cookie, tolerating a request whose headers are * already out. * * get_session_id() can run during page render, and a theme or another * plugin may already have emitted output by then (Elementor's image-loading * optimization does). Calling setcookie() at that point raised a * "Cannot modify header information" warning on every page load AND left * the cookie unset, so the next request minted yet another id — churning * the visitor's session instead of keeping one. Writing $_COOKIE keeps the * rest of THIS request consistent; the real cookie is set whenever headers * are still open (always true on the admin-ajax path that actually starts a * conversation). * * @since 1.6.1 * @param string $name Cookie name. * @param string $value Session id. */ private function remember_session_cookie( $name, $value ) { $_COOKIE[ $name ] = $value; if ( headers_sent() ) { return; } setcookie( $name, $value, time() + ( 86400 * 30 ), COOKIEPATH, COOKIE_DOMAIN, is_ssl() ); } /** * Determine if review form should be shown * * @since 1.0.0 * @param int $conversation_id The conversation ID * @param string $message The user message * @return bool Whether to show review form */ private function should_show_review_form($conversation_id, $message, $session_id = '') { // Check if a review has already been submitted in this session if (!empty($session_id) && get_transient('a1ai_review_submitted_' . $session_id)) { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Review already submitted for session $session_id, not showing form"); } return false; } // Get message count in this conversation $messages = $this->data_manager->get_messages($conversation_id); $message_count = count($messages); if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Conversation $conversation_id has $message_count messages"); } // For the designated review chatbot, show form immediately on first interaction // For other chatbots, show after meaningful conversation $min_messages = 2; // Show immediately after first exchange (1 user + 1 AI) if ($message_count >= $min_messages) { $session_key = 'a1ai_review_shown_' . $conversation_id; $already_shown = get_transient($session_key); if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Session key: $session_key, Already shown: " . ($already_shown ? 'true' : 'false')); } if (!$already_shown) { // Mark as shown for 24 hours to avoid repeated requests set_transient($session_key, true, 24 * HOUR_IN_SECONDS); if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Setting transient and returning true"); } return true; } else { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Already shown, returning false"); } } } else { if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging wrapped in WP_DEBUG check error_log("A1AI Review: Not enough messages ($message_count < $min_messages), returning false"); } } return false; } /** * Check if user message is requesting a review * * @since 1.0.0 * @param string $message The user message * @return bool Whether message is requesting a review */ private function is_review_request($message, $session_id = '') { // Check if a review has already been submitted in this session if (!empty($session_id) && get_transient('a1ai_review_submitted_' . $session_id)) { return false; } $message_lower = strtolower(trim($message)); // Only match phrases that explicitly indicate wanting to leave a review // Broad single words like "experience", "rate", "feedback" are excluded // because they match normal conversation too easily $review_phrases = array( 'leave a review', 'write a review', 'give a review', 'submit a review', 'post a review', 'leave review', 'write review', 'give review', 'leave feedback', 'give feedback', 'submit feedback', 'rate you', 'rate your service', 'rate this service', 'rate this business', 'i want to review', 'i\'d like to review', 'how do i review', 'can i leave a review', 'can i review', ); foreach ($review_phrases as $phrase) { if (strpos($message_lower, $phrase) !== false) { return true; } } return false; } /** * Generate HTML for review form * * @since 1.0.0 * @param int $chatbot_id The chatbot ID * @return string Review form HTML */ public function generate_review_form($chatbot_id) { $rating_system = get_option('a1ai_rating_system', '5-star'); $intro_text = get_option('a1ai_review_intro_text', 'Thank you for taking the time to review us, please let us know how your experience has been!'); $min_star_threshold = get_option('a1ai_min_star_threshold', 3); $min_scale_threshold = get_option('a1ai_min_scale_threshold', 6); // Modern card-based form generation $form_html = '
'; $form_html .= '
'; $form_html .= '
★
'; $form_html .= '

' . esc_html__('Share Your Experience', 'a1ai-chatbot') . '

'; $form_html .= '
'; $form_html .= '
'; $form_html .= '

' . esc_html($intro_text) . '

'; $form_html .= '
'; $form_html .= '
'; // Add rating input based on system if ($rating_system === '10-scale') { $form_html .= '
'; $form_html .= ''; $form_html .= '
'; $form_html .= ''; $form_html .= '
5 / 10
'; $form_html .= '
'; $form_html .= '
'; } else { $form_html .= '
'; $form_html .= ''; $form_html .= '
'; $form_html .= '
'; for ($i = 1; $i <= 5; $i++) { $form_html .= '★'; } $form_html .= '
'; $form_html .= '
' . esc_html__('Click to rate', 'a1ai-chatbot') . '
'; $form_html .= '
'; $form_html .= ''; $form_html .= '
'; } // Initially hide form fields - they'll appear after rating is selected. Feedback textarea only when rating is below threshold. $form_html .= ''; // Close a1ai-review-form-fields $form_html .= '
'; $form_html .= '
'; // Add modern CSS styling $form_html .= ''; // Add working JavaScript $form_html .= ''; return $form_html; } /** * Handle review submission via AJAX * * @since 1.0.0 */ public function handle_submit_review() { // Check if upgrade plugin is active (reviews are a premium feature) if (!class_exists('A1AI_Upgrade_Helper') || !A1AI_Upgrade_Helper::is_upgrade_active()) { wp_send_json_error(array('error' => 'Review submission requires the premium upgrade.')); return; } // Check nonce for security if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_key(wp_unslash($_POST['nonce'])), 'a1ai_submit_review')) { wp_send_json_error(array('error' => 'Security check failed.')); return; } // reCAPTCHA verification if (get_option('a1ai_recaptcha_enabled', false)) { $recaptcha_token = isset($_POST['g-recaptcha-response']) ? sanitize_text_field(wp_unslash($_POST['g-recaptcha-response'])) : ''; if (!$this->verify_recaptcha($recaptcha_token)) { wp_send_json_error(array('error' => __('Security check failed. Please try again.', 'a1ai-chatbot'))); return; } } // Check required parameters if (!isset($_POST['chatbot_id']) || !isset($_POST['rating']) || !isset($_POST['reviewer_name']) || !isset($_POST['reviewer_email'])) { wp_send_json_error(array('error' => 'Missing required parameters.')); return; } // Sanitize inputs $chatbot_id = intval($_POST['chatbot_id']); $rating = intval($_POST['rating']); $comment = isset($_POST['comment']) ? sanitize_textarea_field(wp_unslash($_POST['comment'])) : ''; $reviewer_name = sanitize_text_field(wp_unslash($_POST['reviewer_name'])); $reviewer_email = sanitize_email(wp_unslash($_POST['reviewer_email'])); // Validate data if ($chatbot_id <= 0) { wp_send_json_error(array('error' => 'Invalid chatbot ID.')); return; } if ($rating < 1 || $rating > 10) { wp_send_json_error(array('error' => 'Invalid rating.')); return; } if (empty($reviewer_name) || empty($reviewer_email)) { wp_send_json_error(array('error' => 'Name and email are required.')); return; } if (!is_email($reviewer_email)) { wp_send_json_error(array('error' => 'Invalid email address.')); return; } // Heuristic spam check on review comment if ($this->is_heuristic_spam($comment, 'review')) { wp_send_json_error(array('error' => __('Your message could not be sent.', 'a1ai-chatbot'))); return; } // AI spam check on review comment if ($this->is_ai_spam($comment)) { wp_send_json_error(array('error' => __('Your message could not be sent.', 'a1ai-chatbot'))); return; } // Get chatbot to verify it exists $chatbot = $this->data_manager->get_chatbot($chatbot_id); if (empty($chatbot)) { wp_send_json_error(array('error' => 'Chatbot not found.')); return; } // Store the review (you'll need to create this table or extend existing tables) $review_data = array( 'chatbot_id' => $chatbot_id, 'rating' => $rating, 'comment' => $comment, 'reviewer_name' => $reviewer_name, 'reviewer_email' => $reviewer_email, 'date' => current_time('mysql'), 'status' => 'pending' // Reviews start as pending for moderation ); // For now, store as option until we have a proper reviews table $existing_reviews = get_option('a1ai_reviews', array()); $review_data['id'] = time() . '_' . $chatbot_id; // Simple ID for now $existing_reviews[] = $review_data; update_option('a1ai_reviews', $existing_reviews); // Fire conversion tracking event (if upgrade plugin active) if (class_exists('A1AI_Upgrade_Helper') && A1AI_Upgrade_Helper::is_upgrade_active()) { do_action('a1ai_conversion_event', 'review_submission', array( 'chatbot_id' => $chatbot_id, 'rating' => $rating, 'review_text' => $comment )); } // Mark this session as having submitted a review to prevent duplicate forms $session_id = isset($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''; if (!empty($session_id)) { set_transient('a1ai_review_submitted_' . $session_id, true, 3600); // 1 hour expiry } // Get threshold settings $rating_system = get_option('a1ai_rating_system', '5-star'); $min_star_threshold = get_option('a1ai_min_star_threshold', 3); $min_scale_threshold = get_option('a1ai_min_scale_threshold', 6); // Determine if rating meets threshold $meets_threshold = false; if ($rating_system === '10-scale') { $meets_threshold = ($rating >= $min_scale_threshold); } else { $meets_threshold = ($rating >= $min_star_threshold); } // Prepare response based on threshold if ($meets_threshold) { // High rating - positive response and external links $ai_message = __('Thank you so much for the positive feedback! We\'re thrilled to hear about your great experience. Was there anything else you particularly enjoyed? We\'d love for you to share your experience on our review platforms - the windows should be opening shortly!', 'a1ai-chatbot'); // Get external review links $external_links = array(); $google_link = get_option('a1ai_review_google_link', ''); $yelp_link = get_option('a1ai_review_yelp_link', ''); $facebook_link = get_option('a1ai_review_facebook_link', ''); $other_link = get_option('a1ai_review_other_link', ''); $other_name = get_option('a1ai_review_other_name', 'Other Platform'); if (!empty($google_link)) { $external_links[] = array('name' => 'Google', 'url' => $google_link); } if (!empty($yelp_link)) { $external_links[] = array('name' => 'Yelp', 'url' => $yelp_link); } if (!empty($facebook_link)) { $external_links[] = array('name' => 'Facebook', 'url' => $facebook_link); } if (!empty($other_link)) { $external_links[] = array('name' => $other_name, 'url' => $other_link); } // Send success response with external links and copy functionality wp_send_json_success(array( 'message' => $ai_message, 'external_links' => $external_links, 'show_copy_button' => true, 'review_summary' => $comment, 'rating_display' => ($rating_system === '10-scale') ? "$rating/10" : str_repeat('⭐', $rating) )); } else { // Low rating - supportive response, no external links $ai_message = __('Thank you for your honest feedback. We truly appreciate you taking the time to share your experience with us. We will look into the issues you\'ve mentioned and will get back to you if needed. Is there anything else you would like to discuss or any way we can better assist you?', 'a1ai-chatbot'); // Send response without external links wp_send_json_success(array( 'message' => $ai_message, 'external_links' => array(), // No external links for low ratings 'show_copy_button' => false, 'continue_conversation' => true // Flag to indicate conversation should continue )); } } }