Compare commits
2 Commits
refactor/s
...
refactor/s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d31d378ec1 | ||
|
|
fcc61c0cb8 |
84
includes/providers/class-open-router-config.php
Normal file
84
includes/providers/class-open-router-config.php
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration helpers for OpenRouter provider.
|
||||||
|
*
|
||||||
|
* Resolves admin-configured settings for API endpoint selection
|
||||||
|
* (direct vs. Cloudflare AI Gateway routing) and caching behavior.
|
||||||
|
*
|
||||||
|
* Dependencies: get_option() for WordPress settings lookups.
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this config.
|
||||||
|
* @see class-open-router-validator.php — Also uses API base URL resolution.
|
||||||
|
* @see ARCHITECTURE.md — External API Integrations section.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Config {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default direct-to-OpenRouter endpoint.
|
||||||
|
*
|
||||||
|
* Used when no Cloudflare AI Gateway URL is configured. The active endpoint
|
||||||
|
* is resolved per-request via get_api_base_url() so admins can flip to an
|
||||||
|
* AI Gateway proxy without code changes.
|
||||||
|
*/
|
||||||
|
private const DEFAULT_API_BASE_URL = 'https://openrouter.ai/api/v1';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the API base URL.
|
||||||
|
*
|
||||||
|
* If an admin has configured a Cloudflare AI Gateway URL in settings,
|
||||||
|
* we route through that instead of hitting OpenRouter directly. The
|
||||||
|
* gateway is a transparent OpenAI/OpenRouter-compatible proxy that
|
||||||
|
* adds caching, cost logging, rate-limiting, and provider fallback
|
||||||
|
* — see ARCHITECTURE.md "External API Integrations".
|
||||||
|
*
|
||||||
|
* Expected gateway URL shape:
|
||||||
|
* https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openrouter
|
||||||
|
*
|
||||||
|
* @return string Base URL with no trailing slash.
|
||||||
|
*/
|
||||||
|
public function get_api_base_url(): string {
|
||||||
|
$override = trim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ) );
|
||||||
|
if ( '' === $override ) {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
// Only accept https to avoid plaintext-auth regressions.
|
||||||
|
if ( 0 !== stripos( $override, 'https://' ) ) {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
return rtrim( $override, '/' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache TTL (seconds) for AI Gateway response caching.
|
||||||
|
*
|
||||||
|
* Cloudflare honours the `cf-aig-cache-ttl` request header and serves
|
||||||
|
* cached responses for identical payloads within the TTL window. Only
|
||||||
|
* meaningful when a gateway base URL is configured; harmless otherwise.
|
||||||
|
*
|
||||||
|
* @return int Non-negative integer seconds; 0 disables caching.
|
||||||
|
*/
|
||||||
|
public function get_cache_ttl_seconds(): int {
|
||||||
|
$ttl = (int) get_option( 'prautoblogger_ai_gateway_cache_ttl', 0 );
|
||||||
|
return $ttl > 0 ? $ttl : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if routing through Cloudflare AI Gateway vs. direct-to-OpenRouter.
|
||||||
|
*
|
||||||
|
* @return bool True if a gateway URL is configured.
|
||||||
|
*/
|
||||||
|
public function is_via_gateway(): bool {
|
||||||
|
return self::DEFAULT_API_BASE_URL !== $this->get_api_base_url();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the default OpenRouter API base URL constant.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function get_default_api_base_url(): string {
|
||||||
|
return self::DEFAULT_API_BASE_URL;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,60 +11,17 @@ declare(strict_types=1);
|
|||||||
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
|
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
|
||||||
* Dependencies: PRAutoBlogger_Encryption (for API key decryption), wp_remote_post(), PRAutoBlogger_OpenRouter_Pricing.
|
* Dependencies: PRAutoBlogger_Encryption (for API key decryption), wp_remote_post(), PRAutoBlogger_OpenRouter_Pricing.
|
||||||
*
|
*
|
||||||
* @see interface-llm-provider.php — Interface this class implements.
|
* @see interface-llm-provider.php — Interface this class implements.
|
||||||
* @see class-open-router-pricing.php — Pricing and model list lookups.
|
* @see class-open-router-config.php — Config helpers (base URL, cache TTL).
|
||||||
* @see class-cost-tracker.php — Called after every request to log token usage.
|
* @see class-open-router-pricing.php — Pricing and model list lookups.
|
||||||
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
* @see class-open-router-validator.php — Credential validation (delegated).
|
||||||
|
* @see class-open-router-request-builder.php — Request header building + cURL filter.
|
||||||
|
* @see class-open-router-response-parser.php — Response parsing + error classification.
|
||||||
|
* @see class-cost-tracker.php — Called after every request to log token usage.
|
||||||
|
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
||||||
*/
|
*/
|
||||||
class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_Interface {
|
class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_Interface {
|
||||||
|
|
||||||
/**
|
|
||||||
* Default direct-to-OpenRouter endpoint. Used when no Cloudflare AI Gateway
|
|
||||||
* URL is configured. The active endpoint is resolved per-request via
|
|
||||||
* get_api_base_url() so admins can flip to an AI Gateway proxy without code.
|
|
||||||
*/
|
|
||||||
private const DEFAULT_API_BASE_URL = 'https://openrouter.ai/api/v1';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve the API base URL.
|
|
||||||
*
|
|
||||||
* If an admin has configured a Cloudflare AI Gateway URL in settings,
|
|
||||||
* we route through that instead of hitting OpenRouter directly. The
|
|
||||||
* gateway is a transparent OpenAI/OpenRouter-compatible proxy that
|
|
||||||
* adds caching, cost logging, rate-limiting, and provider fallback
|
|
||||||
* — see ARCHITECTURE.md "External API Integrations".
|
|
||||||
*
|
|
||||||
* Expected gateway URL shape:
|
|
||||||
* https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openrouter
|
|
||||||
*
|
|
||||||
* @return string Base URL with no trailing slash.
|
|
||||||
*/
|
|
||||||
private function get_api_base_url(): string {
|
|
||||||
$override = trim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ) );
|
|
||||||
if ( '' === $override ) {
|
|
||||||
return self::DEFAULT_API_BASE_URL;
|
|
||||||
}
|
|
||||||
// Only accept https to avoid plaintext-auth regressions.
|
|
||||||
if ( 0 !== stripos( $override, 'https://' ) ) {
|
|
||||||
return self::DEFAULT_API_BASE_URL;
|
|
||||||
}
|
|
||||||
return rtrim( $override, '/' );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cache TTL (seconds) for AI Gateway response caching.
|
|
||||||
*
|
|
||||||
* Cloudflare honours the `cf-aig-cache-ttl` request header and serves
|
|
||||||
* cached responses for identical payloads within the TTL window. Only
|
|
||||||
* meaningful when a gateway base URL is configured; harmless otherwise.
|
|
||||||
*
|
|
||||||
* @return int Non-negative integer seconds; 0 disables caching.
|
|
||||||
*/
|
|
||||||
private function get_cache_ttl_seconds(): int {
|
|
||||||
$ttl = (int) get_option( 'prautoblogger_ai_gateway_cache_ttl', 0 );
|
|
||||||
return $ttl > 0 ? $ttl : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a chat completion request to OpenRouter.
|
* Send a chat completion request to OpenRouter.
|
||||||
*
|
*
|
||||||
@@ -133,49 +90,19 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
|
|
||||||
$last_error = '';
|
$last_error = '';
|
||||||
|
|
||||||
$base_url = $this->get_api_base_url();
|
$config = new PRAutoBlogger_OpenRouter_Config();
|
||||||
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
$base_url = $config->get_api_base_url();
|
||||||
$cache_ttl = $this->get_cache_ttl_seconds();
|
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
||||||
$via_gateway = self::DEFAULT_API_BASE_URL !== $base_url;
|
$cache_ttl = $config->get_cache_ttl_seconds();
|
||||||
|
$via_gateway = $config->is_via_gateway();
|
||||||
|
|
||||||
// Build headers once so the wp_remote_post call and the cURL belt-and-
|
$builder = new PRAutoBlogger_OpenRouter_Request_Builder();
|
||||||
// suspenders filter stay in lockstep. The cf-aig-* headers are only
|
$request_headers = $builder->build_headers( $api_key, $via_gateway, $cache_ttl );
|
||||||
// meaningful when going through a Cloudflare AI Gateway; they are
|
$curl_auth_filter = $builder->register_curl_auth_filter( $request_headers, $base_host );
|
||||||
// ignored by direct OpenRouter calls, so sending them unconditionally
|
|
||||||
// when a gateway is configured is safe and keeps the code branch-free.
|
|
||||||
$request_headers = [
|
|
||||||
'Authorization' => 'Bearer ' . $api_key,
|
|
||||||
'Content-Type' => 'application/json',
|
|
||||||
'HTTP-Referer' => home_url(),
|
|
||||||
'X-Title' => 'PRAutoBlogger WordPress Plugin',
|
|
||||||
];
|
|
||||||
if ( $via_gateway && $cache_ttl > 0 ) {
|
|
||||||
$request_headers['cf-aig-cache-ttl'] = (string) $cache_ttl;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Belt-and-suspenders: inject Authorization header at cURL level.
|
|
||||||
// Some hosting environments (Hostinger, certain proxies) strip the
|
|
||||||
// Authorization header from wp_remote_post's 'headers' array before
|
|
||||||
// the request is sent. The http_api_curl action fires after WordPress
|
|
||||||
// configures the cURL handle but before curl_exec — re-setting
|
|
||||||
// CURLOPT_HTTPHEADER here ensures the header reaches the upstream
|
|
||||||
// (either OpenRouter directly or the Cloudflare AI Gateway proxy).
|
|
||||||
$curl_auth_filter = function ( $handle, $parsed_args, $url ) use ( $request_headers, $base_host ): void {
|
|
||||||
// Scope to the configured upstream host only — never leak auth
|
|
||||||
// into unrelated outbound requests made elsewhere in WordPress.
|
|
||||||
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
$curl_headers = [];
|
|
||||||
foreach ( $request_headers as $name => $value ) {
|
|
||||||
$curl_headers[] = $name . ': ' . $value;
|
|
||||||
}
|
|
||||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
|
||||||
curl_setopt( $handle, CURLOPT_HTTPHEADER, $curl_headers );
|
|
||||||
};
|
|
||||||
add_action( 'http_api_curl', $curl_auth_filter, 99, 3 );
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
$parser = new PRAutoBlogger_OpenRouter_Response_Parser();
|
||||||
|
|
||||||
for ( $attempt = 1; $attempt <= PRAUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
for ( $attempt = 1; $attempt <= PRAUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
||||||
$response = wp_remote_post(
|
$response = wp_remote_post(
|
||||||
$base_url . '/chat/completions',
|
$base_url . '/chat/completions',
|
||||||
@@ -205,7 +132,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
$data = json_decode( $body_raw, true );
|
$data = json_decode( $body_raw, true );
|
||||||
|
|
||||||
// Rate limited (429) or server error (5xx) — retry with backoff.
|
// Rate limited (429) or server error (5xx) — retry with backoff.
|
||||||
if ( 429 === $status_code || $status_code >= 500 ) {
|
if ( $parser->is_retryable( $status_code ) ) {
|
||||||
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
|
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
|
||||||
PRAutoBlogger_Logger::instance()->warning(
|
PRAutoBlogger_Logger::instance()->warning(
|
||||||
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, PRAUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
|
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, PRAUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
|
||||||
@@ -225,9 +152,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
|
|
||||||
// Client error — don't retry, fail immediately.
|
// Client error — don't retry, fail immediately.
|
||||||
if ( $status_code >= 400 ) {
|
if ( $status_code >= 400 ) {
|
||||||
$error_msg = isset( $data['error']['message'] )
|
$error_msg = $parser->get_error_message( $data, $status_code );
|
||||||
? $data['error']['message']
|
|
||||||
: 'HTTP ' . $status_code;
|
|
||||||
|
|
||||||
// Log detailed diagnostic info for auth errors to aid debugging.
|
// Log detailed diagnostic info for auth errors to aid debugging.
|
||||||
if ( 401 === $status_code || 403 === $status_code ) {
|
if ( 401 === $status_code || 403 === $status_code ) {
|
||||||
@@ -254,22 +179,7 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Success — parse response.
|
// Success — parse response.
|
||||||
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
|
return $parser->parse_success( $data, $model );
|
||||||
throw new \RuntimeException(
|
|
||||||
__( 'OpenRouter returned unexpected response format.', 'prautoblogger' )
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$usage = $data['usage'] ?? [];
|
|
||||||
|
|
||||||
return [
|
|
||||||
'content' => $data['choices'][0]['message']['content'],
|
|
||||||
'model' => $data['model'] ?? $model,
|
|
||||||
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
|
|
||||||
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
|
|
||||||
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
|
|
||||||
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// All retries exhausted.
|
// All retries exhausted.
|
||||||
@@ -327,9 +237,9 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
/**
|
/**
|
||||||
* Validate that the OpenRouter API key is configured and working.
|
* Validate that the OpenRouter API key is configured and working.
|
||||||
*
|
*
|
||||||
* Makes a lightweight request to the /auth/key endpoint.
|
* Delegates to PRAutoBlogger_OpenRouter_Validator for the actual checks.
|
||||||
*
|
*
|
||||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
* Side effects: HTTP request to OpenRouter (via validator), logs diagnostic info.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
@@ -341,112 +251,16 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
|||||||
/**
|
/**
|
||||||
* Validate credentials with detailed diagnostic info.
|
* Validate credentials with detailed diagnostic info.
|
||||||
*
|
*
|
||||||
* Returns an array with status ('ok' or 'error') and a human-readable
|
* Delegates to PRAutoBlogger_OpenRouter_Validator which returns an array
|
||||||
* message explaining what went wrong if validation fails.
|
* with status ('ok' or 'error') and a human-readable message explaining
|
||||||
|
* what went wrong if validation fails.
|
||||||
*
|
*
|
||||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
* Side effects: HTTP request to OpenRouter (via validator), logs diagnostic info.
|
||||||
*
|
*
|
||||||
* @return array{status: string, message: string, debug?: string}
|
* @return array{status: string, message: string, debug?: string}
|
||||||
*/
|
*/
|
||||||
public function validate_credentials_detailed(): array {
|
public function validate_credentials_detailed(): array {
|
||||||
$encrypted = get_option( 'prautoblogger_openrouter_api_key', '' );
|
return ( new PRAutoBlogger_OpenRouter_Validator() )->run();
|
||||||
if ( '' === $encrypted ) {
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'No API key saved. Enter your OpenRouter key in settings.', 'prautoblogger' ),
|
|
||||||
'debug' => 'option_empty',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$api_key = PRAutoBlogger_Encryption::decrypt( $encrypted );
|
|
||||||
if ( '' === $api_key ) {
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'API key decryption failed. Re-enter your key.', 'prautoblogger' ),
|
|
||||||
'debug' => 'decrypt_failed:encrypted_len=' . strlen( $encrypted ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanity check: OpenRouter keys typically start with "sk-or-".
|
|
||||||
$key_prefix = substr( $api_key, 0, 6 );
|
|
||||||
$key_len = strlen( $api_key );
|
|
||||||
|
|
||||||
if ( 0 !== strpos( $api_key, 'sk-or-' ) ) {
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
sprintf(
|
|
||||||
'API key format invalid (prefix="%s", len=%d). Likely salt changed — re-enter key.',
|
|
||||||
$key_prefix,
|
|
||||||
$key_len
|
|
||||||
),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => __( 'API key appears corrupted (decryption produced invalid data). Your WordPress auth salt may have changed. Please re-enter your OpenRouter API key in settings.', 'prautoblogger' ),
|
|
||||||
'debug' => sprintf( 'bad_format:prefix=%s,len=%d', $key_prefix, $key_len ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Belt-and-suspenders: inject Authorization at cURL level (see send_chat_completion).
|
|
||||||
$base_url = $this->get_api_base_url();
|
|
||||||
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
|
||||||
$auth_header_value = 'Bearer ' . $api_key;
|
|
||||||
$curl_auth_filter_cred = function ( $handle, $parsed_args, $url ) use ( $auth_header_value, $base_host ): void {
|
|
||||||
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
|
||||||
curl_setopt( $handle, CURLOPT_HTTPHEADER, [
|
|
||||||
'Authorization: ' . $auth_header_value,
|
|
||||||
] );
|
|
||||||
};
|
|
||||||
add_action( 'http_api_curl', $curl_auth_filter_cred, 99, 3 );
|
|
||||||
|
|
||||||
$response = wp_remote_get(
|
|
||||||
$base_url . '/auth/key',
|
|
||||||
[
|
|
||||||
'timeout' => 15,
|
|
||||||
'headers' => [
|
|
||||||
'Authorization' => 'Bearer ' . $api_key,
|
|
||||||
],
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
remove_action( 'http_api_curl', $curl_auth_filter_cred, 99 );
|
|
||||||
|
|
||||||
if ( is_wp_error( $response ) ) {
|
|
||||||
$err_msg = $response->get_error_message();
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
sprintf( 'OpenRouter credential check wp_error: %s (key_prefix=%s, key_len=%d)', $err_msg, $key_prefix, $key_len ),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => sprintf( __( 'Network error reaching OpenRouter: %s', 'prautoblogger' ), $err_msg ),
|
|
||||||
'debug' => 'wp_error:' . $err_msg,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$status_code = wp_remote_retrieve_response_code( $response );
|
|
||||||
$body_raw = wp_remote_retrieve_body( $response );
|
|
||||||
|
|
||||||
if ( 200 === $status_code ) {
|
|
||||||
return [
|
|
||||||
'status' => 'ok',
|
|
||||||
'message' => __( 'OpenRouter connected.', 'prautoblogger' ),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
PRAutoBlogger_Logger::instance()->warning(
|
|
||||||
sprintf( 'OpenRouter credential check HTTP %d (key_prefix=%s, key_len=%d): %s', $status_code, $key_prefix, $key_len, substr( $body_raw, 0, 300 ) ),
|
|
||||||
'openrouter'
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => sprintf( __( 'OpenRouter returned HTTP %d. %s', 'prautoblogger' ), $status_code, substr( $body_raw, 0, 200 ) ),
|
|
||||||
'debug' => sprintf( 'http_%d:key_prefix=%s,key_len=%d', $status_code, $key_prefix, $key_len ),
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
79
includes/providers/class-open-router-request-builder.php
Normal file
79
includes/providers/class-open-router-request-builder.php
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request builder for OpenRouter API calls.
|
||||||
|
*
|
||||||
|
* Encapsulates the logic for building HTTP request headers, including
|
||||||
|
* Cloudflare AI Gateway caching directives and belt-and-suspenders
|
||||||
|
* cURL header injection to work around authorization header stripping
|
||||||
|
* in certain hosting environments.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::send_chat_completion()
|
||||||
|
* Dependencies: add_action(), curl_setopt() (via http_api_curl filter).
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this builder.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Request_Builder {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build request headers for OpenRouter API call.
|
||||||
|
*
|
||||||
|
* Includes Authorization, Content-Type, HTTP-Referer, and optional
|
||||||
|
* Cloudflare AI Gateway cache control headers.
|
||||||
|
*
|
||||||
|
* @param string $api_key Decrypted OpenRouter API key.
|
||||||
|
* @param bool $via_gateway Whether the request is routed through Cloudflare AI Gateway.
|
||||||
|
* @param int $cache_ttl Cache TTL in seconds (0 disables caching).
|
||||||
|
*
|
||||||
|
* @return array<string, string> HTTP headers ready for wp_remote_post().
|
||||||
|
*/
|
||||||
|
public function build_headers( string $api_key, bool $via_gateway, int $cache_ttl ): array {
|
||||||
|
$headers = [
|
||||||
|
'Authorization' => 'Bearer ' . $api_key,
|
||||||
|
'Content-Type' => 'application/json',
|
||||||
|
'HTTP-Referer' => home_url(),
|
||||||
|
'X-Title' => 'PRAutoBlogger WordPress Plugin',
|
||||||
|
];
|
||||||
|
|
||||||
|
if ( $via_gateway && $cache_ttl > 0 ) {
|
||||||
|
$headers['cf-aig-cache-ttl'] = (string) $cache_ttl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a cURL filter to inject Authorization header.
|
||||||
|
*
|
||||||
|
* Some hosting environments (Hostinger, certain proxies) strip the
|
||||||
|
* Authorization header from wp_remote_post's 'headers' array before
|
||||||
|
* the request is sent. The http_api_curl action fires after WordPress
|
||||||
|
* configures the cURL handle but before curl_exec — setting
|
||||||
|
* CURLOPT_HTTPHEADER here ensures the header reaches the upstream.
|
||||||
|
*
|
||||||
|
* Side effects: Adds an http_api_curl filter (caller must remove).
|
||||||
|
*
|
||||||
|
* @param array $request_headers Request headers (includes Authorization).
|
||||||
|
* @param string $base_host Upstream host (scopes the filter to avoid leaking auth).
|
||||||
|
*
|
||||||
|
* @return callable The filter function (for later removal via remove_action).
|
||||||
|
*/
|
||||||
|
public function register_curl_auth_filter( array $request_headers, string $base_host ): callable {
|
||||||
|
$curl_auth_filter = function ( $handle, $parsed_args, $url ) use ( $request_headers, $base_host ): void {
|
||||||
|
// Scope to the configured upstream host only — never leak auth
|
||||||
|
// into unrelated outbound requests made elsewhere in WordPress.
|
||||||
|
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$curl_headers = [];
|
||||||
|
foreach ( $request_headers as $name => $value ) {
|
||||||
|
$curl_headers[] = $name . ': ' . $value;
|
||||||
|
}
|
||||||
|
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||||
|
curl_setopt( $handle, CURLOPT_HTTPHEADER, $curl_headers );
|
||||||
|
};
|
||||||
|
add_action( 'http_api_curl', $curl_auth_filter, 99, 3 );
|
||||||
|
return $curl_auth_filter;
|
||||||
|
}
|
||||||
|
}
|
||||||
87
includes/providers/class-open-router-response-parser.php
Normal file
87
includes/providers/class-open-router-response-parser.php
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response parser for OpenRouter API responses.
|
||||||
|
*
|
||||||
|
* Encapsulates the logic for parsing and validating OpenRouter chat completion
|
||||||
|
* responses, including error classification and retry-decision logic.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::send_chat_completion()
|
||||||
|
* Dependencies: PRAutoBlogger_Logger (for error/warning logging).
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php — Parent class that uses this parser.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Response_Parser {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if an HTTP status code indicates a retryable error.
|
||||||
|
*
|
||||||
|
* Returns true if the failure is transient (5xx, 429) and the retry loop
|
||||||
|
* should continue with backoff. Returns false for 4xx errors, which should
|
||||||
|
* fail immediately without retry.
|
||||||
|
*
|
||||||
|
* @param int $status_code HTTP status code.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_retryable( int $status_code ): bool {
|
||||||
|
return 429 === $status_code || $status_code >= 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a successful OpenRouter response.
|
||||||
|
*
|
||||||
|
* Validates the response contains the required fields and extracts
|
||||||
|
* the completion content and token usage.
|
||||||
|
*
|
||||||
|
* @param array $data Decoded JSON response from OpenRouter.
|
||||||
|
* @param string $model The model that was requested (fallback if not in response).
|
||||||
|
*
|
||||||
|
* @return array{
|
||||||
|
* content: string,
|
||||||
|
* model: string,
|
||||||
|
* prompt_tokens: int,
|
||||||
|
* completion_tokens: int,
|
||||||
|
* total_tokens: int,
|
||||||
|
* finish_reason: string,
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException If response structure is invalid.
|
||||||
|
*/
|
||||||
|
public function parse_success( array $data, string $model ): array {
|
||||||
|
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
|
||||||
|
throw new \RuntimeException(
|
||||||
|
__( 'OpenRouter returned unexpected response format.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$usage = $data['usage'] ?? [];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'content' => $data['choices'][0]['message']['content'],
|
||||||
|
'model' => $data['model'] ?? $model,
|
||||||
|
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
|
||||||
|
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
|
||||||
|
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
|
||||||
|
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the error message from a failed response.
|
||||||
|
*
|
||||||
|
* Prefers the `error.message` field if present; falls back to the
|
||||||
|
* HTTP status code as a string.
|
||||||
|
*
|
||||||
|
* @param array $data Decoded JSON response (may be empty or malformed).
|
||||||
|
* @param int $status HTTP status code.
|
||||||
|
*
|
||||||
|
* @return string Human-readable error message.
|
||||||
|
*/
|
||||||
|
public function get_error_message( array $data, int $status ): string {
|
||||||
|
return isset( $data['error']['message'] )
|
||||||
|
? $data['error']['message']
|
||||||
|
: 'HTTP ' . $status;
|
||||||
|
}
|
||||||
|
}
|
||||||
152
includes/providers/class-open-router-validator.php
Normal file
152
includes/providers/class-open-router-validator.php
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Credential + connectivity validator for the OpenRouter LLM provider.
|
||||||
|
*
|
||||||
|
* Split out of the provider to keep each file under the 300-line cap and
|
||||||
|
* to keep the validation path easy to unit-test without spinning up the
|
||||||
|
* retry loop. The provider's `validate_credentials_detailed()` delegates
|
||||||
|
* straight to `run()` here.
|
||||||
|
*
|
||||||
|
* Triggered by: PRAutoBlogger_OpenRouter_Provider::validate_credentials_detailed()
|
||||||
|
* which is called by the admin "Test Connection" action.
|
||||||
|
* Dependencies: PRAutoBlogger_OpenRouter_Config (URL resolution),
|
||||||
|
* PRAutoBlogger_Encryption (API key decryption),
|
||||||
|
* PRAutoBlogger_Logger (WARN/ERROR lines), wp_remote_get().
|
||||||
|
*
|
||||||
|
* @see class-open-router-provider.php Parent class that delegates here.
|
||||||
|
* @see class-open-router-config.php Config helpers for base URL.
|
||||||
|
* @see interface-llm-provider.php Return-shape contract.
|
||||||
|
*/
|
||||||
|
class PRAutoBlogger_OpenRouter_Validator {
|
||||||
|
|
||||||
|
private const TIMEOUT_SECONDS = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a non-destructive credential check.
|
||||||
|
*
|
||||||
|
* Lightweight probe: hits the /auth/key endpoint. Never makes a real
|
||||||
|
* LLM completion request — that would consume tokens on every click.
|
||||||
|
*
|
||||||
|
* Side effects: one HTTP GET; one Logger line on failure.
|
||||||
|
*
|
||||||
|
* @return array{status: string, message: string, debug?: string}
|
||||||
|
*/
|
||||||
|
public function run(): array {
|
||||||
|
$encrypted = get_option( 'prautoblogger_openrouter_api_key', '' );
|
||||||
|
if ( '' === $encrypted ) {
|
||||||
|
return $this->err(
|
||||||
|
'option_empty',
|
||||||
|
__( 'No API key saved. Enter your OpenRouter key in settings.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$api_key = PRAutoBlogger_Encryption::decrypt( $encrypted );
|
||||||
|
if ( '' === $api_key ) {
|
||||||
|
return $this->err(
|
||||||
|
'decrypt_failed:encrypted_len=' . strlen( $encrypted ),
|
||||||
|
__( 'API key decryption failed. Re-enter your key.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sanity check: OpenRouter keys typically start with "sk-or-".
|
||||||
|
$key_prefix = substr( $api_key, 0, 6 );
|
||||||
|
$key_len = strlen( $api_key );
|
||||||
|
|
||||||
|
if ( 0 !== strpos( $api_key, 'sk-or-' ) ) {
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
sprintf(
|
||||||
|
'API key format invalid (prefix="%s", len=%d). Likely salt changed — re-enter key.',
|
||||||
|
$key_prefix,
|
||||||
|
$key_len
|
||||||
|
),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
return $this->err(
|
||||||
|
sprintf( 'bad_format:prefix=%s,len=%d', $key_prefix, $key_len ),
|
||||||
|
__( 'API key appears corrupted (decryption produced invalid data). Your WordPress auth salt may have changed. Please re-enter your OpenRouter API key in settings.', 'prautoblogger' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Belt-and-suspenders: inject Authorization at cURL level (see send_chat_completion).
|
||||||
|
$config = new PRAutoBlogger_OpenRouter_Config();
|
||||||
|
$base_url = $config->get_api_base_url();
|
||||||
|
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
||||||
|
$auth_header_value = 'Bearer ' . $api_key;
|
||||||
|
$curl_auth_filter_cred = function ( $handle, $parsed_args, $url ) use ( $auth_header_value, $base_host ): void {
|
||||||
|
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||||
|
curl_setopt( $handle, CURLOPT_HTTPHEADER, [
|
||||||
|
'Authorization: ' . $auth_header_value,
|
||||||
|
] );
|
||||||
|
};
|
||||||
|
add_action( 'http_api_curl', $curl_auth_filter_cred, 99, 3 );
|
||||||
|
|
||||||
|
$response = wp_remote_get(
|
||||||
|
$base_url . '/auth/key',
|
||||||
|
[
|
||||||
|
'timeout' => self::TIMEOUT_SECONDS,
|
||||||
|
'headers' => [
|
||||||
|
'Authorization' => 'Bearer ' . $api_key,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
remove_action( 'http_api_curl', $curl_auth_filter_cred, 99 );
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
$err_msg = $response->get_error_message();
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
sprintf( 'OpenRouter credential check wp_error: %s (key_prefix=%s, key_len=%d)', $err_msg, $key_prefix, $key_len ),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
return $this->err(
|
||||||
|
'wp_error:' . $err_msg,
|
||||||
|
sprintf(
|
||||||
|
/* translators: %s: transport-layer error message. */
|
||||||
|
esc_html__( 'Network error reaching OpenRouter: %s', 'prautoblogger' ),
|
||||||
|
esc_html( $err_msg )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$status_code = wp_remote_retrieve_response_code( $response );
|
||||||
|
if ( 200 === $status_code ) {
|
||||||
|
return [
|
||||||
|
'status' => 'ok',
|
||||||
|
'message' => __( 'OpenRouter connected.', 'prautoblogger' ),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$body_raw = wp_remote_retrieve_body( $response );
|
||||||
|
PRAutoBlogger_Logger::instance()->warning(
|
||||||
|
sprintf( 'OpenRouter credential check HTTP %d (key_prefix=%s, key_len=%d): %s', $status_code, $key_prefix, $key_len, substr( $body_raw, 0, 300 ) ),
|
||||||
|
'openrouter'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $this->err(
|
||||||
|
sprintf( 'http_%d:key_prefix=%s,key_len=%d', $status_code, $key_prefix, $key_len ),
|
||||||
|
sprintf(
|
||||||
|
/* translators: %1$d: HTTP status, %2$s: response body. */
|
||||||
|
esc_html__( 'OpenRouter returned HTTP %1$d. %2$s', 'prautoblogger' ),
|
||||||
|
$status_code,
|
||||||
|
esc_html( substr( $body_raw, 0, 200 ) )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{status: string, message: string, debug: string}
|
||||||
|
*/
|
||||||
|
private function err( string $debug, string $message ): array {
|
||||||
|
return [
|
||||||
|
'status' => 'error',
|
||||||
|
'message' => $message,
|
||||||
|
'debug' => $debug,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
<?php
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reddit endpoint availability checker.
|
|
||||||
*
|
|
||||||
* Probes Reddit's RSS and .json endpoints to determine which data sources
|
|
||||||
* are reachable from the current server. Datacenter IPs (Hostinger) are
|
|
||||||
* often blocked by Reddit for .json but not RSS, so the client must check
|
|
||||||
* both before deciding which strategy to use.
|
|
||||||
*
|
|
||||||
* Triggered by: PRAutoBlogger_Reddit_JSON_Client::is_available() delegation,
|
|
||||||
* Admin settings page "test connection" button.
|
|
||||||
* Dependencies: wp_remote_get(), PRAutoBlogger_Logger.
|
|
||||||
*
|
|
||||||
* @see providers/class-reddit-json-client.php — Instantiates and delegates to this class.
|
|
||||||
* @see ARCHITECTURE.md — External API integrations table.
|
|
||||||
*/
|
|
||||||
class PRAutoBlogger_Reddit_Availability {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reddit base URL for all endpoints.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
private const BASE_URL = 'https://www.reddit.com';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* User agent — Reddit requires a descriptive UA for unauthenticated requests.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
private const USER_AGENT = 'Mozilla/5.0 (compatible; PRAutoBlogger/0.2.1; +https://peptiderepo.com)';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Transient key for rate limit tracking (.json endpoints only).
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
private const RATE_LIMIT_TRANSIENT = 'prautoblogger_reddit_json_rate_limit';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if any Reddit endpoint is reachable (RSS or .json).
|
|
||||||
*
|
|
||||||
* Side effects: HTTP request to Reddit.
|
|
||||||
*
|
|
||||||
* @return bool True if at least one endpoint is accessible.
|
|
||||||
*/
|
|
||||||
public function is_available(): bool {
|
|
||||||
return $this->is_rss_available() || $this->is_json_available();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if Reddit RSS endpoints are reachable.
|
|
||||||
*
|
|
||||||
* RSS endpoints are rarely blocked by Reddit, even for datacenter IPs.
|
|
||||||
*
|
|
||||||
* Side effects: One HTTP GET to Reddit.
|
|
||||||
*
|
|
||||||
* @return bool True if RSS endpoint returns HTTP 200.
|
|
||||||
*/
|
|
||||||
public function is_rss_available(): bool {
|
|
||||||
$url = self::BASE_URL . '/r/all/hot.rss?limit=1';
|
|
||||||
$response = wp_remote_get(
|
|
||||||
$url,
|
|
||||||
[
|
|
||||||
'timeout' => 10,
|
|
||||||
'headers' => [
|
|
||||||
'User-Agent' => self::USER_AGENT,
|
|
||||||
],
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
if ( is_wp_error( $response ) ) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 200 === wp_remote_retrieve_response_code( $response );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if Reddit .json endpoints are reachable.
|
|
||||||
*
|
|
||||||
* Datacenter IPs are often blocked by Reddit for .json endpoints.
|
|
||||||
*
|
|
||||||
* Side effects: One HTTP GET to Reddit.
|
|
||||||
*
|
|
||||||
* @return bool True if .json endpoint returns HTTP 200.
|
|
||||||
*/
|
|
||||||
public function is_json_available(): bool {
|
|
||||||
$url = self::BASE_URL . '/r/all/hot.json?limit=1';
|
|
||||||
$response = wp_remote_get(
|
|
||||||
$url,
|
|
||||||
[
|
|
||||||
'timeout' => 10,
|
|
||||||
'headers' => [
|
|
||||||
'User-Agent' => self::USER_AGENT,
|
|
||||||
],
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
if ( is_wp_error( $response ) ) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 200 === wp_remote_retrieve_response_code( $response );
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get current rate limit status from cached .json response headers.
|
|
||||||
*
|
|
||||||
* Reddit .json endpoints return rate limit headers. RSS has no rate limits.
|
|
||||||
* The rate data is written by api_get() and read here.
|
|
||||||
*
|
|
||||||
* @return array{remaining: int, limit: int, resets_at: string}
|
|
||||||
*/
|
|
||||||
public function get_rate_limit_status(): array {
|
|
||||||
$status = get_transient( self::RATE_LIMIT_TRANSIENT );
|
|
||||||
|
|
||||||
if ( is_array( $status ) ) {
|
|
||||||
return $status;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'remaining' => 10,
|
|
||||||
'limit' => 10,
|
|
||||||
'resets_at' => '',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Make an HTTP GET request to a Reddit .json endpoint.
|
|
||||||
*
|
|
||||||
* No authentication — just a plain GET with a descriptive User-Agent.
|
|
||||||
* Tracks rate limits from response headers when available.
|
|
||||||
*
|
|
||||||
* Side effects: HTTP request, sets rate limit transient, logs errors.
|
|
||||||
*
|
|
||||||
* @param string $url Full URL with .json suffix and query params.
|
|
||||||
*
|
|
||||||
* @return array<string, mixed>|null Decoded JSON, or null on failure.
|
|
||||||
*/
|
|
||||||
public function api_get( string $url ): ?array {
|
|
||||||
$response = wp_remote_get(
|
|
||||||
$url,
|
|
||||||
[
|
|
||||||
'timeout' => 30,
|
|
||||||
'headers' => [
|
|
||||||
'User-Agent' => self::USER_AGENT,
|
|
||||||
'Accept' => 'application/json',
|
|
||||||
],
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
if ( is_wp_error( $response ) ) {
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
'Reddit .json GET failed: ' . $response->get_error_message(),
|
|
||||||
'reddit'
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Track rate limits from response headers.
|
|
||||||
$rate_remaining = wp_remote_retrieve_header( $response, 'x-ratelimit-remaining' );
|
|
||||||
$rate_used = wp_remote_retrieve_header( $response, 'x-ratelimit-used' );
|
|
||||||
$rate_reset = wp_remote_retrieve_header( $response, 'x-ratelimit-reset' );
|
|
||||||
|
|
||||||
if ( '' !== $rate_remaining ) {
|
|
||||||
set_transient(
|
|
||||||
self::RATE_LIMIT_TRANSIENT,
|
|
||||||
[
|
|
||||||
'remaining' => (int) $rate_remaining,
|
|
||||||
'limit' => (int) $rate_used + (int) $rate_remaining,
|
|
||||||
'resets_at' => gmdate( 'Y-m-d H:i:s', time() + (int) $rate_reset ),
|
|
||||||
],
|
|
||||||
120
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$status_code = wp_remote_retrieve_response_code( $response );
|
|
||||||
|
|
||||||
if ( 200 !== $status_code ) {
|
|
||||||
PRAutoBlogger_Logger::instance()->error(
|
|
||||||
sprintf(
|
|
||||||
'Reddit .json HTTP %d: %s',
|
|
||||||
$status_code,
|
|
||||||
substr( wp_remote_retrieve_body( $response ), 0, 300 )
|
|
||||||
),
|
|
||||||
'reddit'
|
|
||||||
);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return json_decode( wp_remote_retrieve_body( $response ), true );
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,12 +10,10 @@ declare(strict_types=1);
|
|||||||
* for comment fetching (comments are not available in RSS feeds).
|
* for comment fetching (comments are not available in RSS feeds).
|
||||||
*
|
*
|
||||||
* Triggered by: PRAutoBlogger_Reddit_Provider::collect_data().
|
* Triggered by: PRAutoBlogger_Reddit_Provider::collect_data().
|
||||||
* Dependencies: wp_remote_get(), PRAutoBlogger_Logger, PRAutoBlogger_Reddit_RSS_Parser.
|
* Dependencies: wp_remote_get(), PRAutoBlogger_Logger.
|
||||||
*
|
*
|
||||||
* @see providers/class-reddit-provider.php — Instantiates and calls this class.
|
* @see providers/class-reddit-provider.php — Instantiates and calls this class.
|
||||||
* @see providers/class-reddit-rss-parser.php — Parses Atom XML into post arrays.
|
* @see ARCHITECTURE.md — External API integrations table.
|
||||||
* @see providers/class-reddit-availability.php — Endpoint health checks.
|
|
||||||
* @see ARCHITECTURE.md — External API integrations table.
|
|
||||||
*/
|
*/
|
||||||
class PRAutoBlogger_Reddit_JSON_Client {
|
class PRAutoBlogger_Reddit_JSON_Client {
|
||||||
|
|
||||||
@@ -41,6 +39,13 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
|||||||
*/
|
*/
|
||||||
private const TIMEOUT_SECONDS = 30;
|
private const TIMEOUT_SECONDS = 30;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transient key for rate limit tracking (.json endpoints only).
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
private const RATE_LIMIT_TRANSIENT = 'prautoblogger_reddit_json_rate_limit';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch hot posts from a subreddit. Tries RSS first, .json fallback.
|
* Fetch hot posts from a subreddit. Tries RSS first, .json fallback.
|
||||||
*
|
*
|
||||||
@@ -124,8 +129,7 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$body = wp_remote_retrieve_body( $response );
|
$body = wp_remote_retrieve_body( $response );
|
||||||
$parser = new PRAutoBlogger_Reddit_RSS_Parser();
|
return $this->parse_atom_feed( $body, $subreddit );
|
||||||
return $parser->parse( $body, $subreddit );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -169,6 +173,105 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
|||||||
return $posts;
|
return $posts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a Reddit Atom feed into post-data arrays matching .json format.
|
||||||
|
*
|
||||||
|
* Maps Atom entry fields to the standard Reddit post fields so the rest
|
||||||
|
* of the pipeline can consume RSS data without changes. Fields unavailable
|
||||||
|
* in RSS (score, num_comments, upvote_ratio) are set to reasonable defaults.
|
||||||
|
*
|
||||||
|
* @param string $xml Raw Atom XML string.
|
||||||
|
* @param string $subreddit The subreddit name for context.
|
||||||
|
*
|
||||||
|
* @return array<int, array<string, mixed>> Parsed post data.
|
||||||
|
*/
|
||||||
|
private function parse_atom_feed( string $xml, string $subreddit ): array {
|
||||||
|
// Suppress XML errors for malformed feeds.
|
||||||
|
$prev_errors = libxml_use_internal_errors( true );
|
||||||
|
$feed = simplexml_load_string( $xml );
|
||||||
|
libxml_use_internal_errors( $prev_errors );
|
||||||
|
|
||||||
|
if ( false === $feed ) {
|
||||||
|
PRAutoBlogger_Logger::instance()->error( 'Failed to parse Reddit RSS XML.', 'reddit' );
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register the Atom namespace.
|
||||||
|
$feed->registerXPathNamespace( 'atom', 'http://www.w3.org/2005/Atom' );
|
||||||
|
$entries = $feed->xpath( '//atom:entry' );
|
||||||
|
|
||||||
|
if ( empty( $entries ) ) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$posts = [];
|
||||||
|
foreach ( $entries as $entry ) {
|
||||||
|
$title = (string) $entry->title;
|
||||||
|
$link = '';
|
||||||
|
$content = '';
|
||||||
|
|
||||||
|
// Get the HTML link (type="text/html").
|
||||||
|
foreach ( $entry->link as $link_el ) {
|
||||||
|
if ( 'text/html' === (string) $link_el['type'] || 'alternate' === (string) $link_el['rel'] ) {
|
||||||
|
$link = (string) $link_el['href'];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content is in <content> tag as HTML.
|
||||||
|
if ( isset( $entry->content ) ) {
|
||||||
|
$content = wp_strip_all_tags( (string) $entry->content );
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract post ID from the entry id (format: /r/subreddit/comments/ID/...).
|
||||||
|
$entry_id = (string) $entry->id;
|
||||||
|
$post_id = '';
|
||||||
|
if ( preg_match( '#/comments/([a-z0-9]+)#', $entry_id, $m ) ) {
|
||||||
|
$post_id = $m[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract author name.
|
||||||
|
$author = '[deleted]';
|
||||||
|
if ( isset( $entry->author->name ) ) {
|
||||||
|
$author = str_replace( '/u/', '', (string) $entry->author->name );
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse published date to Unix timestamp.
|
||||||
|
$published = (string) ( $entry->published ?? $entry->updated ?? '' );
|
||||||
|
$created_utc = '' !== $published ? (int) strtotime( $published ) : time();
|
||||||
|
|
||||||
|
// Extract permalink (relative path) from full URL.
|
||||||
|
$permalink = '';
|
||||||
|
if ( '' !== $link ) {
|
||||||
|
$parsed = wp_parse_url( $link );
|
||||||
|
$permalink = $parsed['path'] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$posts[] = [
|
||||||
|
'id' => $post_id,
|
||||||
|
'title' => $title,
|
||||||
|
'selftext' => $content,
|
||||||
|
'author' => $author,
|
||||||
|
'score' => 1, // Not available in RSS.
|
||||||
|
'num_comments' => 0, // Not available in RSS.
|
||||||
|
'permalink' => $permalink,
|
||||||
|
'created_utc' => $created_utc,
|
||||||
|
'is_self' => true,
|
||||||
|
'link_flair_text' => null,
|
||||||
|
'upvote_ratio' => null,
|
||||||
|
'is_original_content' => false,
|
||||||
|
'data_source' => 'reddit_rss',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
PRAutoBlogger_Logger::instance()->info(
|
||||||
|
sprintf( 'Parsed %d posts from Reddit RSS for r/%s.', count( $posts ), $subreddit ),
|
||||||
|
'reddit'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $posts;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch top comments for a specific post via Reddit's .json endpoint.
|
* Fetch top comments for a specific post via Reddit's .json endpoint.
|
||||||
*
|
*
|
||||||
@@ -221,47 +324,145 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
|||||||
* @return bool True if we got a valid response from either endpoint.
|
* @return bool True if we got a valid response from either endpoint.
|
||||||
*/
|
*/
|
||||||
public function is_available(): bool {
|
public function is_available(): bool {
|
||||||
return ( new PRAutoBlogger_Reddit_Availability() )->is_available();
|
return $this->is_rss_available() || $this->is_json_available();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if Reddit RSS endpoints are reachable.
|
* Check if Reddit RSS endpoints are reachable.
|
||||||
*
|
*
|
||||||
|
* RSS endpoints are rarely blocked by Reddit, even for datacenter IPs.
|
||||||
|
*
|
||||||
* @return bool True if RSS endpoint returns HTTP 200.
|
* @return bool True if RSS endpoint returns HTTP 200.
|
||||||
*/
|
*/
|
||||||
public function is_rss_available(): bool {
|
public function is_rss_available(): bool {
|
||||||
return ( new PRAutoBlogger_Reddit_Availability() )->is_rss_available();
|
$url = self::BASE_URL . '/r/all/hot.rss?limit=1';
|
||||||
|
$response = wp_remote_get(
|
||||||
|
$url,
|
||||||
|
[
|
||||||
|
'timeout' => 10,
|
||||||
|
'headers' => [
|
||||||
|
'User-Agent' => self::USER_AGENT,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 200 === wp_remote_retrieve_response_code( $response );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if Reddit .json endpoints are reachable.
|
* Check if Reddit .json endpoints are reachable.
|
||||||
*
|
*
|
||||||
|
* Datacenter IPs are often blocked by Reddit for .json endpoints.
|
||||||
|
*
|
||||||
* @return bool True if .json endpoint returns HTTP 200.
|
* @return bool True if .json endpoint returns HTTP 200.
|
||||||
*/
|
*/
|
||||||
public function is_json_available(): bool {
|
public function is_json_available(): bool {
|
||||||
return ( new PRAutoBlogger_Reddit_Availability() )->is_json_available();
|
$url = self::BASE_URL . '/r/all/hot.json?limit=1';
|
||||||
|
$response = wp_remote_get(
|
||||||
|
$url,
|
||||||
|
[
|
||||||
|
'timeout' => 10,
|
||||||
|
'headers' => [
|
||||||
|
'User-Agent' => self::USER_AGENT,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 200 === wp_remote_retrieve_response_code( $response );
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current rate limit status.
|
* Get current rate limit status.
|
||||||
*
|
*
|
||||||
|
* Reddit .json endpoints return rate limit headers. RSS has no rate limits.
|
||||||
|
*
|
||||||
* @return array{remaining: int, limit: int, resets_at: string}
|
* @return array{remaining: int, limit: int, resets_at: string}
|
||||||
*/
|
*/
|
||||||
public function get_rate_limit_status(): array {
|
public function get_rate_limit_status(): array {
|
||||||
return ( new PRAutoBlogger_Reddit_Availability() )->get_rate_limit_status();
|
$status = get_transient( self::RATE_LIMIT_TRANSIENT );
|
||||||
|
|
||||||
|
if ( is_array( $status ) ) {
|
||||||
|
return $status;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'remaining' => 10,
|
||||||
|
'limit' => 10,
|
||||||
|
'resets_at' => '',
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Make an HTTP GET request to a Reddit .json endpoint.
|
* Make an HTTP GET request to a Reddit .json endpoint.
|
||||||
*
|
*
|
||||||
* Delegates to PRAutoBlogger_Reddit_Availability which owns the HTTP
|
* No authentication — just a plain GET with a descriptive User-Agent.
|
||||||
* transport layer and rate-limit tracking.
|
* Tracks rate limits from response headers when available.
|
||||||
|
*
|
||||||
|
* Side effects: HTTP request, sets rate limit transient, logs errors.
|
||||||
*
|
*
|
||||||
* @param string $url Full URL with .json suffix and query params.
|
* @param string $url Full URL with .json suffix and query params.
|
||||||
*
|
*
|
||||||
* @return array<string, mixed>|null Decoded JSON, or null on failure.
|
* @return array<string, mixed>|null Decoded JSON, or null on failure.
|
||||||
*/
|
*/
|
||||||
private function api_get( string $url ): ?array {
|
private function api_get( string $url ): ?array {
|
||||||
return ( new PRAutoBlogger_Reddit_Availability() )->api_get( $url );
|
$response = wp_remote_get(
|
||||||
|
$url,
|
||||||
|
[
|
||||||
|
'timeout' => self::TIMEOUT_SECONDS,
|
||||||
|
'headers' => [
|
||||||
|
'User-Agent' => self::USER_AGENT,
|
||||||
|
'Accept' => 'application/json',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if ( is_wp_error( $response ) ) {
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
'Reddit .json GET failed: ' . $response->get_error_message(),
|
||||||
|
'reddit'
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track rate limits from response headers.
|
||||||
|
$rate_remaining = wp_remote_retrieve_header( $response, 'x-ratelimit-remaining' );
|
||||||
|
$rate_used = wp_remote_retrieve_header( $response, 'x-ratelimit-used' );
|
||||||
|
$rate_reset = wp_remote_retrieve_header( $response, 'x-ratelimit-reset' );
|
||||||
|
|
||||||
|
if ( '' !== $rate_remaining ) {
|
||||||
|
set_transient(
|
||||||
|
self::RATE_LIMIT_TRANSIENT,
|
||||||
|
[
|
||||||
|
'remaining' => (int) $rate_remaining,
|
||||||
|
'limit' => (int) $rate_used + (int) $rate_remaining,
|
||||||
|
'resets_at' => gmdate( 'Y-m-d H:i:s', time() + (int) $rate_reset ),
|
||||||
|
],
|
||||||
|
120
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$status_code = wp_remote_retrieve_response_code( $response );
|
||||||
|
|
||||||
|
if ( 200 !== $status_code ) {
|
||||||
|
PRAutoBlogger_Logger::instance()->error(
|
||||||
|
sprintf(
|
||||||
|
'Reddit .json HTTP %d: %s',
|
||||||
|
$status_code,
|
||||||
|
substr( wp_remote_retrieve_body( $response ), 0, 300 )
|
||||||
|
),
|
||||||
|
'reddit'
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return json_decode( wp_remote_retrieve_body( $response ), true );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
<?php
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reddit RSS/Atom feed parser — parses Atom XML into normalized post arrays.
|
|
||||||
*
|
|
||||||
* Handles parsing of Reddit's Atom/RSS feeds and mapping them to the standard
|
|
||||||
* Reddit post data format (same shape as .json responses). This parser is
|
|
||||||
* self-contained: it takes raw XML and produces normalized arrays.
|
|
||||||
*
|
|
||||||
* Fields unavailable in RSS feeds (score, num_comments, upvote_ratio) are set
|
|
||||||
* to sensible defaults so the rest of the pipeline can treat RSS and .json data uniformly.
|
|
||||||
*
|
|
||||||
* Usage: Called by PRAutoBlogger_Reddit_JSON_Client::fetch_posts_via_rss()
|
|
||||||
* to parse the response body.
|
|
||||||
*
|
|
||||||
* Dependencies: wp_strip_all_tags(), PRAutoBlogger_Logger, built-in SimpleXML.
|
|
||||||
*
|
|
||||||
* @see providers/class-reddit-json-client.php — Main client that calls this parser.
|
|
||||||
* @see ARCHITECTURE.md — External API integrations table.
|
|
||||||
*/
|
|
||||||
class PRAutoBlogger_Reddit_RSS_Parser {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a Reddit Atom feed into post-data arrays matching .json format.
|
|
||||||
*
|
|
||||||
* Maps Atom entry fields to the standard Reddit post fields so the rest
|
|
||||||
* of the pipeline can consume RSS data without changes. Fields unavailable
|
|
||||||
* in RSS (score, num_comments, upvote_ratio) are set to reasonable defaults.
|
|
||||||
*
|
|
||||||
* @param string $xml Raw Atom XML string.
|
|
||||||
* @param string $subreddit The subreddit name for context (logging only).
|
|
||||||
*
|
|
||||||
* @return array<int, array<string, mixed>> Parsed post data.
|
|
||||||
*/
|
|
||||||
public function parse( string $xml, string $subreddit ): array {
|
|
||||||
// Suppress XML errors for malformed feeds.
|
|
||||||
$prev_errors = libxml_use_internal_errors( true );
|
|
||||||
$feed = simplexml_load_string( $xml );
|
|
||||||
libxml_use_internal_errors( $prev_errors );
|
|
||||||
|
|
||||||
if ( false === $feed ) {
|
|
||||||
PRAutoBlogger_Logger::instance()->error( 'Failed to parse Reddit RSS XML.', 'reddit' );
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register the Atom namespace.
|
|
||||||
$feed->registerXPathNamespace( 'atom', 'http://www.w3.org/2005/Atom' );
|
|
||||||
$entries = $feed->xpath( '//atom:entry' );
|
|
||||||
|
|
||||||
if ( empty( $entries ) ) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$posts = [];
|
|
||||||
foreach ( $entries as $entry ) {
|
|
||||||
$post = $this->parse_entry( $entry, $subreddit );
|
|
||||||
if ( null !== $post ) {
|
|
||||||
$posts[] = $post;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
PRAutoBlogger_Logger::instance()->info(
|
|
||||||
sprintf( 'Parsed %d posts from Reddit RSS for r/%s.', count( $posts ), $subreddit ),
|
|
||||||
'reddit'
|
|
||||||
);
|
|
||||||
|
|
||||||
return $posts;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a single Atom entry element into a normalized post array.
|
|
||||||
*
|
|
||||||
* @param \SimpleXMLElement $entry An Atom entry element.
|
|
||||||
* @param string $subreddit The subreddit name (for context/logging).
|
|
||||||
*
|
|
||||||
* @return array<string, mixed>|null The parsed post data, or null if parsing fails.
|
|
||||||
*/
|
|
||||||
private function parse_entry( $entry, string $subreddit ): ?array {
|
|
||||||
$title = (string) $entry->title;
|
|
||||||
$link = '';
|
|
||||||
$content = '';
|
|
||||||
|
|
||||||
// Get the HTML link (type="text/html").
|
|
||||||
foreach ( $entry->link as $link_el ) {
|
|
||||||
if ( 'text/html' === (string) $link_el['type'] || 'alternate' === (string) $link_el['rel'] ) {
|
|
||||||
$link = (string) $link_el['href'];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Content is in <content> tag as HTML.
|
|
||||||
if ( isset( $entry->content ) ) {
|
|
||||||
$content = wp_strip_all_tags( (string) $entry->content );
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract post ID from the entry id (format: /r/subreddit/comments/ID/...).
|
|
||||||
$entry_id = (string) $entry->id;
|
|
||||||
$post_id = '';
|
|
||||||
if ( preg_match( '#/comments/([a-z0-9]+)#', $entry_id, $m ) ) {
|
|
||||||
$post_id = $m[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract author name.
|
|
||||||
$author = '[deleted]';
|
|
||||||
if ( isset( $entry->author->name ) ) {
|
|
||||||
$author = str_replace( '/u/', '', (string) $entry->author->name );
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse published date to Unix timestamp.
|
|
||||||
$published = (string) ( $entry->published ?? $entry->updated ?? '' );
|
|
||||||
$created_utc = '' !== $published ? (int) strtotime( $published ) : time();
|
|
||||||
|
|
||||||
// Extract permalink (relative path) from full URL.
|
|
||||||
$permalink = '';
|
|
||||||
if ( '' !== $link ) {
|
|
||||||
$parsed = wp_parse_url( $link );
|
|
||||||
$permalink = $parsed['path'] ?? '';
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'id' => $post_id,
|
|
||||||
'title' => $title,
|
|
||||||
'selftext' => $content,
|
|
||||||
'author' => $author,
|
|
||||||
'score' => 1, // Not available in RSS.
|
|
||||||
'num_comments' => 0, // Not available in RSS.
|
|
||||||
'permalink' => $permalink,
|
|
||||||
'created_utc' => $created_utc,
|
|
||||||
'is_self' => true,
|
|
||||||
'link_flair_text' => null,
|
|
||||||
'upvote_ratio' => null,
|
|
||||||
'is_original_content' => false,
|
|
||||||
'data_source' => 'reddit_rss',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -48,6 +48,9 @@ class OpenRouterProviderTest extends BaseTestCase {
|
|||||||
);
|
);
|
||||||
Functions\when( 'set_transient' )->justReturn( true );
|
Functions\when( 'set_transient' )->justReturn( true );
|
||||||
|
|
||||||
|
// Stub URL parsing.
|
||||||
|
Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
|
||||||
|
|
||||||
// Stub HTTP functions for API calls.
|
// Stub HTTP functions for API calls.
|
||||||
Functions\when( 'wp_remote_post' )->justReturn( [
|
Functions\when( 'wp_remote_post' )->justReturn( [
|
||||||
'body' => '{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}',
|
'body' => '{"choices":[{"message":{"content":"test"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}',
|
||||||
|
|||||||
199
tests/unit/Providers/OpenRouterValidatorTest.php
Normal file
199
tests/unit/Providers/OpenRouterValidatorTest.php
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* Tests for PRAutoBlogger_OpenRouter_Validator.
|
||||||
|
*
|
||||||
|
* Validates credential checking logic including encryption, format validation,
|
||||||
|
* and HTTP connectivity probes.
|
||||||
|
* All HTTP calls are mocked — no real API calls.
|
||||||
|
*
|
||||||
|
* @package PRAutoBlogger\Tests\Providers
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace PRAutoBlogger\Tests\Providers;
|
||||||
|
|
||||||
|
use PRAutoBlogger\Tests\BaseTestCase;
|
||||||
|
use Brain\Monkey\Functions;
|
||||||
|
|
||||||
|
class OpenRouterValidatorTest extends BaseTestCase {
|
||||||
|
|
||||||
|
protected function setUp(): void {
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
// Stub get_option with default empty state.
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => '',
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub wp_salt for encryption.
|
||||||
|
Functions\when( 'wp_salt' )->justReturn( 'test_salt_key_for_unit_tests' );
|
||||||
|
|
||||||
|
// Stub URL parsing.
|
||||||
|
Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
|
||||||
|
|
||||||
|
// Stub HTTP functions.
|
||||||
|
Functions\when( 'wp_remote_get' )->justReturn( [
|
||||||
|
'body' => '{}',
|
||||||
|
'response' => [ 'code' => 200 ],
|
||||||
|
] );
|
||||||
|
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 200 );
|
||||||
|
Functions\when( 'wp_remote_retrieve_body' )->justReturn( '{}' );
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validator can be instantiated.
|
||||||
|
*/
|
||||||
|
public function test_validator_instantiation(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$this->assertInstanceOf( \PRAutoBlogger_OpenRouter_Validator::class, $validator );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test run() returns array with expected keys.
|
||||||
|
*/
|
||||||
|
public function test_run_returns_array_with_status(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertIsArray( $result );
|
||||||
|
$this->assertArrayHasKey( 'status', $result );
|
||||||
|
$this->assertArrayHasKey( 'message', $result );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when no API key is configured.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_no_api_key(): void {
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'No API key', $result['message'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation succeeds with a valid decrypted key.
|
||||||
|
*/
|
||||||
|
public function test_run_succeeds_with_valid_key(): void {
|
||||||
|
// Round-trip through encryption to get a valid ciphertext.
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'ok', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'connected', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when decryption fails.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_bad_ciphertext(): void {
|
||||||
|
// Stub get_option to return invalid ciphertext.
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => 'corrupted_base64_data_that_is_not_valid',
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'decryption', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when decrypted key has wrong format.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_bad_key_format(): void {
|
||||||
|
// Encrypt a key that doesn't start with "sk-or-".
|
||||||
|
$plaintext = 'invalid-key-format';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'corrupted', strtolower( $result['message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when HTTP request fails.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_wp_error(): void {
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub wp_remote_get to return an error.
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( true );
|
||||||
|
Functions\when( 'wp_remote_get' )->alias(
|
||||||
|
function () {
|
||||||
|
$error = new \WP_Error( 'http_error', 'Connection refused' );
|
||||||
|
return $error;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'Network error', $result['message'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test validation fails when API returns non-200 status.
|
||||||
|
*/
|
||||||
|
public function test_run_fails_with_http_error(): void {
|
||||||
|
$plaintext = 'sk-or-test-key-1234567890';
|
||||||
|
$ciphertext = \PRAutoBlogger_Encryption::encrypt( $plaintext );
|
||||||
|
|
||||||
|
$this->stub_get_option( [
|
||||||
|
'prautoblogger_openrouter_api_key' => $ciphertext,
|
||||||
|
'prautoblogger_ai_gateway_base_url' => '',
|
||||||
|
'prautoblogger_ai_gateway_cache_ttl' => 0,
|
||||||
|
'prautoblogger_log_level' => 'info',
|
||||||
|
] );
|
||||||
|
|
||||||
|
// Stub to return 401 error.
|
||||||
|
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||||
|
Functions\when( 'wp_remote_get' )->justReturn( [
|
||||||
|
'body' => '{"error":{"message":"Unauthorized"}}',
|
||||||
|
'response' => [ 'code' => 401 ],
|
||||||
|
] );
|
||||||
|
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 401 );
|
||||||
|
Functions\when( 'wp_remote_retrieve_body' )->justReturn( '{"error":{"message":"Unauthorized"}}' );
|
||||||
|
|
||||||
|
$validator = new \PRAutoBlogger_OpenRouter_Validator();
|
||||||
|
$result = $validator->run();
|
||||||
|
|
||||||
|
$this->assertSame( 'error', $result['status'] );
|
||||||
|
$this->assertStringContainsString( 'HTTP 401', $result['message'] );
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user