'https://platform.openai.com/usage', 'gemini' => 'https://aistudio.google.com/app/apikey', 'openrouter' => 'https://openrouter.ai/activity', 'claude' => 'https://console.anthropic.com/settings/usage', ); $provider_lower = strtolower( (string) $provider ); $dashboard_url = $provider_dashboards[ $provider_lower ] ?? ''; $attribution = sprintf( /* translators: 1: provider name, 2: dashboard URL or empty */ __( 'Your %1$s account quota is reached. This is NOT a plugin limit. Check your usage at: %2$s', 'ai-product-tools' ), ucfirst( $provider_lower ), $dashboard_url ); $detailed_error = $attribution . "\n" . $detailed_error; } $detailed_error = self::make_urls_readable($detailed_error); $detailed_error = self::sanitize_error_for_display($detailed_error); $detailed_error = self::sanitize_error_for_logging($detailed_error); return $detailed_error; } /** * Extract a retry-after hint (in seconds) from an API error response body. * * Looks for explicit `retry_after` fields (chatbot, providers) first, then * Gemini's structured RetryInfo duration in `error.details[]`, then falls * back to parsing the message text (e.g. "Please retry in 17s" or * OpenAI's actual "Please try again in 20s"/"1m30s"/"250ms" wording). * * @param mixed $error_data Error data from provider (array/string). * @return int|null Seconds to retry, or null when no hint is present. */ public static function extract_retry_after($error_data): ?int { if (is_array($error_data)) { if (isset($error_data['retry_after']) && is_numeric($error_data['retry_after']) && $error_data['retry_after'] > 0) { return min(self::MAX_RETRY_SECONDS, max(1, (int) round((float) $error_data['retry_after']))); } if (isset($error_data['error']['retry_after']) && is_numeric($error_data['error']['retry_after']) && $error_data['error']['retry_after'] > 0) { return min(self::MAX_RETRY_SECONDS, max(1, (int) round((float) $error_data['error']['retry_after']))); } if (isset($error_data['data']['retry_after']) && is_numeric($error_data['data']['retry_after']) && $error_data['data']['retry_after'] > 0) { return min(self::MAX_RETRY_SECONDS, max(1, (int) round((float) $error_data['data']['retry_after']))); } $details = array(); if (isset($error_data['details']) && is_array($error_data['details'])) { $details = $error_data['details']; } elseif (isset($error_data['error']['details']) && is_array($error_data['error']['details'])) { $details = $error_data['error']['details']; } $retry_delay = self::retry_delay_from_details($details); if (null !== $retry_delay) { return min(self::MAX_RETRY_SECONDS, max(1, (int) ceil($retry_delay))); } $message = ''; if (isset($error_data['message']) && is_string($error_data['message'])) { $message = $error_data['message']; } elseif (isset($error_data['error']['message']) && is_string($error_data['error']['message'])) { $message = $error_data['error']['message']; } $seconds = self::retry_delay_from_message($message); if (null !== $seconds) { return min(self::MAX_RETRY_SECONDS, max(1, (int) round($seconds))); } } elseif (is_string($error_data)) { $seconds = self::retry_delay_from_message($error_data); if (null !== $seconds) { return min(self::MAX_RETRY_SECONDS, max(1, (int) round($seconds))); } } return null; } /** * Parse the standard HTTP `Retry-After` response header into whole * seconds, accepting both the delta-seconds form ("30") and the * RFC 7231 HTTP-date form ("Wed, 21 Oct 2026 07:28:00 GMT"). Anthropic * documents this header as the only channel it ever sends a 429 cooldown * through; other providers that also set it get the same benefit. * * @param mixed $header_value Raw `wp_remote_retrieve_header()` result for 'retry-after'. * @return int|null Seconds to wait, or null when the header is absent or unparsable. */ public static function parse_retry_after_header($header_value): ?int { if (is_array($header_value)) { $header_value = reset($header_value); } if (!is_string($header_value) || '' === trim($header_value)) { return null; } $header_value = trim($header_value); if (ctype_digit($header_value)) { $seconds = (int) $header_value; return $seconds > 0 ? min(self::MAX_RETRY_SECONDS, $seconds) : null; } $timestamp = strtotime($header_value); if (false === $timestamp) { return null; } $seconds = $timestamp - time(); return $seconds > 0 ? min(self::MAX_RETRY_SECONDS, $seconds) : null; } /** * Read Gemini's documented RetryInfo `retryDelay` duration (e.g. "12s", * "1.5s") out of a parsed `error.details[]` array. * * @param array $details Parsed `error.details[]`. * @return float|null Seconds, or null when no RetryInfo entry is present. */ private static function retry_delay_from_details(array $details): ?float { foreach ($details as $detail) { if (!is_array($detail)) { continue; } $type = isset($detail['@type']) && is_string($detail['@type']) ? $detail['@type'] : ''; if (false === stripos($type, 'RetryInfo')) { continue; } $retry_delay = isset($detail['retryDelay']) && is_string($detail['retryDelay']) ? $detail['retryDelay'] : ''; if ('' === $retry_delay) { continue; } $seconds = self::parse_duration_to_seconds($retry_delay); if (null !== $seconds && $seconds > 0) { return $seconds; } } return null; } /** * Read a retry delay out of a provider's free-text error message, * matching both "retry in/after Ns" and OpenAI's actual "try again in * Ns" wording, including OpenAI's compact "1m30s"/"250ms" duration forms. * * @param string $message Error message text. * @return float|null Seconds, or null when no recognizable phrase is present. */ private static function retry_delay_from_message(string $message): ?float { if ('' === $message) { return null; } if (preg_match('/(?:retry|try\s+again)\s+(?:in|after)\s+(\d+\s*ms|\d+\s*m\s*[\d.]+\s*s|\d+\s*m|[\d.]+\s*s)/i', $message, $m)) { return self::parse_duration_to_seconds($m[1]); } return null; } /** * Parse a short duration string such as "20s", "1.5s", "1m30s" or * "250ms" into (possibly fractional) seconds. * * @param string $duration Duration text. * @return float|null Seconds, or null when the text does not parse. */ private static function parse_duration_to_seconds(string $duration): ?float { $duration = trim($duration); if ('' === $duration) { return null; } if (preg_match('/^(\d+)\s*ms$/i', $duration, $m)) { return ((float) $m[1]) / 1000; } if (preg_match('/^(\d+)\s*m\s*([\d.]+)\s*s$/i', $duration, $m)) { return ((float) $m[1]) * 60 + (float) $m[2]; } if (preg_match('/^(\d+)\s*m$/i', $duration, $m)) { return ((float) $m[1]) * 60; } if (preg_match('/^([\d.]+)\s*s$/i', $duration, $m)) { return (float) $m[1]; } return is_numeric($duration) ? (float) $duration : null; } /** * Condenses verbose API error messages into concise, user-friendly versions. * Handles rate limit errors with duplicate quota lines, multiple URLs, etc. * * @param string $message Raw error message from the provider * @param mixed $error_code HTTP status code or provider error code * @param string $error_status Provider error status string (e.g. RESOURCE_EXHAUSTED) * @return string Condensed error message */ private static function condense_api_error_message($message, $error_code = '', $error_status = '') { if (empty($message) || !is_string($message)) { return $message; } if (self::is_rate_limit_error($message, $error_code, $error_status)) { return self::condense_rate_limit_message($message); } return self::deduplicate_error_lines($message); } /** * Detects rate limit / quota exceeded errors from code, status, or message content. * * @param string $message Error message text * @param mixed $error_code HTTP or provider error code * @param string $error_status Provider status string * @return bool */ private static function is_rate_limit_error($message, $error_code = '', $error_status = '') { if ((string) $error_code === '429') { return true; } $upper_status = strtoupper((string) $error_status); if ($upper_status === 'RESOURCE_EXHAUSTED' || $upper_status === 'RATE_LIMIT_EXCEEDED') { return true; } $lower_msg = strtolower($message); return strpos($lower_msg, 'quota') !== false || strpos($lower_msg, 'rate limit') !== false || strpos($lower_msg, 'resource_exhausted') !== false || strpos($lower_msg, 'too many requests') !== false; } /** * Detects a genuinely exhausted quota/billing error, as opposed to a * transient per-minute or per-day rate limit that will clear on its own. * * OpenAI marks this explicitly with an `insufficient_quota` code/type. * Other providers only phrase it in the message, as a billing/plan/credit * problem rather than a plain "too many requests" or RESOURCE_EXHAUSTED * rate limit — so a message is only treated as quota-exhausted when it * pairs the word "quota" with one of those billing-shaped cues. * * @param string $message Error message text * @param mixed $error_code HTTP or provider error code * @param string $error_status Provider status string * @param array $details Parsed `error.details[]`, when the caller has it (Gemini only). * @return bool */ private static function is_quota_exhausted_error($message, $error_code = '', $error_status = '', $details = array()) { if (strtolower((string) $error_code) === 'insufficient_quota') { return true; } $lower_msg = strtolower((string) $message); if (strpos($lower_msg, 'insufficient_quota') !== false) { return true; } if ('RESOURCE_EXHAUSTED' === strtoupper((string) $error_status)) { return self::gemini_quota_violation_is_daily_or_billing(is_array($details) ? $details : array()); } return strpos($lower_msg, 'quota') !== false && ( strpos($lower_msg, 'billing') !== false || strpos($lower_msg, 'plan') !== false || strpos($lower_msg, 'credit') !== false ); } /** * Whether a Gemini `error.details[]` array carries a QuotaFailure * violation whose `quotaId`/`quotaMetric` names a daily or billing-level * limit (e.g. "PerDay"), or an ErrorInfo whose quota limit is zero (the * key's Cloud project has no quota at all), as opposed to a per-minute * throttle. Shared between GeminiClient's own classification and this * class's logged wording so the two always agree. * * @param array $details Parsed `error.details[]` from a Gemini error body. * @return bool */ public static function gemini_quota_violation_is_daily_or_billing(array $details): bool { foreach ($details as $detail) { if (!is_array($detail)) { continue; } $type = isset($detail['@type']) && is_string($detail['@type']) ? $detail['@type'] : ''; if (false !== stripos($type, 'ErrorInfo') && '0' === (string) ($detail['metadata']['quota_limit_value'] ?? '')) { return true; } if (false === stripos($type, 'QuotaFailure')) { continue; } $violations = isset($detail['violations']) && is_array($detail['violations']) ? $detail['violations'] : array(); foreach ($violations as $violation) { if (!is_array($violation)) { continue; } $quota_id = isset($violation['quotaId']) && is_string($violation['quotaId']) ? $violation['quotaId'] : ''; $quota_metric = isset($violation['quotaMetric']) && is_string($violation['quotaMetric']) ? $violation['quotaMetric'] : ''; if (self::names_daily_or_billing_limit($quota_id) || self::names_daily_or_billing_limit($quota_metric)) { return true; } } } return false; } /** * Whether a quota metric/id names a daily or billing-level limit rather * than a short per-minute throttle. * * @param string $name `quotaId` or `quotaMetric` value. * @return bool */ private static function names_daily_or_billing_limit(string $name): bool { if ('' === $name) { return false; } return false !== stripos($name, 'PerDay') || false !== stripos($name, 'Billing'); } /** * Extracts the essential information from a verbose rate limit message: * core reason, retry time, and a single reference URL. * * @param string $message Verbose rate limit error message * @return string Condensed message */ private static function condense_rate_limit_message($message) { $core = ''; if (preg_match('/^(.+?)(?:\.\s*(?:For more|To monitor|Please check|\*)|\s*\*\s*Quota|\s*https?:\/\/)/is', $message, $m)) { $core = trim($m[1]); $core = rtrim($core, " ,;:"); } elseif (preg_match('/^(.+?)(?:\.\s*\n|\n\n)/s', $message, $m)) { $core = trim($m[1]); } else { $core = rtrim(trim($message), " .,;:"); } if (empty($core)) { $core = 'API rate limit exceeded'; } $retry = ''; if (preg_match('/retry\s+in\s+([\d.]+)\s*s/i', $message, $m)) { $seconds = (float) $m[1]; $retry = $seconds < 1 ? '< 1s' : round($seconds) . 's'; } $url = ''; if (preg_match('/(https?:\/\/[^\s"\'<>]+)/i', $message, $m)) { $url = rtrim($m[1], '.,;)'); } $result = $core; if ($retry) { $result .= ". Please retry in {$retry}"; } if ($url) { $result .= "\nMore info: {$url}"; } return $result; } /** * Removes duplicate lines from error messages (e.g. repeated quota metric lines). * * @param string $message Error message with potential duplicate lines * @return string Deduplicated message */ private static function deduplicate_error_lines($message) { $lines = preg_split('/\r?\n/', $message); if (count($lines) <= 1) { return $message; } $seen = []; $unique = []; foreach ($lines as $line) { $normalized = trim($line); if ($normalized === '' || !isset($seen[$normalized])) { $unique[] = $line; if ($normalized !== '') { $seen[$normalized] = true; } } } return implode("\n", $unique); } /** * Checks whether the error status string is redundant given the HTTP error code. * Avoids displaying "Status: RESOURCE_EXHAUSTED" when code is already 429. * * @param string $status Error status string * @param mixed $code Error code * @return bool True if status is redundant */ private static function is_status_redundant($status, $code) { $redundancy_map = [ '429' => ['RESOURCE_EXHAUSTED', 'RATE_LIMIT_EXCEEDED', 'TOO_MANY_REQUESTS'], '401' => ['UNAUTHENTICATED'], '403' => ['PERMISSION_DENIED'], '404' => ['NOT_FOUND'], '400' => ['INVALID_ARGUMENT', 'FAILED_PRECONDITION'], '500' => ['INTERNAL'], '503' => ['UNAVAILABLE'], ]; $code_str = (string) $code; $upper_status = strtoupper(trim($status)); if (isset($redundancy_map[$code_str])) { return in_array($upper_status, $redundancy_map[$code_str], true); } return false; } /** * Extract HTTP status code from a formatted API error message * * Parses patterns like "GEMINI API ERROR (503): ..." to recover the original * HTTP status code from provider responses. Falls back to the default when no * status pattern is found (e.g. for non-provider errors). * * @param string $message Formatted error message from format_api_response_error() * @param int $default Default status to return when extraction fails (default 500) * @return int HTTP status code suitable for WP_Error data array */ public static function extract_http_status_from_message($message, $default = 500) { if (empty($message) || !is_string($message)) { return $default; } if (preg_match('/API ERROR \((\d{3})\)\s*:/i', $message, $matches)) { return (int) $matches[1]; } if (preg_match('/API Error \((\d{3})\)\s*:/i', $message, $matches)) { return (int) $matches[1]; } return $default; } /** * Uygun HTTP durum kodu ile bir WP_Error nesnesi döndürür * * @param string $error_message Hata mesajı * @param string $error_code Hata kodu * @return \WP_Error */ public static function create_wp_error($error_message, $error_code = 'aipt_error') { $status_code = 500; if (stripos($error_message, 'Invalid') !== false) { $status_code = 400; } elseif (stripos($error_message, 'API Error') !== false) { $status_code = 502; } return new \WP_Error( $error_code, $error_message, array( 'status' => $status_code ) ); } /** * Connection/firewall block hatalarını detect eder ve kullanıcı dostu hata mesajı oluşturur * * @param string $error_message Orijinal hata mesajı * @param string $provider API sağlayıcı adı * @return string Kullanıcı dostu hata mesajı */ public static function format_connection_error($error_message, $provider) { $is_firewall_block = strpos($error_message, 'not valid JSON') !== false || strpos($error_message, 'firewall') !== false || strpos($error_message, 'security plugin') !== false; if ($is_firewall_block) { return sprintf( /* translators: %s: API provider name */ __('%s API connection was blocked. This is usually caused by server firewall or security plugin restrictions. Please contact your hosting provider or check your security plugin settings.', 'ai-product-tools'), strtoupper($provider) ); } return self::format_api_error_message($provider, $error_message); } /** * Hata mesajını log dosyasına kaydeder * * @param string $message Hata mesajı * @param string $type Hata türü/seviyesi * @return void */ public static function log_error($message, $type = 'error') { if (defined('WP_DEBUG') && \WP_DEBUG && defined('WP_DEBUG_LOG') && \WP_DEBUG_LOG) { $safe_message = self::sanitize_error_for_logging($message); } } /** * Whether a response looks like a firewall/WAF/security-plugin block page * rather than the AI provider's own JSON API: a non-JSON content-type * whose body starts with '<' (an HTML document), never seen from any of * the four providers' real error responses. Shared by every AI client's * own throwIfHtmlBody() so the same detection runs identically for every * provider and every call path (generation and key validation alike). * * @param string $content_type Response content-type header. * @param string $body_str Raw response body. * @return bool */ public static function looks_like_html_body( string $content_type, string $body_str ): bool { return false === strpos( $content_type, 'application/json' ) && '' !== $body_str && '<' === $body_str[0]; } /** * Sanitizes error messages to remove sensitive information before display or logging * * @param string $message Raw error message * @return string Sanitized error message */ public static function sanitize_error_for_logging(string $message): string { $url_placeholder = '<>'; $urls = array(); $message = preg_replace_callback( '/https?:\/\/[^\s"\'<>]+/i', function ($matches) use (&$urls, $url_placeholder) { $urls[] = $matches[0]; return $url_placeholder . (count($urls) - 1); }, $message ); $message = preg_replace('/([A-Za-z]:\\\\|\\\\\\\\|\/|\.\.?\/)[^\s"\'<>:*?|]+\.(php|html|js|css|json|xml|ini|log|txt)/i', '[FILE_PATH_REMOVED]', $message); $message = preg_replace('/SELECT\s+.+?\s+FROM/i', 'SELECT [QUERY_REMOVED] FROM', $message); $message = preg_replace('/INSERT\s+INTO\s+\S+/i', 'INSERT INTO [TABLE]', $message); $message = preg_replace('/UPDATE\s+\S+\s+SET/i', 'UPDATE [TABLE] SET', $message); $message = preg_replace('/DELETE\s+FROM\s+\S+/i', 'DELETE FROM [TABLE]', $message); for ($url_index = count($urls) - 1; $url_index >= 0; $url_index--) { $message = str_replace($url_placeholder . $url_index, $urls[$url_index], $message); } $uuid_placeholder = '<>'; $uuids = array(); $message = preg_replace_callback( '/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i', function ($matches) use (&$uuids, $uuid_placeholder) { $uuids[] = $matches[0]; return $uuid_placeholder . (count($uuids) - 1); }, $message ); $message = preg_replace('/sk-(?:ant-api\d*-|or-v1-|proj-|svcacct-)?[a-zA-Z0-9_-]{20,}/', '[API_KEY_REMOVED]', $message); $message = preg_replace('/AIza[a-zA-Z0-9_-]{32,}/', '[GOOGLE_KEY_REMOVED]', $message); $message = preg_replace('/AQ\.[a-zA-Z0-9_-]{32,}/', '[GOOGLE_KEY_REMOVED]', $message); $message = preg_replace('/AKIA[A-Z0-9]{16,}/', '[AWS_KEY_REMOVED]', $message); $message = preg_replace('/Bearer\s+[a-zA-Z0-9._-]{20,}/', 'Bearer [TOKEN_REMOVED]', $message); $message = preg_replace('/eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+/', '[JWT_REMOVED]', $message); $message = preg_replace('/[a-f0-9]{64,}/i', '[HEX_KEY_REMOVED]', $message); for ($uuid_index = count($uuids) - 1; $uuid_index >= 0; $uuid_index--) { $message = str_replace($uuid_placeholder . $uuid_index, $uuids[$uuid_index], $message); } $message = preg_replace('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', '[IP_REMOVED]', $message); $message = preg_replace('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', '[EMAIL_REMOVED]', $message); return $message; } /** * Creates a user-safe error message (removes technical details) * * @param string $error_message Full error message * @return string User-safe error message */ public static function get_user_safe_error(string $error_message): string { $error_mappings = [ 'cURL error' => __('Unable to connect to the AI service. Please try again later.', 'ai-product-tools'), 'SSL certificate' => __('Secure connection failed. Please contact your hosting provider.', 'ai-product-tools'), 'Connection refused' => __('AI service is temporarily unavailable. Please try again in a few minutes.', 'ai-product-tools'), 'timeout' => __('The request took too long. Please try again with fewer products.', 'ai-product-tools'), 'Out of memory' => __('Server resources exceeded. Please try processing fewer products at once.', 'ai-product-tools'), 'maximum execution time' => __('Processing took too long. Please try with fewer products.', 'ai-product-tools'), ]; foreach ($error_mappings as $technical => $friendly) { if (stripos($error_message, $technical) !== false) { return $friendly; } } if (stripos($error_message, 'API') !== false) { return self::sanitize_error_for_logging($error_message); } return __('An unexpected error occurred. Please try again or contact support.', 'ai-product-tools'); } }