*/ private array $resolvedKeys = array(); /** * Resolves an API key for the given AIPT provider. * * Reads the wp_option aipt_{$aiptProvider}_api_key. Returns the plaintext key * if configured, applying the same three-mode decryption fallback as * ApiKeyManager::attempt_decryption() (lines 37–58). Returns null for absent, * sentinel, or unrecoverable values. Never throws on missing credentials. * * @since 2.6.0 * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return string|null The resolved plaintext key, or null if not configured. * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function getKey( string $aiptProvider ): ?string { self::validateProvider( $aiptProvider ); if ( array_key_exists( $aiptProvider, $this->resolvedKeys ) ) { return $this->resolvedKeys[ $aiptProvider ]; } $resolved = $this->resolveKey( $aiptProvider ); $this->resolvedKeys[ $aiptProvider ] = $resolved; return $resolved; } /** * Returns the credential source for the given provider. * * Returns CredentialSource::DATABASE_LOCAL when getKey() returns a non-null * string, CredentialSource::NONE otherwise. Uses the cached result of getKey() * to avoid repeated decryption calls within the same request. * * @since 2.6.0 * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return string One of the CredentialSource constants. * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function getSource( string $aiptProvider ): string { self::validateProvider( $aiptProvider ); return null !== $this->getKey( $aiptProvider ) ? CredentialSource::DATABASE_LOCAL : CredentialSource::NONE; } /** * Checks if a credential is configured for the given provider. * * Convenience method: returns true iff getKey() returns a non-null string. * * @since 2.6.0 * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return bool True if credential is configured, false otherwise. * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function isConfigured( string $aiptProvider ): bool { return null !== $this->getKey( $aiptProvider ); } /** * Returns the human-readable label for the credential source. * * Delegates to CredentialSource::label( $this->getSource( $aiptProvider ) ). * * @since 2.6.0 * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return string Translated label suitable for display. * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function getSourceLabel( string $aiptProvider ): string { return CredentialSource::label( $this->getSource( $aiptProvider ) ); } /** * Whether the option holds a stored value this provider cannot read: an * encrypted key that opens with none of the key derivations (the security * keys in wp-config.php changed, the database came from another site, or * this server lost OpenSSL), or the re-entry marker an earlier release * wrote. getKey() answers null for such a value, so it is never sent to a * provider; this lets the Settings screen say why the key is missing. * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return bool * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function hasUnreadableKey( string $aiptProvider ): bool { self::validateProvider( $aiptProvider ); return '' !== (string) get_option( "aipt_{$aiptProvider}_api_key", '' ) && null === $this->getKey( $aiptProvider ); } /** * The sentence the Settings screen shows for a stored key this provider * cannot read, or null when there is none to show. * * @param string $aiptProvider One of 'openai', 'gemini', 'claude', 'openrouter'. * @return string|null * * @throws \InvalidArgumentException If $aiptProvider is not recognized. */ public function unreadableKeyMessage( string $aiptProvider ): ?string { if ( ! $this->hasUnreadableKey( $aiptProvider ) ) { return null; } $stored = (string) get_option( "aipt_{$aiptProvider}_api_key", '' ); return self::unreadableKeySentence( ProviderNameMapper::displayName( $aiptProvider ), Encryption::is_available(), false === strpos( $stored, self::FALLBACK_SENTINEL ) ); } /** * Why a stored key cannot be read and what to do about it. Without * OpenSSL a key typed again could not be saved either, so those cases * name the missing extension: a sealed key opens again once OpenSSL is * back, while the re-entry marker holds no key and still has to be * entered again. * * @param string $providerLabel Provider name shown to the merchant. * @param bool $encryptionAvailable Whether this server can encrypt and decrypt. * @param bool $holdsSealedKey False for the re-entry marker, which holds no key. * @return string */ public static function unreadableKeySentence( string $providerLabel, bool $encryptionAvailable, bool $holdsSealedKey ): string { if ( ! $encryptionAvailable && $holdsSealedKey ) { return sprintf( /* translators: %s: Provider name (e.g., OpenAI, Google Gemini) */ __( 'The saved %s key cannot be read: this server is missing the PHP OpenSSL extension. Ask your host to enable OpenSSL, and the key can be read again.', 'ai-product-tools' ), $providerLabel ); } if ( ! $encryptionAvailable ) { return sprintf( /* translators: %s: Provider name (e.g., OpenAI, Google Gemini) */ __( 'The saved %s key has to be entered again, and this server is missing the PHP OpenSSL extension needed to save it. Ask your host to enable OpenSSL first.', 'ai-product-tools' ), $providerLabel ); } return sprintf( /* translators: %s: Provider name (e.g., OpenAI, Google Gemini) */ __( 'The saved %s key can no longer be read on this site, usually because the security keys in wp-config.php changed. Enter the key again, or remove it.', 'ai-product-tools' ), $providerLabel ); } /** * Clears request-level resolved key memoization. * * Runtime credential writes call through CredentialResolver::flushMemoization() * so subsequent reads in the same request observe fresh option values. * * @since 2.6.0 * * @return void */ public function clearCache(): void { $this->resolvedKeys = array(); } /** * Core key resolution logic. * * Reads the raw wp_option value and applies decryption/fallback in order: * 1. Empty value — return null. * 2. Contains ENCRYPTED_FALLBACK_NEEDS_REENTRY sentinel — return null. * 3. No AIPT_ENC_ prefix — return as plaintext (mirrors ApiKeyManager lines 107–110). * 4. Three decryption attempts with legacy_mode null/true/false and silent_mode=true * (ported from ApiKeyManager::attempt_decryption() lines 37–58). * 5. Last-resort: if raw no longer carries the AIPT_ENC_ prefix, return as plaintext * (edge case from unconventional migration paths, ref. ApiKeyManager lines 68–93). * 6. Encrypted but unrecoverable — return null. * * @since 2.6.0 * * @param string $aiptProvider AIPT provider slug (already validated by getKey()). * @return string|null Resolved plaintext key, or null. */ private function resolveKey( string $aiptProvider ): ?string { $raw = (string) get_option( "aipt_{$aiptProvider}_api_key", '' ); if ( '' === $raw ) { return null; } if ( false !== strpos( $raw, self::FALLBACK_SENTINEL ) ) { return null; } if ( 0 !== strpos( $raw, self::ENCRYPTED_PREFIX ) ) { return $raw; } $decryption_modes = array( null, true, false ); foreach ( $decryption_modes as $legacy_mode ) { try { $decrypted = Encryption::decrypt_api_key( $raw, $legacy_mode, true ); if ( $decrypted !== $raw && '' !== $decrypted ) { return $decrypted; } } catch ( \Exception $e ) { } } if ( 0 !== strpos( $raw, self::ENCRYPTED_PREFIX ) ) { return $raw; } return null; } /** * Validates an AIPT provider slug against ProviderNameMapper::aiptProviders(). * * @since 2.6.0 * * @param string $aiptProvider AIPT provider slug to validate. * @return void * * @throws \InvalidArgumentException If $aiptProvider is not in the supported list. */ private static function validateProvider( string $aiptProvider ): void { if ( ! in_array( $aiptProvider, ProviderNameMapper::aiptProviders(), true ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing exception, not user output. throw new \InvalidArgumentException( "Unknown AIPT provider: {$aiptProvider}" ); } } }