__('Your ValueSpace connection needs to be renewed. Please reconnect to continue.', 'valuespace'), VASP_ERROR_MISSING_TOKEN => __('No active ValueSpace connection was found. Please connect to ValueSpace.', 'valuespace'), VASP_ERROR_TOKEN_EXPIRED => __('Your ValueSpace connection has expired. Please reconnect to continue.', 'valuespace'), VASP_ERROR_REFRESH_FAILED => __('Your ValueSpace connection could not be renewed automatically. Please reconnect to continue.', 'valuespace'), VASP_ERROR_NO_REFRESH_TOKEN => __('Your ValueSpace connection cannot be renewed automatically. Please reconnect to continue.', 'valuespace'), VASP_ERROR_RATE_LIMITED => __('Too many sign-in attempts. Please wait a little and try again.', 'valuespace'), // Connection errors VASP_ERROR_CONNECTION_FAILED => __('We are having trouble connecting to ValueSpace AI right now. Please try again shortly.', 'valuespace'), VASP_ERROR_API_ERROR => __('The request could not be completed right now. Please try again later.', 'valuespace'), VASP_ERROR_TIMEOUT => __('The connection to ValueSpace AI timed out. Please try again later.', 'valuespace'), // API transport errors (from api-utils.php) VASP_ERROR_API_REQUEST_FAILED => __('We are having trouble connecting to ValueSpace AI right now. Please try again shortly.', 'valuespace'), VASP_ERROR_API_RESPONSE_ERROR => __('The request could not be completed right now. Please try again later.', 'valuespace'), // Catalog sync errors VASP_ERROR_WC_CATALOG_QUEUE_EXPIRED => __('WooCommerce sync was interrupted before all products were processed. Please start the sync again.', 'valuespace'), VASP_ERROR_WC_CATALOG_SCHEDULE_FAILED => __('WooCommerce sync could not be scheduled. Please try again.', 'valuespace'), // Event delivery errors VASP_ERROR_EVENT_DELIVERY_BUSY => __('Another event delivery is already running. Please wait a moment and try again.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_INTERRUPTED => __('Event delivery was interrupted before it could finish. The events remain queued and will be retried automatically.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_INCOMPLETE_ACKNOWLEDGEMENT => __('Receipt of all events could not be confirmed. The unconfirmed events will be sent again automatically.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_STATE_UPDATE_FAILED => __('WordPress could not save the latest event delivery result. The events will be sent again automatically.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_SCHEDULE_FAILED => __('WordPress could not schedule the next event attempt. Select Send now to try again.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_UNEXPECTED => __('An unexpected error interrupted event delivery. The events remain queued and will be retried automatically.', 'valuespace'), VASP_ERROR_EVENT_DELIVERY_FAILED => __('Event delivery could not be completed. The events remain queued and will be retried automatically.', 'valuespace'), // Configuration errors VASP_ERROR_MISSING_CONFIG => __('Some ValueSpace settings are missing. Please review the plugin settings.', 'valuespace'), VASP_ERROR_INVALID_CREDENTIALS => __('Your saved ValueSpace connection is no longer valid. Please reconnect.', 'valuespace'), VASP_ERROR_MISSING_CREDENTIALS => __('Connection information is missing. Please reconnect using the "Connect to ValueSpace" button.', 'valuespace'), VASP_ERROR_MISSING_ENDPOINT => __('A required ValueSpace service address is missing. Please contact support if this keeps happening.', 'valuespace'), // Registration error codes VASP_ERROR_REGISTRATION_FAILED => __('Could not finish setting up this connection. Please try again later.', 'valuespace'), VASP_ERROR_INVALID_STATE => __('The connection security check did not complete. Please try connecting again.', 'valuespace'), VASP_ERROR_PERMISSION_DENIED => __('You do not have permission to perform this action.', 'valuespace'), // Integration error codes VASP_ERROR_ALREADY_CONNECTED => __('Already connected to ValueSpace.', 'valuespace'), VASP_ERROR_NOT_CONNECTED => __('You must connect to ValueSpace.ai first.', 'valuespace'), VASP_ERROR_ALREADY_ENABLED => __('Integration is already enabled.', 'valuespace'), VASP_ERROR_NOT_ENABLED => __('Integration is not enabled.', 'valuespace'), VASP_ERROR_DISCONNECT_FAILED => __('Could not disconnect from ValueSpace. Please try again.', 'valuespace'), VASP_ERROR_INVALID_PARAMETERS => __('Some required information was missing or invalid. Please check and try again.', 'valuespace'), VASP_ERROR_MISSING_CREDENTIAL_ID => __('Connection information is missing. Please reconnect if this keeps happening.', 'valuespace'), // Security error codes VASP_ERROR_INVALID_DATA => __('Some information could not be processed. Please check and try again.', 'valuespace'), VASP_ERROR_ENCRYPTION_FAILED => __('A secure storage issue occurred. Please try again or contact support.', 'valuespace'), VASP_ERROR_DECRYPTION_FAILED => __('A secure storage issue occurred. Please reconnect or contact support.', 'valuespace'), VASP_ERROR_KEY_UPDATE_FAILED => __('Secure storage could not be updated. Please try again or contact support.', 'valuespace'), // Authorization error codes VASP_ERROR_AUTH_FILE_NOT_FOUND => __('A required sign-in component is missing. Please contact support.', 'valuespace'), VASP_ERROR_PKCE_FUNCTION_NOT_FOUND => __('A required sign-in component is unavailable. Please contact support.', 'valuespace'), VASP_ERROR_PKCE_GENERATION_FAILED => __('Could not prepare secure sign-in. Please try again.', 'valuespace'), VASP_ERROR_NOT_REGISTERED => __('This site is not registered with ValueSpace yet. Please reconnect.', 'valuespace'), // File operation errors VASP_ERROR_FILE_UPLOAD_FAILED => __('File upload failed. Please try again.', 'valuespace'), VASP_ERROR_FILE_TOO_LARGE => __('The uploaded file is too large. Maximum size is {max_size}.', 'valuespace'), VASP_ERROR_INVALID_FILE_TYPE => __('Invalid file type. Allowed types: {allowed_types}.', 'valuespace'), // Database errors VASP_ERROR_DATABASE_ERROR => __('A database error occurred. Please try again later.', 'valuespace'), VASP_ERROR_RECORD_NOT_FOUND => __('The requested record was not found.', 'valuespace'), VASP_ERROR_DUPLICATE_ENTRY => __('This record already exists.', 'valuespace'), // Validation errors VASP_ERROR_VALIDATION_FAILED => __('Please check the information entered and try again.', 'valuespace'), VASP_ERROR_REQUIRED_FIELD => __('The {field} field is required.', 'valuespace'), VASP_ERROR_INVALID_EMAIL => __('Please enter a valid email address.', 'valuespace'), VASP_ERROR_INVALID_URL => __('Please enter a valid URL.', 'valuespace'), // Rate limiting VASP_ERROR_RATE_LIMIT_EXCEEDED => __('Too many requests in a short time. Please try again in {retry_after} seconds.', 'valuespace'), VASP_ERROR_TOO_MANY_REQUESTS => __('Too many requests in a short time. Please wait a moment and try again.', 'valuespace'), // General error codes VASP_ERROR_UNKNOWN_ERROR => __('Something went wrong. Please try again later.', 'valuespace'), // ─── Success / flow messages ───────────────────────────────────────── VASP_MSG_CONNECTED_VALUESPACE => __('Successfully connected to ValueSpace.', 'valuespace'), VASP_MSG_CONNECTED_WORDPRESS => __('WordPress integration completed successfully.', 'valuespace'), VASP_MSG_CONNECTED_WOOCOMMERCE => __('WooCommerce integration completed successfully.', 'valuespace'), VASP_MSG_WOOCOMMERCE_UPTODATE => __('WooCommerce catalog is already up to date.', 'valuespace'), VASP_MSG_WOOCOMMERCE_CATALOG_IN_PROGRESS => __('Your catalog update is continuing in the background.', 'valuespace'), VASP_MSG_DISCONNECTED_WORDPRESS => __('WordPress disconnected successfully.', 'valuespace'), VASP_MSG_DISCONNECTED_WOOCOMMERCE => __('WooCommerce disconnected successfully.', 'valuespace'), VASP_MSG_WORKFLOW_SUCCESS => __('Integration setup completed successfully.', 'valuespace'), VASP_MSG_RESET_SUCCESS => __('ValueSpace connection has been reset successfully.', 'valuespace'), VASP_MSG_WOOCOMMERCE_DENIED => __('WooCommerce integration was not completed. You can try again when ready.', 'valuespace'), ]; // Unknown machine codes and upstream strings never become public messages. $message = $messages[$error_code] ?? __('Something went wrong. Please try again. If this keeps happening, contact support.', 'valuespace'); // Replace context variables if any if (!empty($context)) { $public_placeholders = ['max_size', 'allowed_types', 'field', 'retry_after']; foreach ($context as $key => $value) { if (!in_array((string) $key, $public_placeholders, true)) { continue; } $replace_value = ''; if (is_scalar($value)) { $replace_value = sanitize_text_field(substr((string) $value, 0, 200)); } if (!empty($message)) { $message = str_replace('{' . $key . '}', $replace_value, $message); } } } return $message; } /** * Build the small allowlisted data object safe to return with a WP_Error. * * @param array $context Technical log context. * @param array $data Explicit candidate public data. * @return array */ function vasp_error_public_data(array $context = [], array $data = []): array { $allowed = ['status', 'retry_after', 'retryable', 'can_retry', 'integration', 'error_code', 'oauth_error', 'endpoint', 'method', 'step', 'reason', 'transport_reason', 'timeout_seconds', 'image_file', 'validation_field', 'entity_type', 'entity_id']; $candidate = array_merge($context, $data); $public = []; foreach ($allowed as $key) { if (!array_key_exists($key, $candidate) || !is_scalar($candidate[$key])) { continue; } if ($key === 'status' || $key === 'retry_after') { $public[$key] = max(0, (int) $candidate[$key]); } elseif ($key === 'transport_reason') { if (in_array($candidate[$key], ['timeout', 'dns', 'connection', 'tls'], true)) { $public[$key] = $candidate[$key]; } } elseif ($key === 'timeout_seconds') { if (is_numeric($candidate[$key]) && (float) $candidate[$key] >= 1 && (float) $candidate[$key] <= 300 && (float) $candidate[$key] === (float) (int) $candidate[$key] ) { $public[$key] = (int) $candidate[$key]; } } elseif ($key === 'can_retry' || $key === 'retryable') { $public[$key] = (bool) $candidate[$key]; } elseif ($key === 'method') { $method = strtoupper((string) $candidate[$key]); if (in_array($method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], true)) { $public[$key] = $method; } } elseif ($key === 'image_file') { $public[$key] = sanitize_text_field(substr(basename(str_replace('\\', '/', (string) $candidate[$key])), 0, 180)); } else { $public[$key] = sanitize_key((string) $candidate[$key]); } } if (is_array($candidate['supported_schema_versions'] ?? null)) { $public['supported_schema_versions'] = array_slice(array_values(array_unique(array_filter( array_map('absint', $candidate['supported_schema_versions']) ))), 0, 10); } foreach (['image_ids', 'product_ids'] as $id_key) { if (!is_array($candidate[$id_key] ?? null)) { continue; } $public[$id_key] = array_slice(array_values(array_unique(array_filter( array_map('absint', $candidate[$id_key]) ))), 0, 10); } foreach (['image_files', 'entity_ids'] as $list_key) { if (!is_array($candidate[$list_key] ?? null)) { continue; } $public[$list_key] = array_slice(array_values(array_unique(array_filter(array_map( static function ($value) use ($list_key): string { $value = $list_key === 'image_files' ? basename(str_replace('\\', '/', (string) $value)) : (string) $value; return sanitize_text_field(substr($value, 0, $list_key === 'image_files' ? 180 : 80)); }, $candidate[$list_key] )))), 0, 10); } return $public; } /** * Return whether an authentication error proves that recovery is impossible. * * OAuth error names are terminal only when the authorization server returned * them with HTTP 400 or 401. The same text on a proxy/server failure is not a * credential verdict. Local credential-state errors remain terminal. * * @param WP_Error $error Authentication or token-refresh failure. * @return bool */ function vasp_is_terminal_auth_error(WP_Error $error): bool { $data = (array) $error->get_error_data(); $code = sanitize_key((string) $error->get_error_code()); $status = (int) ($data['status'] ?? 0); $oauth_error = sanitize_key((string) ($data['oauth_error'] ?? '')); $terminal_oauth_errors = ['invalid_grant', 'invalid_client', 'unauthorized_client']; $terminal_local_codes = [ VASP_ERROR_INVALID_TOKEN, VASP_ERROR_MISSING_TOKEN, VASP_ERROR_NO_REFRESH_TOKEN, VASP_ERROR_INVALID_CREDENTIALS, VASP_ERROR_MISSING_CREDENTIALS, VASP_ERROR_ENCRYPTION_FAILED, VASP_ERROR_DECRYPTION_FAILED, VASP_ERROR_KEY_UPDATE_FAILED, ]; return (in_array($status, [400, 401], true) && in_array($oauth_error, $terminal_oauth_errors, true)) || in_array($code, $terminal_local_codes, true) || (($data['can_retry'] ?? true) === false); } /** * Build a safe, actionable authentication notice without exposing upstream text. * * @param WP_Error $error Authentication or token-refresh failure. * @return array{title:string,description:string,type:string,actions:array,can_retry:bool} */ function vasp_format_auth_error_notice(WP_Error $error): array { $can_retry = !vasp_is_terminal_auth_error($error); if ($can_retry) { return [ 'title' => __('ValueSpace connection could not be renewed', 'valuespace'), 'description' => __('Automatic renewal of the saved connection will be retried.', 'valuespace'), 'type' => 'warning', 'actions' => [ [ 'label' => __('Open System Info', 'valuespace'), 'url' => admin_url('admin.php?page=valuespace-info'), 'style' => 'secondary', ], ], 'can_retry' => true, ]; } return [ 'title' => __('ValueSpace connection needs attention', 'valuespace'), 'description' => __('Reconnect ValueSpace to restore the saved connection.', 'valuespace'), 'type' => 'error', 'actions' => [ [ 'label' => __('Reconnect ValueSpace', 'valuespace'), 'url' => admin_url('admin.php?page=valuespace'), 'style' => 'primary', ], ], 'can_retry' => false, ]; } /** * Format error for API response * * @param string $error_code Error code * @param array $context Optional context variables * @param int $status_code HTTP status code * @return array Formatted error response */ function vasp_format_error_response($error_code, $context = [], $status_code = 400) { return [ 'code' => $error_code, 'message' => vasp_get_error_message($error_code, $context), 'status' => $status_code, ]; } /** * Log error and return formatted message * * @param string $error_code Error code * @param array $context Optional context variables * @param bool $store_as_connection_error Whether to store as connection error * @return string User-friendly error message */ function vasp_handle_error($error_code, $context = [], $store_as_connection_error = false) { $message = vasp_get_error_message($error_code, $context); // Keep the compatibility argument, but logging and persistent integration // state are separate responsibilities. The old fourth logger argument was // never part of the logger contract. unset($store_as_connection_error); vasp_log('ValueSpace operation failed', 'error', array_merge(['error_code' => $error_code], $context)); return $message; } /** * Display a settings error message if in admin context * * @param string $setting The slug-name of the setting to which this error applies * @param string $code Slug-name to identify the error * @param string $message The formatted message text to display * @param string $type Optional. Message type, controls HTML class. 'error', 'success', 'warning', 'info' * @return bool True if the error was added, false if not in admin or add_settings_error doesn't exist */ function vasp_add_settings_error($setting, $code, $message, $type = 'error') { if (function_exists('add_settings_error') && is_admin()) { add_settings_error($setting, $code, $message, $type); return true; } return false; } /** * Create a WP_Error object using centralized error codes * * @param string $error_code One of the VASP_ERROR_* constants * @param array $context Optional context variables for the error message * @param array $data Optional additional data to include in the error * @param bool $log_error Whether construction owns the error log entry * @return WP_Error WordPress error object */ function vasp_create_error($error_code, $context = [], $data = [], $log_error = true) { // Get the user-friendly error message $message = vasp_get_error_message($error_code, $context); // Log a stable event rather than the translated public message. The logger // applies recursive redaction to compatibility context supplied by callers. $log_facts = vasp_error_public_data(is_array($context) ? $context : [], is_array($data) ? $data : []); $log_facts = array_intersect_key($log_facts, array_fill_keys([ 'status', 'error_code', 'oauth_error', 'endpoint', 'method', 'step', 'reason', 'transport_reason', 'timeout_seconds', ], true)); if (empty($log_facts['error_code'])) { $log_facts['error_code'] = sanitize_key((string) $error_code); } if ($log_facts['error_code'] !== sanitize_key((string) $error_code)) { $log_facts['wrapper_code'] = sanitize_key((string) $error_code); } if ($log_error) { vasp_log('ValueSpace operation failed', 'error', $log_facts); } // Returned data is intentionally separate from technical log context. $error_data = vasp_error_public_data(is_array($context) ? $context : [], is_array($data) ? $data : []); return new WP_Error($error_code, $message, $error_data); }