This commit is contained in:
Javier Casares 2026-06-09 12:52:52 +00:00
commit 19ef0566df
610 changed files with 21958 additions and 3112 deletions

View file

@ -1,3 +1,11 @@
= 2.1.3 =
* Fixed nonce handling in manual quota refresh to correctly handle false values returned by filter_input().
* Fixed admin notices display to skip non-array notice entries.
* Fixed input normalization for recipients, attachments, and headers to properly skip non-string values instead of attempting unsafe casts.
* Removed unused internal method (dead code cleanup).
* Updated compatibility: tested up to WordPress 7.1.
= 2.1.2 = = 2.1.2 =
* Fixed charset encoding issue that caused "expected parameter value, got null" error when sending emails through Amazon SES. * Fixed charset encoding issue that caused "expected parameter value, got null" error when sending emails through Amazon SES.

400
class-robotstxt-updater.php Normal file
View file

@ -0,0 +1,400 @@
<?php
/**
* Generic JSON-based updater for ROBOTSTXT plugins.
*
* This file is designed to be copied to any ROBOTSTXT plugin.
* It auto-configures itself by reading the plugin headers.
*
* @package ROBOTSTXT
* @version 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Robotstxt_Updater' ) ) {
/**
* Class Robotstxt_Updater
*
* Generic updater that works with any plugin.
* Reads plugin headers and constructs update URL automatically.
*/
class Robotstxt_Updater {
/**
* Plugin file path.
*
* @var string
*/
private string $plugin_file_path;
/**
* Plugin basename (e.g., 'my-plugin/my-plugin.php').
*
* @var string
*/
private string $plugin_basename;
/**
* Plugin slug (directory name).
*
* @var string
*/
private string $plugin_slug;
/**
* Remote JSON URL.
*
* @var string
*/
private string $json_url;
/**
* Cache key.
*
* @var string
*/
private string $cache_key;
/**
* Plugin headers.
*
* @var array<string, string|bool>
*/
private array $plugin_data;
/**
* Initialize the updater.
*
* Usage in your main plugin file:
* require_once __DIR__ . '/robotstxt-updater.php';
* Robotstxt_Updater::init( __FILE__ );
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
public static function init( string $plugin_file_path ): void {
$instance = new self( $plugin_file_path );
$instance->register();
}
/**
* Constructor.
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
private function __construct( string $plugin_file_path ) {
$this->plugin_file_path = $plugin_file_path;
$this->plugin_basename = plugin_basename( $plugin_file_path );
$this->plugin_slug = dirname( $this->plugin_basename );
$this->plugin_data = $this->get_plugin_data();
$this->json_url = $this->build_json_url();
$this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename );
}
/**
* Register WordPress hooks.
*/
private function register(): void {
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) );
add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 );
add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) );
}
/**
* Get plugin headers.
*
* @return array<string, string|bool> Plugin data.
*/
private function get_plugin_data(): array {
if ( ! function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
return get_plugin_data( $this->plugin_file_path, false, false );
}
/**
* Build JSON URL from plugin headers.
*
* Tries to use "Gitea Plugin URI" header to construct the URL.
* Falls back to Plugin URI if Gitea URI is not available.
*
* @return string JSON URL.
*/
private function build_json_url(): string {
// Try Gitea Plugin URI (format: "OWNER/REPO" or full URL).
$gitea_uri_raw = $this->plugin_data['Gitea Plugin URI'] ?? '';
if ( ! empty( $gitea_uri_raw ) && is_string( $gitea_uri_raw ) ) {
$gitea_uri = $gitea_uri_raw;
// If it's already a full URL, use it.
if ( str_starts_with( $gitea_uri, 'http' ) ) {
// Extract base URL and construct JSON path.
return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json';
}
// If it's in format "OWNER/REPO", construct full URL.
if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) {
return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json";
}
}
// Fallback: try to extract from Plugin URI.
$plugin_uri_raw = $this->plugin_data['PluginURI'] ?? '';
if ( ! empty( $plugin_uri_raw ) && is_string( $plugin_uri_raw ) ) {
$plugin_uri = $plugin_uri_raw;
if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) {
return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json';
}
}
// Last resort: construct from plugin slug.
return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json";
}
/**
* Inject update info into WP's plugin update transient.
*
* @param object|mixed $transient The update_plugins transient.
*
* @return object The modified transient.
*/
public function inject_update_info( $transient ) {
if ( ! $transient instanceof stdClass ) {
$transient = new stdClass();
}
if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) {
return $transient;
}
if ( empty( $transient->checked[ $this->plugin_basename ] ) ) {
return $transient;
}
$current_version_raw = $transient->checked[ $this->plugin_basename ] ?? '';
$current_version = is_string( $current_version_raw ) ? $current_version_raw : '';
$remote = $this->get_remote_data();
$remote_version = isset( $remote['version'] ) && is_string( $remote['version'] ) ? $remote['version'] : '';
$remote_download = isset( $remote['download_url'] ) && is_string( $remote['download_url'] ) ? $remote['download_url'] : '';
if ( '' === $remote_version || '' === $remote_download ) {
return $transient;
}
if ( ! $this->is_compatible( $remote ) ) {
return $transient;
}
if ( version_compare( $remote_version, $current_version, '>' ) ) {
$plugin_uri = $this->plugin_data['PluginURI'] ?? '';
$update = (object) array(
'slug' => isset( $remote['slug'] ) && is_string( $remote['slug'] ) ? $remote['slug'] : $this->plugin_slug,
'plugin' => $this->plugin_basename,
'new_version' => $remote_version,
'url' => isset( $remote['homepage'] ) && is_string( $remote['homepage'] ) ? $remote['homepage'] : ( is_string( $plugin_uri ) ? $plugin_uri : '' ),
'package' => $remote_download,
'tested' => isset( $remote['tested'] ) && is_string( $remote['tested'] ) ? $remote['tested'] : '',
'requires' => isset( $remote['requires'] ) && is_string( $remote['requires'] ) ? $remote['requires'] : '',
'requires_php' => isset( $remote['requires_php'] ) && is_string( $remote['requires_php'] ) ? $remote['requires_php'] : '',
);
$transient->response[ $this->plugin_basename ] = $update;
}
return $transient;
}
/**
* Provide "View details" modal content.
*
* @param false|object|array<string, mixed> $result The result object or array.
* @param string $action The type of information being requested.
* @param object $args Plugin API arguments.
*
* @return false|object|array<string, mixed>
*/
public function provide_plugin_details( $result, string $action, object $args ) {
if ( 'plugin_information' !== $action ) {
return $result;
}
if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) {
return $result;
}
$remote = $this->get_remote_data();
$remote_version = isset( $remote['version'] ) && is_string( $remote['version'] ) ? $remote['version'] : '';
if ( '' === $remote_version ) {
return $result;
}
$pd_name = $this->plugin_data['Name'] ?? '';
$pd_author = $this->plugin_data['Author'] ?? '';
$pd_plugin_uri = $this->plugin_data['PluginURI'] ?? '';
$pd_description = $this->plugin_data['Description'] ?? '';
return (object) array(
'name' => isset( $remote['name'] ) && is_string( $remote['name'] ) ? $remote['name'] : ( is_string( $pd_name ) ? $pd_name : $this->plugin_slug ),
'slug' => isset( $remote['slug'] ) && is_string( $remote['slug'] ) ? $remote['slug'] : $this->plugin_slug,
'version' => $remote_version,
'author' => isset( $remote['author'] ) && is_string( $remote['author'] ) ? $remote['author'] : ( is_string( $pd_author ) ? $pd_author : '' ),
'homepage' => isset( $remote['homepage'] ) && is_string( $remote['homepage'] ) ? $remote['homepage'] : ( is_string( $pd_plugin_uri ) ? $pd_plugin_uri : '' ),
'requires' => isset( $remote['requires'] ) && is_string( $remote['requires'] ) ? $remote['requires'] : '',
'tested' => isset( $remote['tested'] ) && is_string( $remote['tested'] ) ? $remote['tested'] : '',
'requires_php' => isset( $remote['requires_php'] ) && is_string( $remote['requires_php'] ) ? $remote['requires_php'] : '',
'sections' => array(
'description' => isset( $remote['description'] ) && is_string( $remote['description'] ) ? $remote['description'] : ( is_string( $pd_description ) ? $pd_description : '' ),
'changelog' => isset( $remote['changelog'] ) && is_string( $remote['changelog'] ) ? $remote['changelog'] : '',
),
'download_link' => isset( $remote['download_url'] ) && is_string( $remote['download_url'] ) ? $remote['download_url'] : '',
);
}
/**
* Get remote data with caching and HMAC signature verification.
*
* @return array<string, mixed> Remote data.
*/
private function get_remote_data(): array {
$cached = get_site_transient( $this->cache_key );
// Verify HMAC signature if AUTH_SALT is defined and cache has signature.
if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) {
$expected_sig = hash_hmac( 'sha256', $this->cache_key . wp_json_encode( $cached['data'] ), AUTH_SALT );
if ( hash_equals( $expected_sig, $cached['signature'] ) ) {
// Signature valid, return data.
return is_array( $cached['data'] ) ? $cached['data'] : array();
}
// Signature invalid, delete corrupted cache.
delete_site_transient( $this->cache_key );
$cached = false;
}
}
// If no valid cache, fetch fresh data.
if ( false === $cached ) {
$remote = $this->fetch_json();
// Store with HMAC signature if AUTH_SALT is available.
if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
$remote_data = ! empty( $remote ) ? $remote : array();
$payload = array(
'data' => $remote_data,
'timestamp' => time(),
'signature' => hash_hmac( 'sha256', $this->cache_key . wp_json_encode( $remote_data ), AUTH_SALT ),
);
set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS );
} else {
// Fallback to standard caching.
set_site_transient( $this->cache_key, ( ! empty( $remote ) ? $remote : array() ), 6 * HOUR_IN_SECONDS );
}
return $remote;
}
// Legacy cache format without signature (backward compatibility).
return is_array( $cached ) ? $cached : array();
}
/**
* Fetch JSON from remote URL.
*
* @return array<string, mixed> Decoded JSON data.
*/
private function fetch_json(): array {
$response = wp_remote_get(
$this->json_url,
array(
'timeout' => 10,
'headers' => array(
'Accept' => 'application/json',
),
)
);
if ( is_wp_error( $response ) ) {
return array();
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( $code < 200 || $code >= 300 ) {
return array();
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
return is_array( $data ) ? $data : array();
}
/**
* Check compatibility.
*
* @param array<string, mixed> $remote Remote data.
*
* @return bool True if compatible.
*/
private function is_compatible( array $remote ): bool {
$requires_php = isset( $remote['requires_php'] ) && is_string( $remote['requires_php'] ) ? $remote['requires_php'] : '';
if ( '' !== $requires_php ) {
if ( version_compare( PHP_VERSION, $requires_php, '<' ) ) {
return false;
}
}
$requires = isset( $remote['requires'] ) && is_string( $remote['requires'] ) ? $remote['requires'] : '';
if ( '' !== $requires ) {
if ( version_compare( get_bloginfo( 'version' ), $requires, '<' ) ) {
return false;
}
}
return true;
}
/**
* Handle manual cache clear via URL parameter.
*/
public function handle_cache_clear(): void {
// Check if this is a cache clear request first.
$clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW );
if ( null === $clear_cache ) {
return;
}
// This is a cache clear request - now verify nonce.
$nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW );
$nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : '';
if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) {
wp_die( esc_html__( 'Security check failed', 'robotstxt-smtp-amazonses' ) );
}
// Check permissions.
if ( ! current_user_can( 'update_plugins' ) ) {
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-smtp-amazonses' ) );
}
$this->clear_cache();
wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) );
exit;
}
/**
* Clear update cache.
*/
public function clear_cache(): void {
delete_site_transient( $this->cache_key );
delete_site_transient( 'update_plugins' );
}
}
}

View file

@ -126,12 +126,10 @@ class Plugin {
$secret_key = (string) ( $settings[ self::OPTION_SECRET_KEY ] ?? '' ); $secret_key = (string) ( $settings[ self::OPTION_SECRET_KEY ] ?? '' );
$region = (string) ( $settings[ self::OPTION_REGION ] ?? '' ); $region = (string) ( $settings[ self::OPTION_REGION ] ?? '' );
if ( '' === $access_key || '' === $secret_key || '' === $region ) { if ( '' === $access_key || '' === $secret_key || '' === $region ) {
return $pre_wp_mail; return $pre_wp_mail;
} }
$mail_data = \wp_parse_args( $mail_data = \wp_parse_args(
$mail_data, $mail_data,
array( array(
@ -198,9 +196,9 @@ class Plugin {
/** /**
* Sends the email data to Amazon SES using the SDK client. * Sends the email data to Amazon SES using the SDK client.
* *
* @param array<string, mixed> $mail_context Normalized mail data. * @param array{to: array<int, string>, subject: string, message: string, headers: mixed, attachments: array<int, string>} $mail_context Normalized mail data.
* @param array<string, mixed> $settings Stored plugin settings. * @param array{host: string, username: string, password: string, from_email: string, from_name: string, reply_to_email: string, reply_to_name: string, security: string, port: int, amazon_ses_access_key: string, amazon_ses_secret_key: string, amazon_ses_region: string, logs_enabled: bool, logs_retention_mode: string, logs_retention_count: int, logs_retention_days: int, stats_retention_days: int, rate_limit_per_second: int, rate_limit_per_hour: int, rate_limit_per_day: int, delete_data_on_uninstall: bool} $settings Stored plugin settings.
* @param array<string, mixed> $parsed_headers Structured header data. * @param array{content_type: string|null, charset: string|null, cc: array<int, string>, bcc: array<int, string>, reply_to: array<int, string>, custom: array<int, array{name: string, value: string}>} $parsed_headers Structured header data.
* @param string $access_key AWS access key ID. * @param string $access_key AWS access key ID.
* @param string $secret_key AWS secret access key. * @param string $secret_key AWS secret access key.
* @param string $region AWS region identifier. * @param string $region AWS region identifier.
@ -314,9 +312,9 @@ class Plugin {
/** /**
* Builds a PHPMailer instance configured with the provided mail data. * Builds a PHPMailer instance configured with the provided mail data.
* *
* @param array<string, mixed> $mail_context Normalized mail data. * @param array{to: array<int, string>, subject: string, message: string, headers: mixed, attachments: array<int, string>} $mail_context Normalized mail data.
* @param array<string, mixed> $settings Stored plugin settings. * @param array{host: string, username: string, password: string, from_email: string, from_name: string, reply_to_email: string, reply_to_name: string, security: string, port: int, amazon_ses_access_key: string, amazon_ses_secret_key: string, amazon_ses_region: string, logs_enabled: bool, logs_retention_mode: string, logs_retention_count: int, logs_retention_days: int, stats_retention_days: int, rate_limit_per_second: int, rate_limit_per_hour: int, rate_limit_per_day: int, delete_data_on_uninstall: bool} $settings Stored plugin settings.
* @param array<string, mixed> $parsed_headers Structured header data. * @param array{content_type: string|null, charset: string|null, cc: array<int, string>, bcc: array<int, string>, reply_to: array<int, string>, custom: array<int, array{name: string, value: string}>} $parsed_headers Structured header data.
* *
* @return PHPMailer|WP_Error * @return PHPMailer|WP_Error
*/ */
@ -326,11 +324,18 @@ class Plugin {
$default_content_type = \apply_filters( 'wp_mail_content_type', 'text/plain' ); $default_content_type = \apply_filters( 'wp_mail_content_type', 'text/plain' );
$default_charset = \apply_filters( 'wp_mail_charset', \get_bloginfo( 'charset' ) ); $default_charset = \apply_filters( 'wp_mail_charset', \get_bloginfo( 'charset' ) );
$content_type = is_string( $parsed_headers['content_type'] ?? '' ) && '' !== $parsed_headers['content_type'] ? $parsed_headers['content_type'] : ( is_string( $default_content_type ) ? $default_content_type : 'text/plain' ); $content_type_header = $parsed_headers['content_type'];
$charset = is_string( $parsed_headers['charset'] ?? '' ) && '' !== $parsed_headers['charset'] ? $parsed_headers['charset'] : ( is_string( $default_charset ) ? $default_charset : 'utf-8' ); $content_type = ( null !== $content_type_header && '' !== $content_type_header )
? $content_type_header
: ( is_string( $default_content_type ) ? $default_content_type : 'text/plain' );
$charset_header = $parsed_headers['charset'];
$charset = ( null !== $charset_header && '' !== $charset_header )
? $charset_header
: ( is_string( $default_charset ) ? $default_charset : 'utf-8' );
// Ensure charset is never empty, null, or the string "null". // Ensure charset is never empty, null, or the string "null".
$charset = \trim( (string) $charset ); $charset = \trim( $charset );
if ( '' === $charset || 'null' === \strtolower( $charset ) ) { if ( '' === $charset || 'null' === \strtolower( $charset ) ) {
$charset = 'utf-8'; $charset = 'utf-8';
} }
@ -538,43 +543,43 @@ class Plugin {
/** /**
* Determines the From email address based on the stored settings and filters. * Determines the From email address based on the stored settings and filters.
* *
* @param array<string, mixed> $settings Stored plugin settings. * @param array{host: string, username: string, password: string, from_email: string, from_name: string, reply_to_email: string, reply_to_name: string, security: string, port: int, amazon_ses_access_key: string, amazon_ses_secret_key: string, amazon_ses_region: string, logs_enabled: bool, logs_retention_mode: string, logs_retention_count: int, logs_retention_days: int, stats_retention_days: int, rate_limit_per_second: int, rate_limit_per_hour: int, rate_limit_per_day: int, delete_data_on_uninstall: bool} $settings Stored plugin settings.
* *
* @return string * @return string
*/ */
private function determine_from_email( array $settings ): string { private function determine_from_email( array $settings ): string {
$default_email = \get_bloginfo( 'admin_email' ); $default_email = \get_bloginfo( 'admin_email' );
if ( isset( $settings['from_email'] ) && \is_email( $settings['from_email'] ) ) { if ( \is_email( $settings['from_email'] ) ) {
$default_email = $settings['from_email']; $default_email = $settings['from_email'];
} }
$filtered = \apply_filters( 'wp_mail_from', $default_email ); $filtered = \apply_filters( 'wp_mail_from', $default_email );
if ( ! \is_email( $filtered ) ) { if ( ! is_string( $filtered ) || ! \is_email( $filtered ) ) {
return (string) $default_email; return $default_email;
} }
return (string) $filtered; return $filtered;
} }
/** /**
* Determines the From name based on stored settings and filters. * Determines the From name based on stored settings and filters.
* *
* @param array<string, mixed> $settings Stored plugin settings. * @param array{host: string, username: string, password: string, from_email: string, from_name: string, reply_to_email: string, reply_to_name: string, security: string, port: int, amazon_ses_access_key: string, amazon_ses_secret_key: string, amazon_ses_region: string, logs_enabled: bool, logs_retention_mode: string, logs_retention_count: int, logs_retention_days: int, stats_retention_days: int, rate_limit_per_second: int, rate_limit_per_hour: int, rate_limit_per_day: int, delete_data_on_uninstall: bool} $settings Stored plugin settings.
* *
* @return string * @return string
*/ */
private function determine_from_name( array $settings ): string { private function determine_from_name( array $settings ): string {
$default_name = \get_bloginfo( 'name', 'display' ); $default_name = \get_bloginfo( 'name', 'display' );
if ( isset( $settings['from_name'] ) && '' !== $settings['from_name'] ) { if ( '' !== $settings['from_name'] ) {
$default_name = $settings['from_name']; $default_name = $settings['from_name'];
} }
$filtered = \apply_filters( 'wp_mail_from_name', $default_name ); $filtered = \apply_filters( 'wp_mail_from_name', $default_name );
return (string) $filtered; return is_string( $filtered ) ? $filtered : $default_name;
} }
/** /**
@ -600,11 +605,11 @@ class Plugin {
$normalized = array(); $normalized = array();
foreach ( $headers as $header ) { foreach ( $headers as $header ) {
if ( is_array( $header ) ) { if ( ! is_string( $header ) ) {
continue; continue;
} }
$line = trim( (string) $header ); $line = trim( $header );
if ( '' !== $line ) { if ( '' !== $line ) {
$normalized[] = $line; $normalized[] = $line;
@ -619,7 +624,14 @@ class Plugin {
* *
* @param array<int, string> $headers Normalized header lines. * @param array<int, string> $headers Normalized header lines.
* *
* @return array<string, mixed> * @return array{
* content_type: string|null,
* charset: string|null,
* cc: array<int, string>,
* bcc: array<int, string>,
* reply_to: array<int, string>,
* custom: array<int, array{name: string, value: string}>
* }
*/ */
private function parse_headers( array $headers ): array { private function parse_headers( array $headers ): array {
$parsed = array( $parsed = array(
@ -701,17 +713,17 @@ class Plugin {
} }
if ( ! is_array( $recipients ) ) { if ( ! is_array( $recipients ) ) {
$recipients = explode( ',', (string) $recipients ); $recipients = is_string( $recipients ) ? explode( ',', $recipients ) : array();
} }
$normalized = array(); $normalized = array();
foreach ( $recipients as $recipient ) { foreach ( $recipients as $recipient ) {
if ( is_array( $recipient ) ) { if ( ! is_string( $recipient ) ) {
continue; continue;
} }
$address = trim( (string) $recipient ); $address = trim( $recipient );
if ( '' !== $address ) { if ( '' !== $address ) {
$normalized[] = $address; $normalized[] = $address;
@ -740,11 +752,11 @@ class Plugin {
$normalized = array(); $normalized = array();
foreach ( $attachments as $attachment ) { foreach ( $attachments as $attachment ) {
if ( is_array( $attachment ) ) { if ( ! is_string( $attachment ) ) {
continue; continue;
} }
$path = trim( (string) $attachment ); $path = trim( $attachment );
if ( '' !== $path ) { if ( '' !== $path ) {
$normalized[] = $path; $normalized[] = $path;
@ -828,7 +840,6 @@ class Plugin {
public function declare_active( bool $is_active ): bool { public function declare_active( bool $is_active ): bool {
unset( $is_active ); unset( $is_active );
return true; return true;
} }
@ -854,8 +865,12 @@ class Plugin {
\delete_transient( 'robotstxt_smtp_admin_notices' ); \delete_transient( 'robotstxt_smtp_admin_notices' );
foreach ( $notices as $notice ) { foreach ( $notices as $notice ) {
$type = $notice['type'] ?? 'info'; if ( ! is_array( $notice ) ) {
$message = $notice['message'] ?? ''; continue;
}
$type = isset( $notice['type'] ) && is_string( $notice['type'] ) ? $notice['type'] : 'info';
$message = isset( $notice['message'] ) && is_string( $notice['message'] ) ? $notice['message'] : '';
if ( $message ) { if ( $message ) {
printf( printf(
@ -888,7 +903,8 @@ class Plugin {
// This is a refresh quota request - now verify nonce. // This is a refresh quota request - now verify nonce.
$nonce_post = \filter_input( INPUT_POST, 'robotstxt_smtp_refresh_quota_nonce', FILTER_UNSAFE_RAW ); $nonce_post = \filter_input( INPUT_POST, 'robotstxt_smtp_refresh_quota_nonce', FILTER_UNSAFE_RAW );
$nonce_get = \filter_input( INPUT_GET, 'robotstxt_smtp_refresh_quota_nonce', FILTER_UNSAFE_RAW ); $nonce_get = \filter_input( INPUT_GET, 'robotstxt_smtp_refresh_quota_nonce', FILTER_UNSAFE_RAW );
$nonce = $nonce_post ?? $nonce_get ?? ''; $nonce_raw = $nonce_post ?? $nonce_get ?? '';
$nonce = is_string( $nonce_raw ) ? $nonce_raw : '';
if ( ! \wp_verify_nonce( $nonce, 'robotstxt_smtp_refresh_quota' ) ) { if ( ! \wp_verify_nonce( $nonce, 'robotstxt_smtp_refresh_quota' ) ) {
\wp_die( \esc_html__( 'Security check failed.', 'robotstxt-smtp-amazonses' ) ); \wp_die( \esc_html__( 'Security check failed.', 'robotstxt-smtp-amazonses' ) );
@ -1079,8 +1095,6 @@ class Plugin {
public function sanitize_settings( array $clean, array $options, Settings_Page $settings ): array { public function sanitize_settings( array $clean, array $options, Settings_Page $settings ): array {
unset( $settings ); unset( $settings );
// Debug: Log incoming $clean array.
if ( ! SMTP_Plugin::is_amazon_ses_integration_active() ) { if ( ! SMTP_Plugin::is_amazon_ses_integration_active() ) {
return $clean; return $clean;
} }
@ -1094,7 +1108,8 @@ class Plugin {
$credentials_changed = false; $credentials_changed = false;
if ( array_key_exists( self::OPTION_ACCESS_KEY, $options ) ) { if ( array_key_exists( self::OPTION_ACCESS_KEY, $options ) ) {
$submitted_access_key = \trim( (string) $options[ self::OPTION_ACCESS_KEY ] ); $raw_access_key = $options[ self::OPTION_ACCESS_KEY ] ?? null;
$submitted_access_key = \trim( is_string( $raw_access_key ) ? $raw_access_key : '' );
if ( '' !== $submitted_access_key ) { if ( '' !== $submitted_access_key ) {
$sanitized_access_key = \sanitize_text_field( $submitted_access_key ); $sanitized_access_key = \sanitize_text_field( $submitted_access_key );
@ -1108,7 +1123,8 @@ class Plugin {
} }
if ( array_key_exists( self::OPTION_SECRET_KEY, $options ) ) { if ( array_key_exists( self::OPTION_SECRET_KEY, $options ) ) {
$submitted_secret_key = \trim( (string) $options[ self::OPTION_SECRET_KEY ] ); $raw_secret_key = $options[ self::OPTION_SECRET_KEY ] ?? null;
$submitted_secret_key = \trim( is_string( $raw_secret_key ) ? $raw_secret_key : '' );
if ( '' !== $submitted_secret_key ) { if ( '' !== $submitted_secret_key ) {
$sanitized_secret_key = \sanitize_text_field( $submitted_secret_key ); $sanitized_secret_key = \sanitize_text_field( $submitted_secret_key );
@ -1122,7 +1138,8 @@ class Plugin {
} }
if ( array_key_exists( self::OPTION_REGION, $options ) ) { if ( array_key_exists( self::OPTION_REGION, $options ) ) {
$submitted_region = \sanitize_text_field( (string) $options[ self::OPTION_REGION ] ); $raw_region = $options[ self::OPTION_REGION ] ?? null;
$submitted_region = \sanitize_text_field( is_string( $raw_region ) ? $raw_region : '' );
if ( '' === $submitted_region ) { if ( '' === $submitted_region ) {
if ( '' !== $region ) { if ( '' !== $region ) {
@ -1152,10 +1169,6 @@ class Plugin {
$clean[ self::OPTION_SECRET_KEY ] = $secret_key; $clean[ self::OPTION_SECRET_KEY ] = $secret_key;
$clean[ self::OPTION_REGION ] = $region; $clean[ self::OPTION_REGION ] = $region;
// Temporary debug logging
// Debug: Check credentials_changed and values
if ( $credentials_changed && ( '' === $access_key || '' === $secret_key || '' === $region ) ) { if ( $credentials_changed && ( '' === $access_key || '' === $secret_key || '' === $region ) ) {
\add_settings_error( \add_settings_error(
$settings_error_slug, $settings_error_slug,
@ -1197,8 +1210,6 @@ class Plugin {
} }
} }
// Debug: Log final $clean array before return.
return $clean; return $clean;
} }
@ -1206,7 +1217,7 @@ class Plugin {
* Restores the previously stored Amazon SES values in case validation fails. * Restores the previously stored Amazon SES values in case validation fails.
* *
* @param array<string, mixed> $clean Current sanitized values. * @param array<string, mixed> $clean Current sanitized values.
* @param array<string, mixed> $stored_settings Stored settings merged with defaults. * @param array{amazon_ses_access_key: string, amazon_ses_secret_key: string, amazon_ses_region: string, host: string, username: string, password: string, from_email: string, from_name: string, reply_to_email: string, reply_to_name: string, security: string, port: int, logs_enabled: bool, logs_retention_mode: string, logs_retention_count: int, logs_retention_days: int, stats_retention_days: int, rate_limit_per_second: int, rate_limit_per_hour: int, rate_limit_per_day: int, delete_data_on_uninstall: bool} $stored_settings Stored settings merged with defaults.
* *
* @return array<string, mixed> * @return array<string, mixed>
*/ */
@ -1221,7 +1232,29 @@ class Plugin {
/** /**
* Retrieves the stored settings merged with defaults for the active scope. * Retrieves the stored settings merged with defaults for the active scope.
* *
* @return array<string, mixed> * @return array{
* host: string,
* username: string,
* password: string,
* from_email: string,
* from_name: string,
* reply_to_email: string,
* reply_to_name: string,
* security: string,
* port: int,
* amazon_ses_access_key: string,
* amazon_ses_secret_key: string,
* amazon_ses_region: string,
* logs_enabled: bool,
* logs_retention_mode: string,
* logs_retention_count: int,
* logs_retention_days: int,
* stats_retention_days: int,
* rate_limit_per_second: int,
* rate_limit_per_hour: int,
* rate_limit_per_day: int,
* delete_data_on_uninstall: bool
* }
*/ */
private function get_stored_settings(): array { private function get_stored_settings(): array {
$option_name = $this->get_settings_option_name(); $option_name = $this->get_settings_option_name();
@ -1238,16 +1271,43 @@ class Plugin {
$settings = \wp_parse_args( $settings, Settings_Page::get_default_settings() ); $settings = \wp_parse_args( $settings, Settings_Page::get_default_settings() );
$s = (array) $settings;
$access_key = is_string( $s[ self::OPTION_ACCESS_KEY ] ?? null ) ? $s[ self::OPTION_ACCESS_KEY ] : '';
$secret_key = is_string( $s[ self::OPTION_SECRET_KEY ] ?? null ) ? $s[ self::OPTION_SECRET_KEY ] : '';
// Decrypt Amazon SES credentials after loading from database. // Decrypt Amazon SES credentials after loading from database.
if ( isset( $settings[ self::OPTION_ACCESS_KEY ] ) && '' !== $settings[ self::OPTION_ACCESS_KEY ] ) { if ( '' !== $access_key ) {
$settings[ self::OPTION_ACCESS_KEY ] = \Robotstxt_SMTP_Encryption::decrypt( $settings[ self::OPTION_ACCESS_KEY ] ); $access_key = \Robotstxt_SMTP_Encryption::decrypt( $access_key );
} }
if ( isset( $settings[ self::OPTION_SECRET_KEY ] ) && '' !== $settings[ self::OPTION_SECRET_KEY ] ) { if ( '' !== $secret_key ) {
$settings[ self::OPTION_SECRET_KEY ] = \Robotstxt_SMTP_Encryption::decrypt( $settings[ self::OPTION_SECRET_KEY ] ); $secret_key = \Robotstxt_SMTP_Encryption::decrypt( $secret_key );
} }
return $settings; return array(
'host' => is_string( $s['host'] ?? null ) ? $s['host'] : '',
'username' => is_string( $s['username'] ?? null ) ? $s['username'] : '',
'password' => is_string( $s['password'] ?? null ) ? $s['password'] : '',
'from_email' => is_string( $s['from_email'] ?? null ) ? $s['from_email'] : '',
'from_name' => is_string( $s['from_name'] ?? null ) ? $s['from_name'] : '',
'reply_to_email' => is_string( $s['reply_to_email'] ?? null ) ? $s['reply_to_email'] : '',
'reply_to_name' => is_string( $s['reply_to_name'] ?? null ) ? $s['reply_to_name'] : '',
'security' => is_string( $s['security'] ?? null ) ? $s['security'] : 'none',
'port' => is_int( $s['port'] ?? null ) ? $s['port'] : 25,
self::OPTION_ACCESS_KEY => $access_key,
self::OPTION_SECRET_KEY => $secret_key,
self::OPTION_REGION => is_string( $s[ self::OPTION_REGION ] ?? null ) ? $s[ self::OPTION_REGION ] : '',
'logs_enabled' => is_bool( $s['logs_enabled'] ?? null ) ? $s['logs_enabled'] : false,
'logs_retention_mode' => is_string( $s['logs_retention_mode'] ?? null ) ? $s['logs_retention_mode'] : 'count',
'logs_retention_count' => is_int( $s['logs_retention_count'] ?? null ) ? $s['logs_retention_count'] : 1024,
'logs_retention_days' => is_int( $s['logs_retention_days'] ?? null ) ? $s['logs_retention_days'] : 28,
'stats_retention_days' => is_int( $s['stats_retention_days'] ?? null ) ? $s['stats_retention_days'] : 28,
'rate_limit_per_second' => is_int( $s['rate_limit_per_second'] ?? null ) ? $s['rate_limit_per_second'] : 0,
'rate_limit_per_hour' => is_int( $s['rate_limit_per_hour'] ?? null ) ? $s['rate_limit_per_hour'] : 0,
'rate_limit_per_day' => is_int( $s['rate_limit_per_day'] ?? null ) ? $s['rate_limit_per_day'] : 0,
'delete_data_on_uninstall' => is_bool( $s['delete_data_on_uninstall'] ?? null ) ? $s['delete_data_on_uninstall'] : false,
);
} }
/** /**
@ -1303,7 +1363,7 @@ class Plugin {
$regions = $partition->getAvailableEndpoints( 'ses' ); $regions = $partition->getAvailableEndpoints( 'ses' );
foreach ( $regions as $region ) { foreach ( $regions as $region ) {
if ( is_string( $region ) && '' !== $region ) { if ( '' !== $region ) {
$discovered_list[ $region ] = $labels[ $region ] ?? $this->format_region_label( $region ); $discovered_list[ $region ] = $labels[ $region ] ?? $this->format_region_label( $region );
} }
} }
@ -1561,17 +1621,21 @@ class Plugin {
$send_quota = $result->get( 'SendQuota' ); $send_quota = $result->get( 'SendQuota' );
if ( ! $send_quota ) { if ( ! is_array( $send_quota ) ) {
return new WP_Error( return new WP_Error(
'no_quota_data', 'no_quota_data',
__( 'Amazon SES did not return quota data.', 'robotstxt-smtp-amazonses' ) __( 'Amazon SES did not return quota data.', 'robotstxt-smtp-amazonses' )
); );
} }
$raw_max_24 = $send_quota['Max24HourSend'] ?? 0;
$raw_rate = $send_quota['MaxSendRate'] ?? 0;
$raw_sent_24 = $send_quota['SentLast24Hours'] ?? 0;
return array( return array(
'max_24_hour_send' => (int) ( $send_quota['Max24HourSend'] ?? 0 ), 'max_24_hour_send' => is_numeric( $raw_max_24 ) ? (int) $raw_max_24 : 0,
'max_send_rate' => (float) ( $send_quota['MaxSendRate'] ?? 0 ), 'max_send_rate' => is_numeric( $raw_rate ) ? (float) $raw_rate : 0.0,
'sent_last_24_hours' => (int) ( $send_quota['SentLast24Hours'] ?? 0 ), 'sent_last_24_hours' => is_numeric( $raw_sent_24 ) ? (int) $raw_sent_24 : 0,
'fetched_at' => time(), 'fetched_at' => time(),
); );
@ -1606,56 +1670,6 @@ class Plugin {
} }
} }
/**
* Applies SES quota limits to the SMTP plugin rate limiting settings.
*
* @since 1.0.1
*
* @param array<string, mixed> $quota Quota data from SES.
* @return void
*/
private function apply_ses_quota_to_rate_limits( array $quota ): void {
$max_send_rate = (float) ( $quota['max_send_rate'] ?? 0 );
$max_24_hour_send = (int) ( $quota['max_24_hour_send'] ?? 0 );
$settings_page = \Robotstxt_SMTP\Admin\Settings_Page::class;
if ( ! class_exists( $settings_page ) ) {
return;
}
$is_network = ROBOTSTXT_SMTP_IS_MULTISITE && $settings_page::is_network_mode_enabled();
$option_name = $is_network ? $settings_page::NETWORK_OPTION_NAME : $settings_page::OPTION_NAME;
$settings = $is_network ? get_site_option( $option_name, array() ) : get_option( $option_name, array() );
if ( ! is_array( $settings ) ) {
$settings = array();
}
$settings['rate_limit_per_second'] = (int) floor( $max_send_rate );
$settings['rate_limit_per_hour'] = (int) floor( $max_send_rate * 3600 * 0.9 );
$settings['rate_limit_per_day'] = $max_24_hour_send;
if ( $is_network ) {
update_site_option( $option_name, $settings );
} else {
update_option( $option_name, $settings );
}
if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log(
sprintf(
'ROBOTSTXT SMTP: Updated rate limits from Amazon SES quota - Per second: %d, Per hour: %d, Per day: %d',
$settings['rate_limit_per_second'],
$settings['rate_limit_per_hour'],
$settings['rate_limit_per_day']
)
);
}
}
/** /**
* Gets the transient cache key for Amazon SES quota data. * Gets the transient cache key for Amazon SES quota data.
* *
@ -1682,9 +1696,10 @@ class Plugin {
* *
* @since 1.0.1 * @since 1.0.1
* *
* @return array<string, mixed>|false Quota data or false if not cached. * @return array<string|int, mixed>|false Quota data or false if not cached.
*/ */
public function get_cached_ses_quota() { public function get_cached_ses_quota(): array|false {
return get_site_transient( self::get_quota_cache_key() ); $result = \get_site_transient( self::get_quota_cache_key() );
return is_array( $result ) ? $result : false;
} }
} }

View file

@ -2,10 +2,10 @@
Contributors: javiercasares Contributors: javiercasares
Tags: amazon-ses, smtp, email, mail Tags: amazon-ses, smtp, email, mail
Requires at least: 6.5 Requires at least: 6.5
Tested up to: 6.9 Tested up to: 7.1
Stable tag: 2.1.2 Stable tag: 2.1.3
Requires PHP: 8.2 Requires PHP: 8.2
Version: 2.1.2 Version: 2.1.3
License: GPL-3.0-or-later License: GPL-3.0-or-later
License URI: https://www.gnu.org/licenses/gpl-3.0.html License URI: https://www.gnu.org/licenses/gpl-3.0.html
@ -46,6 +46,14 @@ Yes. Network administrators can manage credentials centrally or allow individual
== Changelog == == Changelog ==
= 2.1.3 =
* Fixed nonce handling in manual quota refresh to correctly handle false values returned by filter_input().
* Fixed admin notices display to skip non-array notice entries.
* Fixed input normalization for recipients, attachments, and headers to properly skip non-string values instead of attempting unsafe casts.
* Removed unused internal method (dead code cleanup).
* Updated compatibility: tested up to WordPress 7.1.
* Internal: renamed updater file to follow WordPress naming conventions.
= 2.1.2 = = 2.1.2 =
* Fixed charset encoding issue that caused "expected parameter value, got null" error when sending emails through Amazon SES. * Fixed charset encoding issue that caused "expected parameter value, got null" error when sending emails through Amazon SES.
* Added robust charset validation in header parsing to prevent empty or invalid charset values. * Added robust charset validation in header parsing to prevent empty or invalid charset values.

View file

@ -3,7 +3,7 @@
* Plugin Name: SMTP (by ROBOTSTXT) Amazon SES * Plugin Name: SMTP (by ROBOTSTXT) Amazon SES
* Plugin URI: https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses * Plugin URI: https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses
* Description: Adds Amazon SES configuration support to the ROBOTSTXT SMTP plugin. * Description: Adds Amazon SES configuration support to the ROBOTSTXT SMTP plugin.
* Version: 2.1.2 * Version: 2.1.3
* Requires at least: 6.5 * Requires at least: 6.5
* Requires PHP: 8.2 * Requires PHP: 8.2
* Network: true * Network: true
@ -26,7 +26,7 @@ if ( ! defined( 'ABSPATH' ) ) {
} }
if ( ! defined( 'ROBOTSTXT_SMTP_AMAZONSES_VERSION' ) ) { if ( ! defined( 'ROBOTSTXT_SMTP_AMAZONSES_VERSION' ) ) {
define( 'ROBOTSTXT_SMTP_AMAZONSES_VERSION', '2.1.2' ); define( 'ROBOTSTXT_SMTP_AMAZONSES_VERSION', '2.1.3' );
} }
if ( ! defined( 'ROBOTSTXT_SMTP_AMAZONSES_FILE' ) ) { if ( ! defined( 'ROBOTSTXT_SMTP_AMAZONSES_FILE' ) ) {
@ -62,5 +62,5 @@ require_once ROBOTSTXT_SMTP_AMAZONSES_PATH . 'includes/class-plugin.php';
\Robotstxt_SMTP_AmazonSES\Plugin::get_instance()->run(); \Robotstxt_SMTP_AmazonSES\Plugin::get_instance()->run();
// Initialize ROBOTSTXT updater (auto-configures from plugin headers). // Initialize ROBOTSTXT updater (auto-configures from plugin headers).
require_once __DIR__ . '/robotstxt-updater.php'; require_once __DIR__ . '/class-robotstxt-updater.php';
Robotstxt_Updater::init( __FILE__ ); Robotstxt_Updater::init( __FILE__ );

View file

@ -1,383 +0,0 @@
<?php
/**
* Generic JSON-based updater for ROBOTSTXT plugins.
*
* This file is designed to be copied to any ROBOTSTXT plugin.
* It auto-configures itself by reading the plugin headers.
*
* @package ROBOTSTXT
* @version 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Robotstxt_Updater' ) ) {
/**
* Class Robotstxt_Updater
*
* Generic updater that works with any plugin.
* Reads plugin headers and constructs update URL automatically.
*/
class Robotstxt_Updater {
/**
* Plugin file path.
*
* @var string
*/
private string $plugin_file_path;
/**
* Plugin basename (e.g., 'my-plugin/my-plugin.php').
*
* @var string
*/
private string $plugin_basename;
/**
* Plugin slug (directory name).
*
* @var string
*/
private string $plugin_slug;
/**
* Remote JSON URL.
*
* @var string
*/
private string $json_url;
/**
* Cache key.
*
* @var string
*/
private string $cache_key;
/**
* Plugin headers.
*
* @var array
*/
private array $plugin_data;
/**
* Initialize the updater.
*
* Usage in your main plugin file:
* require_once __DIR__ . '/robotstxt-updater.php';
* Robotstxt_Updater::init( __FILE__ );
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
public static function init( string $plugin_file_path ): void {
$instance = new self( $plugin_file_path );
$instance->register();
}
/**
* Constructor.
*
* @param string $plugin_file_path Absolute path to the main plugin file.
*/
private function __construct( string $plugin_file_path ) {
$this->plugin_file_path = $plugin_file_path;
$this->plugin_basename = plugin_basename( $plugin_file_path );
$this->plugin_slug = dirname( $this->plugin_basename );
$this->plugin_data = $this->get_plugin_data();
$this->json_url = $this->build_json_url();
$this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename );
}
/**
* Register WordPress hooks.
*/
private function register(): void {
add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) );
add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 );
add_action( 'admin_init', array( $this, 'handle_cache_clear' ) );
add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) );
}
/**
* Get plugin headers.
*
* @return array Plugin data.
*/
private function get_plugin_data(): array {
if ( ! function_exists( 'get_plugin_data' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
return get_plugin_data( $this->plugin_file_path, false, false );
}
/**
* Build JSON URL from plugin headers.
*
* Tries to use "Gitea Plugin URI" header to construct the URL.
* Falls back to Plugin URI if Gitea URI is not available.
*
* @return string JSON URL.
*/
private function build_json_url(): string {
// Try Gitea Plugin URI (format: "OWNER/REPO" or full URL).
if ( ! empty( $this->plugin_data['Gitea Plugin URI'] ) ) {
$gitea_uri = $this->plugin_data['Gitea Plugin URI'];
// If it's already a full URL, use it.
if ( str_starts_with( $gitea_uri, 'http' ) ) {
// Extract base URL and construct JSON path.
return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json';
}
// If it's in format "OWNER/REPO", construct full URL.
if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) {
return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json";
}
}
// Fallback: try to extract from Plugin URI.
if ( ! empty( $this->plugin_data['PluginURI'] ) ) {
$plugin_uri = $this->plugin_data['PluginURI'];
if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) {
return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json';
}
}
// Last resort: construct from plugin slug.
return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json";
}
/**
* Inject update info into WP's plugin update transient.
*
* @param object|mixed $transient The update_plugins transient.
*
* @return object The modified transient.
*/
public function inject_update_info( $transient ) {
if ( ! is_object( $transient ) ) {
$transient = new stdClass();
}
if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) {
return $transient;
}
if ( empty( $transient->checked[ $this->plugin_basename ] ) ) {
return $transient;
}
$current_version = $transient->checked[ $this->plugin_basename ];
$remote = $this->get_remote_data();
if ( empty( $remote['version'] ) || empty( $remote['download_url'] ) ) {
return $transient;
}
if ( ! $this->is_compatible( $remote ) ) {
return $transient;
}
if ( version_compare( $remote['version'], $current_version, '>' ) ) {
$update = (object) array(
'slug' => $remote['slug'] ?? $this->plugin_slug,
'plugin' => $this->plugin_basename,
'new_version' => $remote['version'],
'url' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
'package' => $remote['download_url'],
'tested' => $remote['tested'] ?? '',
'requires' => $remote['requires'] ?? '',
'requires_php' => $remote['requires_php'] ?? '',
);
$transient->response[ $this->plugin_basename ] = $update;
}
return $transient;
}
/**
* Provide "View details" modal content.
*
* @param false|object|array $result The result object or array.
* @param string $action The type of information being requested.
* @param object $args Plugin API arguments.
*
* @return false|object The plugin information object or false.
*/
public function provide_plugin_details( $result, string $action, object $args ) {
if ( 'plugin_information' !== $action ) {
return $result;
}
if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) {
return $result;
}
$remote = $this->get_remote_data();
if ( empty( $remote['version'] ) ) {
return $result;
}
return (object) array(
'name' => $remote['name'] ?? $this->plugin_data['Name'] ?? $this->plugin_slug,
'slug' => $remote['slug'] ?? $this->plugin_slug,
'version' => $remote['version'],
'author' => $remote['author'] ?? $this->plugin_data['Author'] ?? '',
'homepage' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '',
'requires' => $remote['requires'] ?? '',
'tested' => $remote['tested'] ?? '',
'requires_php' => $remote['requires_php'] ?? '',
'sections' => array(
'description' => $remote['description'] ?? $this->plugin_data['Description'] ?? '',
'changelog' => $remote['changelog'] ?? '',
),
'download_link' => $remote['download_url'] ?? '',
);
}
/**
* Get remote data with caching and HMAC signature verification.
*
* @return array Remote data.
*/
private function get_remote_data(): array {
$cached = get_site_transient( $this->cache_key );
// Verify HMAC signature if AUTH_SALT is defined and cache has signature.
if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) {
$expected_sig = hash_hmac( 'sha256', $this->cache_key . serialize( $cached['data'] ), AUTH_SALT );
if ( hash_equals( $expected_sig, $cached['signature'] ) ) {
// Signature valid, return data.
return is_array( $cached['data'] ) ? $cached['data'] : array();
}
// Signature invalid, delete corrupted cache.
delete_site_transient( $this->cache_key );
$cached = false;
}
}
// If no valid cache, fetch fresh data.
if ( false === $cached ) {
$remote = $this->fetch_json();
// Store with HMAC signature if AUTH_SALT is available.
if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) {
$payload = array(
'data' => $remote ?: array(),
'timestamp' => time(),
'signature' => hash_hmac( 'sha256', $this->cache_key . serialize( $remote ?: array() ), AUTH_SALT ),
);
set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS );
} else {
// Fallback to standard caching.
set_site_transient( $this->cache_key, $remote ?: array(), 6 * HOUR_IN_SECONDS );
}
return is_array( $remote ) ? $remote : array();
}
// Legacy cache format without signature (backward compatibility).
return is_array( $cached ) ? $cached : array();
}
/**
* Fetch JSON from remote URL.
*
* @return array Decoded JSON data.
*/
private function fetch_json(): array {
$response = wp_remote_get(
$this->json_url,
array(
'timeout' => 10,
'headers' => array(
'Accept' => 'application/json',
),
)
);
if ( is_wp_error( $response ) ) {
return array();
}
$code = (int) wp_remote_retrieve_response_code( $response );
if ( $code < 200 || $code >= 300 ) {
return array();
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
return is_array( $data ) ? $data : array();
}
/**
* Check compatibility.
*
* @param array $remote Remote data.
*
* @return bool True if compatible.
*/
private function is_compatible( array $remote ): bool {
if ( ! empty( $remote['requires_php'] ) ) {
if ( version_compare( PHP_VERSION, $remote['requires_php'], '<' ) ) {
return false;
}
}
if ( ! empty( $remote['requires'] ) ) {
if ( version_compare( get_bloginfo( 'version' ), $remote['requires'], '<' ) ) {
return false;
}
}
return true;
}
/**
* Handle manual cache clear via URL parameter.
*/
public function handle_cache_clear(): void {
// Check if this is a cache clear request first.
$clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW );
if ( null === $clear_cache ) {
return;
}
// This is a cache clear request - now verify nonce.
$nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW );
$nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : '';
if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) {
wp_die( esc_html__( 'Security check failed', 'robotstxt-smtp-amazonses' ) );
}
// Check permissions.
if ( ! current_user_can( 'update_plugins' ) ) {
wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-smtp-amazonses' ) );
}
$this->clear_cache();
wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) );
exit;
}
/**
* Clear update cache.
*/
public function clear_cache(): void {
delete_site_transient( $this->cache_key );
delete_site_transient( 'update_plugins' );
}
}
}

View file

@ -1,21 +1,21 @@
{ {
"name": "SMTP (by ROBOTSTXT) Amazon SES", "name": "SMTP (by ROBOTSTXT) Amazon SES",
"slug": "robotstxt-smtp-amazonses", "slug": "robotstxt-smtp-amazonses",
"version": "2.1.2", "version": "2.1.3",
"download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses/releases/download/2.1.2/robotstxt-smtp-amazonses-2.1.2.zip", "download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses/releases/download/2.1.3/robotstxt-smtp-amazonses-2.1.3.zip",
"requires": "6.5", "requires": "6.5",
"requires_php": "8.2", "requires_php": "8.2",
"tested": "6.9", "tested": "7.1",
"last_updated": "2026-02-12", "last_updated": "2026-06-09",
"author": "ROBOTSTXT", "author": "ROBOTSTXT",
"author_profile": "https://www.robotstxt.es/", "author_profile": "https://www.robotstxt.es/",
"homepage": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses", "homepage": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-smtp-amazonses",
"requires_plugins": ["robotstxt-smtp"], "requires_plugins": ["robotstxt-smtp"],
"description": "Adds Amazon SES (Simple Email Service) configuration support to the ROBOTSTXT SMTP plugin. Integrates seamlessly with AWS SDK for PHP to send emails through Amazon SES infrastructure.", "description": "Adds Amazon SES (Simple Email Service) configuration support to the ROBOTSTXT SMTP plugin. Integrates seamlessly with AWS SDK for PHP to send emails through Amazon SES infrastructure.",
"changelog": "<h3>2.1.1 - 2026-02-09</h3><ul><li><strong>Added:</strong> Comprehensive Amazon SES debug context to test email error reports</li><li><strong>Added:</strong> Debug information now includes AWS region, masked access key, SDK version, endpoint URL, and UTC timestamp</li><li><strong>Improved:</strong> Enhanced AWS error reporting with request IDs, HTTP status codes, and error codes for easier troubleshooting</li><li><strong>Security:</strong> Access keys are now masked in error output (shows only first 4 and last 4 characters)</li></ul><h3>2.1.0 - 2026-02-09</h3><ul><li><strong>Changed:</strong> Uninstall behavior: plugin no longer performs cleanup on uninstall, all data cleanup is now handled by the core SMTP plugin</li><li><strong>Changed:</strong> This ensures Amazon SES credentials are preserved when only the add-on is removed, and properly cleaned when the core plugin is uninstalled</li><li><strong>Technical:</strong> Simplified uninstall.php to delegate all cleanup responsibility to core SMTP plugin</li><li><strong>Technical:</strong> Improved data preservation and cleanup consistency across the plugin ecosystem</li></ul><h3>2.0.0 - 2026-01-29</h3><p><strong>⚠️ BREAKING CHANGE:</strong> This version requires PHP 8.2 or higher due to AWS SDK requirements.</p><ul><li><strong>Added:</strong> Reply-To header support for emails sent via Amazon SES</li><li><strong>Fixed:</strong> Improved error handling and validation</li><li><strong>Fixed:</strong> Enhanced compatibility with core SMTP plugin 2.0.0</li><li><strong>Security:</strong> Improved credential handling and encryption</li><li><strong>Security:</strong> Updated AWS SDK for PHP to latest version (3.369.20) with security patches</li><li><strong>Changed:</strong> Minimum PHP version increased to 8.2</li><li><strong>Improved:</strong> Code quality and documentation</li></ul><h3>1.0.0 - 2026-01-27</h3><ul><li>Initial release</li><li>Amazon SES integration via AWS SDK v3</li><li>Full compatibility with ROBOTSTXT SMTP plugin</li><li>Support for AWS regions and credentials configuration</li><li>Automatic dependency management with Composer</li></ul>", "changelog": "<h3>2.1.3 - 2026-06-09</h3><ul><li><strong>Fixed:</strong> Nonce handling in manual quota refresh to correctly handle false values from filter_input()</li><li><strong>Fixed:</strong> Admin notices display now skips non-array notice entries</li><li><strong>Fixed:</strong> Input normalization for recipients, attachments, and headers now properly skips non-string values</li><li><strong>Removed:</strong> Unused internal rate limit method (dead code cleanup)</li><li><strong>Compatibility:</strong> Tested up to WordPress 7.1</li></ul><h3>2.1.2 - 2026-02-12</h3><ul><li><strong>Fixed:</strong> Charset encoding issue that caused \"expected parameter value, got null\" error when sending emails through Amazon SES</li><li><strong>Improved:</strong> Added robust charset validation in header parsing to prevent empty or invalid charset values</li><li><strong>Improved:</strong> Enhanced charset handling with automatic fallback to UTF-8 when no valid charset is provided</li></ul><h3>2.1.1 - 2026-02-09</h3><ul><li><strong>Added:</strong> Comprehensive Amazon SES debug context to test email error reports</li><li><strong>Added:</strong> Debug information now includes AWS region, masked access key, SDK version, endpoint URL, and UTC timestamp</li><li><strong>Improved:</strong> Enhanced AWS error reporting with request IDs, HTTP status codes, and error codes for easier troubleshooting</li><li><strong>Security:</strong> Access keys are now masked in error output (shows only first 4 and last 4 characters)</li></ul>",
"sections": { "sections": {
"description": "Adds Amazon SES (Simple Email Service) configuration support to the ROBOTSTXT SMTP plugin. Integrates seamlessly with AWS SDK for PHP to send emails through Amazon SES infrastructure.", "description": "Adds Amazon SES (Simple Email Service) configuration support to the ROBOTSTXT SMTP plugin. Integrates seamlessly with AWS SDK for PHP to send emails through Amazon SES infrastructure.",
"changelog": "<h3>2.1.2 - 2026-02-12</h3><ul><li><strong>Fixed:</strong> Charset encoding issue that caused \"expected parameter value, got null\" error when sending emails through Amazon SES</li><li><strong>Improved:</strong> Added robust charset validation in header parsing to prevent empty or invalid charset values</li><li><strong>Improved:</strong> Enhanced charset handling with automatic fallback to UTF-8 when no valid charset is provided</li></ul><h3>2.1.1 - 2026-02-09</h3><ul><li><strong>Added:</strong> Comprehensive Amazon SES debug context to test email error reports</li><li><strong>Added:</strong> Debug information now includes AWS region, masked access key, SDK version, endpoint URL, and UTC timestamp</li><li><strong>Improved:</strong> Enhanced AWS error reporting with request IDs, HTTP status codes, and error codes for easier troubleshooting</li><li><strong>Security:</strong> Access keys are now masked in error output (shows only first 4 and last 4 characters)</li></ul><h3>2.1.0 - 2026-02-09</h3><ul><li><strong>Changed:</strong> Uninstall behavior: plugin no longer performs cleanup on uninstall, all data cleanup is now handled by the core SMTP plugin</li><li><strong>Changed:</strong> This ensures Amazon SES credentials are preserved when only the add-on is removed, and properly cleaned when the core plugin is uninstalled</li><li><strong>Technical:</strong> Simplified uninstall.php to delegate all cleanup responsibility to core SMTP plugin</li><li><strong>Technical:</strong> Improved data preservation and cleanup consistency across the plugin ecosystem</li></ul><h3>2.0.0 - 2026-01-29</h3><p><strong>⚠️ BREAKING CHANGE:</strong> This version requires PHP 8.2 or higher due to AWS SDK requirements.</p><ul><li><strong>Added:</strong> Reply-To header support for emails sent via Amazon SES</li><li><strong>Fixed:</strong> Improved error handling and validation</li><li><strong>Fixed:</strong> Enhanced compatibility with core SMTP plugin 2.0.0</li><li><strong>Security:</strong> Improved credential handling and encryption</li><li><strong>Security:</strong> Updated AWS SDK for PHP to latest version (3.369.20) with security patches</li><li><strong>Changed:</strong> Minimum PHP version increased to 8.2</li><li><strong>Improved:</strong> Code quality and documentation</li></ul><h3>1.0.0 - 2026-01-27</h3><ul><li>Initial release</li><li>Amazon SES integration via AWS SDK v3</li><li>Full compatibility with ROBOTSTXT SMTP plugin</li><li>Support for AWS regions and credentials configuration</li><li>Automatic dependency management with Composer</li></ul>" "changelog": "<h3>2.1.3 - 2026-06-09</h3><ul><li><strong>Fixed:</strong> Nonce handling in manual quota refresh to correctly handle false values from filter_input()</li><li><strong>Fixed:</strong> Admin notices display now skips non-array notice entries</li><li><strong>Fixed:</strong> Input normalization for recipients, attachments, and headers now properly skips non-string values</li><li><strong>Removed:</strong> Unused internal rate limit method (dead code cleanup)</li><li><strong>Compatibility:</strong> Tested up to WordPress 7.1</li></ul><h3>2.1.2 - 2026-02-12</h3><ul><li><strong>Fixed:</strong> Charset encoding issue that caused \"expected parameter value, got null\" error when sending emails through Amazon SES</li><li><strong>Improved:</strong> Added robust charset validation in header parsing to prevent empty or invalid charset values</li><li><strong>Improved:</strong> Enhanced charset handling with automatic fallback to UTF-8 when no valid charset is provided</li></ul><h3>2.1.1 - 2026-02-09</h3><ul><li><strong>Added:</strong> Comprehensive Amazon SES debug context to test email error reports</li><li><strong>Added:</strong> Debug information now includes AWS region, masked access key, SDK version, endpoint URL, and UTC timestamp</li><li><strong>Improved:</strong> Enhanced AWS error reporting with request IDs, HTTP status codes, and error codes for easier troubleshooting</li><li><strong>Security:</strong> Access keys are now masked in error output (shows only first 4 and last 4 characters)</li></ul><h3>2.1.0 - 2026-02-09</h3><ul><li><strong>Changed:</strong> Uninstall behavior: plugin no longer performs cleanup on uninstall, all data cleanup is now handled by the core SMTP plugin</li></ul>"
}, },
"banners": { "banners": {
"low": "", "low": "",

5
vendor/autoload.php vendored
View file

@ -14,10 +14,7 @@ if (PHP_VERSION_ID < 50600) {
echo $err; echo $err;
} }
} }
trigger_error( throw new RuntimeException($err);
$err,
E_USER_ERROR
);
} }
require_once __DIR__ . '/composer/autoload_real.php'; require_once __DIR__ . '/composer/autoload_real.php';

View file

@ -21,10 +21,14 @@ use Aws\AwsClient;
* @method \GuzzleHttp\Promise\Promise createAnalyzerAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise createAnalyzerAsync(array $args = [])
* @method \Aws\Result createArchiveRule(array $args = []) * @method \Aws\Result createArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise createArchiveRuleAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise createArchiveRuleAsync(array $args = [])
* @method \Aws\Result createServiceLinkedAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise createServiceLinkedAnalyzerAsync(array $args = [])
* @method \Aws\Result deleteAnalyzer(array $args = []) * @method \Aws\Result deleteAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAnalyzerAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise deleteAnalyzerAsync(array $args = [])
* @method \Aws\Result deleteArchiveRule(array $args = []) * @method \Aws\Result deleteArchiveRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteArchiveRuleAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise deleteArchiveRuleAsync(array $args = [])
* @method \Aws\Result deleteServiceLinkedAnalyzer(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteServiceLinkedAnalyzerAsync(array $args = [])
* @method \Aws\Result generateFindingRecommendation(array $args = []) * @method \Aws\Result generateFindingRecommendation(array $args = [])
* @method \GuzzleHttp\Promise\Promise generateFindingRecommendationAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise generateFindingRecommendationAsync(array $args = [])
* @method \Aws\Result getAccessPreview(array $args = []) * @method \Aws\Result getAccessPreview(array $args = [])

View file

@ -36,6 +36,8 @@ use Aws\AwsClient;
* @method \GuzzleHttp\Promise\Promise resendValidationEmailAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise resendValidationEmailAsync(array $args = [])
* @method \Aws\Result revokeCertificate(array $args = []) * @method \Aws\Result revokeCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise revokeCertificateAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise revokeCertificateAsync(array $args = [])
* @method \Aws\Result searchCertificates(array $args = [])
* @method \GuzzleHttp\Promise\Promise searchCertificatesAsync(array $args = [])
* @method \Aws\Result updateCertificateOptions(array $args = []) * @method \Aws\Result updateCertificateOptions(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateCertificateOptionsAsync(array $args = []) * @method \GuzzleHttp\Promise\Promise updateCertificateOptionsAsync(array $args = [])
*/ */

View file

@ -0,0 +1,664 @@
<?php
namespace Aws\Api\Cbor;
use Aws\Api\Cbor\Exception\CborException;
/**
* Decodes Concise Binary Object Representation encoded strings
* into PHP values according to RFC 8949
*
* https://www.rfc-editor.org/rfc/rfc8949.html
*
* Supports Major types 0-7 including:
* - Type 0: Unsigned integers
* - Type 1: Negative integers
* - Type 2: Byte strings
* - Type 3: Text strings (UTF-8)
* - Type 4: Arrays
* - Type 5: Maps
* - Type 6: Tagged values (timestamps)
* - Type 7: Simple values (null, bool, float)
*
* @internal
*/
final class CborDecoder
{
private int $offset;
private int $length;
/**
* Decode CBOR binary data to PHP value
*
* @param string $data The CBOR-encoded binary data to decode
*
* @return mixed The decoded PHP value (can be any type: int, string, array, bool, null, float)
* @throws CborException If data is empty or malformed CBOR
*/
public function decode(string $data): mixed
{
if ($data === '') {
throw new CborException("No data to decode");
}
$this->offset = 0;
$this->length = strlen($data);
return $this->decodeValue($data);
}
/**
* Decode multiple CBOR values from sequential binary data
*
* @param string $data The CBOR-encoded binary data containing multiple values
*
* @return array Array of decoded PHP values in the order they appear in the data
* @throws CborException If data is malformed CBOR
*/
public function decodeAll(string $data): array
{
$this->length = strlen($data);
$this->offset = 0;
$values = [];
while ($this->offset < $this->length) {
$values[] = $this->decodeValue($data);
}
return $values;
}
/**
* Decodes a single CBOR value at the current offset
*
* @param string $data Reference to the CBOR data being decoded
*
* @return mixed The decoded value
* @throws CborException If unexpected end of data or invalid CBOR format
*/
private function decodeValue(string &$data): mixed
{
$offset = $this->offset;
$length = $this->length;
if ($offset >= $length) {
throw new CborException("Unexpected end of data");
}
$byte = ord($data[$offset++]);
$majorType = $byte >> 5;
$info = $byte & 0x1F;
switch ($majorType) {
case 0: // Unsigned integer
if ($info < 24) {
$this->offset = $offset;
return $info;
}
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 1;
return ord($data[$offset]);
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 2;
return (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 4;
return unpack('N', $data, $offset)[1];
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 8;
return unpack('J', $data, $offset)[1];
default:
throw new CborException("Invalid additional info for integer: $info");
}
case 1: // Negative integer
if ($info < 24) {
$this->offset = $offset;
return -1 - $info;
}
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 1;
return -1 - ord($data[$offset]);
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 2;
return -1 - ((ord($data[$offset]) << 8) | ord($data[$offset + 1]));
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 4;
return -1 - unpack('N', $data, $offset)[1];
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 8;
$unsigned = unpack('J', $data, $offset)[1];
return ($unsigned === 9223372036854775807) ? PHP_INT_MIN : -1 - $unsigned;
default:
throw new CborException("Invalid additional info for integer: $info");
}
case 2: // Byte string
if ($info < 24) {
$len = $info;
} else {
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$len = ord($data[$offset++]);
break;
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$len = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$offset += 2;
break;
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('N', $data, $offset)[1];
$offset += 4;
break;
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('J', $data, $offset)[1];
$offset += 8;
break;
case 31:
$this->offset = $offset;
return $this->decodeIndefiniteString($data, 0x40);
default:
throw new CborException("Invalid additional info for byte string: $info");
}
}
if ($offset + $len > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + $len;
return substr($data, $offset, $len);
case 3: // Text string
if ($info < 24) {
$len = $info;
} else {
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$len = ord($data[$offset++]);
break;
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$len = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$offset += 2;
break;
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('N', $data, $offset)[1];
$offset += 4;
break;
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('J', $data, $offset)[1];
$offset += 8;
break;
case 31:
$this->offset = $offset;
return $this->decodeIndefiniteString($data, 0x60);
default:
throw new CborException("Invalid additional info for text string: $info");
}
}
if ($offset + $len > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + $len;
return substr($data, $offset, $len);
case 4: // Array
if ($info < 24) {
$count = $info;
} else {
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$count = ord($data[$offset++]);
break;
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$count = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$offset += 2;
break;
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$count = unpack('N', $data, $offset)[1];
$offset += 4;
break;
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$count = unpack('J', $data, $offset)[1];
$offset += 8;
break;
case 31:
$this->offset = $offset;
return $this->decodeIndefiniteArray($data);
default:
throw new CborException("Invalid additional info for array: $info");
}
}
$this->offset = $offset;
$arr = [];
for ($i = 0; $i < $count; $i++) {
$arr[] = $this->decodeValue($data);
}
return $arr;
case 5: // Map
if ($info < 24) {
$count = $info;
} else {
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$count = ord($data[$offset++]);
break;
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$count = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$offset += 2;
break;
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$count = unpack('N', $data, $offset)[1];
$offset += 4;
break;
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$count = unpack('J', $data, $offset)[1];
$offset += 8;
break;
case 31:
$this->offset = $offset;
return $this->decodeIndefiniteMap($data);
default:
throw new CborException("Invalid additional info for map: $info");
}
}
$this->offset = $offset;
$map = [];
for ($i = 0; $i < $count; $i++) {
$key = $this->decodeValue($data);
$map[$key] = $this->decodeValue($data);
}
return $map;
case 6: // Tag
switch ($info) {
case 24:
$offset++;
break;
case 25:
$offset += 2;
break;
case 26:
$offset += 4;
break;
case 27:
$offset += 8;
break;
}
$this->offset = $offset;
return $this->decodeValue($data);
case 7: // Simple/float
switch ($info) {
case 20:
$this->offset = $offset;
return false;
case 21:
$this->offset = $offset;
return true;
case 22:
case 23:
$this->offset = $offset;
return null;
case 25: // Half-precision float
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 2;
$half = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$sign = ($half >> 15) & 0x01;
$exp = ($half >> 10) & 0x1F;
$mant = $half & 0x3FF;
if ($exp === 0) {
return $mant === 0
? ($sign ? -0.0 : 0.0)
: ($sign ? -1 : 1) * pow(2, -14) * ($mant / 1024);
}
if ($exp === 31) {
return $mant === 0 ? ($sign ? -INF : INF) : NAN;
}
return (float) (($sign ? -1 : 1) * pow(2, $exp - 15) * (1 + $mant / 1024));
case 26: // Single-precision float
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 4;
return unpack('G', $data, $offset)[1];
case 27: // Double-precision float
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$this->offset = $offset + 8;
return unpack('E', $data, $offset)[1];
case 31:
throw new CborException("Unexpected break");
default:
throw new CborException("Unknown simple value: $info");
}
default:
throw new CborException("Unknown major type: $majorType");
}
}
/**
* Decode indefinite-length string (byte or text)
*
* @param string $data Reference to the CBOR data being decoded
* @param int $expectedMajor Expected major type (0x40 for byte string, 0x60 for text string)
*
* @return string The concatenated string from all chunks
* @throws CborException If invalid chunk format or unexpected end of data
*/
private function decodeIndefiniteString(string &$data, int $expectedMajor): string
{
$chunks = [];
while (true) {
$offset = $this->offset;
$length = $this->length;
if ($offset >= $length) {
throw new CborException("Unexpected end of data");
}
$byte = ord($data[$offset++]);
if ($byte === 0xFF) {
$this->offset = $offset;
return implode('', $chunks);
}
if (($byte & 0xE0) !== $expectedMajor) {
throw new CborException("Invalid chunk in indefinite string");
}
$info = $byte & 0x1F;
if ($info === 31) {
throw new CborException("Nested indefinite string");
}
if ($info < 24) {
$len = $info;
} else {
switch ($info) {
case 24:
if ($offset >= $length) {
throw new CborException("Not enough data");
}
$len = ord($data[$offset++]);
break;
case 25:
if ($offset + 2 > $length) {
throw new CborException("Not enough data");
}
$len = (ord($data[$offset]) << 8) | ord($data[$offset + 1]);
$offset += 2;
break;
case 26:
if ($offset + 4 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('N', $data, $offset)[1];
$offset += 4;
break;
case 27:
if ($offset + 8 > $length) {
throw new CborException("Not enough data");
}
$len = unpack('J', $data, $offset)[1];
$offset += 8;
break;
default:
throw new CborException("Invalid chunk length info: $info");
}
}
if ($offset + $len > $length) {
throw new CborException("Not enough data for chunk");
}
$chunks[] = substr($data, $offset, $len);
$this->offset = $offset + $len;
}
}
/**
* Decode indefinite-length array
*
* @param string $data Reference to the CBOR data being decoded
*
* @return array The decoded array elements
* @throws CborException If unexpected end of data
*/
private function decodeIndefiniteArray(string &$data): array
{
$result = [];
while (true) {
if ($this->offset >= $this->length) {
throw new CborException("Unexpected end of data");
}
if (ord($data[$this->offset]) === 0xFF) {
$this->offset++;
return $result;
}
$result[] = $this->decodeValue($data);
}
}
/**
* Decode indefinite-length map
*
* @param string $data Reference to the CBOR data being decoded
*
* @return array The decoded map as associative array
* @throws CborException If unexpected end of data or odd number of items
*/
private function decodeIndefiniteMap(string &$data): array
{
$result = [];
while (true) {
if ($this->offset >= $this->length) {
throw new CborException("Unexpected end of data");
}
if (ord($data[$this->offset]) === 0xFF) {
$this->offset++;
return $result;
}
$key = $this->decodeValue($data);
$result[$key] = $this->decodeValue($data);
}
}
}

View file

@ -0,0 +1,345 @@
<?php
namespace Aws\Api\Cbor;
use Aws\Api\Cbor\Exception\CborException;
/**
* Encodes PHP values to Concise Binary Object Representation according to RFC 8949
* https://www.rfc-editor.org/rfc/rfc8949.html
*
* Supports Major types 0-7 including:
* - Type 0: Unsigned integers
* - Type 1: Negative integers
* - Type 2: Byte strings (via ['__cbor_bytes' => $data] wrappers)
* - Type 3: Text strings (UTF-8)
* - Type 4: Arrays
* - Type 5: Maps
* - Type 6: Tagged values (timestamps)
* - Type 7: Simple values (null, bool, float)
*
* @internal
*/
final class CborEncoder
{
/**
* Pre-encoded integers 0-23 (single byte) and common larger values
* CBOR major type 0 (unsigned integer)
*/
private const INT_CACHE = [
0 => "\x00", 1 => "\x01", 2 => "\x02", 3 => "\x03",
4 => "\x04", 5 => "\x05", 6 => "\x06", 7 => "\x07",
8 => "\x08", 9 => "\x09", 10 => "\x0A", 11 => "\x0B",
12 => "\x0C", 13 => "\x0D", 14 => "\x0E", 15 => "\x0F",
16 => "\x10", 17 => "\x11", 18 => "\x12", 19 => "\x13",
20 => "\x14", 21 => "\x15", 22 => "\x16", 23 => "\x17",
24 => "\x18\x18", 25 => "\x18\x19", 26 => "\x18\x1A",
32 => "\x18\x20", 50 => "\x18\x32", 64 => "\x18\x40",
100 => "\x18\x64", 128 => "\x18\x80", 200 => "\x18\xC8",
255 => "\x18\xFF", 256 => "\x19\x01\x00", 500 => "\x19\x01\xF4",
1000 => "\x19\x03\xE8", 1023 => "\x19\x03\xFF",
];
/**
* Pre-encoded negative integers -1 to -24 and common larger values
* CBOR major type 1 (negative integer)
*/
private const NEG_CACHE = [
-1 => "\x20", -2 => "\x21", -3 => "\x22", -4 => "\x23",
-5 => "\x24", -10 => "\x29", -20 => "\x33", -24 => "\x37",
-25 => "\x38\x18", -50 => "\x38\x31", -100 => "\x38\x63",
];
/**
* Encode a PHP value to CBOR binary string
*
* @param mixed $value The value to encode
*
* @return string
*/
public function encode(mixed $value): string
{
return $this->encodeValue($value);
}
/**
* Recursively encode a value to CBOR
*
* @param mixed $value Value to encode
* @return string Encoded CBOR bytes
*/
private function encodeValue(mixed $value): string
{
switch (gettype($value)) {
case 'string':
$len = strlen($value);
if ($len < 24) {
return chr(0x60 | $len) . $value;
}
if ($len < 0x100) {
return "\x78" . chr($len) . $value;
}
return $this->encodeTextString($value);
case 'array':
if (isset($value['__cbor_timestamp'])) {
return "\xC1\xFB" . pack('E', $value['__cbor_timestamp']);
}
// Encode a byte string (major type 2)
if (isset($value['__cbor_bytes'])) {
$bytes = $value['__cbor_bytes'];
$len = strlen($bytes);
if ($len < 24) {
return chr(0x40 | $len) . $bytes;
}
if ($len < 0x100) {
return "\x58" . chr($len) . $bytes;
}
if ($len < 0x10000) {
return "\x59" . pack('n', $len) . $bytes;
}
return "\x5A" . pack('N', $len) . $bytes;
}
if (array_is_list($value)) {
return $this->encodeArray($value);
}
return $this->encodeMap($value);
case 'integer':
if (isset(self::INT_CACHE[$value])) {
return self::INT_CACHE[$value];
}
if (isset(self::NEG_CACHE[$value])) {
return self::NEG_CACHE[$value];
}
// Fast path for positive integers
// Major type 0: unsigned integer
if ($value >= 0) {
if ($value < 24) {
return chr($value);
}
if ($value < 0x100) {
return "\x18" . chr($value);
}
if ($value < 0x10000) {
return "\x19" . pack('n', $value);
}
if ($value < 0x100000000) {
return "\x1A" . pack('N', $value);
}
return "\x1B" . pack('J', $value);
}
return $this->encodeInteger($value);
case 'double':
// Encode a float (major type 7, float 64)
return "\xFB" . pack('E', $value);
case 'boolean':
// Encode a boolean (major type 7, simple)
return $value ? "\xF5" : "\xF4";
case 'NULL':
// Encode null (major type 7, simple)
return "\xF6";
case 'object':
throw new CborException("Cannot encode object of type: " . get_class($value));
default:
throw new CborException("Cannot encode value of type: " . gettype($value));
}
}
/**
* Encode an integer (major type 0 or 1)
*
* @param int $value
* @return string
*/
private function encodeInteger(int $value): string
{
if (isset(self::INT_CACHE[$value])) {
return self::INT_CACHE[$value];
}
if (isset(self::NEG_CACHE[$value])) {
return self::NEG_CACHE[$value];
}
if ($value >= 0) {
// Major type 0: unsigned integer
if ($value < 24) {
return chr($value);
}
if ($value < 0x100) {
return "\x18" . chr($value);
}
if ($value < 0x10000) {
return "\x19" . pack('n', $value);
}
if ($value < 0x100000000) {
return "\x1A" . pack('N', $value);
}
return "\x1B" . pack('J', $value);
}
// Major type 1: negative integer (-1 - n)
$value = -1 - $value;
if ($value < 24) {
return chr(0x20 | $value);
}
if ($value < 0x100) {
return "\x38" . chr($value);
}
if ($value < 0x10000) {
return "\x39" . pack('n', $value);
}
if ($value < 0x100000000) {
return "\x3A" . pack('N', $value);
}
return "\x3B" . pack('J', $value);
}
/**
* Encode a text string (major type 3)
*
* @param string $value
* @return string
*/
private function encodeTextString(string $value): string
{
$len = strlen($value);
if ($len < 24) {
return chr(0x60 | $len) . $value;
}
if ($len < 0x100) {
return "\x78" . chr($len) . $value;
}
if ($len < 0x10000) {
return "\x79" . pack('n', $len) . $value;
}
if ($len < 0x100000000) {
return "\x7A" . pack('N', $len) . $value;
}
return "\x7B" . pack('J', $len) . $value;
}
/**
* Encode an array (major type 4)
*
* @param array $value
* @return string
*/
private function encodeArray(array $value): string
{
$count = count($value);
if ($count < 24) {
$result = chr(0x80 | $count);
} elseif ($count < 0x100) {
$result = "\x98" . chr($count);
} elseif ($count < 0x10000) {
$result = "\x99" . pack('n', $count);
} elseif ($count < 0x100000000) {
$result = "\x9A" . pack('N', $count);
} else {
$result = "\x9B" . pack('J', $count);
}
foreach ($value as $item) {
$result .= $this->encodeValue($item);
}
return $result;
}
/**
* Encode a map (major type 5)
*
* @param array $value
* @return string
*/
private function encodeMap(array $value): string
{
$count = count($value);
if ($count < 24) {
$result = chr(0xA0 | $count);
} elseif ($count < 0x100) {
$result = "\xB8" . chr($count);
} elseif ($count < 0x10000) {
$result = "\xB9" . pack('n', $count);
} elseif ($count < 0x100000000) {
$result = "\xBA" . pack('N', $count);
} else {
$result = "\xBB" . pack('J', $count);
}
foreach ($value as $k => $v) {
if (is_int($k)) {
$result .= $this->encodeInteger($k);
} else {
$len = strlen($k);
if ($len < 24) {
$result .= chr(0x60 | $len) . $k;
} elseif ($len < 0x100) {
$result .= "\x78" . chr($len) . $k;
} else {
$result .= "\x79" . pack('n', $len) . $k;
}
}
$result .= $this->encodeValue($v);
}
return $result;
}
/**
* Create an empty map (major type 5 with 0 elements)
*
* @return string
*/
public function encodeEmptyMap(): string
{
return "\xA0";
}
/**
* Create an empty indefinite map (major type 5 indefinite length)
*
* @return string
*/
public function encodeEmptyIndefiniteMap(): string
{
return "\xBF\xFF";
}
}

View file

@ -0,0 +1,6 @@
<?php
namespace Aws\Api\Cbor\Exception;
use RuntimeException;
class CborException extends RuntimeException {}

View file

@ -30,11 +30,6 @@ class DateTimeResult extends \DateTime implements \JsonSerializable
throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromEpoch'); throw new ParserException('Invalid timestamp value passed to DateTimeResult::fromEpoch');
} }
// PHP 5.5 does not support sub-second precision
if (\PHP_VERSION_ID < 56000) {
return new self(gmdate('c', $unixTimestamp));
}
$decimalSeparator = isset(localeconv()['decimal_point']) ? localeconv()['decimal_point'] : "."; $decimalSeparator = isset(localeconv()['decimal_point']) ? localeconv()['decimal_point'] : ".";
$formatString = "U" . $decimalSeparator . "u"; $formatString = "U" . $decimalSeparator . "u";
$dateTime = DateTime::createFromFormat( $dateTime = DateTime::createFromFormat(

View file

@ -31,19 +31,6 @@ abstract class AbstractErrorParser
StructureShape $member StructureShape $member
); );
protected function extractPayload(
StructureShape $member,
ResponseInterface $response
) {
if ($member instanceof StructureShape) {
// Structure members parse top-level data into a specific key.
return $this->payload($response, $member);
} else {
// Streaming data is just the stream from the response body.
return $response->getBody();
}
}
protected function populateShape( protected function populateShape(
array &$data, array &$data,
ResponseInterface $response, ResponseInterface $response,
@ -57,16 +44,15 @@ abstract class AbstractErrorParser
if (!empty($data['code'])) { if (!empty($data['code'])) {
$errors = $this->api->getOperation($command->getName())->getErrors(); $errors = $this->api->getOperation($command->getName())->getErrors();
foreach ($errors as $key => $error) { foreach ($errors as $error) {
// If error code matches a known error shape, populate the body // If error code matches a known error shape, populate the body
if ($this->errorCodeMatches($data, $error)) { if ($this->errorCodeMatches($data, $error)) {
$modeledError = $error; $data['body'] = $this->payload(
$data['body'] = $this->extractPayload( $response,
$modeledError, $error
$response
); );
$data['error_shape'] = $modeledError; $data['error_shape'] = $error;
foreach ($error->getMembers() as $name => $member) { foreach ($error->getMembers() as $name => $member) {
switch ($member['location']) { switch ($member['location']) {

View file

@ -0,0 +1,159 @@
<?php
namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\AbstractParser;
use Aws\Api\StructureShape;
use Aws\CommandInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Base implementation for Smithy RPC V2 protocol error parsers.
*
* @internal
*/
abstract class AbstractRpcV2ErrorParser extends AbstractErrorParser
{
private const HEADER_QUERY_ERROR = 'x-amzn-query-error';
private const HEADER_ERROR_TYPE = 'x-amzn-errortype';
private const HEADER_REQUEST_ID = 'x-amzn-requestid';
/**
* @param ResponseInterface $response
* @param CommandInterface|null $command
*
* @return array
*/
public function __invoke(
ResponseInterface $response,
?CommandInterface $command = null
) {
$response = AbstractParser::getResponseWithCachingStream($response);
$data = $this->parseError($response);
if (isset($data['parsed']['__type'])) {
$data['message'] = $data['parsed']['message'] ?? null;
}
$this->populateShape($data, $response, $command);
return $data;
}
/**
* @param ResponseInterface $response
* @param StructureShape $member
*
* @return array
*/
abstract protected function payload(
ResponseInterface $response,
StructureShape $member
): array;
/**
* @param StreamInterface $body
* @param ResponseInterface $response
*
* @return mixed
*/
abstract protected function parseBody(
StreamInterface $body,
ResponseInterface $response
): mixed;
/**
* @param ResponseInterface $response
*
* @return array
*/
private function parseError(ResponseInterface $response): array
{
$statusCode = (string) $response->getStatusCode();
$errorCode = null;
$errorType = null;
if ($this->api?->getMetadata('awsQueryCompatible') !== null
&& $response->hasHeader(self::HEADER_QUERY_ERROR)
&& $awsQueryError = $this->parseQueryCompatibleHeader($response)
) {
$errorCode = $awsQueryError['code'];
$errorType = $awsQueryError['type'];
}
if (!$errorCode && $response->hasHeader(self::HEADER_ERROR_TYPE)) {
$errorCode = $this->extractErrorCode(
$response->getHeaderLine(self::HEADER_ERROR_TYPE)
);
}
$parsedBody = null;
$body = $response->getBody();
if ($body->getSize()) {
//TODO handle unseekable streams with CachingStream
$parsedBody = array_change_key_case($this->parseBody($body, $response));
}
if (!$errorCode && $parsedBody) {
$errorCode = $this->extractErrorCode(
$parsedBody['code'] ?? $parsedBody['__type'] ?? ''
);
}
return [
'request_id' => $response->getHeaderLine(self::HEADER_REQUEST_ID),
'code' => $errorCode ?: null,
'message' => null,
'type' => $errorType ?? ($statusCode[0] === '4' ? 'client' : 'server'),
'parsed' => $parsedBody,
];
}
/**
* Parse AWS Query Compatible error from header
*
* @param ResponseInterface $response
*
* @return array|null Returns ['code' => string, 'type' => string] or null
*/
private function parseQueryCompatibleHeader(ResponseInterface $response): ?array
{
$parts = explode(';', $response->getHeaderLine(self::HEADER_QUERY_ERROR));
if (count($parts) === 2 && $parts[0] && $parts[1]) {
return [
'code' => $parts[0],
'type' => $parts[1],
];
}
return null;
}
/**
* Extract error code from raw error string containing # and/or : delimiters
*
* @param string $rawErrorCode
* @return string
*/
private function extractErrorCode(string $rawErrorCode): string
{
// Handle format with both # and uri (e.g., "namespace#ErrorCode:http://foo-bar")
if (str_contains($rawErrorCode, ':') && str_contains($rawErrorCode, '#')) {
$start = strpos($rawErrorCode, '#') + 1;
$end = strpos($rawErrorCode, ':', $start);
return substr($rawErrorCode, $start, $end - $start);
}
// Handle format with uri only : (e.g., "ErrorCode:http://foo-bar.com/baz")
if (str_contains($rawErrorCode, ':')) {
return substr($rawErrorCode, 0, strpos($rawErrorCode, ':'));
}
// Handle format with only # (e.g., "namespace#ErrorCode")
if (str_contains($rawErrorCode, '#')) {
return substr($rawErrorCode, strpos($rawErrorCode, '#') + 1);
}
return $rawErrorCode;
}
}

View file

@ -1,6 +1,7 @@
<?php <?php
namespace Aws\Api\ErrorParser; namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\AbstractParser;
use Aws\Api\Parser\PayloadParserTrait; use Aws\Api\Parser\PayloadParserTrait;
use Aws\Api\StructureShape; use Aws\Api\StructureShape;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -38,9 +39,10 @@ trait JsonParserTrait
} }
$parsedBody = null; $parsedBody = null;
$body = $response->getBody();
if (!$body->isSeekable() || $body->getSize()) { $rawBody = AbstractParser::getBodyContents($response);
$parsedBody = $this->parseJson((string) $body, $response); if (!empty($rawBody)) {
$parsedBody = $this->parseJson($rawBody, $response);
} }
// Parse error code from response body // Parse error code from response body
@ -132,11 +134,12 @@ trait JsonParserTrait
ResponseInterface $response, ResponseInterface $response,
StructureShape $member StructureShape $member
) { ) {
$body = $response->getBody(); $rawBody = AbstractParser::getBodyContents($response);
if (!$body->isSeekable() || $body->getSize()) {
$jsonBody = $this->parseJson($body, $response); if (!empty($rawBody)) {
$jsonBody = $this->parseJson($rawBody, $response);
} else { } else {
$jsonBody = (string) $body; $jsonBody = $rawBody;
} }
return $this->parser->parse($member, $jsonBody); return $this->parser->parse($member, $jsonBody);

View file

@ -1,6 +1,7 @@
<?php <?php
namespace Aws\Api\ErrorParser; namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\AbstractParser;
use Aws\Api\Parser\JsonParser; use Aws\Api\Parser\JsonParser;
use Aws\Api\Service; use Aws\Api\Service;
use Aws\CommandInterface; use Aws\CommandInterface;
@ -25,6 +26,7 @@ class JsonRpcErrorParser extends AbstractErrorParser
ResponseInterface $response, ResponseInterface $response,
?CommandInterface $command = null ?CommandInterface $command = null
) { ) {
$response = AbstractParser::getResponseWithCachingStream($response);
$data = $this->genericHandler($response); $data = $this->genericHandler($response);
// Make the casing consistent across services. // Make the casing consistent across services.

View file

@ -1,6 +1,7 @@
<?php <?php
namespace Aws\Api\ErrorParser; namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\AbstractParser;
use Aws\Api\Parser\JsonParser; use Aws\Api\Parser\JsonParser;
use Aws\Api\Service; use Aws\Api\Service;
use Aws\Api\StructureShape; use Aws\Api\StructureShape;
@ -26,6 +27,7 @@ class RestJsonErrorParser extends AbstractErrorParser
ResponseInterface $response, ResponseInterface $response,
?CommandInterface $command = null ?CommandInterface $command = null
) { ) {
$response = AbstractParser::getResponseWithCachingStream($response);
$data = $this->genericHandler($response); $data = $this->genericHandler($response);
// Merge in error data from the JSON body // Merge in error data from the JSON body
@ -40,7 +42,9 @@ class RestJsonErrorParser extends AbstractErrorParser
// Retrieve error message directly // Retrieve error message directly
$data['message'] = $data['parsed']['message'] $data['message'] = $data['parsed']['message']
?? ($data['parsed']['Message'] ?? null); ?? $data['parsed']['Message']
?? $data['parsed']['error_description']
?? null;
$this->populateShape($data, $response, $command); $this->populateShape($data, $response, $command);

Some files were not shown because too many files have changed in this diff Show more