'application/json', 'X-Request-ID' => $request_id, ]; // Merge custom headers if provided if (!empty($custom_headers)) { $headers = array_merge($headers, $custom_headers); } return $headers; } /** * Prepare request body for API call * * @since 1.0.0 * @param string $method HTTP method * @param array $data Request data * @param string $content_type Content type * @return array|string Prepared request body */ function vasp_prepare_request_body($method, $data, $content_type) { if (empty($data) || $method === 'GET') { return null; } if ($content_type === 'application/json') { // Use shortest round-trip numbers, independent of the host PHP setting. $vasp_previous_precision = ini_get('serialize_precision'); ini_set('serialize_precision', '-1'); try { return json_encode($data); } finally { ini_set('serialize_precision', $vasp_previous_precision); } } // WordPress will automatically convert to form data return $data; } /** * Return whether a log field can contain sensitive data. * * @since 1.0.0 * @param string $key Field name. * @return bool */ function vasp_is_sensitive_log_key(string $key): bool { $normalized_key = strtolower(str_replace('-', '_', $key)); if (in_array($normalized_key, ['authorization_code', 'code_verifier'], true)) { return true; } return (bool) preg_match('/(?:^|_)(?:password|secret|token|authorization|cookie|api_key)$/', $normalized_key); } /** * Redact sensitive values before writing structured data to logs. * * @since 1.0.0 * @param mixed $data Data to redact. * @return mixed Redacted data. */ function vasp_redact_sensitive_log_data($data) { if (!is_array($data)) { return $data; } $redacted = []; foreach ($data as $key => $value) { if (is_string($key) && vasp_is_sensitive_log_key($key)) { $redacted[$key] = '[REDACTED]'; continue; } $redacted[$key] = is_array($value) ? vasp_redact_sensitive_log_data($value) : $value; } return $redacted; } /** * Redact sensitive query parameters before writing a URL to logs. * * @since 1.0.0 * @param string $url URL to redact. * @return string Redacted URL. */ function vasp_redact_sensitive_log_url(string $url): string { return preg_replace_callback( '/([?&])([^=&#]+)=([^&#]*)/', static function (array $matches): string { $key = strtolower(str_replace('-', '_', urldecode($matches[2]))); $is_sensitive = vasp_is_sensitive_log_key($key) || in_array($key, ['code', 'state'], true); return $matches[1] . $matches[2] . '=' . ($is_sensitive ? '[REDACTED]' : $matches[3]); }, $url ); } /** * Send a raw request through the deployment-selected transport policy. * * Public deployments always use WordPress's SSRF-safe request boundary. A * generated development runtime may explicitly allow private endpoints; this * policy is immutable after configuration loading. * * @param string $url Explicit endpoint. * @param array $args WordPress HTTP arguments. * @return array|WP_Error */ function vasp_http_transport_url(string $url, array $args = []) { $parts = wp_parse_url($url); $scheme = is_array($parts) && isset($parts['scheme']) ? strtolower((string) $parts['scheme']) : ''; if (!is_array($parts) || empty($parts['host']) || !in_array($scheme, ['http', 'https'], true)) { return new WP_Error('vasp_http_invalid_url', __('The remote request could not be prepared.', 'valuespace')); } if (!empty(vasp_get_config('allow_private_network'))) { return wp_remote_request($url, $args); } if (!wp_http_validate_url($url)) { return new WP_Error('vasp_http_invalid_url', __('The remote request could not be prepared.', 'valuespace')); } return wp_safe_remote_request($url, $args); } /** Apply WordPress's explicit local-development TLS policy to a Requests cURL handle. */ function vasp_http_parallel_disable_ssl_verification(&$handle): void { // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt -- Requests transport hook for the explicit local runtime only; public runtime forces TLS verification. curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0); // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt -- Same local Requests hook; not a separate HTTP client. curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0); } /** Send at most four prepared requests together through WordPress Requests. */ function vasp_http_transport_parallel(array $requests): array { $responses = []; $requests_class = class_exists('WpOrg\\Requests\\Requests') ? 'WpOrg\\Requests\\Requests' : (class_exists('Requests') ? 'Requests' : ''); if (!apply_filters('vasp_api_parallel_requests_enabled', true) || $requests_class === '') { foreach ($requests as $key => $request) { $responses[$key] = vasp_http_transport_url($request['request_url'], $request['args']); } return $responses; } $multiple = []; foreach ($requests as $key => $request) { $url = $request['request_url']; if (empty(vasp_get_config('allow_private_network')) && !wp_http_validate_url($url)) { $responses[$key] = new WP_Error('vasp_http_invalid_url', __('The remote request could not be prepared.', 'valuespace')); continue; } $args = $request['args']; $options = [ 'timeout' => $args['timeout'], 'verify' => $args['sslverify'], ]; if ($args['sslverify'] === false) { $hooks_class = class_exists('WpOrg\\Requests\\Hooks') ? 'WpOrg\\Requests\\Hooks' : (class_exists('Requests_Hooks') ? 'Requests_Hooks' : ''); if ($hooks_class === '') { $responses[$key] = vasp_http_transport_url($url, $args); continue; } $hooks = new $hooks_class(); $hooks->register('curl.before_request', 'vasp_http_parallel_disable_ssl_verification'); $options['hooks'] = $hooks; } $multiple[$key] = [ 'url' => $url, 'headers' => $args['headers'], 'data' => $args['body'] ?? [], 'type' => $args['method'], 'options' => $options, ]; } try { return $responses + (array) call_user_func([$requests_class, 'request_multiple'], $multiple); } catch (Throwable $error) { foreach ($multiple as $key => $request) { $responses[$key] = new WP_Error('http_request_failed'); } return $responses; } } /** Return the effective HTTP port represented by parsed URL parts. */ function vasp_http_url_port(array $vasp_parts): int { if (isset($vasp_parts['port'])) { return (int) $vasp_parts['port']; } return strtolower((string) ($vasp_parts['scheme'] ?? '')) === 'https' ? 443 : 80; } /** Return an RFC-compatible Host header, retaining a non-default port. */ function vasp_http_loopback_host_header(array $vasp_parts): string { $vasp_host = (string) ($vasp_parts['host'] ?? ''); if (strpos($vasp_host, ':') !== false && substr($vasp_host, 0, 1) !== '[') { $vasp_host = '[' . $vasp_host . ']'; } $vasp_port = isset($vasp_parts['port']) ? (int) $vasp_parts['port'] : 0; $vasp_default_port = strtolower((string) ($vasp_parts['scheme'] ?? '')) === 'https' ? 443 : 80; return $vasp_port > 0 && $vasp_port !== $vasp_default_port ? $vasp_host . ':' . $vasp_port : $vasp_host; } /** Dispatch a trusted local WordPress request without waiting for its response. */ function vasp_http_dispatch_local(string $url, array $args = []) { $vasp_target = wp_parse_url($url); $vasp_admin = wp_parse_url(admin_url()); $vasp_target_scheme = is_array($vasp_target) ? strtolower((string) ($vasp_target['scheme'] ?? '')) : ''; $vasp_admin_scheme = is_array($vasp_admin) ? strtolower((string) ($vasp_admin['scheme'] ?? '')) : ''; if (!is_array($vasp_target) || !is_array($vasp_admin) || !in_array($vasp_target_scheme, ['http', 'https'], true) || $vasp_target_scheme !== $vasp_admin_scheme || empty($vasp_target['host']) || empty($vasp_admin['host']) || isset($vasp_target['user']) || isset($vasp_target['pass']) || strcasecmp((string) $vasp_target['host'], (string) $vasp_admin['host']) !== 0 || vasp_http_url_port($vasp_target) !== vasp_http_url_port($vasp_admin) ) { return new WP_Error('vasp_http_invalid_local_url'); } $vasp_dispatch_url = $url; $vasp_wait_for_ack = !empty($args['wait_for_ack']); unset($args['wait_for_ack']); $vasp_request_args = array_merge($args, [ // FastCGI workers can acknowledge receipt before continuing the job. // Other runtimes retain the nonblocking transport fallback. 'timeout' => $vasp_wait_for_ack ? 5 : 1, 'blocking' => $vasp_wait_for_ack, 'sslverify' => apply_filters('https_local_ssl_verify', false), ]); if (!empty(vasp_get_config('allow_private_network'))) { $vasp_local_dispatch_host = (string) vasp_get_config('local_dispatch_host'); if ($vasp_local_dispatch_host === '') { return new WP_Error('vasp_http_local_dispatch_unconfigured'); } $vasp_port = isset($vasp_target['port']) ? ':' . (int) $vasp_target['port'] : ''; $vasp_path = isset($vasp_target['path']) && $vasp_target['path'] !== '' ? (string) $vasp_target['path'] : '/'; $vasp_query = isset($vasp_target['query']) && $vasp_target['query'] !== '' ? '?' . $vasp_target['query'] : ''; $vasp_dispatch_url = $vasp_target_scheme . '://' . $vasp_local_dispatch_host . $vasp_port . $vasp_path . $vasp_query; $vasp_headers = is_array($vasp_request_args['headers'] ?? null) ? $vasp_request_args['headers'] : []; foreach (array_keys($vasp_headers) as $vasp_header_name) { if (strcasecmp((string) $vasp_header_name, 'Host') === 0) { unset($vasp_headers[$vasp_header_name]); } } $vasp_headers['Host'] = vasp_http_loopback_host_header($vasp_target); $vasp_request_args['headers'] = $vasp_headers; $vasp_request_args['sslverify'] = false; } return wp_remote_post($vasp_dispatch_url, $vasp_request_args); } /** * Send a request to an explicit URL using shared safe response handling. * * The raw mode is intentionally explicit and returns the WordPress response * object after transport and status validation. JSON is the secure default. * * @param string $url Explicit HTTPS endpoint. * @param array $args WordPress HTTP arguments. * @param string $response_mode json or raw. * @return mixed|WP_Error */ function vasp_http_request_url(string $url, array $args = [], string $response_mode = 'json') { if (!in_array($response_mode, ['json', 'raw'], true)) { return new WP_Error('vasp_http_invalid_response_mode', __('The remote request could not be prepared.', 'valuespace')); } $response = vasp_http_transport_url($url, $args); if (is_wp_error($response)) { return $response; } $status = (int) wp_remote_retrieve_response_code($response); if ($status < 200 || $status >= 300) { return new WP_Error( 'vasp_http_status_error', __('The remote service could not complete the request.', 'valuespace'), ['status' => $status] ); } if ($response_mode === 'raw') { return $response; } $body = (string) wp_remote_retrieve_body($response); $data = json_decode($body, true); if (json_last_error() !== JSON_ERROR_NONE) { return new WP_Error( 'vasp_http_invalid_json', __('The remote service returned an invalid response.', 'valuespace'), ['status' => $status] ); } return $data; } /** * Log request body with sensitive data redaction * * @since 1.0.0 * @param string $request_id Request ID * @param mixed $body Request body * @param string $content_type Content type */ function vasp_log_request_body($request_id, $body, $content_type) { if (empty($body)) { return; } $body_size = is_string($body) ? strlen($body) : strlen((string) wp_json_encode($body)); vasp_log('API request prepared', 'debug', [ 'request_id' => $request_id, 'content_type' => $content_type, 'body_size_bytes' => $body_size, ]); } /** * Return whether routine debug logs should be skipped for high-volume endpoints. * * @param string $endpoint Config endpoint key. * @return bool */ function vasp_api_should_skip_routine_debug_logs(string $endpoint): bool { /** * Routine API request/response traces are intentionally opt-in. They are * useful while debugging transport issues, but too noisy for WordPress admin * logs during normal catalog and image sync work. */ return !apply_filters('vasp_api_log_routine_requests', false, $endpoint); } /** * Classify a transport failure without logging or retaining upstream text. * * @param WP_Error $vasp_error Original WordPress transport failure. * @param int $vasp_timeout_seconds Configured request timeout, or zero when unknown. * @return array Bounded transport reason and optional known timeout limit. */ function vasp_http_transport_details(WP_Error $vasp_error, $vasp_timeout_seconds = 0): array { $vasp_details = []; // Inspect upstream text only to recognize a transport code; never retain it. $vasp_transport_reason = ''; if ($vasp_error->get_error_code() === 'http_request_timed_out') { $vasp_transport_reason = 'timeout'; } elseif (preg_match('/\bcURL error ([0-9]+):/i', $vasp_error->get_error_message(), $vasp_matches)) { $vasp_curl_reasons = [ 28 => 'timeout', 5 => 'dns', 6 => 'dns', 7 => 'connection', 35 => 'tls', 51 => 'tls', 58 => 'tls', 60 => 'tls', 77 => 'tls', ]; $vasp_transport_reason = $vasp_curl_reasons[(int) $vasp_matches[1]] ?? ''; } if ($vasp_transport_reason !== '') { $vasp_details['transport_reason'] = $vasp_transport_reason; } if ($vasp_transport_reason === 'timeout') { $vasp_details['timeout_seconds'] = $vasp_timeout_seconds; } return vasp_error_public_data([], $vasp_details); } /** * Handle API error response * * @since 1.0.0 * @param WP_Error $response Error response * @param string $request_id Request ID * @param string $endpoint Endpoint * @param string $method HTTP method * @param string $endpoint_url Full URL * @param float $duration Request duration in ms * @param int $vasp_timeout_seconds Configured request timeout, or zero when unknown. * @return WP_Error Formatted error */ function vasp_handle_request_error($response, $request_id, $endpoint, $method, $endpoint_url, $duration, $vasp_timeout_seconds = 0) { $error_code = sanitize_key((string) $response->get_error_code()); if ($error_code === '' || strlen($error_code) > 64) { $error_code = 'http_request_failed'; } $safe_endpoint = sanitize_key((string) $endpoint); $safe_endpoint = $safe_endpoint !== '' && strlen($safe_endpoint) <= 96 ? $safe_endpoint : 'api_endpoint'; $safe_method = strtoupper(substr(sanitize_key((string) $method), 0, 12)); $safe_request_id = substr(sanitize_text_field((string) $request_id), 0, 64); return vasp_create_error(VASP_ERROR_API_REQUEST_FAILED, array_merge([ 'error_code' => $error_code, 'status' => 0, 'endpoint' => $safe_endpoint, 'method' => $safe_method, 'request_id' => $safe_request_id, ], vasp_http_transport_details($response, $vasp_timeout_seconds))); } /** * Try to refresh token and retry request * * @since 1.0.0 * @param string $request_id Request ID * @param string $endpoint Endpoint * @param string $request_url Full request URL * @param array $args Request arguments * @param float $start_time Request start time * @param string $response_mode Original request response mode. * @return mixed|WP_Error Response on success, exact refresh/retry error on failure. */ function vasp_try_token_refresh_and_retry($request_id, $endpoint, $request_url, $args, $start_time, string $response_mode = 'json') { vasp_log('Received 401 Unauthorized, attempting automatic token refresh', 'info', [ 'request_id' => $request_id, 'endpoint' => $endpoint ]); // Try to refresh the token $refresh_result = vasp_refresh_access_token(); if (is_wp_error($refresh_result)) { return $refresh_result; } if (empty($refresh_result['access_token'])) { return vasp_create_error(VASP_ERROR_API_RESPONSE_ERROR, [ 'endpoint' => 'token_endpoint', 'reason' => 'access_token_missing_after_refresh', ], ['can_retry' => true]); } vasp_log('Token refreshed successfully, retrying original request', 'info', [ 'request_id' => $request_id, 'endpoint' => $endpoint ]); // Update the Authorization header with the new token $args['headers']['Authorization'] = 'Bearer ' . $refresh_result['access_token']; // Retry the original request with the new token $retry_response = vasp_http_transport_url($request_url, $args); $retry_duration = (int) round((microtime(true) - $start_time) * 1000); if (is_wp_error($retry_response)) { return vasp_handle_request_error( $retry_response, $request_id, $endpoint, $args['method'] ?? 'GET', $request_url, $retry_duration, $args['timeout'] ?? 0 ); } $retry_code = wp_remote_retrieve_response_code($retry_response); $retry_body = wp_remote_retrieve_body($retry_response); $retry_data = json_decode($retry_body, true); $retry_json_error = json_last_error(); vasp_log('Retry request completed', 'debug', [ 'request_id' => $request_id, 'status' => $retry_code, 'duration_ms' => $retry_duration ]); // If retry succeeded, return the response if ($retry_code < 400) { if ($response_mode === 'raw') { return $retry_response; } if ($retry_json_error !== JSON_ERROR_NONE) { return new WP_Error( 'vasp_http_invalid_json', __('The remote service returned an invalid response.', 'valuespace'), [ 'status' => (int) $retry_code, 'endpoint' => substr(sanitize_key((string) $endpoint), 0, 96), ] ); } vasp_log('Retry request succeeded after token refresh', 'info', [ 'request_id' => $request_id, 'endpoint' => $endpoint, 'status' => $retry_code ]); return $retry_data; } return vasp_handle_error_status( $retry_code, is_array($retry_data) ? $retry_data : [], $request_id, $endpoint, $args['method'] ?? 'GET', $request_url, [], $request_url, $args, $start_time, false ); } /** * Handle API error status codes (4xx, 5xx) * * @since 1.0.0 * @param int $response_code HTTP status code * @param array $response_data Response data * @param string $request_id Request ID * @param string $endpoint Endpoint * @param string $method HTTP method * @param string $endpoint_url Full URL * @param array $params Query parameters * @param string $request_url Full request URL * @param array $args Request arguments * @param float $start_time Request start time * @return array|WP_Error Response data on success (after retry), WP_Error on failure */ function vasp_handle_error_status($response_code, $response_data, $request_id, $endpoint, $method, $endpoint_url, $params, $request_url, $args, $start_time, bool $allow_refresh = true, string $response_mode = 'json') { $response_data = is_array($response_data) ? $response_data : []; $raw_error = is_string($response_data['error'] ?? null) ? trim((string) $response_data['error']) : ''; $oauth_error = preg_match('/^[a-z0-9][a-z0-9._-]{0,63}$/', $raw_error) === 1 ? $raw_error : ''; $error_code = sanitize_key((string) ($response_data['code'] ?? 'api_error')); $validation_field = ''; $oauth_error = strlen($oauth_error) <= 64 ? $oauth_error : ''; $error_code = $error_code !== '' && strlen($error_code) <= 64 ? $error_code : 'api_error'; $validation_errors = $response_data['data']['errors'] ?? ($response_data['errors'] ?? []); if (is_array($validation_errors) && !empty($validation_errors)) { $first_key = array_key_first($validation_errors); $first_error = reset($validation_errors); $error_code = 'validation_failed'; if (is_string($first_key)) { $validation_field = sanitize_key(str_replace(['$.', '[', ']', '.'], ['', '_', '', '_'], $first_key)); $validation_field = substr($validation_field, 0, 96); } if (is_array($first_error)) { $error_code = sanitize_key((string) ($first_error['code'] ?? $error_code)); } } elseif (preg_match('/^activities\[([0-9]{1,3})\]\.([a-zA-Z0-9_.]+)/', $raw_error, $matches)) { $error_code = 'invalid_activity_contract'; $validation_field = sanitize_key('activities_' . $matches[1] . '_' . str_replace('.', '_', $matches[2])); } elseif ($raw_error === 'Invalid WordPress application identity.') { $error_code = 'invalid_application_identity'; } $error_code = $error_code !== '' && strlen($error_code) <= 64 ? $error_code : 'api_error'; // A 401 from the token endpoint is the result of a refresh attempt. Never // recursively try to refresh while handling that response. if ($allow_refresh && $response_code === 401 && $endpoint !== 'token_endpoint') { $retry_data = vasp_try_token_refresh_and_retry($request_id, $endpoint, $request_url, $args, $start_time, $response_mode); return $retry_data; } $error_context = [ 'error_code' => $error_code, 'oauth_error' => $oauth_error, 'status' => (int) $response_code, 'endpoint' => $endpoint, 'method' => strtoupper((string) $method), ]; if (isset($response_data['retryable']) && is_bool($response_data['retryable'])) { $error_context['retryable'] = $response_data['retryable']; } $retry_after_seconds = $response_data['data']['retryAfterSeconds'] ?? ($response_data['retryAfterSeconds'] ?? null); if (is_numeric($retry_after_seconds)) { $error_context['retry_after'] = max(1, min(300, (int) $retry_after_seconds)); } if (isset($response_data['supportedSchemaVersions']) && is_array($response_data['supportedSchemaVersions'])) { $error_context['supported_schema_versions'] = array_values(array_unique(array_filter( array_map('absint', $response_data['supportedSchemaVersions']) ))); } if ($validation_field !== '') { $error_context['validation_field'] = $validation_field; } return vasp_create_error(VASP_ERROR_API_RESPONSE_ERROR, $error_context); } /** * Get user-friendly error message for error code * * @since 1.0.0 * @param int|string $error_code Error code * @param string $default_message Default message * @return string User-friendly error message */ function vasp_get_user_friendly_error_message($error_code, $default_message = '') { $mapping = function_exists('vasp_get_error_mapping') ? vasp_get_error_mapping() : []; $key = strtolower(trim((string) $error_code)); if (preg_match('/^http_([4-5][0-9]{2})$/', $key, $matches)) { $key = $matches[1]; } if (isset($mapping[$key])) { return (string) $mapping[$key]['description']; } return $default_message !== '' ? $default_message : __('The request could not be completed. Please try again.', 'valuespace'); } /** * Make an authenticated request to ValueSpace API * * Handles all API communication with ValueSpace, including authentication, * request formatting, error handling, automatic token refresh, and response processing. * * @since 1.0.0 * * @param string $endpoint API endpoint path (without base URL) * @param string $method HTTP method (GET, POST, PUT, DELETE, etc.) * @param array $data Optional. Request body data for non-GET requests. * @param array $params Optional. Query parameters for GET requests. * @param array $custom_headers Optional. Custom headers to include in request. * @param string $content_type Optional. Content type for request body. Default 'application/json'. * @param bool $allow_refresh Whether a 401 may refresh credentials and retry. * @return array|WP_Error Response data on success, WP_Error on failure. */ function vasp_api_prepare_request(string $endpoint, string $method, $data, array $params, array $custom_headers, string $content_type, int $timeout, ?string $access_token = null) { $request_id = uniqid('req_'); $endpoint_url = vasp_get_endpoint_url($endpoint, $params); if (is_wp_error($endpoint_url)) { return $endpoint_url; } $headers = vasp_build_request_headers($request_id, $custom_headers, $endpoint); if ($endpoint !== 'token_endpoint' && empty($headers['Authorization'])) { $access_token = $access_token ?? vasp_resolve_access_token(); if (is_wp_error($access_token)) { return $access_token; } $headers['Authorization'] = 'Bearer ' . $access_token; } $args = [ 'method' => strtoupper($method), 'headers' => $headers, 'timeout' => $timeout, 'sslverify' => vasp_get_config('ssl_verify'), ]; $body = vasp_prepare_request_body($method, $data, $content_type); if ($body !== null) { $args['headers']['Content-Type'] = $content_type; $args['body'] = $body; } $request_url = !empty($params) ? add_query_arg($params, $endpoint_url) : $endpoint_url; return compact('endpoint', 'method', 'params', 'request_id', 'endpoint_url', 'request_url', 'args') + ['start_time' => microtime(true)]; } /** Interpret one transport response through the shared API error contract. */ function vasp_api_parse_response($response, array $request, string $response_mode, bool $allow_refresh) { $duration = (int) round((microtime(true) - $request['start_time']) * 1000); if ($response instanceof Throwable) { $response = new WP_Error('http_request_failed'); } if (is_wp_error($response)) { return vasp_handle_request_error($response, $request['request_id'], $request['endpoint'], $request['method'], $request['endpoint_url'], $duration, $request['args']['timeout']); } $response_code = is_array($response) ? (int) wp_remote_retrieve_response_code($response) : (int) ($response->status_code ?? 0); $response_body = is_array($response) ? (string) wp_remote_retrieve_body($response) : (string) ($response->body ?? ''); $response_data = json_decode($response_body, true); $json_error = json_last_error(); if ($response_code >= 400) { return vasp_handle_error_status( $response_code, $response_data, $request['request_id'], $request['endpoint'], $request['method'], $request['endpoint_url'], $request['params'], $request['request_url'], $request['args'], $request['start_time'], $allow_refresh, $response_mode ); } if ($response_mode === 'raw') { return $response; } if ($response_mode !== 'json') { return new WP_Error('vasp_http_invalid_response_mode', __('The remote request could not be prepared.', 'valuespace')); } if ($json_error !== JSON_ERROR_NONE) { vasp_log('API response JSON validation failed', 'error', [ 'request_id' => $request['request_id'], 'endpoint' => $request['endpoint'], 'status' => $response_code, 'response_size' => strlen($response_body), ]); return new WP_Error( 'vasp_http_invalid_json', __('The remote service returned an invalid response.', 'valuespace'), [ 'status' => (int) $response_code, 'endpoint' => substr(sanitize_key((string) $request['endpoint']), 0, 96), ] ); } return $response_data; } function vasp_api_request(string $endpoint, string $method = 'GET', $data = [], array $params = [], array $custom_headers = [], string $content_type = 'application/json', int $timeout = 30, string $response_mode = 'json', bool $allow_refresh = true) { $request = vasp_api_prepare_request($endpoint, $method, $data, $params, $custom_headers, $content_type, $timeout); return is_wp_error($request) ? $request : vasp_api_parse_response(vasp_http_transport_url($request['request_url'], $request['args']), $request, $response_mode, $allow_refresh); } /** * Execute independent API requests in caller-sized parallel groups. * * A caller may stop after one completed group establishes backpressure. Every * response from that already-started group is still returned so successful * siblings can be acknowledged before later groups are withheld. */ function vasp_api_request_parallel(array $specs, int $max_concurrency = 4, ?callable $should_stop = null): array { $max_concurrency = max(1, $max_concurrency); if (empty($specs)) { return []; } $token = vasp_resolve_access_token(); if (is_wp_error($token)) { return array_fill_keys(array_keys($specs), $token); } $prepared = []; $results = []; foreach ($specs as $key => $spec) { $request = vasp_api_prepare_request( (string) ($spec['endpoint'] ?? ''), (string) ($spec['method'] ?? 'GET'), $spec['data'] ?? [], (array) ($spec['params'] ?? []), (array) ($spec['headers'] ?? []), (string) ($spec['content_type'] ?? 'application/json'), (int) ($spec['timeout'] ?? 30), $token ); is_wp_error($request) ? $results[$key] = $request : $prepared[$key] = $request; } $refresh_available = true; foreach (array_chunk($prepared, $max_concurrency, true) as $chunk) { $stop_after_chunk = false; foreach (vasp_http_transport_parallel($chunk) as $key => $response) { $status = is_array($response) ? (int) wp_remote_retrieve_response_code($response) : (int) ($response->status_code ?? 0); $allow_refresh = $refresh_available && $status === 401; $refresh_available = $allow_refresh ? false : $refresh_available; $results[$key] = vasp_api_parse_response($response, $chunk[$key], 'json', $allow_refresh); if ($should_stop !== null && $should_stop($results[$key], $key)) { $stop_after_chunk = true; } } if ($stop_after_chunk) { return $results; } } return $results; } /** * Get the site URL with HTTPS protocol * * Always returns HTTPS for OAuth compatibility. * * @since 1.0.0 * @return string The site URL with HTTPS protocol */ function vasp_get_site_url() { return set_url_scheme(home_url(), 'https'); } /** * Get admin URL with HTTPS protocol * * Always returns HTTPS for OAuth compatibility. * * @since 1.0.0 * @param string $path Optional. Path relative to the admin URL. * @return string Admin URL with HTTPS protocol */ function vasp_get_admin_url($path = '') { return set_url_scheme(admin_url($path), 'https'); } /** * Check if WordPress credentials exist and are working in the Dashboard * * @since 1.0.5 * @param string $site_url The WordPress site URL * @return array|WP_Error Array with 'exists' and 'working' keys, or WP_Error on failure */ function vasp_check_wordpress_credentials($site_url) { vasp_log('Checking WordPress credentials in Dashboard', 'info', [ 'source' => 'credential-check', 'site_url' => $site_url ]); $response = vasp_api_request('wordpress_status_endpoint', 'GET', [], ['testConnection' => 'true']); if (is_wp_error($response)) { return $response; } // Check for authentication/authorization errors if (isset($response['error'])) { $error = sanitize_key((string) $response['error']); $error = $error !== '' && strlen($error) <= 64 ? $error : 'authentication_failed'; return vasp_create_error(VASP_ERROR_WORDPRESS_CONNECTION_TEST_FAILED, [ 'source' => 'credential-check', 'error_code' => $error, ], ['error_code' => $error]); } vasp_log('WordPress credentials check result', 'info', [ 'source' => 'credential-check', 'exists' => $response['exists'] ?? false, 'working' => $response['working'] ?? false, ]); return $response; } /** * Store the authoritative tenant ID returned by the authenticated Gateway. * * @param array $status_data Decoded token-status response. * @return string|WP_Error Stored tenant ID or an error. */ function vasp_store_authenticated_tenant_id(array $status_data) { $tenant_id = $status_data['tenantId'] ?? $status_data['TenantId'] ?? ''; $tenant_id = sanitize_text_field((string) $tenant_id); if ($tenant_id === '') { return vasp_create_error(VASP_ERROR_VASP_CONNECTION_TEST_FAILED, [ 'reason' => 'missing_tenant_id_in_token_status', ]); } $previous_tenant_id = (string) get_option(VASP_OPTION_TENANT_ID, ''); update_option(VASP_OPTION_TENANT_ID, $tenant_id, false); if ($previous_tenant_id !== '' && $previous_tenant_id !== $tenant_id) { vasp_log('Authenticated tenant ID changed', 'warning', [ 'previous_tenant_id' => $previous_tenant_id, 'tenant_id' => $tenant_id, ]); } else { vasp_log('Authenticated tenant ID synchronized', 'info', [ 'tenant_id' => $tenant_id, ]); } $tenant_id_fallback = vasp_get_tenant_id_fallback(); if ($tenant_id_fallback !== '' && $tenant_id_fallback !== $tenant_id) { vasp_log('Configured tenant ID fallback differs from authenticated tenant; authenticated tenant retained', 'warning', [ 'authenticated_tenant_id' => $tenant_id, 'fallback_tenant_id' => $tenant_id_fallback, ]); } return $tenant_id; } /** * Resolve and persist tenant identity from the authenticated token-status API. * * @param string $access_token Decrypted OAuth access token. * @return string|WP_Error Authenticated tenant ID or an error. */ function vasp_sync_authenticated_tenant_id(string $access_token) { if ($access_token === '') { return vasp_create_error(VASP_ERROR_VASP_CONNECTION_TEST_FAILED, [ 'reason' => 'missing_access_token', ]); } $status_data = vasp_api_request('status_endpoint', 'GET'); if (is_wp_error($status_data)) { return $status_data; } return vasp_store_authenticated_tenant_id($status_data); } /** * Get the explicit tenant ID override used by test configurations. * * The fallback is used only when no authenticated tenant has been synchronized. * It never supersedes VASP_OPTION_TENANT_ID. * * @return string Configured test override, or an empty string. */ function vasp_get_tenant_id_fallback(): string { if (!defined('VASP_TENANT_ID') || empty(VASP_TENANT_ID)) { return ''; } return sanitize_text_field((string) VASP_TENANT_ID); } /** * Get the effective tenant ID for this WordPress connection. * * The tenant is never inferred from the website URL. Gateway derives it from * the validated token/application binding and the plugin persists it locally. * Explicit test configurations may supply a fallback only when no * authenticated value is available. * * @since 1.0.11 * @return string The authenticated tenant ID, or an empty string when unavailable. */ function vasp_get_widget_tenant_id() { $authenticated_tenant_id = sanitize_text_field( (string) get_option(VASP_OPTION_TENANT_ID, '') ); if ($authenticated_tenant_id !== '') { return $authenticated_tenant_id; } return vasp_get_tenant_id_fallback(); } /** * Check if WooCommerce credentials exist and are working in the Dashboard * * @since 1.0.5 * @param string $site_url The WooCommerce site URL * @return array|WP_Error Array with 'exists' and 'working' keys, or WP_Error on failure */ function vasp_check_woocommerce_credentials($site_url) { vasp_log('Checking WooCommerce credentials in Dashboard', 'info', [ 'source' => 'credential-check', 'site_url' => $site_url ]); $response = vasp_api_request('woocommerce_status_endpoint', 'GET', [], ['testConnection' => 'true']); if (is_wp_error($response)) { vasp_log('Failed to check WooCommerce credentials', 'error', [ 'source' => 'credential-check', 'error_code' => $response->get_error_code(), ]); return $response; } vasp_log('WooCommerce credentials check result', 'info', [ 'source' => 'credential-check', 'exists' => $response['exists'] ?? false, 'working' => $response['working'] ?? false, ]); return $response; } /** * Return a valid local WordPress widget display status. * * @param mixed $status Candidate status. * @return string Empty when the candidate is invalid. */ function vasp_normalize_site_widget_visibility_status($status): string { $status = is_string($status) ? sanitize_key($status) : ''; return in_array($status, ['published', 'draft'], true) ? $status : ''; } /** * Perform the protected ValueSpace status GET and replace the request cache. * * @return array|WP_Error Decoded status response, or the transport error. */ function vasp_refresh_vasp_status() { $response = vasp_api_request( 'valuespace_status_endpoint', 'GET', [], [], [], 'application/json', 5 ); $GLOBALS['vasp_valuespace_status_request_response'] = $response; return $response; } /** * Get the canonical ValueSpace status, reusing one response within the request. * * @return array|WP_Error Decoded status response, or the transport error. */ function vasp_get_vasp_status() { if (!array_key_exists('vasp_valuespace_status_request_response', $GLOBALS)) { return vasp_refresh_vasp_status(); } return $GLOBALS['vasp_valuespace_status_request_response']; } /** Clear request-scoped status state after a mutation or deterministic test. */ function vasp_reset_vasp_status_request_cache(): void { unset($GLOBALS['vasp_valuespace_status_request_response']); } /** * Normalize the authoritative usage block, with a temporary fallback for older Gateways. * * @param array $billing Raw billing block from the status endpoint. * @return array Normalized usage summary. */ function vasp_normalize_billing_usage(array $billing): array { if (isset($billing['usage']) && is_array($billing['usage'])) { return $billing['usage']; } $vasp_subscription_allocated = (int) ($billing['subscriptionAllocation'] ?? 0); $vasp_subscription_used = (int) ($billing['subscriptionUsed'] ?? 0); $vasp_subscription_remaining = (int) ($billing['subscriptionUnits'] ?? 0); $vasp_addon_allocated = (int) ($billing['totalAddonUnits'] ?? 0); $vasp_addon_used = (int) ($billing['addonUsed'] ?? 0); $vasp_addon_remaining = (int) ($billing['addonUnits'] ?? 0); $vasp_allocated = $vasp_subscription_allocated + $vasp_addon_allocated; $vasp_used = $vasp_subscription_used + $vasp_addon_used; $vasp_remaining = $vasp_subscription_remaining + $vasp_addon_remaining; $vasp_percentage = $vasp_allocated > 0 ? max(0, min(100, $vasp_used / $vasp_allocated * 100)) : 0; if ($vasp_allocated <= 0) { $vasp_level = 'normal'; } elseif ($vasp_remaining <= 0) { $vasp_level = 'exhausted'; } elseif ($vasp_percentage >= 90) { $vasp_level = 'critical'; } elseif ($vasp_percentage >= 70) { $vasp_level = 'low'; } else { $vasp_level = 'normal'; } return [ 'allocated' => $vasp_allocated, 'used' => $vasp_used, 'remaining' => $vasp_remaining, 'usedPercentage' => $vasp_percentage, 'level' => $vasp_level, 'subscription' => [ 'allocated' => $vasp_subscription_allocated, 'used' => $vasp_subscription_used, 'remaining' => $vasp_subscription_remaining, ], 'addon' => [ 'allocated' => $vasp_addon_allocated, 'used' => $vasp_addon_used, 'remaining' => $vasp_addon_remaining, 'nextExpiryQty' => $billing['addonExpiryQty'] ?? null, 'nextExpiresAt' => $billing['addonExpiryDate'] ?? null, ], ]; } /** * Get the billing summary for the connected ValueSpace tenant. * * Fetches billing data via a live HTTP call, cached for 1 hour via transient. * A 5-second HTTP timeout is used so a slow gateway degrades gracefully. * * @since 0.9.0 * @param bool $force_refresh Whether to bypass request-local and transient caches. * @return array|WP_Error|null * - array Billing summary on success. * - WP_Error On API or auth failure (use is_wp_error() to detect). * - null If ValueSpace is not connected. */ function vasp_get_billing_summary(bool $force_refresh = false) { static $static_cache = null; static $has_fetched = false; if (!$force_refresh && $has_fetched) { return $static_cache; } if (!vasp_valuespace_is_connected()) { return null; } if (!$force_refresh) { $cached = get_transient(VASP_TRANSIENT_BILLING_SUMMARY_CACHE); if ($cached !== false) { $static_cache = $cached; $has_fetched = true; return $cached; } } // Circuit breaker: if the gateway failed recently, don't block this page load. // Returns null (same as "not connected") for up to 60 s after a failure. if (get_transient(VASP_TRANSIENT_GATEWAY_UNREACHABLE) !== false) { return $static_cache; // null on first failure, stale WP_Error otherwise } // Use a short timeout (5 s) — billing is non-critical UI data. $response = $force_refresh ? vasp_refresh_vasp_status() : vasp_get_vasp_status(); $has_fetched = true; if (is_wp_error($response)) { vasp_log('vasp_get_billing_summary: API request failed', 'error', [ 'error' => $response->get_error_message(), ]); // Circuit open: skip retries for the next 60 seconds set_transient(VASP_TRANSIENT_GATEWAY_UNREACHABLE, 1, 60); $static_cache = $response; return $response; } if (empty($response['billing'])) { vasp_log('vasp_get_billing_summary: API returned no billing block', 'warning'); $static_cache = new WP_Error('vasp_no_billing', __('No billing data returned by ValueSpace.', 'valuespace')); return $static_cache; } $b = $response['billing']; vasp_log('vasp_get_billing_summary: raw billing block received', 'debug', [ 'planName' => $b['planName'] ?? null, 'isFreePlan' => $b['isFreePlan'] ?? null, 'isInTrial' => $b['isInTrial'] ?? null, 'subscriptionStatus' => $b['subscriptionStatus'] ?? null, 'conversationsRemaining' => $b['conversationsRemaining'] ?? null, 'subscriptionAllocation' => $b['subscriptionAllocation'] ?? null, 'subscriptionUnits' => $b['subscriptionUnits'] ?? null, 'subscriptionUsed' => $b['subscriptionUsed'] ?? null, 'totalAddonUnits' => $b['totalAddonUnits'] ?? null, 'addonUnits' => $b['addonUnits'] ?? null, 'addonUsed' => $b['addonUsed'] ?? null, 'currentPeriodStart' => $b['currentPeriodStart'] ?? null, 'currentPeriodEnd' => $b['currentPeriodEnd'] ?? null, 'cancellationDate' => $b['cancellationDate'] ?? null, 'planPrice' => $b['planPrice'] ?? null, 'planCurrency' => $b['planCurrency'] ?? null, 'planInterval' => $b['planInterval'] ?? null, 'planDescription' => $b['planDescription'] ?? null, 'addonExpiryQty' => $b['addonExpiryQty'] ?? null, 'addonExpiryDate' => $b['addonExpiryDate'] ?? null, ]); $vasp_usage = vasp_normalize_billing_usage($b); $vasp_subscription_usage = is_array($vasp_usage['subscription'] ?? null) ? $vasp_usage['subscription'] : []; $vasp_addon_usage = is_array($vasp_usage['addon'] ?? null) ? $vasp_usage['addon'] : []; $result = [ 'planName' => $b['planName'] ?? null, 'isFreePlan' => (bool) ($b['isFreePlan'] ?? false), 'isInTrial' => (bool) ($b['isInTrial'] ?? false), 'isPaymentRequired' => (bool) ($b['isPaymentRequired'] ?? false), 'trialExpiresAt' => $b['trialExpiresAt'] ?? null, 'subscriptionStatus' => $b['subscriptionStatus'] ?? null, 'currentPeriodStart' => $b['currentPeriodStart'] ?? null, 'currentPeriodEnd' => $b['currentPeriodEnd'] ?? null, 'cancellationDate' => $b['cancellationDate'] ?? null, // Hero number: total remaining across all pools 'usage' => $vasp_usage, 'computedAtUtc' => $b['computedAtUtc'] ?? null, 'conversationsRemaining' => (int) ($vasp_usage['remaining'] ?? 0), // Subscription pool 'subscriptionAllocation' => (int) ($vasp_subscription_usage['allocated'] ?? 0), 'subscriptionUnits' => (int) ($vasp_subscription_usage['remaining'] ?? 0), 'subscriptionUsed' => (int) ($vasp_subscription_usage['used'] ?? 0), // Addon / trial pool 'totalAddonUnits' => (int) ($vasp_addon_usage['allocated'] ?? 0), 'addonUnits' => (int) ($vasp_addon_usage['remaining'] ?? 0), 'addonUsed' => (int) ($vasp_addon_usage['used'] ?? 0), // Plan display details (nominal, from pricing catalog) 'planPrice' => isset($b['planPrice']) ? (float) $b['planPrice'] : null, 'planCurrency' => $b['planCurrency'] ?? null, 'planInterval' => $b['planInterval'] ?? null, 'planDescription' => $b['planDescription'] ?? null, // Nearest addon expiry (FIFO bucket — from ledger projection) 'addonExpiryQty' => isset($vasp_addon_usage['nextExpiryQty']) ? (int) $vasp_addon_usage['nextExpiryQty'] : null, 'addonExpiryDate' => $vasp_addon_usage['nextExpiresAt'] ?? null, ]; set_transient(VASP_TRANSIENT_BILLING_SUMMARY_CACHE, $result, HOUR_IN_SECONDS); $static_cache = $result; return $result; }