, ), parentheses, quotes, apostrophes and multi-line * structure, so they are routed through normalizePromptText() (UTF-8 + * control-char + newline normalization only) on BOTH the write and read * paths instead of the destructive sanitize_text_field() / * wp_strip_all_tags() / wp_kses_post() chain. The names mirror * RestEndpoints::$settings_fields and the options the per-type PromptFactory * classes consume via get_option(). * * @var string[] */ private const PROMPT_FIELDS = [ 'short_custom_prompt', 'full_custom_prompt', 'title_additional_prompt', 'faq_additional_prompt', 'seo_meta_additional_prompt', 'taxonomy_additional_prompt', 'image_alt_additional_prompt', 'brand_context', ]; /** * Paid Settings fields, with the feature key that gates each one. * * Always-shipped classification for the write gate: the premium module's * 'aipt_settings_premium_fields' filter only lists these for entitled * installs (and the free build has no registrant), so relying on it alone * let every plan write them. Writes still ask the * 'aipt_settings_can_write_field' filter (false by default). * * @var array */ private const PREMIUM_FIELD_FEATURES = [ 'title_additional_prompt' => 'additionalTitlePrompts', 'faq_additional_prompt' => 'additionalFaqPrompts', 'seo_meta_additional_prompt' => 'additionalSeoMetaPrompts', 'taxonomy_additional_prompt' => 'taxonomyAdditionalPrompt', 'image_alt_additional_prompt' => 'imageAltAdditionalPrompt', ]; /** * Maximum byte length accepted for a single prompt field. * * @var int */ private const MAX_PROMPT_BYTES = 65535; /** * Default "Pause between requests" interval, in seconds. * * Matches the Description generator's own pre-existing default * (`generationInterval` seeded at 0 via `loadOverride('description', * 'generationInterval', 0)`), since this Connection setting replaces that * per-screen control. * * @var int */ private const DEFAULT_REQUEST_INTERVAL_SECONDS = 0; /** * Upper bound for the "Pause between requests" interval, in seconds. * * Mirrors the Description generator's own Stepper bounds * (`INTERVAL_MIN`/`INTERVAL_MAX` in `DescriptionConfigPopoverBody.tsx`). * * @var int */ private const MAX_REQUEST_INTERVAL_SECONDS = 60; /** * Boolean settings fields. * * These MUST be coerced via rest_sanitize_boolean() before update_option() * so the stored value remains a canonical 0/1 — never an empty string. * * Background: sanitize_text_field((string) false) returns '', and an empty * option_value fails WP REST's rest_is_boolean() check on the next save * roundtrip (valid string list is only ['true','false','0','1']). That * cycle surfaces to users as "rest_invalid_param: enable_tooltip" when * saving any setting — a self-poisoning data-corruption loop triggered the * first time a user toggles one of these booleans OFF. * * `metabox_hidden` is included even though it is not declared in the * /settings REST schema args because it is in $this->settings_fields and * hits the same sanitize_text_field branch — without coercion here it * would still corrupt silently. * * @since 2.6.2 * @var array */ private const BOOLEAN_FIELDS = [ 'enable_tooltip', 'metabox_hidden', 'preserve_content_images', 'editor_clear_ai_mark_on_manual_edit', 'content_history_enabled', ]; /** * Valid settings fields * * @var array */ private $settings_fields; /** * Style descriptions * * @var array */ private $style_descriptions; /** * AI Client Factory * * @var AIClientFactoryInterface */ private $ai_client_factory; /** * Constructor * * @param array $settings_fields Valid settings field names * @param array $style_descriptions Style descriptions mapping * @param AIClientFactoryInterface $ai_client_factory AI client factory instance */ public function __construct( array $settings_fields, array $style_descriptions, AIClientFactoryInterface $ai_client_factory ) { $this->settings_fields = $settings_fields; $this->style_descriptions = $style_descriptions; $this->ai_client_factory = $ai_client_factory; } /** * Get all settings * * @return array|\WP_Error Settings data or error */ public function getSettings() { if ( ! current_user_can( 'manage_aipt_settings' ) ) { return new \WP_Error( 'rest_forbidden', 'Sorry, you are not allowed to do that.', array( 'status' => 401 ) ); } $resolver = CredentialResolver::instance(); $settings = array(); foreach ( $this->settings_fields as $field ) { if ( $field === 'openai_api_key' ) { $settings[ $field ] = $this->getApiKeyDisplayValue( 'openai', $resolver ); continue; } if ( $field === 'gemini_api_key' ) { $settings[ $field ] = $this->getApiKeyDisplayValue( 'gemini', $resolver ); continue; } if ( $field === 'openrouter_api_key' ) { $settings[ $field ] = $this->getApiKeyDisplayValue( 'openrouter', $resolver ); continue; } if ( $field === 'claude_api_key' ) { $settings[ $field ] = $this->getApiKeyDisplayValue( 'claude', $resolver ); continue; } if ( $field === 'request_interval' ) { $raw = get_option( 'aipt_request_interval', (string) self::DEFAULT_REQUEST_INTERVAL_SECONDS ); $settings[ $field ] = (string) self::clampRequestInterval( $raw ); continue; } $option_value = get_option( 'aipt_' . $field, Activator::get_default_value( $field ) ); $premium_fields = apply_filters( 'aipt_settings_premium_fields', array() ); if ( in_array( $field, $premium_fields, true ) ) { $can_read = apply_filters( 'aipt_settings_can_read_field', false, $field ); if ( ! $can_read ) { continue; } } if ( $field === 'model' ) { $provider_option = get_option( 'aipt_api_provider', 'openai' ); $normalized_model = $this->ai_client_factory->normalizeModel( $provider_option, $option_value ); $settings[ $field ] = sanitize_text_field( $normalized_model ); continue; } if ( in_array( $field, self::PROMPT_FIELDS, true ) ) { $settings[ $field ] = self::normalizePromptText( $option_value ); continue; } if ( $field === 'content_length_preset' ) { $valid = array( 'short', 'medium', 'long', 'very_long' ); $settings[ $field ] = in_array( $option_value, $valid, true ) ? $option_value : 'medium'; continue; } if ( $field === 'short_length_preset' ) { $valid = array( 'brief', 'standard', 'detailed' ); $settings[ $field ] = in_array( $option_value, $valid, true ) ? $option_value : 'standard'; continue; } if ( $field === 'allowed_html_tags' || $field === 'disallowed_html_tags' ) { if ( is_string( $option_value ) && ! empty( $option_value ) ) { $settings[ $field ] = array_filter( array_map( 'trim', explode( ',', $option_value ) ) ); } elseif ( is_array( $option_value ) ) { $settings[ $field ] = array_map( 'sanitize_text_field', $option_value ); } else { $settings[ $field ] = array(); } continue; } if ( in_array( $field, self::BOOLEAN_FIELDS, true ) ) { $settings[ $field ] = rest_sanitize_boolean( $option_value ); continue; } $settings[ $field ] = sanitize_text_field( $option_value ); } $this->appendApiKeyPresenceFlags( $settings, $resolver ); return $settings; } private function getApiKeyDisplayValue( string $provider, CredentialResolver $resolver ): string { $source = $resolver->getSource( $provider ); if ( in_array( $source, array( CredentialSource::ENV, CredentialSource::CONSTANT, CredentialSource::DATABASE_CONNECTORS ), true ) ) { return ApiKeyManager::get_api_key_for_display( $provider ); } if ( CredentialSource::DATABASE_LOCAL === $source ) { return ApiKeyManager::get_masked_api_key( $provider ); } return ''; } private function appendApiKeyPresenceFlags( array &$settings, CredentialResolver $resolver ): void { foreach ( array( 'openai', 'gemini', 'openrouter', 'claude' ) as $provider ) { $settings[ "{$provider}_api_key_is_set" ] = $resolver->isConfigured( $provider ); } } /** * Update settings * * @param array $request_params Request parameters containing settings to update * @return array|\WP_Error Success response or error */ public function updateSettings( array $request_params ) { try { if ( ! current_user_can( 'manage_aipt_settings' ) ) { return new \WP_Error( 'rest_forbidden', 'Sorry, you are not allowed to do that.', array( 'status' => 401 ) ); } $stored_api_provider = get_option( 'aipt_api_provider', 'openai' ); $api_provider = isset( $request_params['api_provider'] ) ? sanitize_text_field( $request_params['api_provider'] ) : $stored_api_provider; if ( isset( $request_params['api_provider'] ) && ! isset( $request_params['model'] ) && $api_provider !== $stored_api_provider ) { $request_params['model'] = ModelCatalog::normalize_model( $api_provider, get_option( 'aipt_model', '' ) ); } if ( isset( $request_params['api_provider'] ) || isset( $request_params['model'] ) ) { $effective_model = isset( $request_params['model'] ) ? sanitize_text_field( $request_params['model'] ) : get_option( 'aipt_model', '' ); $compatibility_error = $this->validateModelProviderCompatibility( $api_provider, $effective_model ); if ( is_wp_error( $compatibility_error ) ) { return $compatibility_error; } } $pending_key_writes = array(); $api_key_error = $this->processApiKeys( $request_params, $pending_key_writes ); if ( is_wp_error( $api_key_error ) ) { return $api_key_error; } $skipped_premium_fields = array(); $pending_updates = array(); foreach ( $this->settings_fields as $field ) { if ( isset( $request_params[ $field ] ) && ! in_array( $field, array( 'openai_api_key', 'gemini_api_key', 'openrouter_api_key', 'claude_api_key' ) ) ) { $value = $request_params[ $field ]; $premium_fields = array_merge( array_keys( self::PREMIUM_FIELD_FEATURES ), (array) apply_filters( 'aipt_settings_premium_fields', array() ) ); if ( in_array( $field, $premium_fields, true ) ) { $can_write = apply_filters( 'aipt_settings_can_write_field', false, $field ); if ( ! $can_write ) { if ( $this->premiumFieldChanged( $field, $value ) ) { $skipped_premium_fields[] = $field; } continue; } } if ( in_array( $field, self::PROMPT_FIELDS, true ) ) { if ( is_string( $value ) ) { $value = self::normalizePromptText( $value ); } } elseif ( in_array( $field, self::BOOLEAN_FIELDS, true ) ) { $value = (int) rest_sanitize_boolean( $value ); } elseif ( $field === 'allowed_html_tags' || $field === 'disallowed_html_tags' ) { if ( is_array( $value ) ) { $value = array_map( 'sanitize_text_field', $value ); } elseif ( is_string( $value ) ) { $value = array_filter( array_map( 'trim', explode( ',', $value ) ) ); $value = array_map( 'sanitize_text_field', $value ); } else { $value = array(); } } else { $value = sanitize_text_field( $value ); } if ( $field === 'model' ) { $value = ModelCatalog::normalize_model( $api_provider, $value ); } $validation_error = $this->validateField( $field, $value ); if ( is_wp_error( $validation_error ) ) { return $validation_error; } $pending_updates[ $field ] = $value; } } $key_write_error = $this->commitApiKeyWrites( $pending_key_writes ); if ( is_wp_error( $key_write_error ) ) { return $key_write_error; } foreach ( $pending_updates as $pending_field => $pending_value ) { update_option( 'aipt_' . $pending_field, $pending_value ); } $api_key_fields = array( 'openai_api_key', 'gemini_api_key', 'openrouter_api_key', 'claude_api_key' ); $keys_in_request = (bool) array_intersect( $api_key_fields, array_keys( $request_params ) ); $response = array( 'success' => true, 'message' => esc_html__( 'Settings updated successfully!', 'ai-product-tools' ), ); if ( ! empty( $skipped_premium_fields ) ) { $response['skipped_premium_fields'] = $skipped_premium_fields; $response['skipped_premium_fields_reason'] = PlanDenial::reason( self::PREMIUM_FIELD_FEATURES[ $skipped_premium_fields[0] ] ?? 'additionalTitlePrompts', PlanDenial::PLAN_PAID ); } if ( isset( $request_params['api_provider'] ) ) { $provider_labels = array( 'openai' => 'OpenAI', 'gemini' => 'Gemini', 'openrouter' => 'OpenRouter', 'claude' => 'Claude', ); if ( isset( $provider_labels[ $api_provider ] ) && ! CredentialResolver::instance()->isConfigured( $api_provider ) ) { $response['warning'] = sprintf( /* translators: %s: provider display name (e.g. OpenAI, Claude). */ esc_html__( '%s is now the default provider, but no API key is saved for it yet.', 'ai-product-tools' ), $provider_labels[ $api_provider ] ); } } if ( $keys_in_request ) { $response['connectors'] = $this->buildConnectorsSnapshot(); } return $response; } catch ( \Exception $e ) { return new \WP_Error( 'update_failed', esc_html($e->getMessage()), array( 'status' => 500 ) ); } finally { try { Activator::check_and_update_setup_status(); } catch ( \Exception $e ) { } } } /** * Whether a paid field's requested value differs from the stored value. * * Compared after the same normalization the write path applies, so a * whole-object save that sends the stored value back is not reported. * * @param string $field Settings field. * @param mixed $value Requested value. * @return bool */ private function premiumFieldChanged( string $field, $value ): bool { $stored = get_option( 'aipt_' . $field, Activator::get_default_value( $field ) ); if ( in_array( $field, self::PROMPT_FIELDS, true ) ) { return ! is_string( $value ) || self::normalizePromptText( $stored ) !== self::normalizePromptText( $value ); } if ( ! is_scalar( $value ) ) { return true; } return sanitize_text_field( is_scalar( $stored ) ? (string) $stored : '' ) !== sanitize_text_field( (string) $value ); } /** * Validate API key * * @param string $api_key API key to validate * @param string $api_provider Provider name (openai|gemini|openrouter|claude) * @param string $claude_workspace_id Optional Workspace ID, used only when $api_provider is 'claude' and the key is not scoped to a workspace. * @return array|\WP_Error Validation result or error */ public function validateApiKey( string $api_key, string $api_provider = 'openai', string $claude_workspace_id = '' ) { $api_key = preg_replace( '/\s+/', '', $api_key ); if ( empty( $api_key ) ) { return new \WP_Error( 'empty_api_key', 'API key cannot be empty.', array( 'status' => 400, 'error_details' => 'API key cannot be empty. Please enter a valid API key.', ) ); } try { if ( $api_provider === 'gemini' ) { GeminiClient::validate_api_key( $api_key ); } elseif ( $api_provider === 'openrouter' ) { OpenRouterClient::validate_api_key( $api_key ); } elseif ( $api_provider === 'claude' ) { ClaudeClient::validate_api_key( $api_key, $claude_workspace_id ); } else { OpenAIClient::validate_api_key( $api_key ); } return array( 'success' => true, 'message' => __( 'API key validated successfully', 'ai-product-tools' ), 'data' => array( 'provider' => $api_provider, 'validated_at' => current_time( 'mysql' ), ), ); } catch ( ProviderCallException $e ) { return self::keyValidationErrorResponse( $e, $api_provider ); } catch ( \Exception $e ) { return new \WP_Error( 'validation_error', __( 'An error occurred while validating the API key. Please try again.', 'ai-product-tools' ), array( 'status' => 400, 'error_details' => sanitize_text_field( $e->getMessage() ), ) ); } } /** * The WP_Error for a classified key-validation failure, shared by * validateApiKey() (the dedicated /validate-api-key route) and * processProviderKey() (saving a key from Settings). * * Only auth_invalid_key keeps the existing 'invalid_api_key' code and * says the key itself is bad; every other reason (a transient outage, * rate limit, quota, access or malformed-response problem) gets its own * accurate message under a distinct code, at a status that tells the * caller whether retrying later can plausibly help (isRetryable()), * never a flat "this key is invalid" for a problem the key did not * cause. * * @param ProviderCallException $e Caught provider failure. * @param string $api_provider AIPT provider id the key was validated for. * @return \WP_Error * * @since 2.8.0 */ private static function keyValidationErrorResponse( ProviderCallException $e, string $api_provider ): \WP_Error { $message = $e->merchantMessage( $api_provider ); if ( ProviderCallException::AUTH_INVALID_KEY === $e->reason() ) { $message = sprintf( /* translators: %s: AI provider name, e.g. "OpenAI". */ __( '%s rejected this API key. Check that you copied the whole key and that it is still active.', 'ai-product-tools' ), ProviderCallException::providerLabel( '' !== $e->provider() ? $e->provider() : $api_provider ) ); return new \WP_Error( 'invalid_api_key', $message, array( 'status' => 400, 'reason' => $e->reason(), 'helpUrl' => ProviderCallException::helpUrl( $e->reason() ), 'error_details' => sanitize_text_field( $e->getMessage() ), ) ); } return new \WP_Error( 'provider_error', $message, array( 'status' => $e->isRetryable() ? 503 : 400, 'reason' => $e->reason(), 'helpUrl' => ProviderCallException::helpUrl( $e->reason() ), 'error_details' => sanitize_text_field( $e->getMessage() ), ) ); } /** * Sanitize API key * * @param string $key API key to sanitize * @return string Sanitized key */ public function sanitizeApiKey( string $key ): string { $key = trim( $key ); $key = preg_replace( '/\s+/', '', $key ); return sanitize_text_field( $key ); } /** * Normalize a prompt field for storage/display WITHOUT destroying meaning. * * Prompt options are literal instruction text handed to the AI provider — * they are NOT HTML. The defaults intentionally contain XML-like tags * (, ), parentheses, quotes, apostrophes and multi-line * structure. Running them through sanitize_text_field() / * wp_strip_all_tags() / wp_kses_post() (as the old write and read paths * did) silently corrupted that structure. These fields * are admin-only (manage_options) and are rendered escaped in React * textareas, so we only enforce valid UTF-8, strip dangerous control * characters (keeping \n and \t) and normalize line endings. * * @param mixed $text Raw prompt text. * @return string Normalized prompt text. */ public static function normalizePromptText( $text ): string { if ( is_array( $text ) || is_object( $text ) ) { return ''; } $text = wp_check_invalid_utf8( (string) $text, true ); $text = str_replace( array( "\r\n", "\r" ), "\n", $text ); $normalized = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text ); return is_string( $normalized ) ? $normalized : ''; } /** * Clamp a raw "Pause between requests" value to a valid whole-second range. * * A non-numeric or missing value falls back to the default rather than 0, * so a corrupted option never silently removes the pause. * * @param mixed $raw Raw option or request value. * @return int Seconds, clamped to [0, MAX_REQUEST_INTERVAL_SECONDS]. */ private static function clampRequestInterval( $raw ): int { if ( ! is_numeric( $raw ) ) { return self::DEFAULT_REQUEST_INTERVAL_SECONDS; } return max( 0, min( self::MAX_REQUEST_INTERVAL_SECONDS, intval( $raw ) ) ); } /** * Validate model/provider compatibility * * @param string $api_provider Provider name * @param string $model Model identifier * @return true|\WP_Error True if valid, WP_Error if invalid */ public static function validateModelProviderCompatibility( string $api_provider, string $model ) { if ( $api_provider === 'openai' && strpos( $model, 'gemini-' ) === 0 ) { return new \WP_Error( 'invalid_model', esc_html__( 'OpenAI API provider cannot be used with Gemini models.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( $api_provider === 'gemini' && ! ModelCatalog::is_supported( 'gemini', $model ) ) { return new \WP_Error( 'invalid_model', esc_html__( 'Gemini API provider cannot be used with non-Gemini models.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( $api_provider === 'openrouter' && ( strpos( $model, 'gemini-' ) === 0 || strpos( $model, 'gpt-' ) === 0 ) ) { return new \WP_Error( 'invalid_model', esc_html__( 'OpenRouter API provider cannot be used with OpenAI or Gemini direct models.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( $api_provider === 'claude' && strpos( $model, 'claude-' ) !== 0 ) { return new \WP_Error( 'invalid_model', esc_html__( 'Claude API provider cannot be used with non-Claude models.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( in_array( $api_provider, array( 'openai', 'gemini', 'claude', 'openrouter' ), true ) && ! ModelCatalog::is_valid_model_choice( $api_provider, $model ) ) { return new \WP_Error( 'invalid_model', sprintf( /* translators: %1$s: submitted model id, %2$s: AI provider id. */ esc_html__( '"%1$s" is not a model %2$s currently offers.', 'ai-product-tools' ), $model, $api_provider ), array( 'status' => 400 ) ); } return true; } /** * Validate API key updates and stage their writes * * @param array $request_params Request parameters * @param array $pending_writes Receives the validated writes for commitApiKeyWrites(). * @return true|\WP_Error True if every submitted key validated, WP_Error on failure */ private function processApiKeys( array $request_params, array &$pending_writes ) { $api_key = (array_key_exists( 'openai_api_key', $request_params ) && is_string( $request_params['openai_api_key'] )) ? $this->sanitizeApiKey( $request_params['openai_api_key'] ) : null; $result = $this->processProviderKey( $api_key, self::explicitKeyRemovalRequested( $request_params, 'openai' ), [ OpenAIClient::class, 'validate_api_key' ], [ ApiKeyManager::class, 'get_openai_key' ], [ ApiKeyManager::class, 'set_openai_key' ], 'OpenAI', 'openai', $pending_writes ); if ( is_wp_error( $result ) ) { return $result; } $gemini_api_key = (array_key_exists( 'gemini_api_key', $request_params ) && is_string( $request_params['gemini_api_key'] )) ? $this->sanitizeApiKey( $request_params['gemini_api_key'] ) : null; $result = $this->processProviderKey( $gemini_api_key, self::explicitKeyRemovalRequested( $request_params, 'gemini' ), [ GeminiClient::class, 'validate_api_key' ], [ ApiKeyManager::class, 'get_gemini_key' ], [ ApiKeyManager::class, 'set_gemini_key' ], 'Gemini', 'gemini', $pending_writes ); if ( is_wp_error( $result ) ) { return $result; } $openrouter_api_key = (array_key_exists( 'openrouter_api_key', $request_params ) && is_string( $request_params['openrouter_api_key'] )) ? $this->sanitizeApiKey( $request_params['openrouter_api_key'] ) : null; $result = $this->processProviderKey( $openrouter_api_key, self::explicitKeyRemovalRequested( $request_params, 'openrouter' ), [ OpenRouterClient::class, 'validate_api_key' ], [ ApiKeyManager::class, 'get_openrouter_key' ], [ ApiKeyManager::class, 'set_openrouter_key' ], 'OpenRouter', 'openrouter', $pending_writes ); if ( is_wp_error( $result ) ) { return $result; } $claude_api_key = (array_key_exists( 'claude_api_key', $request_params ) && is_string( $request_params['claude_api_key'] )) ? $this->sanitizeApiKey( $request_params['claude_api_key'] ) : null; $claude_workspace_id = ( array_key_exists( 'claude_workspace_id', $request_params ) && is_string( $request_params['claude_workspace_id'] ) ) ? sanitize_text_field( $request_params['claude_workspace_id'] ) : (string) get_option( 'aipt_claude_workspace_id', '' ); $result = $this->processProviderKey( $claude_api_key, self::explicitKeyRemovalRequested( $request_params, 'claude' ), static function ( string $key ) use ( $claude_workspace_id ): bool { return ClaudeClient::validate_api_key( $key, $claude_workspace_id ); }, [ ApiKeyManager::class, 'get_claude_key' ], [ ApiKeyManager::class, 'set_claude_key' ], 'Claude', 'claude', $pending_writes ); if ( is_wp_error( $result ) ) { return $result; } return true; } /** * Whether the request explicitly asked to remove a provider's key, via its * own `{provider}_api_key_remove` flag (the Settings UI's "Remove key" * action sends it; so can a direct API caller that means to delete the * key on purpose). * * @param array $request_params Request parameters. * @param string $provider_id AIPT provider id (openai/gemini/openrouter/claude). * @return bool */ private static function explicitKeyRemovalRequested( array $request_params, string $provider_id ): bool { return rest_sanitize_boolean( $request_params[ $provider_id . '_api_key_remove' ] ?? false ); } /** * Process a single provider API key * * @param string|null $api_key API key value (null = param not provided, '' = clear when $explicit_remove is true, otherwise a no-op) * @param bool $explicit_remove Whether the caller explicitly asked to remove this provider's key, distinguishing a deliberate deletion from an empty value sent for any other reason. * @param callable $validator Validation function * @param callable $getter Function to get current key * @param callable $setter Function to set key * @param string $provider_label Provider display name * @param string $provider_id AIPT provider id (openai/gemini/openrouter/claude), for the credential-source check * @param array $pending_writes Receives the write when the key changes. * @return true|\WP_Error True if the key validated (or needs no write), WP_Error on failure */ private function processProviderKey( ?string $api_key, bool $explicit_remove, callable $validator, callable $getter, callable $setter, string $provider_label, string $provider_id, array &$pending_writes ) { if ( $api_key === null ) { return true; } if ( false !== strpos( $api_key, "\u{2022}" ) ) { return true; } if ( '' === $api_key && ! $explicit_remove ) { return true; } if ( ! ApiKeyManager::localWriteAllowed( $provider_id ) ) { $source = CredentialResolver::instance()->getSource( $provider_id ); return new \WP_Error( 'aipt_provider_immutable', sprintf( /* translators: %s: where the credential is managed, e.g. "WordPress Connectors", "Environment variable", "PHP constant". */ __( "This provider's API key is managed by %s and cannot be edited here. Update it there instead.", 'ai-product-tools' ), CredentialSource::label( $source ) ), array( 'status' => 403, 'source' => $source ) ); } $current_key = call_user_func( $getter ); if ( $api_key === '' ) { if ( ! empty( $current_key ) ) { $pending_writes[] = array( $setter, '', $provider_label ); } return true; } if ( $api_key === $current_key ) { return true; } try { call_user_func( $validator, $api_key ); } catch ( ProviderCallException $e ) { return self::keyValidationErrorResponse( $e, $provider_label ); } catch ( \Exception $e ) { return new \WP_Error( 'invalid_api_key', sprintf( /* translators: %s: Provider name (e.g., OpenAI, Gemini) */ __( 'Invalid %s API key', 'ai-product-tools' ), $provider_label ), array( 'status' => 400 ) ); } $pending_writes[] = array( $setter, $api_key, $provider_label ); return true; } /** * Write the API keys processApiKeys() validated and staged. * * @param array $pending_writes Setter, value ('' clears) and provider name. * @return true|\WP_Error True when every key was written. */ private function commitApiKeyWrites( array $pending_writes ) { foreach ( $pending_writes as $pending_write ) { list( $setter, $value, $provider_label ) = $pending_write; if ( ! call_user_func( $setter, $value ) ) { return new \WP_Error( 'api_key_save_failed', sprintf( /* translators: %s: Provider name (e.g., OpenAI, Gemini) */ __( 'Failed to save %s API key. Please try again.', 'ai-product-tools' ), $provider_label ), array( 'status' => 500 ) ); } } return true; } /** * Build a fresh connectors snapshot mirroring LocalizationDataBuilder's * inner `connectors` sub-array. * * Returned shape (must match LocalizationDataBuilder.php:1130-1135 — same * keys, same types — so the SPA can patch window.aiptData.connectors * in place after a successful save): * - hasAnyConfigured bool * - hasAnyUsableKey bool * - hasAnyConnectorsManaged bool * - connectorsManagedCount int * - providers array (CredentialResolver::getStatus()) * * Built from CredentialResolver directly (NOT via reflection on * LocalizationDataBuilder) to keep coupling minimal and the change * self-contained. The resolver returns fresh data here because * ApiKeyManager setters invoked by commitApiKeyWrites() flushed the * request-memo + ai-availability transient on every successful key write. * * @since 2.6.3 * @return array{hasAnyConfigured: bool, hasAnyUsableKey: bool, hasAnyConnectorsManaged: bool, connectorsManagedCount: int, providers: array>} */ private function buildConnectorsSnapshot(): array { $resolver = CredentialResolver::instance(); $providers_state = $resolver->getStatus(); $managed_count = count( array_filter( $providers_state, static function ( $provider_state ) { return ! empty( $provider_state['isConnectorsManaged'] ); } ) ); return array( 'hasAnyConfigured' => $resolver->hasAnyConfiguredProvider(), 'hasAnyUsableKey' => $resolver->hasAnyUsableKey(), 'hasAnyConnectorsManaged' => $managed_count > 0, 'connectorsManagedCount' => $managed_count, 'providers' => $providers_state, ); } /** * Validate individual field value * * @param string $field Field name * @param mixed $value Field value * @return true|\WP_Error True if valid, WP_Error if invalid */ private function validateField( string $field, $value ) { if ( in_array( $field, self::PROMPT_FIELDS, true ) ) { if ( ! is_string( $value ) ) { return new \WP_Error( 'invalid_prompt_type', 'Prompt field must be a string.', array( 'status' => 400 ) ); } if ( strlen( $value ) > self::MAX_PROMPT_BYTES ) { return new \WP_Error( 'prompt_too_long', 'Prompt field exceeds the maximum allowed length.', array( 'status' => 400 ) ); } } switch ( $field ) { case 'content_length_preset': $valid_presets = array( 'short', 'medium', 'long', 'very_long' ); if ( ! in_array( $value, $valid_presets, true ) ) { return new \WP_Error( 'invalid_content_length_preset', 'Invalid content length preset', array( 'status' => 400 ) ); } break; case 'short_length_preset': $valid_presets = array( 'brief', 'standard', 'detailed' ); if ( ! in_array( $value, $valid_presets, true ) ) { return new \WP_Error( 'invalid_short_length_preset', 'Invalid short description length preset', array( 'status' => 400 ) ); } break; case 'max_tags_count': if ( ! is_numeric( $value ) || intval( $value ) < 1 || intval( $value ) > 20 ) { return new \WP_Error( 'invalid_max_tags_count', 'Maximum tag count must be a positive number between 1 and 20', array( 'status' => 400 ) ); } break; case 'request_interval': if ( ! is_numeric( $value ) || intval( $value ) < 0 || intval( $value ) > self::MAX_REQUEST_INTERVAL_SECONDS ) { return new \WP_Error( 'invalid_request_interval', sprintf( /* translators: %d: maximum allowed seconds. */ 'Pause between requests must be a number between 0 and %d seconds', self::MAX_REQUEST_INTERVAL_SECONDS ), array( 'status' => 400 ) ); } break; case 'content_history_retention': if ( ! is_numeric( $value ) || intval( $value ) < 1 || intval( $value ) > 10 ) { return new \WP_Error( 'invalid_content_history_retention', 'Content History retention must be between 1 and 10', array( 'status' => 400 ) ); } break; case 'language': if ( ! in_array( $value, ContentDefaultsService::SUPPORTED_LANGUAGES ) ) { return new \WP_Error( 'invalid_language', 'Invalid language selection', array( 'status' => 400 ) ); } break; case 'writing_style': if ( ! array_key_exists( $value, $this->style_descriptions ) ) { return new \WP_Error( 'invalid_style', 'Invalid writing style selection', array( 'status' => 400 ) ); } break; case 'api_provider': if ( ! in_array( $value, array( 'openai', 'gemini', 'openrouter', 'claude' ) ) ) { return new \WP_Error( 'invalid_provider', 'Invalid API provider selection', array( 'status' => 400 ) ); } break; } return true; } }