settings = $settings ?? new ChatbotSettings(); $this->message_queue = $message_queue ?? new MessageQueue(); $this->rate_limiter = $rate_limiter ?? new RateLimiter( $this->settings ); $this->provider_cooldown = $provider_cooldown ?? new ProviderCooldown( $this->settings ); $this->service = $service ?? new ChatbotService($this->settings, null, null, null, null, $this->message_queue); } /** * Get string length with proper UTF-8 support. * * Uses mb_strlen when available, falls back to iconv_strlen, * and finally to a regex-based byte count as last resort. * * @param string $string The string to measure. * @return int Character count. */ private static function getStringLength( string $string ): int { if ( function_exists( 'mb_strlen' ) ) { return mb_strlen( $string, 'UTF-8' ); } if ( function_exists( 'iconv_strlen' ) ) { $length = iconv_strlen( $string, 'UTF-8' ); if ( false !== $length ) { return $length; } } $count = preg_match_all( '/./us', $string, $matches ); return false === $count ? 0 : $count; } /** * Register REST API routes. * * @return void */ public function register_routes(): void { ( new DiagController() )->register_routes(); register_rest_route(self::NAMESPACE, '/chat', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'handle_chat'], 'permission_callback' => '__return_true', 'args' => [ 'message' => [ 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', 'validate_callback' => function ($value) { if (!is_string($value)) { return false; } return self::getStringLength( trim( $value ) ) >= self::MIN_MESSAGE_LENGTH; }, ], 'session_id' => [ 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ($value) { return is_string($value) && preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $value); }, ], 'history' => [ 'required' => false, 'type' => 'array', 'default' => [], 'description' => __('Conversation history for context.', 'ai-product-tools'), 'validate_callback' => function ($value) { if (!is_array($value)) { return false; } if (count($value) > ChatbotConstants::maxHistoryMessages()) { return false; } foreach ($value as $msg) { if (!is_array($msg)) { return false; } if (!isset($msg['role']) || !isset($msg['content'])) { return false; } if (!in_array($msg['role'], ['user', 'assistant'], true)) { return false; } if (!is_string($msg['content'])) { return false; } } return true; }, 'sanitize_callback' => function ($value) { if (!is_array($value)) { return []; } return array_map(function ($msg) { return [ 'role' => sanitize_text_field($msg['role'] ?? 'user'), 'content' => self::clampHistoryContent(sanitize_textarea_field($msg['content'] ?? '')), ]; }, array_slice($value, 0, ChatbotConstants::maxHistoryMessages())); }, ], '_wpnonce' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'description' => __('Optional nonce for enhanced CSRF protection.', 'ai-product-tools'), ], 'user_name' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ($value) { if (!is_string($value)) { return false; } if (empty($value)) { return true; } return mb_strlen($value, 'UTF-8') <= ChatbotConstants::maxUserNameLength(); }, 'description' => __('User name from pre-chat form.', 'ai-product-tools'), ], 'user_email' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_email', 'validate_callback' => function ($value) { if (empty($value)) { return true; } return (bool) \is_email($value); }, 'description' => __('User email from pre-chat form.', 'ai-product-tools'), ], 'consent_given' => [ 'required' => false, 'type' => 'boolean', 'default' => false, 'description' => __('Whether user gave consent for email storage.', 'ai-product-tools'), ], 'consent_timestamp' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'validate_callback' => function ($value) { if (empty($value)) { return true; } $min_timestamp = strtotime('2020-01-01'); $max_timestamp = time() + DAY_IN_SECONDS; return $value >= $min_timestamp && $value <= $max_timestamp; }, 'description' => __('Unix timestamp when consent was given.', 'ai-product-tools'), ], ], ]); register_rest_route(self::NAMESPACE, '/labels', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_labels'], 'permission_callback' => '__return_true', 'args' => [ 'language' => [ 'required' => true, 'type' => 'string', 'validate_callback' => function ($value) { return is_string($value) && in_array($value, ChatbotSettings::getSupportedLanguages(), true); }, ], ], ]); register_rest_route(self::NAMESPACE, '/widget-extensions', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_widget_extensions'], 'permission_callback' => '__return_true', ]); register_rest_route(self::NAMESPACE, '/settings', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'update_settings'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'enabled' => [ 'type' => 'boolean', 'required' => false, ], 'provider' => [ 'type' => 'string', 'required' => false, 'enum' => ['openai', 'gemini', 'openrouter', 'claude'], ], 'model' => [ 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ], 'theme_primary_color' => [ 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_hex_color', ], ], ]); register_rest_route(self::NAMESPACE, '/settings/full', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_full_settings'], 'permission_callback' => [$this, 'check_permissions_write'], ]); register_rest_route(self::NAMESPACE, '/messages/(?P\d+)/respond', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'respond_to_message'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => $this->respond_route_args(), ]); register_rest_route(self::NAMESPACE, '/messages/(?P\d+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_message'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], ], ]); register_rest_route(self::NAMESPACE, '/messages/(?P\d+)', [ 'methods' => WP_REST_Server::DELETABLE, 'callback' => [$this, 'delete_message'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], ], ]); register_rest_route(self::NAMESPACE, '/cart/add', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'add_to_cart'], 'permission_callback' => [$this, 'check_cart_add_permission'], 'args' => $this->cart_add_route_args(), ]); register_rest_route(self::NAMESPACE, '/messages/stats', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_queue_stats'], 'permission_callback' => [$this, 'check_permissions_write'], ]); register_rest_route(self::NAMESPACE, '/messages/(?P[a-f0-9-]{36})/poll', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'poll_responses'], 'permission_callback' => '__return_true', 'args' => [ 'session_id' => [ 'required' => true, 'type' => 'string', 'validate_callback' => function ($value) { return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $value); }, ], ], ]); register_rest_route(self::NAMESPACE, '/messages/(?P\d+)/delivered', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'mark_delivered'], 'permission_callback' => '__return_true', 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], 'session_id' => [ 'required' => true, 'type' => 'string', 'validate_callback' => function ($value) { return preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $value); }, ], ], ]); register_rest_route(self::NAMESPACE, '/messages/bulk-delete', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'bulk_delete_messages'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'ids' => [ 'required' => true, 'type' => 'array', 'items' => ['type' => 'integer'], 'validate_callback' => function ($value) { return is_array($value) && !empty($value) && count($value) <= ChatbotConstants::maxBulkDeleteItems(); }, ], ], ]); register_rest_route(self::NAMESPACE, '/messages/search', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'search_messages'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'search' => [ 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ], 'status' => [ 'type' => 'string', 'default' => '', 'enum' => ['', 'queued', 'responded', 'retried', 'failed', 'delivered', 'info'], ], 'record_type' => [ 'type' => 'string', 'default' => '', 'enum' => ['', 'first_contact', 'error', 'conversation'], ], 'page' => [ 'type' => 'integer', 'default' => 1, 'minimum' => 1, ], 'per_page' => $this->per_page_arg(), ], ]); register_rest_route(self::NAMESPACE, '/messages/(?P\d+)/contact', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_message_contact'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], ], ]); } /** * Permission callback for write (admin) endpoints, also reused by a few * admin-only GET routes (messages/queued, messages/{id}, .../contact). * * Enforces manage_woocommerce capability, plus REST nonce verification * for a mutating request that was authenticated through the login * cookie. A GET read never needs the nonce, and neither does an * Application-Password/Basic-Auth (or other non-cookie) REST client, * which is already authenticated and has no way to ever obtain one * ({@see \AIPT\Utils\RestNonceGuard}). * * @param WP_REST_Request $request Request instance. * @return bool|WP_Error True when allowed, WP_Error when forbidden. */ public function check_permissions_write(WP_REST_Request $request) { if ('GET' !== $request->get_method() && \AIPT\Utils\RestNonceGuard::isCookieAuthenticated()) { $nonce = $request->get_header('X-WP-Nonce'); if (empty($nonce)) { $nonce = $request->get_param('_wpnonce'); } $nonce = is_string($nonce) ? sanitize_text_field(wp_unslash($nonce)) : ''; if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) { return new WP_Error( 'rest_forbidden_nonce', __('Invalid security token. Please refresh and try again.', 'ai-product-tools'), ['status' => 403] ); } } if (!current_user_can('manage_woocommerce')) { return new WP_Error( 'rest_forbidden', __('You do not have permission to manage chatbot settings.', 'ai-product-tools'), ['status' => 403] ); } return true; } /** * Check paid-plan access for the storefront cart action. * * G9 filter-bridge: asks the 'aipt_chatbot_add_to_cart_enabled' filter * (default false) whether the site holds the Business entitlement. The * premium module is the sole registrant; on a free build the filter is * never registered and this stays fail-closed (403 premium_required). * * @param WP_REST_Request $request Request instance. * @return bool|WP_Error True when allowed, WP_Error when forbidden. */ public function check_cart_add_permission(WP_REST_Request $request) { if (!apply_filters('aipt_chatbot_add_to_cart_enabled', false)) { return PlanDenial::publicError( 'chatbotAddToCart', PlanDenial::PLAN_BUSINESS, __('Add to cart is not available in this chat.', 'ai-product-tools') ); } return true; } /** * Handle chat request. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function handle_chat(WP_REST_Request $request): WP_REST_Response { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { return new \WP_REST_Response( array( 'success' => false, 'code' => $ai_gate->get_error_code(), 'message' => $ai_gate->get_error_message(), ), 503 ); } if ( \AIPT\Core\Services\SpendLimit::isReached() ) { return new WP_REST_Response( ChatbotService::spendLimitReply(), 503 ); } $nonce = $request->get_param('_wpnonce'); if (!empty($nonce) && !wp_verify_nonce($nonce, 'wp_rest')) { return new WP_REST_Response([ 'success' => false, 'code' => 'invalid_nonce', 'message' => __('Security verification failed. Please refresh and try again.', 'ai-product-tools'), ], 403); } $release_slot = ChatSlots::acquire(); if ( false === $release_slot ) { return $this->createChatBusyResponse(); } try { return $this->answerChat( $request ); } finally { if ( is_callable( $release_slot ) ) { $release_slot(); } } } /** * Answer a synchronous chat request, within the reply budget. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ private function answerChat( WP_REST_Request $request ): WP_REST_Response { $message = $request->get_param('message'); $session_id = $request->get_param('session_id'); $history = $request->get_param('history') ?? []; $user_name = $request->get_param('user_name') ?? ''; $user_email = $request->get_param('user_email') ?? ''; $consent_given = (bool) $request->get_param('consent_given'); $consent_timestamp = $request->get_param('consent_timestamp') ? (int) $request->get_param('consent_timestamp') : null; $rate_limit_check = $this->rate_limiter->check( $session_id ); if ( ! $rate_limit_check['allowed'] ) { return $this->createRateLimitFailureResponse( $rate_limit_check ); } $client_ip = $this->rate_limiter->getClientIp(); $ip_rate_limit_check = $this->rate_limiter->checkByIp( $client_ip ); if ( ! $ip_rate_limit_check['allowed'] ) { return $this->createRateLimitFailureResponse( $ip_rate_limit_check ); } $message = $request->get_param('message'); if (is_string($message) && self::getStringLength($message) > ChatbotConstants::maxMessageLength()) { return new WP_REST_Response([ 'success' => false, 'code' => 'message_too_long', 'message' => sprintf( /* translators: %d: maximum allowed message length in characters */ __('Message exceeds maximum length of %d characters.', 'ai-product-tools'), ChatbotConstants::maxMessageLength() ), ], 400); } $cooldown_provider = (string) ( $this->settings->get( 'behavior.provider' ) ?: '' ); $cooldown_retry_after = $this->provider_cooldown->getProviderCooldownRetryAfter( $cooldown_provider ); if ( $cooldown_retry_after > 0 ) { $response = new WP_REST_Response([ 'success' => false, 'code' => 'provider_cooldown', 'message' => __('The AI service is temporarily unavailable. Please try again shortly.', 'ai-product-tools'), 'data' => [ 'retry_after' => $cooldown_retry_after, ], ], 503); $response->header( 'Retry-After', $cooldown_retry_after ); return $response; } if (!$this->settings->isEnabled()) { return new WP_REST_Response([ 'success' => false, 'code' => 'chatbot_disabled', 'message' => __('The chatbot is currently disabled.', 'ai-product-tools'), ], 503); } try { $result = ProviderCallDeadline::run( $this->replyDeadline(), function () use ( $message, $session_id, $history, $user_name, $user_email, $consent_given, $consent_timestamp ) { return $this->service->processMessage( $message, $session_id, $history, $user_name, $user_email, $consent_given, $consent_timestamp ); } ); $this->activateProviderCooldownIfTransient( $result, $cooldown_provider ); if ($result['success']) { return new WP_REST_Response($result, 200); } $status_code = 500; if (isset($result['error'])) { switch ($result['error']) { case 'chatbot_unavailable': case 'service_unavailable': case 'rate_limit': case 'spend_limit_reached': $status_code = 503; break; case 'invalid_session': case 'message_too_long': $status_code = 400; break; } } return new WP_REST_Response($result, $status_code); } catch (\InvalidArgumentException $e) { Logger::debug('chatbot', 'Chat request rejected as invalid', ['error' => $e->getMessage()]); return new WP_REST_Response([ 'success' => false, 'code' => 'invalid_request', 'message' => $this->sanitizeErrorMessage($e->getMessage()), ], 400); } catch (\Exception $e) { Logger::error('chatbot', 'Chat request failed', ['error' => $e->getMessage()]); return new WP_REST_Response([ 'success' => false, 'code' => 'ai_error', 'message' => __('An error occurred processing your request.', 'ai-product-tools'), ], 500); } } /** * When the reply to this request must be ready: the reply budget counted * from the start of the request, which the product search and WordPress * itself already used part of. * * @return float Unix time with microseconds. */ private function replyDeadline(): float { $now = microtime( true ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- A float PHP sets itself; cast below. $start = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? (float) $_SERVER['REQUEST_TIME_FLOAT'] : $now; if ( $start > $now || $now - $start > 60 ) { $start = $now; } return $start + ChatbotConstants::replyBudgetSeconds(); } /** * Response for a chat that arrives while every chat slot is taken. * * @return WP_REST_Response */ private function createChatBusyResponse(): WP_REST_Response { $response = new WP_REST_Response( array( 'success' => false, 'code' => 'chat_busy', 'message' => __( 'The assistant is answering other shoppers right now. Please try again in a moment.', 'ai-product-tools' ), 'data' => array( 'retry_after' => ChatbotConstants::CHAT_BUSY_RETRY_SECONDS, ), ), 503 ); $response->header( 'Retry-After', (string) ChatbotConstants::CHAT_BUSY_RETRY_SECONDS ); return $response; } /** * Activate the per-provider cooldown when processMessage() reports a * transient outage, whether it queued the message (success=>true, the * category under data.error_code) or failed outright (success=>false, * the category under error). Only failures that recover by waiting * qualify (see ProviderCooldown::shouldActivateForErrorCode()). * * @param array $result processMessage()'s return value. * @param string $provider The provider this request used. */ private function activateProviderCooldownIfTransient( array $result, string $provider ): void { $error_code = $result['data']['error_code'] ?? ( $result['error'] ?? '' ); if ( '' === $provider || ! is_string( $error_code ) || '' === $error_code ) { return; } if ( ! ProviderCooldown::shouldActivateForErrorCode( $error_code ) ) { return; } $this->provider_cooldown->activateForProvider( $provider, $this->provider_cooldown->getCooldownSeconds() ); } /** * Clamp a history entry to the chat message cap instead of rejecting the request. * * Assistant replies are not length-capped, so a long reply must not make * every later request fail validation. * * @param string $content Sanitized history content. * @return string */ private static function clampHistoryContent( string $content ): string { return mb_substr( $content, 0, ChatbotConstants::maxMessageLength(), 'UTF-8' ); } private function createRateLimitFailureResponse( array $rate_limit_check ): WP_REST_Response { $is_degraded = ! empty( $rate_limit_check['degraded'] ); $retry_after = isset( $rate_limit_check['retry_after'] ) ? (int) $rate_limit_check['retry_after'] : 60; $error_code = $is_degraded ? 'rate_limit_store_unavailable' : 'rate_limited'; $status_code = $is_degraded ? 503 : 429; $message = $is_degraded ? __( 'The chat service is temporarily unavailable. Please try again shortly.', 'ai-product-tools' ) : __( 'Too many requests. Please wait a moment before trying again.', 'ai-product-tools' ); if ( isset( $rate_limit_check['error_code'] ) && is_string( $rate_limit_check['error_code'] ) && '' !== $rate_limit_check['error_code'] ) { $error_code = sanitize_key( $rate_limit_check['error_code'] ); } if ( 'visitor_daily_limited' === $error_code ) { $message = __( 'You have reached the daily message limit. Please come back tomorrow.', 'ai-product-tools' ); } if ( 'site_daily_limited' === $error_code ) { $message = __( 'The assistant has reached its limit for today. Please try again tomorrow.', 'ai-product-tools' ); } if ( 'site_rate_limited' === $error_code ) { $minutes = max( 1, (int) ceil( $retry_after / 60 ) ); $message = sprintf( /* translators: %d: number of minutes until the assistant is available again */ _n( 'The assistant is very busy right now. Please try again in about %d minute.', 'The assistant is very busy right now. Please try again in about %d minutes.', $minutes, 'ai-product-tools' ), $minutes ); } if ( 'site_rate_limited' === $error_code ) { $custom_message = (string) $this->settings->get( 'general.rate_limit_message', '' ); if ( '' !== $custom_message && 'custom' === $this->settings->get( 'general.error_message_mode', 'neutral' ) ) { $message = $custom_message; } } $response_data = [ 'success' => false, 'code' => $error_code, 'message' => $message, 'data' => [ 'retry_after' => $retry_after, ], ]; if ( $is_degraded ) { $response_data['data']['degraded'] = true; } $response = new WP_REST_Response( $response_data, $status_code ); $response->header( 'Retry-After', $retry_after ); if ( $is_degraded ) { $response->header( 'X-AIPT-RateLimit-Degraded', '1' ); } return $response; } /** * Sanitize error message for client response. * * Removes sensitive information like file paths, database details, * and API keys from error messages before returning to client. * * @param string $message Original error message. * @return string Sanitized message. */ private function sanitizeErrorMessage(string $message): string { $allowed_messages = [ __('Message cannot be empty.', 'ai-product-tools'), __('Message is too long (max 2000 characters).', 'ai-product-tools'), __('Invalid session ID format.', 'ai-product-tools'), __('The chatbot is currently unavailable.', 'ai-product-tools'), ]; foreach ($allowed_messages as $allowed) { if (stripos($message, $allowed) !== false) { return $message; } } $sensitive_patterns = [ '/\/[a-zA-Z0-9_\-\/]+\.php/i', '/line \d+/i', '/API key/i', '/password/i', '/SELECT|INSERT|UPDATE|DELETE/i', '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', '/sk-[a-zA-Z0-9]+/', ]; foreach ($sensitive_patterns as $pattern) { if (preg_match($pattern, $message)) { return __('An error occurred. Please try again.', 'ai-product-tools'); } } return wp_strip_all_tags($message); } /** * Get the widget labels for one supported language. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_labels(WP_REST_Request $request): WP_REST_Response { $language = (string) $request->get_param('language'); $labels = $this->settings->getStorefrontLabelsForLanguage($language); if (null === $labels) { return new WP_REST_Response([ 'success' => false, 'message' => __('Unsupported language.', 'ai-product-tools'), ], 400); } return new WP_REST_Response([ 'success' => true, 'data' => [ 'language' => $language, 'labels' => $labels, ], ], 200); } /** * Public read-only list of the widget's extension script URLs. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_widget_extensions(WP_REST_Request $request): WP_REST_Response { return new WP_REST_Response([ 'success' => true, 'data' => [ 'extensions' => \AIPT\Core\Services\ChatbotWidgetExtensionUrls::collect(), ], ], 200); } /** * Get full settings (admin). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_full_settings(WP_REST_Request $request): WP_REST_Response { $pages = (array) \get_pages(['post_status' => 'publish']); $page_options = array_map(function ($page) { return [ 'id' => $page->ID, 'title' => $page->post_title, 'type' => 'page', ]; }, $pages); return new WP_REST_Response([ 'success' => true, 'data' => [ 'settings' => $this->settings->getAll(), 'pages' => $page_options, ], ], 200); } /** * Update settings. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object or persistence drift error. */ public function update_settings(WP_REST_Request $request) { $body = $request->get_json_params(); if (empty($body)) { return new WP_REST_Response([ 'success' => false, 'code' => 'empty_body', 'message' => __('Request body is empty.', 'ai-product-tools'), ], 400); } try { $result = $this->settings->update($body); if (is_wp_error($result)) { return $result; } $data = [ 'message' => __('Settings updated successfully.', 'ai-product-tools'), 'settings' => $this->settings->getAll(), 'coerced_fields' => $this->settings->getLastCoercedFields(), ]; $coerced_reason = $this->settings->getLastCoercedReason(); if (!empty($data['coerced_fields']) && '' !== $coerced_reason) { $data['coerced_reason'] = $coerced_reason; } return new WP_REST_Response([ 'success' => true, 'data' => $data, ], 200); } catch (\InvalidArgumentException $e) { $raw_message = $e->getMessage(); $decoded = json_decode( $raw_message, true ); if ( is_array( $decoded ) ) { $errors = $decoded; } else { $errors = [ 'general' => [ $raw_message ?: __( 'An unknown validation error occurred.', 'ai-product-tools' ) ], ]; } return new WP_REST_Response([ 'success' => false, 'code' => 'validation_error', 'message' => __('Validation failed.', 'ai-product-tools'), 'data' => [ 'errors' => $errors, ], ], 400); } } /** * REST arg schema for a paginated list route's `per_page` parameter. * * Clamps an out-of-range value to [1, ChatbotConstants::maxPaginationPerPage()] * instead of rejecting the request, so this schema and the storage * layer's own pagination bound (MessageQueue::getAllMessages()) * agree on one behavior rather than the schema hard-rejecting a value the * storage layer would have happily clamped. * * @return array */ private function per_page_arg(): array { return [ 'type' => 'integer', 'default' => ChatbotConstants::defaultPaginationPerPage(), 'sanitize_callback' => function ($value) { return min(ChatbotConstants::maxPaginationPerPage(), max(1, (int) $value)); }, ]; } /** * Arguments of POST /messages/{id}/respond, shared with the Business * build's registration of the same route. * * @return array> */ public function respond_route_args(): array { return [ 'id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], 'response' => [ 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', 'validate_callback' => function ($value) { $length = mb_strlen(trim((string) $value), 'UTF-8'); return $length >= self::MIN_MESSAGE_LENGTH && $length <= ChatbotConstants::maxResponseLength(); }, ], 'product_ids' => [ 'type' => 'array', 'items' => ['type' => 'integer'], 'default' => [], ], ]; } /** * Replying to a queued message is Business. This handler only refuses * it; the Business build registers its own in its place * (`Premium\Chatbot\QueueReplyController`). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function respond_to_message(WP_REST_Request $request): WP_REST_Response { $denial = PlanDenial::error( 'chatbotQueueReply', PlanDenial::PLAN_PAID, __('Business plan adds replies to queued chatbot messages.', 'ai-product-tools') ); return new WP_REST_Response([ 'success' => false, 'code' => $denial->get_error_code(), 'message' => $denial->get_error_message(), 'data' => $denial->get_error_data(), ], 403); } /** * Get a single queued message by ID. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_message(WP_REST_Request $request): WP_REST_Response { $id = (int) $request->get_param('id'); $message = $this->message_queue->get($id); if (!$message) { return new WP_REST_Response([ 'success' => false, 'code' => 'not_found', 'message' => __('Message not found.', 'ai-product-tools'), ], 404); } return new WP_REST_Response([ 'success' => true, 'data' => self::withUtcTimestamps($message), ], 200); } /** * Queue rows are written with current_time('mysql') (site time). The admin * UI gets explicit UTC so absolute and relative times agree in any browser. * * @param array $message Queue row. * @return array Row with created_at and updated_at as ISO 8601 UTC. */ private static function withUtcTimestamps(array $message): array { foreach (['created_at', 'updated_at'] as $column) { if (isset($message[$column])) { $message[$column] = UtcTimestamp::fromStored($message[$column], true); } } return $message; } /** * Delete queued message. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function delete_message(WP_REST_Request $request): WP_REST_Response { $id = (int) $request->get_param('id'); $message = $this->message_queue->get($id); if (!$message) { return new WP_REST_Response([ 'success' => false, 'code' => 'not_found', 'message' => __('Message not found.', 'ai-product-tools'), ], 404); } $result = $this->message_queue->delete($id); if ($result) { return new WP_REST_Response([ 'success' => true, 'data' => [ 'message' => __('Message deleted successfully.', 'ai-product-tools'), ], ], 200); } return new WP_REST_Response([ 'success' => false, 'code' => 'delete_failed', 'message' => __('Failed to delete message.', 'ai-product-tools'), ], 500); } /** * Arguments of POST /cart/add, shared with the Business build's * registration of the same route. * * @return array> */ public function cart_add_route_args(): array { return [ 'product_id' => [ 'required' => true, 'type' => 'integer', 'validate_callback' => function ($value) { return is_numeric($value) && $value > 0; }, ], 'quantity' => [ 'type' => 'integer', 'default' => 1, 'minimum' => 1, ], ]; } /** * Adding a product to the cart from the chatbot is Business. This * handler only refuses it; the Business build registers its own in its * place (`Premium\Chatbot\CartAddController`). Public storefront route: * the denial never discloses the store's license state. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function add_to_cart(WP_REST_Request $request): WP_REST_Response { $denial = PlanDenial::publicError( 'chatbotAddToCart', PlanDenial::PLAN_BUSINESS, __('Add to cart is not available in this chat.', 'ai-product-tools') ); return new WP_REST_Response([ 'success' => false, 'code' => $denial->get_error_code(), 'message' => $denial->get_error_message(), 'data' => $denial->get_error_data(), ], 403); } /** * Get queue stats. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_queue_stats(WP_REST_Request $request): WP_REST_Response { $stats = $this->message_queue->getStats(); return new WP_REST_Response([ 'success' => true, 'data' => $stats, ], 200); } /** * Rate limit one public reply route (the poll and the delivered mark). * * The session id is the client's own choice, so the session limit alone * cannot stop a script that sends a new one every time: the hashed IP * bucket comes first, before any database read. * * @param string $session_id Visitor session id. * @return WP_REST_Response|null The refusal, or null when the request may go on. */ private function checkReplyPollLimits( string $session_id ): ?WP_REST_Response { $ip_rate_limit_check = $this->rate_limiter->checkReplyPollByIp( $this->rate_limiter->getClientIp() ); if ( ! ( $ip_rate_limit_check['allowed'] ?? false ) ) { return $this->createRateLimitFailureResponse( $ip_rate_limit_check ); } $rate_limit_check = $this->rate_limiter->checkPoll( $session_id ); if ( ! $rate_limit_check['allowed'] ) { if ( ! empty( $rate_limit_check['degraded'] ) ) { return $this->createRateLimitFailureResponse( $rate_limit_check ); } $response = new WP_REST_Response([ 'success' => false, 'code' => 'rate_limited', 'message' => __('Too many requests. Please wait a moment.', 'ai-product-tools'), 'data' => [ 'retry_after' => $rate_limit_check['retry_after'], ], ], 429); $response->header( 'Retry-After', $rate_limit_check['retry_after'] ); return $response; } return null; } /** * Poll for admin responses (public endpoint for widget). * * Returns admin responses that are ready to be delivered to the customer. * Uses session_id to ensure customers can only see their own responses. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function poll_responses(WP_REST_Request $request): WP_REST_Response { $session_id = $request->get_param('session_id'); $rate_limit_response = $this->checkReplyPollLimits( $session_id ); if ( $rate_limit_response instanceof WP_REST_Response ) { return $rate_limit_response; } $responses = $this->message_queue->getPendingResponses($session_id, 5); if (empty($responses)) { return new WP_REST_Response([ 'success' => true, 'data' => [ 'has_response' => false, 'responses' => [], ], ], 200); } return new WP_REST_Response([ 'success' => true, 'data' => [ 'has_response' => true, 'responses' => $responses, ], ], 200); } /** * Mark message as delivered to customer (public endpoint for widget). * * Verifies that the session_id matches the message to prevent * unauthorized marking of other users' messages as delivered. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function mark_delivered(WP_REST_Request $request): WP_REST_Response { $id = (int) $request->get_param('id'); $session_id = $request->get_param('session_id'); $rate_limit_response = $this->checkReplyPollLimits( $session_id ); if ( $rate_limit_response instanceof WP_REST_Response ) { return $rate_limit_response; } $message = $this->message_queue->get($id); if (!$message) { return new WP_REST_Response([ 'success' => false, 'code' => 'not_found', 'message' => __('Message not found.', 'ai-product-tools'), ], 404); } if ($message['session_id'] !== $session_id) { return new WP_REST_Response([ 'success' => false, 'code' => 'forbidden', 'message' => __('Access denied.', 'ai-product-tools'), ], 403); } if ( 'delivered' === $message['status'] ) { return new WP_REST_Response([ 'success' => true, 'data' => [ 'message' => __('Message marked as delivered.', 'ai-product-tools'), ], ], 200); } if ( 'responded' !== $message['status'] || '' === trim( (string) ( $message['admin_response'] ?? '' ) ) ) { return new WP_REST_Response([ 'success' => false, 'code' => 'not_deliverable', 'message' => __('This message has no reply waiting to be delivered.', 'ai-product-tools'), ], 409); } $result = $this->message_queue->markDelivered($id); if ($result) { return new WP_REST_Response([ 'success' => true, 'data' => [ 'message' => __('Message marked as delivered.', 'ai-product-tools'), ], ], 200); } return new WP_REST_Response([ 'success' => false, 'code' => 'update_failed', 'message' => __('Failed to update message.', 'ai-product-tools'), ], 500); } /** * Bulk delete messages (admin endpoint). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function bulk_delete_messages(WP_REST_Request $request): WP_REST_Response { $ids = $request->get_param('ids'); if (empty($ids)) { return new WP_REST_Response([ 'success' => false, 'code' => 'empty_ids', 'message' => __('No messages selected.', 'ai-product-tools'), ], 400); } $deleted_count = $this->message_queue->bulkDelete($ids); return new WP_REST_Response([ 'success' => true, 'data' => [ 'deleted' => $deleted_count, 'message' => sprintf($this->getBulkDeleteMessageTemplate($deleted_count), $deleted_count), ], ], 200); } /** * Search messages (admin endpoint). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function search_messages(WP_REST_Request $request): WP_REST_Response { $args = [ 'search' => $request->get_param('search'), 'status' => $request->get_param('status'), 'record_type' => $request->get_param('record_type'), 'page' => $request->get_param('page'), 'per_page' => $request->get_param('per_page'), ]; $result = $this->message_queue->getAllMessages($args); return new WP_REST_Response([ 'success' => true, 'data' => [ 'messages' => array_map([self::class, 'withUtcTimestamps'], $result['messages']), 'pagination' => [ 'total' => $result['total'], 'pages' => $result['pages'], 'current' => (int) $args['page'], 'per_page' => (int) $args['per_page'], ], ], ], 200); } /** * Get decrypted contact information for a message (admin endpoint). * * Returns the decrypted email address for display in the admin modal. * This is a separate endpoint to ensure emails are only decrypted when * explicitly requested, not in list views (PII security best practice). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function get_message_contact(WP_REST_Request $request): WP_REST_Response { $id = (int) $request->get_param('id'); $message = $this->message_queue->get($id); if (!$message) { return new WP_REST_Response([ 'success' => false, 'code' => 'not_found', 'message' => __('Message not found.', 'ai-product-tools'), ], 404); } $decrypted_email = null; if (!empty($message['user_email'])) { $decrypted_email = $this->message_queue->decryptEmail($message['user_email']); } return new WP_REST_Response([ 'success' => true, 'data' => [ 'user_name' => $message['user_name'] ?? null, 'user_email' => $decrypted_email, 'consent_given' => !empty($message['consent_given']), 'consent_timestamp' => $message['consent_timestamp'] ?? null, ], ], 200); } /** * Validate request origin for CSRF protection. * * Checks that the Origin or Referer header matches the site URL * to prevent cross-site request forgery attacks on public endpoints. * * Supports multiple domains pointing to the same site via: * - WordPress site_url() and home_url() * - AIPT_ALLOWED_ORIGINS constant (comma-separated domains) * - 'aipt_chatbot_allowed_origins' filter hook * * @return bool True if origin is valid. */ private function validateRequestOrigin(): bool { $allowed_hosts = []; $site_host = \wp_parse_url(\site_url(), PHP_URL_HOST); if ($site_host) { $allowed_hosts[] = $this->normalize_host($site_host); } $home_host = \wp_parse_url(\home_url(), PHP_URL_HOST); if ($home_host) { $allowed_hosts[] = $this->normalize_host($home_host); } if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) { $current_host = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])); $current_host = preg_replace('/:\d+$/', '', $current_host); if (!empty($current_host)) { $allowed_hosts[] = $this->normalize_host($current_host); } } if (defined('AIPT_ALLOWED_ORIGINS') && \AIPT_ALLOWED_ORIGINS) { $extra_domains = array_map('trim', explode(',', \AIPT_ALLOWED_ORIGINS)); foreach ($extra_domains as $domain) { if (!empty($domain)) { $allowed_hosts[] = $this->normalize_host($domain); } } } /** * Filter the allowed origin hosts for chatbot CSRF protection. * * Allows adding additional domains that should be permitted to make * chatbot API requests. Useful for sites with multiple domains * pointing to the same WordPress installation. * * @since 2.3.2 * @param array $allowed_hosts Array of normalized hostnames (without www.). */ $allowed_hosts = apply_filters('aipt_chatbot_allowed_origins', $allowed_hosts); $allowed_hosts = array_unique($allowed_hosts); $origin = isset($_SERVER['HTTP_ORIGIN']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_ORIGIN'])) : ''; if (!empty($origin)) { $origin_host = \wp_parse_url($origin, PHP_URL_HOST); if ($origin_host && in_array($this->normalize_host($origin_host), $allowed_hosts, true)) { return true; } return false; } $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; if (!empty($referer)) { $referer_host = \wp_parse_url($referer, PHP_URL_HOST); if ($referer_host && in_array($this->normalize_host($referer_host), $allowed_hosts, true)) { return true; } return false; } return true; } /** * Normalize host by removing www. prefix and converting to lowercase. * * @param string $host Hostname. * @return string Normalized hostname. */ private function normalize_host(string $host): string { return preg_replace('/^www\./i', '', strtolower($host)); } private function getBulkDeleteMessageTemplate(int $deleted_count): string { /* translators: %d: number of chatbot messages successfully deleted. */ return (string) \_n( '%d message deleted successfully.', '%d messages deleted successfully.', $deleted_count, 'ai-product-tools' ); } }