'aipt_chatbot_validate_starter_messages', 'appearance.custom_launcher_icon_url' => 'aipt_chatbot_validate_custom_launcher_icon', 'appearance.custom_css' => 'aipt_chatbot_validate_custom_css', 'appearance.launcher_animation' => 'aipt_chatbot_validate_launcher_animation', 'appearance.hero_image_url' => 'aipt_chatbot_validate_hero_image', 'behavior.max_products' => 'aipt_chatbot_validate_max_products', 'behavior.show_add_to_cart' => 'aipt_chatbot_validate_show_add_to_cart', 'behavior.response_length' => 'aipt_chatbot_validate_response_length', 'behavior.product_recommendation_mode' => 'aipt_chatbot_validate_recommendation_mode', 'localization.custom_labels' => 'aipt_chatbot_validate_custom_labels', ]; /** * The Business Add to Cart setting path. */ private const ADD_TO_CART_PATH = 'behavior.show_add_to_cart'; /** * Free values of the paid settings (mirror PremiumChatbotService's clamps). */ private const FREE_MAX_PRODUCTS = 10; private const FREE_RESPONSE_LENGTH = 'concise'; private const FREE_RECOMMENDATION_MODE = 'auto'; private const FREE_LAUNCHER_ANIMATION = 'pulse'; /** * Settings as stored before the current update (merged with defaults). * * @var array */ private $current_settings = []; /** * Denial reason of the plan clamps applied during the last update, '' when none. * * @var string */ private $last_coerced_reason = ''; /** * Changed paid setting paths the license could not be verified for in the current update. * * @var string[] */ private $unverified_fields = []; /** * Feature and required plan of the first unverified paid change. * * @var array{0:string,1:string}|null */ private $unverified_denial = null; /** * Per-update memo of the entitlement bridges and denial reasons. * * @var array */ private $plan_decisions = []; /** * Get default settings. * * @return array Default values. */ public static function getDefaults(): array { return [ 'general' => [ 'enabled' => false, 'bot_name' => __('Shop Assistant', 'ai-product-tools'), 'greeting_message' => __('Hi! How can I help you find what you\'re looking for today?', 'ai-product-tools'), 'language' => 'en', 'tone' => 'friendly', 'fallback_contact_url' => '', 'rate_limit_message' => __('We\'re experiencing high demand. Please try again in a moment.', 'ai-product-tools'), 'error_message_mode' => 'neutral', 'store_context' => '', 'pre_chat_form_enabled' => false, 'terms_page_id' => null, 'privacy_page_id' => null, 'show_powered_by' => false, 'whatsapp_number' => '', 'knowledge_pages' => [], 'starter_messages_enabled' => true, 'starter_messages' => [ __('What products do you recommend?', 'ai-product-tools'), __('Do you have any deals or discounts?', 'ai-product-tools'), __('Tell me about your shipping policy', 'ai-product-tools'), ], ], 'placement' => [ 'position' => 'bottom-right', 'offset_x' => 20, 'offset_y' => 20, 'visibility_mode' => 'all', 'specific_pages' => [], 'excluded_pages' => [], 'device' => 'all', 'excluded_page_types' => ['checkout'], ], 'appearance' => [ 'theme_preset' => 'light', 'launcher_icon' => 'chat', 'custom_launcher_icon_url' => '', 'profile_picture_url' => '', 'colors' => [ 'primary' => '#3b82f6', 'secondary' => '#64748b', 'background' => '#ffffff', 'text' => '#1f2937', 'user_bubble' => '#3b82f6', 'bot_bubble' => '#f0f0f0', 'header_bg' => '#ffffff', 'footer_bg' => '#ffffff', 'button_hover' => '#1e88e5', 'online_indicator' => '#22c55e', 'launcher_bg' => '#3b82f6', 'launcher_icon_color' => '#ffffff', 'attention_bubble_bg' => '#ffffff', 'attention_bubble_text' => '#1f2937', 'attention_badge_bg' => '#ef4444', 'attention_badge_text' => '#ffffff', 'hero_bg' => '#3b82f6', ], 'font_family' => 'inherit', 'border_radius' => 12, 'custom_css' => '', 'launcher_animation' => 'none', 'hero_image_url' => '', 'attention_bubble_enabled' => false, 'attention_bubble_text' => __('Chat with us!', 'ai-product-tools'), 'attention_badge_enabled' => false, 'attention_badge_text' => '1', ], 'behavior' => [ 'index_profile' => '1', 'max_products' => 10, 'show_view_product' => true, 'show_add_to_cart' => false, 'show_stock_status' => true, 'response_length' => 'balanced', 'provider' => 'openai', 'model' => 'gpt-5.6-terra', 'product_recommendation_mode' => 'auto', ], 'rate_limit' => [ 'enabled' => true, 'max_requests' => ChatbotConstants::DEFAULT_RATE_LIMIT_MAX_REQUESTS, 'window_seconds' => ChatbotConstants::DEFAULT_RATE_LIMIT_WINDOW_SECONDS, 'key_mode' => 'session', 'site_max_requests' => ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_MAX_REQUESTS, 'visitor_daily_max_requests' => ChatbotConstants::DEFAULT_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS, 'site_daily_max_requests' => ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS, ], 'provider_cooldown' => [ 'enabled' => true, 'seconds' => ChatbotConstants::DEFAULT_PROVIDER_COOLDOWN_SECONDS, 'enqueue_on_failure' => false, ], 'localization' => [ 'auto_detect_enabled' => true, 'fallback_language' => 'en', 'custom_labels' => [], ], ]; } /** * Check if chatbot is enabled. * * @return bool */ public function isEnabled(): bool { return (bool) $this->get('general.enabled', false); } /** * Get default model for a provider. * * Delegates to the shared catalog (the server authority for supported * models) instead of keeping a second, driftable default-per-provider * map here. * * @param string $provider The provider name. * @return string Default model identifier. */ private function getDefaultModelForProvider(string $provider): string { return \AIPT\Api\ModelCatalog::get_default_model($provider); } /** * Get all settings. * * @return array Complete settings array. */ public function getAll(): array { if ($this->cached_settings !== null) { return $this->cached_settings; } $stored = get_option(self::OPTION_KEY, []); $defaults = self::getDefaults(); $this->cached_settings = self::unifyLanguage($this->mergeSettings($defaults, $stored)); if (is_array($stored)) { $this->cached_settings['general'] = self::migrateLegacyErrorSettings( $this->cached_settings['general'], is_array($stored['general'] ?? null) ? $stored['general'] : [] ); } if (!is_array($stored) || !isset($stored['behavior']['provider'])) { $this->applyKeyedProviderDefault(is_array($stored) && isset($stored['behavior']['model'])); } if (is_array($this->cached_settings['localization']['custom_labels'] ?? null)) { $this->cached_settings['localization']['custom_labels'] = self::aliasDeprecatedLabelKeys($this->cached_settings['localization']['custom_labels']); } $this->normalizeLoadedBehaviorModel(); return $this->cached_settings; } /** * Fold the two retired error toggles into `error_message_mode`. * * `show_errors_to_user` and `use_custom_error_message` contradicted each * other and their default showed provider errors to shoppers. A merchant * who chose their own message (shown, custom on) keeps it; everyone else * gets the neutral message. Idempotent: a stored `error_message_mode` wins. * * @param array $general Merged general settings. * @param array $stored The stored general section, before the merge with defaults. * @return array General settings without the retired keys. */ public static function migrateLegacyErrorSettings(array $general, array $stored): array { $stored_mode = $stored['error_message_mode'] ?? null; if (!in_array($stored_mode, self::ERROR_MESSAGE_MODES, true)) { $shown = rest_sanitize_boolean($stored['show_errors_to_user'] ?? true); $custom = rest_sanitize_boolean($stored['use_custom_error_message'] ?? false); $general['error_message_mode'] = ($shown && $custom) ? 'custom' : 'neutral'; } unset($general['show_errors_to_user'], $general['use_custom_error_message']); return $general; } /** * Rewrite the stored option once so it no longer carries the retired * error toggles. Safe to run repeatedly. */ public static function persistLegacyErrorSettingsMigration(): void { $stored = get_option(self::OPTION_KEY, []); if (!is_array($stored) || !is_array($stored['general'] ?? null)) { return; } if (!array_key_exists('show_errors_to_user', $stored['general']) && !array_key_exists('use_custom_error_message', $stored['general'])) { return; } $stored['general'] = self::migrateLegacyErrorSettings($stored['general'], $stored['general']); update_option(self::OPTION_KEY, $stored); } /** * Keep the pre-chat form on for stores that saved their settings before * the form became opt-in. * * New installs start with the form off. Saved settings that never * recorded `pre_chat_form_enabled` (no general section, or one without * the key) were running on the old default of on, so they get an explicit * true once. A stored true or false is never touched, and a store with no * saved settings has nothing to preserve. The permanent guard option is * written last, so a failed settings write retries on the next pass. * * @return void */ public static function migrateExistingStoresToKeepPreChatForm(): void { if (null !== get_option(self::PRE_CHAT_FORM_MIGRATION_OPTION, null)) { return; } $stored = get_option(self::OPTION_KEY, null); if (is_array($stored) && [] !== $stored) { $general = $stored['general'] ?? []; if (is_array($general) && !array_key_exists('pre_chat_form_enabled', $general)) { $general['pre_chat_form_enabled'] = true; $stored['general'] = $general; if (!update_option(self::OPTION_KEY, $stored)) { return; } } } update_option(self::PRE_CHAT_FORM_MIGRATION_OPTION, true, false); } /** * The chat language is one setting: localization.fallback_language, the * field the Language tab edits, with general.language kept as its mirror * for older readers and API clients. It sets the widget labels when * auto-detect is off or the browser language is not supported, and the * AI's reply language when the customer's language cannot be detected. * * @param array $settings Settings merged with defaults. * @param string[] $requested_paths Paths an update sets; none when loading. * @return array */ private static function unifyLanguage(array $settings, array $requested_paths = []): array { $general = (string) ($settings['general']['language'] ?? 'en'); $fallback = (string) ($settings['localization']['fallback_language'] ?? 'en'); $general_valid = in_array($general, self::VALID_LANGUAGES, true); $fallback_valid = in_array($fallback, self::VALID_LANGUAGES, true); if (in_array('localization.fallback_language', $requested_paths, true)) { $language = $fallback; } elseif (in_array('general.language', $requested_paths, true)) { $language = $general; } elseif ('en' === $fallback && $general_valid && 'en' !== $general) { $language = $general; } else { $language = $fallback_valid ? $fallback : ($general_valid ? $general : 'en'); } $settings['general']['language'] = $language; $settings['localization']['fallback_language'] = $language; return $settings; } /** * A store that never saved a provider choice defaults to the first * provider that has a key, in the order the admin UI lists them, so the * provider field is never blank for a store with only a Claude key. * An explicit saved choice is never swapped, and a stored model is kept * (normalizeLoadedBehaviorModel() resets it if the provider does not offer it). * * @param bool $has_stored_model Whether the stored row already names a model. */ private function applyKeyedProviderDefault(bool $has_stored_model): void { $key_getters = [ 'openai' => 'get_openai_key', 'gemini' => 'get_gemini_key', 'openrouter' => 'get_openrouter_key', 'claude' => 'get_claude_key', ]; foreach ($key_getters as $provider => $getter) { if ('' === \AIPT\Utils\ApiKeyManager::$getter()) { continue; } if ('openai' !== $provider) { $this->cached_settings['behavior']['provider'] = $provider; if (!$has_stored_model) { $this->cached_settings['behavior']['model'] = $this->getDefaultModelForProvider($provider); } } return; } } private function normalizeLoadedBehaviorModel(): void { $provider = $this->cached_settings['behavior']['provider'] ?? 'openai'; $provider = is_string($provider) && in_array($provider, self::VALID_PROVIDERS, true) ? $provider : 'openai'; $model = $this->cached_settings['behavior']['model'] ?? ''; $normalized = $this->getDefaultModelForProvider($provider); if ($provider === 'openrouter') { if (is_string($model) && preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:-]*$/', $model)) { $normalized = $model; } } elseif (is_string($model) && \AIPT\Api\ModelCatalog::is_supported($provider, $model)) { $normalized = $model; } if ($normalized === $model && $this->cached_settings['behavior']['provider'] === $provider) { return; } $this->cached_settings['behavior']['provider'] = $provider; $this->cached_settings['behavior']['model'] = $normalized; } /** * Get a specific setting section. * * @param string $section Section name (general, placement, appearance, behavior). * @return array Section settings. */ public function getSection(string $section): array { if (!in_array($section, self::VALID_SECTIONS, true)) { return []; } $settings = $this->getAll(); return $settings[$section] ?? []; } /** * Get a specific setting value using dot notation. * * @param string $key Dot-notation key (e.g., 'general.bot_name'). * @param mixed $default Default value if not set. * @return mixed Setting value. */ public function get(string $key, $default = null) { $settings = $this->getAll(); $keys = explode('.', $key); $value = $settings; foreach ($keys as $k) { if (!isset($value[$k])) { return $default; } $value = $value[$k]; } return $value; } /** * Update settings. * * @param array $settings Partial or full settings array. * @return bool|\WP_Error True on success or a drift error when persistence differs. * @throws \InvalidArgumentException If validation fails. */ public function update(array $settings) { $this->last_coerced_fields = []; $this->last_coerced_reason = ''; $this->unverified_fields = []; $this->unverified_denial = null; $this->plan_decisions = []; $current = $this->getAll(); $this->current_settings = $current; $requested_paths = $this->collectRequestedPaths($settings); $this->requested_paths = $requested_paths; if ( in_array('behavior.provider', $requested_paths, true) && !in_array('behavior.model', $requested_paths, true) ) { $provider_before = $current['behavior']['provider'] ?? self::getDefaults()['behavior']['provider']; $provider_requested = sanitize_text_field($settings['behavior']['provider'] ?? $provider_before); if ($provider_requested !== $provider_before) { $settings['behavior']['model'] = $this->getDefaultModelForProvider($provider_requested); } } if (is_array($settings['localization']['custom_labels'] ?? null)) { $settings['localization']['custom_labels'] = self::aliasDeprecatedLabelKeys($settings['localization']['custom_labels']); } $merged = self::unifyLanguage($this->mergeSettings($current, $settings), $requested_paths); $errors = $this->validate($merged); if (!empty($errors)) { throw new \InvalidArgumentException(wp_json_encode($errors)); } $sanitized = $this->sanitize($merged); if (null !== $this->unverified_denial) { $this->last_coerced_fields = []; $this->last_coerced_reason = ''; return PlanDenial::error( $this->unverified_denial[0], $this->unverified_denial[1], __('Business plan adds full control over these chatbot settings.', 'ai-product-tools'), 'premium_required', ['fields' => $this->unverified_fields] ); } update_option(self::OPTION_KEY, $sanitized); $persisted_raw = get_option(self::OPTION_KEY, []); $persisted = is_array($persisted_raw) ? $this->mergeSettings(self::getDefaults(), $persisted_raw) : self::getDefaults(); $drift = $this->detectPersistenceDrift($requested_paths, $sanitized, $persisted, $current); $this->cached_settings = $persisted; if (!empty($drift)) { return new \WP_Error( 'aipt_settings_drift', __('Some chatbot settings could not be persisted as requested.', 'ai-product-tools'), [ 'status' => 422, 'drift' => $drift, ] ); } return true; } /** * Get submitted fields changed by plan enforcement during the last update. * * @return string[] Dot-notation setting paths. */ public function getLastCoercedFields(): array { return $this->last_coerced_fields; } /** * Get the denial reason of the plan clamps applied during the last update. * * @return string A PlanDenial reason, or '' when no paid value was clamped. */ public function getLastCoercedReason(): string { return $this->last_coerced_reason; } /** * Project stored settings onto what a storefront render may use. * * Stored values are never changed: a paid value the site is not entitled * to right now is replaced by its Free value in the returned copy only, so * it becomes effective again when access returns. Values equal to the Free * value or to the shipped default are always kept, so Free sites keep * their current defaults. * * Deliberately the _cache_only bridge siblings: this runs for storefront * visitors (widget localization, the public settings route, chat replies) * and must never trigger a synchronous Freemius API call. The premium * callbacks fall back to the SDK plan only while nothing is verified yet, * so a paying site keeps its configuration on a cold cache. Save-time * clamps, the cart action and the Add to Cart button on product cards * (isCartActionAvailable()) stay on the authoritative bridges. * * @param array $settings Settings (full or partial) to project. * @return array Projected settings; paths missing from $settings stay missing. */ public static function projectForStorefront(array $settings): array { $paid_enabled = (bool) apply_filters('aipt_chatbot_premium_settings_enabled_cache_only', false); $cart_enabled = (bool) apply_filters('aipt_chatbot_add_to_cart_enabled_cache_only', false); foreach (array_keys(self::PAID_SETTING_HOOKS) as $path) { list($section, $key) = explode('.', $path, 2); if (!isset($settings[$section]) || !is_array($settings[$section]) || !array_key_exists($key, $settings[$section])) { continue; } $settings[$section][$key] = self::projectPaidValue( $path, $settings[$section][$key], self::ADD_TO_CART_PATH === $path ? $cart_enabled : $paid_enabled ); } return $settings; } /** * Whether a storefront surface may offer the Add to Cart action right now. * * Uses the authoritative 'aipt_chatbot_add_to_cart_enabled' bridge, the * same gate ChatbotController::check_cart_add_permission() applies to the * click, so an offered button is never refused by the cart route. It is * asked only when the store turned Add to Cart on, and the entitlement * verification behind it is cached, so replies do not phone home each * time. Page renders keep using projectForStorefront(), which never * phones home. * * @param mixed $stored Stored behavior.show_add_to_cart value. * @return bool */ public static function isCartActionAvailable($stored): bool { return (bool) $stored && (bool) apply_filters('aipt_chatbot_add_to_cart_enabled', false); } /** * Project one stored paid setting value for a storefront render. * * @param string $path Dot-notation paid setting path. * @param mixed $value Stored value. * @return mixed Effective value. */ public static function projectStorefrontValue(string $path, $value) { if (!isset(self::PAID_SETTING_HOOKS[$path])) { return $value; } $enabled = self::ADD_TO_CART_PATH === $path ? (bool) apply_filters('aipt_chatbot_add_to_cart_enabled_cache_only', false) : (bool) apply_filters('aipt_chatbot_premium_settings_enabled_cache_only', false); return self::projectPaidValue($path, $value, $enabled); } /** * @param string $path Dot-notation paid setting path. * @param mixed $value Stored value. * @param bool $enabled Whether the site is entitled to the setting. * @return mixed Effective value. */ private static function projectPaidValue(string $path, $value, bool $enabled) { if (self::ADD_TO_CART_PATH === $path) { return (bool) $value && $enabled; } if ($enabled) { return $value; } $free = self::getFreePaidSettingValue($path); list($section, $key) = explode('.', $path, 2); $defaults = self::getDefaults(); return ($value === $free || $value === $defaults[$section][$key]) ? $value : $free; } /** * Free value of a paid setting, matching PremiumChatbotService's clamps. * * @param string $path Dot-notation paid setting path. * @return mixed */ private static function getFreePaidSettingValue(string $path) { switch ($path) { case 'general.starter_messages': return self::getDefaults()['general']['starter_messages']; case 'appearance.launcher_animation': return self::FREE_LAUNCHER_ANIMATION; case 'behavior.max_products': return self::FREE_MAX_PRODUCTS; case self::ADD_TO_CART_PATH: return false; case 'behavior.response_length': return self::FREE_RESPONSE_LENGTH; case 'behavior.product_recommendation_mode': return self::FREE_RECOMMENDATION_MODE; case 'localization.custom_labels': return []; default: return ''; } } /** * Public URL for a selected terms/privacy page, or null when it is not * safe to link: never selected, no longer existing, or existing but not * published (trashed, drafted, pending, private). * * get_permalink() only returns false once the post row is gone * entirely; for a trashed, draft, pending, or private page it still * returns a fallback `?page_id=N` permalink, so the post's status must * be checked too or a trashed page keeps a broken link in the footer * instead of the link disappearing. * * @param int|string|null $page_id Selected page ID, or null/0/'' when none is set. * @return string|null Escaped permalink, or null when not publicly linkable. */ public static function publicPageUrl($page_id): ?string { if (empty($page_id)) { return null; } $permalink = get_permalink($page_id); if ($permalink === false || get_post_status($page_id) !== 'publish') { return null; } return esc_url_raw($permalink); } /** * The site's own Privacy Policy page URL, or null while WordPress has none * to offer. get_privacy_policy_url() is non-empty only for a published page. * * @return string|null Raw URL safe for a JSON payload, or null. */ public static function wpPrivacyPolicyUrl(): ?string { if (!function_exists('get_privacy_policy_url')) { return null; } $url = get_privacy_policy_url(); return is_string($url) && $url !== '' ? esc_url_raw($url) : null; } /** * URL the consent line links as the privacy policy: the page chosen for the * assistant, else the merchant's own published WordPress privacy page. * * @param int|string|null $page_id Chatbot privacy page ID, or null/0/'' when none is set. * @return string|null URL, or null when neither page can be linked. */ public static function privacyLinkUrl($page_id): ?string { return self::publicPageUrl($page_id) ?? self::wpPrivacyPolicyUrl(); } /** * Get public settings subset (for storefront widget). * * @return array Public-safe settings. */ public function getPublicSettings(): array { $settings = self::projectForStorefront($this->getAll()); $terms_url = self::publicPageUrl($settings['general']['terms_page_id'] ?? null); $privacy_url = self::privacyLinkUrl($settings['general']['privacy_page_id'] ?? null); return [ 'enabled' => $settings['general']['enabled'], 'bot_name' => $settings['general']['bot_name'], 'greeting_message' => $settings['general']['greeting_message'], 'language' => $settings['general']['language'], 'pre_chat_form_enabled' => $settings['general']['pre_chat_form_enabled'] ?? false, 'starter_messages_enabled' => $settings['general']['starter_messages_enabled'] ?? true, 'starter_messages' => $settings['general']['starter_messages'] ?? [], 'terms_url' => $terms_url, 'privacy_url' => $privacy_url, 'show_powered_by' => $settings['general']['show_powered_by'] ?? false, 'fallback_contact_url' => esc_url_raw($settings['general']['fallback_contact_url'] ?? ''), 'placement' => [ 'position' => $settings['placement']['position'], 'offset_x' => $settings['placement']['offset_x'], 'offset_y' => $settings['placement']['offset_y'], ], 'appearance' => [ 'launcher_icon' => $settings['appearance']['launcher_icon'] ?? 'chat', 'custom_launcher_icon_url' => $settings['appearance']['custom_launcher_icon_url'] ?? '', 'profile_picture_url' => $settings['appearance']['profile_picture_url'] ?? '', 'colors' => $settings['appearance']['colors'], 'font_family' => $settings['appearance']['font_family'], 'border_radius' => $settings['appearance']['border_radius'], 'custom_css' => $settings['appearance']['custom_css'], 'launcher_animation' => $settings['appearance']['launcher_animation'] ?? 'none', 'hero_image_url' => $settings['appearance']['hero_image_url'] ?? '', 'attention_bubble_enabled' => $settings['appearance']['attention_bubble_enabled'] ?? false, 'attention_bubble_text' => $settings['appearance']['attention_bubble_text'] ?? __('Chat with us!', 'ai-product-tools'), 'attention_badge_enabled' => $settings['appearance']['attention_badge_enabled'] ?? false, 'attention_badge_text' => $settings['appearance']['attention_badge_text'] ?? '1', ], 'behavior' => [ 'max_products' => $settings['behavior']['max_products'], 'show_view_product' => $settings['behavior']['show_view_product'], 'show_add_to_cart' => $settings['behavior']['show_add_to_cart'], 'show_stock_status' => $settings['behavior']['show_stock_status'], ], 'labels' => self::getLabelsForLanguage( (string) ($settings['general']['language'] ?? 'en'), (array) ($settings['localization']['custom_labels'] ?? []) ), ]; } /** * Get UI labels in configured language with custom overrides applied. * * @return array Translated labels. */ public function getLabels(): array { $language = $this->get('general.language', 'en'); $custom_labels = $this->get('localization.custom_labels', []); return self::getLabelsForLanguage($language, $custom_labels); } /** * Get all label keys. * * @return array List of all valid label keys. */ public static function getAllLabelKeys(): array { return self::ALL_LABEL_KEYS; } /** * Check if auto-detect language is enabled. * * @return bool */ public function isAutoDetectEnabled(): bool { return (bool) $this->get('localization.auto_detect_enabled', true); } /** * Get fallback language for auto-detection. * * @return string Fallback language code. */ public function getFallbackLanguage(): string { return $this->get('localization.fallback_language', 'en'); } /** * Get supported languages list. * * @return array Array of supported language codes. */ public static function getSupportedLanguages(): array { return self::VALID_LANGUAGES; } /** * Get the storefront labels for a supported language. * * Serves the same Free-projected custom labels as the widget payload. * * @param string $language Supported language code. * @return array|null Labels, or null when the language is not supported. */ public function getStorefrontLabelsForLanguage(string $language): ?array { if (!in_array($language, self::VALID_LANGUAGES, true)) { return null; } $settings = self::projectForStorefront($this->getAll()); return self::getLabelsForLanguage( $language, (array) ($settings['localization']['custom_labels'] ?? []) ); } /** * Get labels for a specific language with optional custom overrides. * * @param string $language Language code. * @param array $custom_labels Optional custom label overrides. * @return array Translated labels. */ public static function getLabelsForLanguage(string $language, array $custom_labels = []): array { $defaults = self::getDefaultLabelsForLanguage($language); $custom_labels = self::aliasDeprecatedLabelKeys($custom_labels); if (!empty($custom_labels)) { $defaults = array_merge($defaults, array_filter($custom_labels, function($value) { return !empty($value) && is_string($value); })); } return $defaults; } /** * Move a custom label saved under a pre-rename key ('placeholder', * 'send') onto the key the widget and the Language tab read * ('input_placeholder', 'send_message'). The old keys still validate for * API clients, but nothing reads them, so a value left there had no * effect. The real key wins when both are set. * * @param array $custom_labels Custom label overrides. * @return array Custom label overrides with the old keys moved. */ private static function aliasDeprecatedLabelKeys(array $custom_labels): array { $deprecated_key_aliases = [ 'placeholder' => 'input_placeholder', 'send' => 'send_message', ]; foreach ($deprecated_key_aliases as $old_key => $new_key) { if (empty($custom_labels[$new_key]) && !empty($custom_labels[$old_key])) { $custom_labels[$new_key] = $custom_labels[$old_key]; } unset($custom_labels[$old_key]); } return $custom_labels; } /** * Static cache for labels per language (in-memory for single request). * * @var array */ private static array $labels_cache = []; /** * Get default labels for a specific language (without custom overrides). * * Uses PHP native arrays for optimal performance via opcache. * Falls back to JSON for backwards compatibility if PHP files don't exist. * * @param string $language Language code. * @return array Default translated labels. */ public static function getDefaultLabelsForLanguage(string $language): array { if (isset(self::$labels_cache[$language])) { return self::$labels_cache[$language]; } $labels = self::loadLabelsFromPhp($language); self::$labels_cache[$language] = $labels; return $labels; } /** * Load labels from PHP files with WordPress transient caching. * * PHP files are opcached by the server, providing ~100x faster access * compared to JSON parsing on every request. * * @param string $language Language code. * @return array Labels for the specified language. */ private static function loadLabelsFromPhp(string $language): array { $safe_language = preg_replace('/[^a-zA-Z0-9\-]/', '', $language); $cache_key = 'aipt_chatbot_labels_' . $safe_language; $cached = get_transient($cache_key); if ($cached !== false && is_array($cached)) { return $cached; } $defaults = self::getDefaultLabelsFromPhp(); if ($safe_language === 'en') { set_transient($cache_key, $defaults, DAY_IN_SECONDS); return $defaults; } $lang_file = AIPT_PLUGIN_DIR . 'src/Assets/data/languages/' . $safe_language . '.php'; if (file_exists($lang_file)) { $translations = include $lang_file; if (is_array($translations)) { $merged = array_merge($defaults, $translations); set_transient($cache_key, $merged, DAY_IN_SECONDS); return $merged; } } set_transient($cache_key, $defaults, DAY_IN_SECONDS); return $defaults; } /** * Get default (English) labels from PHP file. * * @return array Default English labels. */ private static function getDefaultLabelsFromPhp(): array { static $defaults = null; if ($defaults !== null) { return $defaults; } $php_file = AIPT_PLUGIN_DIR . 'src/Assets/data/chatbot-labels.php'; if (file_exists($php_file)) { require_once $php_file; if (function_exists('aipt_get_chatbot_labels')) { $all_labels = aipt_get_chatbot_labels(); $defaults = $all_labels['defaults'] ?? []; if (!empty($defaults)) { return $defaults; } } } $defaults = self::getFallbackLabels()['defaults']; return $defaults; } /** * Get fallback labels when all other sources are unavailable. * * Provides comprehensive English defaults for chatbot functionality. * This is the last resort fallback - normally PHP files are used. * * @return array Fallback labels structure with 'defaults' and 'translations' keys. */ private static function getFallbackLabels(): array { return [ 'defaults' => [ 'placeholder' => __('Type your message...', 'ai-product-tools'), 'input_placeholder' => __('Type your message...', 'ai-product-tools'), 'send' => __('Send', 'ai-product-tools'), 'send_message' => __('Send', 'ai-product-tools'), 'clear' => __('Clear Chat', 'ai-product-tools'), 'emoji' => __('Emoji', 'ai-product-tools'), 'thinking' => __('Thinking...', 'ai-product-tools'), 'error' => __('Something went wrong. Please try again.', 'ai-product-tools'), 'queued' => __('Message queued', 'ai-product-tools'), 'online' => __('Online', 'ai-product-tools'), 'offline' => __('Offline', 'ai-product-tools'), 'close' => __('Close', 'ai-product-tools'), 'open_chat' => __('Open chat', 'ai-product-tools'), 'close_chat' => __('Close chat', 'ai-product-tools'), 'prechat_title' => __('Start a conversation', 'ai-product-tools'), 'prechat_subtitle' => __('Fill in your details to get started', 'ai-product-tools'), 'name_label' => __('Name', 'ai-product-tools'), 'name_placeholder' => __('Your name', 'ai-product-tools'), 'name_required' => __('Name is required', 'ai-product-tools'), 'email_label' => __('Email', 'ai-product-tools'), 'email_placeholder' => __('your@email.com', 'ai-product-tools'), 'email_required' => __('Email is required', 'ai-product-tools'), 'invalid_email' => __('Invalid email address', 'ai-product-tools'), 'message_label' => __('Message', 'ai-product-tools'), 'prechat_message_placeholder' => __('How can we help you?', 'ai-product-tools'), 'message_required' => __('Message is required', 'ai-product-tools'), 'consent_text_before' => __('I agree to the ', 'ai-product-tools'), 'consent_text' => __('I agree to the privacy policy', 'ai-product-tools'), 'consent_and' => __(' and ', 'ai-product-tools'), 'consent_required' => __('Please agree to continue', 'ai-product-tools'), 'start_chat' => __('Start Chat', 'ai-product-tools'), 'view_product' => __('View Product', 'ai-product-tools'), 'add_to_cart' => __('Add to Cart', 'ai-product-tools'), 'addedToCart' => __('Added to cart!', 'ai-product-tools'), 'out_of_stock' => __('Out of Stock', 'ai-product-tools'), 'backorder' => __('Backorder', 'ai-product-tools'), 'variable_options' => __('Multiple options available', 'ai-product-tools'), 'cart_error' => __('Could not add to cart', 'ai-product-tools'), 'cart_error_generic' => __('Error adding to cart', 'ai-product-tools'), 'support_team' => __('Support Team', 'ai-product-tools'), 'message_queued' => __('Message queued', 'ai-product-tools'), 'start_conversation' => __('Start a conversation!', 'ai-product-tools'), 'retry' => __('Retry', 'ai-product-tools'), /* translators: %1$s is a literal {seconds} placeholder the widget replaces with the remaining whole seconds. Keep it. */ 'retry_countdown' => __('Retry in {seconds}s', 'ai-product-tools'), 'contact_us' => __('Contact us', 'ai-product-tools'), 'need_help' => __('Need help?', 'ai-product-tools'), /* translators: {seconds} is a literal placeholder the widget replaces with the number of seconds to wait. Keep it. */ 'retry_after' => __('Please try again in {seconds} seconds.', 'ai-product-tools'), 'send_failed' => __('Failed to send message. Please try again.', 'ai-product-tools'), 'service_unavailable' => __('Service temporarily unavailable, please try again shortly.', 'ai-product-tools'), 'chat_messages' => __('Chat messages', 'ai-product-tools'), 'bot_avatar' => __('Bot avatar', 'ai-product-tools'), 'support_team_avatar' => __('Support team avatar', 'ai-product-tools'), 'support_team_response' => __('Support Team Response', 'ai-product-tools'), 'previous_products' => __('Previous products', 'ai-product-tools'), 'next_products' => __('Next products', 'ai-product-tools'), 'today' => __('Today', 'ai-product-tools'), 'yesterday' => __('Yesterday', 'ai-product-tools'), 'privacy_label' => __('Privacy', 'ai-product-tools'), 'terms_label' => __('Terms', 'ai-product-tools'), 'powered_by' => __('Powered by AI Product Tools', 'ai-product-tools'), 'home_tab' => __('Home', 'ai-product-tools'), 'messages_tab' => __('Messages', 'ai-product-tools'), 'hero_greeting' => __('Hi there', 'ai-product-tools'), 'hero_subtitle' => __('How can we help?', 'ai-product-tools'), 'send_message_cta' => __('Send us a message', 'ai-product-tools'), 'send_message_subtitle' => __('We typically reply in a few minutes', 'ai-product-tools'), 'whatsapp_cta' => __('Chat on WhatsApp', 'ai-product-tools'), 'whatsapp_subtitle' => __('Get instant support via WhatsApp', 'ai-product-tools'), 'attention_bubble' => __('Chat with us!', 'ai-product-tools'), 'collapse_products' => __('Show less', 'ai-product-tools'), 'expand_products' => __('Show details', 'ai-product-tools'), ], 'translations' => [], ]; } /** * Clear the labels cache (useful for testing or after label updates). * * Clears both in-memory cache and WordPress transients. * * @return void */ public static function clearLabelsCache(): void { self::$labels_cache = []; global $wpdb; $transient_pattern = $wpdb->esc_like( '_transient_aipt_chatbot_labels_' ) . '%'; $timeout_pattern = $wpdb->esc_like( '_transient_timeout_aipt_chatbot_labels_' ) . '%'; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $transient_pattern ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $timeout_pattern ) ); } /** * Sanitize a hex color value with fallback for environments without Customizer. * * @param string $color The color value to sanitize. * @return string Sanitized hex color or empty string. */ private function sanitizeHexColorSafe( string $color ): string { $color = trim( $color ); if ( empty( $color ) ) { return ''; } if ( function_exists( 'sanitize_hex_color' ) ) { $sanitized = \sanitize_hex_color( $color ); return $sanitized ? $sanitized : ''; } if ( function_exists( 'sanitize_hex_color_no_hash' ) ) { $color_no_hash = ltrim( $color, '#' ); $sanitized = \sanitize_hex_color_no_hash( $color_no_hash ); if ( ! empty( $sanitized ) ) { return '#' . $sanitized; } } if ( preg_match( '/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/', $color ) ) { return strtolower( $color ); } return ''; } /** * Detect brand colors from theme. * * @return array Detected colors or empty array. */ public function detectBrandColors(): array { $colors = []; $primary = \get_theme_mod('primary_color'); if ($primary) { $colors['primary'] = $primary; } $secondary = \get_theme_mod('secondary_color'); if ($secondary) { $colors['secondary'] = $secondary; } $background = \get_theme_mod('background_color'); if ($background) { $colors['background'] = '#' . ltrim($background, '#'); } $global_styles = function_exists('wp_get_global_styles') ? (array) \wp_get_global_styles(['color']) : []; if (!empty($global_styles)) { if (!empty($global_styles['background'])) { $colors['background'] = $global_styles['background']; } if (!empty($global_styles['text'])) { $colors['text'] = $global_styles['text']; } } return $colors; } /** * Merge settings arrays recursively. * * A keyed settings map (a section, or a map like localization.custom_labels) * merges key by key so a partial update preserves keys it did not mention. * A sequential list (placement.specific_pages, general.knowledge_pages, * general.starter_messages, ...) has no such stable keys to merge by * position: position N of the posted list is not "update item N", so * recursing would only ever let it grow or have an item overwritten, * never shrink, and could never express "clear it" at all. The posted * list (or map) IS the new value whenever either side is list-shaped * (isSequentialOrEmpty()), including the empty-array case, so an empty * array in the request (whether `[]` or `{}` on the wire) always clears * the field instead of silently merging into a no-op. * * That list-or-empty rule must not reach the outermost call, which * merges the fixed settings SECTIONS (self::VALID_SECTIONS) against * each other: a section is never list-shaped, so posting `{}` for an * entire section (e.g. `{"rate_limit": {}}`) is not "clear a list" — * it carries no fields to change, and must stay the key-by-key no-op * it always was, never a wholesale replace. A wholesale replace there * would wipe the section to `[]` before sanitize() runs, which then * silently rebuilds it from hardcoded fallbacks, discarding every * stored value in it (including, for rate_limit, the operator's * configured limits). $is_root disables the wholesale-replace branch * for exactly that one level; every section's own subtree * (rate_limit.*, localization.custom_labels, ...) still goes through * the normal list-or-empty rule above. * * @param array $defaults Default values. * @param array $stored Stored values. * @param bool $is_root Whether $defaults/$stored are the full settings * tree, keyed by VALID_SECTIONS and never list-shaped. * @return array Merged settings. */ private function mergeSettings(array $defaults, array $stored, bool $is_root = true): array { $merged = $defaults; foreach ($stored as $key => $value) { $existing = $merged[$key] ?? null; if ( is_array($value) && is_array($existing) && ($is_root || (!$this->isSequentialOrEmpty($existing) && !$this->isSequentialOrEmpty($value))) ) { $merged[$key] = $this->mergeSettings($existing, $value, false); } else { $merged[$key] = $value; } } return $merged; } private function collectRequestedPaths(array $settings, string $prefix = ''): array { $paths = []; foreach ($settings as $key => $value) { $path = '' === $prefix ? (string) $key : $prefix . '.' . (string) $key; if (is_array($value) && $this->shouldCollectChildPaths($value)) { $paths = array_merge($paths, $this->collectRequestedPaths($value, $path)); continue; } $paths[] = $path; } return array_values(array_unique($paths)); } private function shouldCollectChildPaths(array $value): bool { return !$this->isSequentialOrEmpty($value); } /** * Whether an array is a sequential, zero-based list (PHP 7.4-compatible * equivalent of PHP 8.1's array_is_list()), counting an empty array as * one: it carries no keys of either shape, so it has nothing to merge * by and is always safe to replace wholesale. * * @param array $value Array to inspect. * @return bool */ private function isSequentialOrEmpty(array $value): bool { return empty($value) || array_keys($value) === range(0, count($value) - 1); } private function applyPlanFilter(string $hook, $value, string $path) { $filtered = apply_filters($hook, $value); if ($filtered !== $value) { $this->recordCoercedField($path); } return $filtered; } private function recordCoercedField(string $path): void { if (!$this->wasPathRequested($path)) { return; } $this->last_coerced_fields[] = $path; $this->last_coerced_fields = array_values(array_unique($this->last_coerced_fields)); } private function wasPathRequested(string $path): bool { foreach ($this->requested_paths as $requested_path) { if ($requested_path === $path || strpos($requested_path, $path . '.') === 0) { return true; } } return false; } private function detectPersistenceDrift(array $paths, array $requested, array $persisted, array $previous): array { $drift = []; foreach ($paths as $path) { $requested_exists = $this->hasPath($requested, $path); $persisted_exists = $this->hasPath($persisted, $path); if (!$requested_exists && !$persisted_exists) { continue; } $requested_value = $requested_exists ? $this->getPathValue($requested, $path) : null; $persisted_value = $persisted_exists ? $this->getPathValue($persisted, $path) : null; if ($requested_value === $persisted_value) { continue; } $previous_exists = $this->hasPath($previous, $path); $previous_value = $previous_exists ? $this->getPathValue($previous, $path) : null; $drift[] = [ 'field' => $path, 'requested' => $requested_value, 'persisted' => $persisted_value, 'reason' => $previous_exists && $previous_value === $persisted_value ? 'persisted_value_mismatch' : 'filter_modified_or_db_refused', ]; } return $drift; } private function hasPath(array $settings, string $path): bool { $value = $settings; foreach (explode('.', $path) as $segment) { if (!is_array($value) || !array_key_exists($segment, $value)) { return false; } $value = $value[$segment]; } return true; } private function getPathValue(array $settings, string $path) { $value = $settings; foreach (explode('.', $path) as $segment) { $value = $value[$segment]; } return $value; } /** * Validate settings. * * @param array $settings Settings to validate. * @return array Validation errors. */ private function validate(array $settings): array { $errors = []; if (empty($settings['general']['bot_name'])) { $errors['general.bot_name'] = [__('Bot name is required', 'ai-product-tools')]; } elseif (mb_strlen($settings['general']['bot_name'], 'UTF-8') > ChatbotConstants::maxBotNameLength()) { $errors['general.bot_name'] = [__('Bot name must be under 50 characters', 'ai-product-tools')]; } if (mb_strlen($settings['general']['greeting_message'] ?? '', 'UTF-8') > ChatbotConstants::maxGreetingMessageLength()) { $errors['general.greeting_message'] = [__('Greeting message must be under 500 characters', 'ai-product-tools')]; } if (!in_array($settings['general']['language'] ?? 'en', self::VALID_LANGUAGES, true)) { $errors['general.language'] = [__('Invalid language code', 'ai-product-tools')]; } if (!in_array($settings['general']['tone'] ?? 'friendly', self::VALID_TONES, true)) { $errors['general.tone'] = [__('Invalid tone type', 'ai-product-tools')]; } if (mb_strlen($settings['general']['store_context'] ?? '', 'UTF-8') > ChatbotConstants::maxStoreContextLength()) { $errors['general.store_context'] = [__('Store context must be under 5000 characters', 'ai-product-tools')]; } $starter_messages = $settings['general']['starter_messages'] ?? []; if (!is_array($starter_messages)) { $errors['general.starter_messages'] = [__('Starter messages must be an array', 'ai-product-tools')]; } elseif (count($starter_messages) > 5) { $errors['general.starter_messages'] = [__('Maximum 5 starter messages allowed', 'ai-product-tools')]; } else { foreach ($starter_messages as $msg) { if (!is_string($msg) || mb_strlen($msg, 'UTF-8') > 100) { $errors['general.starter_messages'] = [__('Each starter message must be a string under 100 characters', 'ai-product-tools')]; break; } } } $offset_x = $settings['placement']['offset_x'] ?? 20; if ($offset_x < 0 || $offset_x > 500) { $errors['placement.offset_x'] = [__('Offset must be between 0 and 500 pixels', 'ai-product-tools')]; } $offset_y = $settings['placement']['offset_y'] ?? 20; if ($offset_y < 0 || $offset_y > 500) { $errors['placement.offset_y'] = [__('Offset must be between 0 and 500 pixels', 'ai-product-tools')]; } if (!in_array($settings['placement']['position'] ?? 'bottom-right', self::VALID_POSITIONS, true)) { $errors['placement.position'] = [__('Invalid position', 'ai-product-tools')]; } if (!in_array($settings['placement']['visibility_mode'] ?? 'all', self::VALID_VISIBILITY_MODES, true)) { $errors['placement.visibility_mode'] = [__('Invalid visibility mode', 'ai-product-tools')]; } if (!in_array($settings['placement']['device'] ?? 'all', self::VALID_DEVICES, true)) { $errors['placement.device'] = [__('Invalid device type', 'ai-product-tools')]; } $all_color_keys = [ 'primary', 'secondary', 'background', 'text', 'user_bubble', 'bot_bubble', 'header_bg', 'footer_bg', 'button_hover', 'online_indicator', 'hero_bg', 'launcher_bg', 'launcher_icon_color', 'attention_bubble_bg', 'attention_bubble_text', 'attention_badge_bg', 'attention_badge_text' ]; foreach ($all_color_keys as $colorKey) { $color = $settings['appearance']['colors'][$colorKey] ?? ''; if (!empty($color) && !preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) { $errors["appearance.colors.{$colorKey}"] = [__('Must be valid hex color', 'ai-product-tools')]; } } $border_radius = $settings['appearance']['border_radius'] ?? 12; if ($border_radius < 0 || $border_radius > 50) { $errors['appearance.border_radius'] = [__('Border radius must be between 0 and 50 pixels', 'ai-product-tools')]; } if (!in_array($settings['appearance']['theme_preset'] ?? 'light', self::VALID_THEME_PRESETS, true)) { $errors['appearance.theme_preset'] = [__('Invalid theme preset', 'ai-product-tools')]; } $launcher_icon = $settings['appearance']['launcher_icon'] ?? 'chat'; if (!empty($launcher_icon) && !in_array($launcher_icon, self::VALID_WIDGET_ICONS, true)) { $errors['appearance.launcher_icon'] = [__('Invalid launcher icon', 'ai-product-tools')]; } $launcher_animation = $settings['appearance']['launcher_animation'] ?? 'none'; if (!in_array($launcher_animation, self::VALID_LAUNCHER_ANIMATIONS, true)) { $errors['appearance.launcher_animation'] = [__('Invalid launcher animation', 'ai-product-tools')]; } $attention_bubble_text = $settings['appearance']['attention_bubble_text'] ?? ''; if (mb_strlen($attention_bubble_text, 'UTF-8') > 50) { $errors['appearance.attention_bubble_text'] = [__('Attention bubble text must be under 50 characters', 'ai-product-tools')]; } $attention_badge_text = $settings['appearance']['attention_badge_text'] ?? ''; if (mb_strlen($attention_badge_text, 'UTF-8') > 5) { $errors['appearance.attention_badge_text'] = [__('Attention badge text must be under 5 characters', 'ai-product-tools')]; } $terms_page_id = $settings['general']['terms_page_id'] ?? null; if ($terms_page_id !== null && $terms_page_id > 0 && $this->pageSelectionChanged('terms_page_id', $terms_page_id)) { $terms_page = \get_post($terms_page_id); if (!$terms_page || $terms_page->post_type !== 'page' || $terms_page->post_status !== 'publish') { $errors['general.terms_page_id'] = [__('Selected terms page does not exist or is not published', 'ai-product-tools')]; } } $privacy_page_id = $settings['general']['privacy_page_id'] ?? null; if ($privacy_page_id !== null && $privacy_page_id > 0 && $this->pageSelectionChanged('privacy_page_id', $privacy_page_id)) { $privacy_page = \get_post($privacy_page_id); if (!$privacy_page || $privacy_page->post_type !== 'page' || $privacy_page->post_status !== 'publish') { $errors['general.privacy_page_id'] = [__('Selected privacy page does not exist or is not published', 'ai-product-tools')]; } } $knowledge_pages = $this->sanitizeKnowledgePages((array) ($settings['general']['knowledge_pages'] ?? [])); if (!empty($knowledge_pages)) { foreach ($knowledge_pages as $page_id) { $page = \get_post($page_id); if (!$page || $page->post_type !== 'page' || $page->post_status !== 'publish') { $errors['general.knowledge_pages'] = [__('One or more selected pages do not exist or are not published', 'ai-product-tools')]; break; } } } $max_products = $settings['behavior']['max_products'] ?? 10; if ($max_products < 1 || $max_products > 10) { $errors['behavior.max_products'] = [__('Must be between 1 and 10 products', 'ai-product-tools')]; } if (!in_array($settings['behavior']['response_length'] ?? 'balanced', self::VALID_RESPONSE_LENGTHS, true)) { $errors['behavior.response_length'] = [__('Invalid response length', 'ai-product-tools')]; } $defaults = self::getDefaults(); $provider = $settings['behavior']['provider'] ?? $defaults['behavior']['provider']; if (!in_array($provider, self::VALID_PROVIDERS, true)) { $errors['behavior.provider'] = [__('Invalid AI provider', 'ai-product-tools')]; } else { $api_key_getters = [ 'openai' => [\AIPT\Utils\ApiKeyManager::class, 'get_openai_key'], 'gemini' => [\AIPT\Utils\ApiKeyManager::class, 'get_gemini_key'], 'openrouter' => [\AIPT\Utils\ApiKeyManager::class, 'get_openrouter_key'], 'claude' => [\AIPT\Utils\ApiKeyManager::class, 'get_claude_key'], ]; $api_key = isset($api_key_getters[$provider]) ? call_user_func($api_key_getters[$provider]) : null; if (empty($api_key)) { $provider_names = [ 'openai' => 'OpenAI', 'gemini' => 'Google Gemini', 'openrouter' => 'OpenRouter', 'claude' => 'Claude', ]; $errors['behavior.provider'] = [ sprintf( /* translators: %s: AI provider name (e.g. OpenAI, Gemini) */ __('No API key configured for %s. Please configure an API key in plugin settings.', 'ai-product-tools'), $provider_names[$provider] ?? $provider ) ]; } } $model = $settings['behavior']['model'] ?? ''; if (empty($model) || mb_strlen($model, 'UTF-8') > 100) { $errors['behavior.model'] = [__('Model must be between 1 and 100 characters', 'ai-product-tools')]; } elseif (in_array($provider, self::VALID_PROVIDERS, true) && !\AIPT\Api\ModelCatalog::is_valid_model_choice($provider, $model)) { $errors['behavior.model'] = [ sprintf( /* translators: %1$s: submitted model id, %2$s: AI provider id. */ __('"%1$s" is not a model %2$s currently offers.', 'ai-product-tools'), $model, $provider ) ]; } $recommendation_mode = $settings['behavior']['product_recommendation_mode'] ?? 'auto'; if (!in_array($recommendation_mode, self::VALID_RECOMMENDATION_MODES, true)) { $errors['behavior.product_recommendation_mode'] = [__('Invalid product recommendation mode', 'ai-product-tools')]; } if (isset($settings['rate_limit'])) { $max_requests = $settings['rate_limit']['max_requests'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_MAX_REQUESTS; if ($max_requests < 1 || $max_requests > ChatbotConstants::MAX_RATE_LIMIT_MAX_REQUESTS) { $errors['rate_limit.max_requests'] = [__('Must be between 1 and 200', 'ai-product-tools')]; } $window_seconds = $settings['rate_limit']['window_seconds'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_WINDOW_SECONDS; if ($window_seconds < ChatbotConstants::MIN_RATE_LIMIT_WINDOW_SECONDS || $window_seconds > ChatbotConstants::MAX_RATE_LIMIT_WINDOW_SECONDS) { $errors['rate_limit.window_seconds'] = [__('Must be between 10 and 3600 seconds', 'ai-product-tools')]; } $key_mode = $settings['rate_limit']['key_mode'] ?? 'session'; if (!in_array($key_mode, self::VALID_KEY_MODES, true)) { $errors['rate_limit.key_mode'] = [__('Invalid key mode', 'ai-product-tools')]; } $daily_limits = [ 'visitor_daily_max_requests' => [ChatbotConstants::DEFAULT_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS, ChatbotConstants::MAX_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS], 'site_daily_max_requests' => [ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS, ChatbotConstants::MAX_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS], ]; foreach ($daily_limits as $field => $bounds) { $value = $settings['rate_limit'][$field] ?? $bounds[0]; if (!is_numeric($value) || $value < 0 || $value > $bounds[1]) { $errors['rate_limit.' . $field] = [ sprintf( /* translators: %d: maximum number of requests per day */ __('Must be between 0 and %d', 'ai-product-tools'), $bounds[1] ), ]; } } $site_max_requests = $settings['rate_limit']['site_max_requests'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_MAX_REQUESTS; if (!is_numeric($site_max_requests) || $site_max_requests < 0 || $site_max_requests > ChatbotConstants::MAX_RATE_LIMIT_SITE_MAX_REQUESTS) { $errors['rate_limit.site_max_requests'] = [ sprintf( /* translators: %d: maximum number of requests per hour */ __('Must be between 0 and %d', 'ai-product-tools'), ChatbotConstants::MAX_RATE_LIMIT_SITE_MAX_REQUESTS ), ]; } } if (isset($settings['provider_cooldown'])) { $cooldown_seconds = $settings['provider_cooldown']['seconds'] ?? ChatbotConstants::DEFAULT_PROVIDER_COOLDOWN_SECONDS; if ($cooldown_seconds < ChatbotConstants::MIN_PROVIDER_COOLDOWN_SECONDS || $cooldown_seconds > ChatbotConstants::MAX_PROVIDER_COOLDOWN_SECONDS) { $errors['provider_cooldown.seconds'] = [__('Must be between 5 and 600 seconds', 'ai-product-tools')]; } } if (isset($settings['localization'])) { $fallback_language = $settings['localization']['fallback_language'] ?? 'en'; if (!in_array($fallback_language, self::VALID_LANGUAGES, true)) { $errors['localization.fallback_language'] = [__('Invalid fallback language code', 'ai-product-tools')]; } $custom_labels = $settings['localization']['custom_labels'] ?? []; if (!is_array($custom_labels)) { $errors['localization.custom_labels'] = [__('Custom labels must be an array', 'ai-product-tools')]; } else { $label_errors = []; foreach ($custom_labels as $key => $value) { if (!in_array($key, self::ALL_LABEL_KEYS, true)) { $label_errors[] = sprintf( /* translators: %s: label key name */ __('Invalid label key: %s', 'ai-product-tools'), esc_html($key) ); continue; } if (!empty($value) && !is_string($value)) { $label_errors[] = sprintf( /* translators: %s: label key name */ __('Label "%s" must be a string', 'ai-product-tools'), esc_html($key) ); continue; } if (is_string($value) && mb_strlen($value, 'UTF-8') > ChatbotConstants::MAX_LABEL_LENGTH) { $label_errors[] = sprintf( /* translators: %s: label key name */ __('Label "%s" exceeds 500 characters', 'ai-product-tools'), esc_html($key) ); } } if (!empty($label_errors)) { $errors['localization.custom_labels'] = $label_errors; } } } return $errors; } /** * Whether this save selects a different page than the stored one for a * `general` page setting. * * @param string $key Setting key under `general`, e.g. 'terms_page_id'. * @param mixed $page_id Page id after merging the request. * @return bool */ private function pageSelectionChanged(string $key, $page_id): bool { return absint($this->current_settings['general'][$key] ?? 0) !== absint($page_id); } /** * Sanitize settings. * * @param array $settings Settings to sanitize. * @return array Sanitized settings. */ private function sanitize(array $settings): array { $settings['general']['enabled'] = (bool) ($settings['general']['enabled'] ?? false); $settings['general']['bot_name'] = sanitize_text_field($settings['general']['bot_name'] ?? ''); $settings['general']['greeting_message'] = sanitize_textarea_field($settings['general']['greeting_message'] ?? ''); $settings['general']['language'] = sanitize_text_field($settings['general']['language'] ?? 'en'); $settings['general']['tone'] = sanitize_text_field($settings['general']['tone'] ?? 'friendly'); $settings['general']['fallback_contact_url'] = esc_url_raw((string) ($settings['general']['fallback_contact_url'] ?? '')); $settings['general']['rate_limit_message'] = sanitize_textarea_field($settings['general']['rate_limit_message'] ?? ''); $error_message_mode = (string) ($settings['general']['error_message_mode'] ?? 'neutral'); $settings['general']['error_message_mode'] = in_array($error_message_mode, self::ERROR_MESSAGE_MODES, true) ? $error_message_mode : 'neutral'; unset($settings['general']['show_errors_to_user'], $settings['general']['use_custom_error_message']); $settings['general']['store_context'] = sanitize_textarea_field($settings['general']['store_context'] ?? ''); $settings['general']['pre_chat_form_enabled'] = (bool) ($settings['general']['pre_chat_form_enabled'] ?? false); $settings['general']['terms_page_id'] = isset($settings['general']['terms_page_id']) && $settings['general']['terms_page_id'] > 0 ? absint($settings['general']['terms_page_id']) : null; $settings['general']['privacy_page_id'] = isset($settings['general']['privacy_page_id']) && $settings['general']['privacy_page_id'] > 0 ? absint($settings['general']['privacy_page_id']) : null; $whatsapp_number = $settings['general']['whatsapp_number'] ?? ''; $settings['general']['whatsapp_number'] = preg_replace('/[^0-9+]/', '', sanitize_text_field($whatsapp_number)); $settings['general']['knowledge_pages'] = $this->sanitizeKnowledgePages( (array) ($settings['general']['knowledge_pages'] ?? []) ); $settings['general']['starter_messages_enabled'] = (bool) ($settings['general']['starter_messages_enabled'] ?? true); $settings['general']['show_powered_by'] = rest_sanitize_boolean($settings['general']['show_powered_by'] ?? false); $settings['general']['starter_messages'] = $this->resolvePaidSetting('general.starter_messages', $settings); $settings['placement']['position'] = sanitize_text_field($settings['placement']['position'] ?? 'bottom-right'); $settings['placement']['offset_x'] = absint($settings['placement']['offset_x'] ?? 20); $settings['placement']['offset_y'] = absint($settings['placement']['offset_y'] ?? 20); $settings['placement']['visibility_mode'] = sanitize_text_field($settings['placement']['visibility_mode'] ?? 'all'); $settings['placement']['specific_pages'] = array_map('absint', (array) ($settings['placement']['specific_pages'] ?? [])); $settings['placement']['excluded_pages'] = array_map('absint', (array) ($settings['placement']['excluded_pages'] ?? [])); $settings['placement']['device'] = sanitize_text_field($settings['placement']['device'] ?? 'all'); $settings['placement']['excluded_page_types'] = array_map('sanitize_text_field', (array) ($settings['placement']['excluded_page_types'] ?? [])); $settings['appearance']['theme_preset'] = sanitize_text_field($settings['appearance']['theme_preset'] ?? 'light'); $launcher_icon = sanitize_text_field($settings['appearance']['launcher_icon'] ?? 'chat'); $settings['appearance']['launcher_icon'] = in_array($launcher_icon, self::VALID_WIDGET_ICONS, true) ? $launcher_icon : 'chat'; $settings['appearance']['custom_launcher_icon_url'] = $this->resolvePaidSetting('appearance.custom_launcher_icon_url', $settings); $settings['appearance']['profile_picture_url'] = esc_url_raw((string) ($settings['appearance']['profile_picture_url'] ?? '')); $all_color_keys = [ 'primary', 'secondary', 'background', 'text', 'user_bubble', 'bot_bubble', 'header_bg', 'footer_bg', 'button_hover', 'online_indicator', 'hero_bg', 'launcher_bg', 'launcher_icon_color', 'attention_bubble_bg', 'attention_bubble_text', 'attention_badge_bg', 'attention_badge_text' ]; foreach ($all_color_keys as $colorKey) { $color_value = $settings['appearance']['colors'][$colorKey] ?? ''; $settings['appearance']['colors'][$colorKey] = $this->sanitizeHexColorSafe( is_string( $color_value ) ? $color_value : '' ); } $settings['appearance']['font_family'] = sanitize_text_field($settings['appearance']['font_family'] ?? 'inherit'); $settings['appearance']['border_radius'] = absint($settings['appearance']['border_radius'] ?? 12); $settings['appearance']['custom_css'] = $this->resolvePaidSetting('appearance.custom_css', $settings); $launcher_animation = $this->resolvePaidSetting('appearance.launcher_animation', $settings); $settings['appearance']['launcher_animation'] = in_array($launcher_animation, self::VALID_LAUNCHER_ANIMATIONS, true) ? $launcher_animation : 'pulse'; $settings['appearance']['hero_image_url'] = $this->resolvePaidSetting('appearance.hero_image_url', $settings); $settings['appearance']['attention_bubble_enabled'] = (bool) ($settings['appearance']['attention_bubble_enabled'] ?? false); $attention_bubble_text = sanitize_text_field($settings['appearance']['attention_bubble_text'] ?? ''); $settings['appearance']['attention_bubble_text'] = mb_substr($attention_bubble_text, 0, 50); $settings['appearance']['attention_badge_enabled'] = (bool) ($settings['appearance']['attention_badge_enabled'] ?? false); $attention_badge_text = sanitize_text_field($settings['appearance']['attention_badge_text'] ?? '1'); $settings['appearance']['attention_badge_text'] = mb_substr($attention_badge_text, 0, 5); $index_profile = $settings['behavior']['index_profile'] ?? '0'; $index_profile = sanitize_text_field((string) $index_profile); $index_profile_int = is_numeric($index_profile) ? (int) $index_profile : 0; $settings['behavior']['index_profile'] = (string) max(0, $index_profile_int); $settings['behavior']['max_products'] = $this->resolvePaidSetting('behavior.max_products', $settings); $settings['behavior']['show_view_product'] = (bool) ($settings['behavior']['show_view_product'] ?? true); $settings['behavior']['show_add_to_cart'] = (bool) $this->resolvePaidSetting('behavior.show_add_to_cart', $settings); $settings['behavior']['show_stock_status'] = (bool) ($settings['behavior']['show_stock_status'] ?? true); $settings['behavior']['response_length'] = $this->resolvePaidSetting('behavior.response_length', $settings); $recommendation_mode = $this->resolvePaidSetting('behavior.product_recommendation_mode', $settings); $settings['behavior']['product_recommendation_mode'] = in_array($recommendation_mode, self::VALID_RECOMMENDATION_MODES, true) ? $recommendation_mode : 'auto'; $default_provider = self::getDefaults()['behavior']['provider']; $input_provider = sanitize_text_field($settings['behavior']['provider'] ?? $default_provider); $valid_provider = in_array($input_provider, self::VALID_PROVIDERS, true) ? $input_provider : $default_provider; $settings['behavior']['provider'] = $valid_provider; $input_model = sanitize_text_field($settings['behavior']['model'] ?? ''); if ($input_provider !== $valid_provider || empty($input_model)) { $settings['behavior']['model'] = $this->getDefaultModelForProvider($valid_provider); } else { $settings['behavior']['model'] = $input_model; } $settings['rate_limit']['enabled'] = (bool) ($settings['rate_limit']['enabled'] ?? true); $settings['rate_limit']['max_requests'] = max(1, min(200, absint($settings['rate_limit']['max_requests'] ?? 10))); $settings['rate_limit']['window_seconds'] = max(10, min(3600, absint($settings['rate_limit']['window_seconds'] ?? 60))); $key_mode = sanitize_text_field($settings['rate_limit']['key_mode'] ?? 'session'); $settings['rate_limit']['key_mode'] = in_array($key_mode, self::VALID_KEY_MODES, true) ? $key_mode : 'session'; $settings['rate_limit']['site_max_requests'] = min( ChatbotConstants::MAX_RATE_LIMIT_SITE_MAX_REQUESTS, absint($settings['rate_limit']['site_max_requests'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_MAX_REQUESTS) ); $settings['rate_limit']['visitor_daily_max_requests'] = min( ChatbotConstants::MAX_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS, absint($settings['rate_limit']['visitor_daily_max_requests'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS) ); $settings['rate_limit']['site_daily_max_requests'] = min( ChatbotConstants::MAX_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS, absint($settings['rate_limit']['site_daily_max_requests'] ?? ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS) ); $settings['provider_cooldown']['enabled'] = (bool) ($settings['provider_cooldown']['enabled'] ?? true); $settings['provider_cooldown']['seconds'] = max(5, min(600, absint($settings['provider_cooldown']['seconds'] ?? 60))); $settings['provider_cooldown']['enqueue_on_failure'] = (bool) ($settings['provider_cooldown']['enqueue_on_failure'] ?? false); $settings['localization']['auto_detect_enabled'] = (bool) ($settings['localization']['auto_detect_enabled'] ?? true); $fallback_language = sanitize_text_field($settings['localization']['fallback_language'] ?? 'en'); $settings['localization']['fallback_language'] = in_array($fallback_language, self::VALID_LANGUAGES, true) ? $fallback_language : 'en'; $settings['localization']['custom_labels'] = $this->resolvePaidSetting('localization.custom_labels', $settings); return $settings; } /** * Sanitize a paid setting and apply its plan clamp when the save changed it. * * - Unchanged (equal to the stored value after sanitization): kept as is. * A save never re-clamps stored paid configuration it did not change. * - Changed on an entitled site: the legacy validation filter normalizes it. * - Changed to a non-Free value without entitlement: the G9 bridge defaults * to false, so this also clamps in the free build. * - license_unverified: the stored value is kept and the save is * rejected before anything is written (see update()). * - any other reason: the Free value is saved and reported through * getLastCoercedFields() / getLastCoercedReason(). * * Known asymmetry (recorded as a product decision, not changed): two shipped * defaults differ from their Free values (response_length 'balanced' vs * 'concise', launcher_animation 'none' vs 'pulse'). projectForStorefront() * keeps a stored default so Free sites keep their current defaults, while a * save that CHANGES the value back to that default without entitlement is * clamped to the Free value here, matching PremiumChatbotService's clamps. * * @param string $path Dot-notation paid setting path. * @param array $settings Merged settings being saved. * @return mixed Value to persist. */ private function resolvePaidSetting(string $path, array $settings) { $value = $this->sanitizePaidSettingInput($path, $this->readPath($settings, $path)); $current = $this->sanitizePaidSettingInput($path, $this->readPath($this->current_settings, $path)); if ($value === $current) { return $value; } if ($this->isPaidSettingEnabled($path)) { return $this->applyPlanFilter(self::PAID_SETTING_HOOKS[$path], $value, $path); } $free = $this->sanitizePaidSettingInput($path, self::getFreePaidSettingValue($path)); if ($value === $free) { return $value; } list($feature, $required_plan) = $this->getPaidSettingFeature($path); $reason = $this->getPaidSettingDenialReason($feature, $required_plan); if (PlanDenial::isVerificationUnavailable($reason)) { $this->unverified_fields[] = $path; if (null === $this->unverified_denial) { $this->unverified_denial = [$feature, $required_plan]; } return $current; } $this->recordCoercedField($path); if ('' === $this->last_coerced_reason || PlanDenial::REASON_PLAN_REQUIRED === $this->last_coerced_reason) { $this->last_coerced_reason = $reason; } return $free; } /** * Whether the site may set a paid setting (authoritative G9 bridge, false by default). * * @param string $path Dot-notation paid setting path. * @return bool */ private function isPaidSettingEnabled(string $path): bool { $bridge = self::ADD_TO_CART_PATH === $path ? 'aipt_chatbot_add_to_cart_enabled' : 'aipt_chatbot_premium_settings_enabled'; if (!array_key_exists($bridge, $this->plan_decisions)) { $this->plan_decisions[$bridge] = (bool) apply_filters($bridge, false); } return (bool) $this->plan_decisions[$bridge]; } /** * Feature key and required plan reported for a denied paid setting. * * @param string $path Dot-notation paid setting path. * @return array{0:string,1:string} */ private function getPaidSettingFeature(string $path): array { return self::ADD_TO_CART_PATH === $path ? ['chatbotAddToCart', PlanDenial::PLAN_BUSINESS] : ['chatbotPremiumSettings', PlanDenial::PLAN_PAID]; } /** * Memoized denial reason for a feature within the current update. * * @param string $feature Feature key. * @param string $required_plan PlanDenial plan constant. * @return string */ private function getPaidSettingDenialReason(string $feature, string $required_plan): string { $key = 'reason:' . $feature; if (!array_key_exists($key, $this->plan_decisions)) { $this->plan_decisions[$key] = PlanDenial::reason($feature, $required_plan); } return (string) $this->plan_decisions[$key]; } /** * Sanitize a raw paid setting value (before any plan clamp). * * @param string $path Dot-notation paid setting path. * @param mixed $raw Raw value, null when missing. * @return mixed */ private function sanitizePaidSettingInput(string $path, $raw) { switch ($path) { case 'general.starter_messages': $messages = []; foreach (array_slice((array) ($raw ?? []), 0, 5) as $msg) { if (is_string($msg) && !empty(trim($msg))) { $messages[] = mb_substr(sanitize_text_field($msg), 0, 100); } } return $messages; case 'appearance.custom_launcher_icon_url': case 'appearance.hero_image_url': return esc_url_raw(is_scalar($raw) ? (string) $raw : ''); case 'appearance.custom_css': return $this->sanitizeCustomCss(is_scalar($raw) ? (string) $raw : ''); case 'appearance.launcher_animation': return sanitize_text_field($raw ?? 'pulse'); case 'behavior.max_products': return absint($raw ?? 10); case self::ADD_TO_CART_PATH: return (bool) ($raw ?? true); case 'behavior.response_length': return sanitize_text_field($raw ?? 'balanced'); case 'behavior.product_recommendation_mode': return (string) ($raw ?? 'auto'); case 'localization.custom_labels': $labels = []; foreach ((array) ($raw ?? []) as $key => $label) { if (in_array($key, self::ALL_LABEL_KEYS, true) && is_string($label) && !empty(trim($label))) { $labels[$key] = mb_substr(sanitize_textarea_field($label), 0, 500); } } return self::aliasDeprecatedLabelKeys($labels); default: return $raw; } } /** * Read a dot-notation path, null when it is missing. * * @param array $settings Settings. * @param string $path Dot-notation path. * @return mixed */ private function readPath(array $settings, string $path) { return $this->hasPath($settings, $path) ? $this->getPathValue($settings, $path) : null; } /** * Sanitize knowledge pages to existing, published page IDs. * * @param array $knowledge_pages Raw knowledge page IDs. * @return array Sanitized knowledge page IDs. */ private function sanitizeKnowledgePages(array $knowledge_pages): array { $knowledge_pages = array_values(array_filter(array_map('absint', $knowledge_pages))); return array_values(array_filter($knowledge_pages, static function ($page_id) { $page = get_post($page_id); return $page && isset($page->post_type, $page->post_status) && $page->post_type === 'page' && $page->post_status === 'publish'; })); } /** * Clear cached settings. * * @return void */ public function clearCache(): void { $this->cached_settings = null; } /** * Sanitize custom CSS to prevent XSS attacks. * * Removes dangerous CSS patterns while preserving valid styles. * * @param string $css Raw CSS input. * @return string Sanitized CSS. */ private function sanitizeCustomCss(string $css): string { $css = wp_strip_all_tags($css); $dangerous_patterns = [ '/expression\s*\(/i', '/javascript\s*:/i', '/vbscript\s*:/i', '/data\s*:/i', '/behavior\s*:/i', '/-moz-binding\s*:/i', '/url\s*\(\s*["\']?\s*(?!https?:\/\/|\/|\.\/|\.\.\/|#)/i', '/@import/i', '/@charset/i', '/&#/i', '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', ]; foreach ($dangerous_patterns as $pattern) { $css = preg_replace($pattern, '', $css); } $css = substr($css, 0, 10000); return trim($css); } }