robotstxt-smtp/includes/class-plugin.php
2026-06-09 12:49:44 +00:00

1299 lines
39 KiB
PHP

<?php
/**
* Main plugin bootstrap file.
*
* @package Robotstxt_SMTP
*/
namespace Robotstxt_SMTP;
// Security check.
defined( 'ABSPATH' ) || exit;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use Robotstxt_SMTP\Admin\Settings_Page;
use WP_Error;
/**
* Main plugin class.
*/
class Plugin {
/**
* Custom post type used to store email logs.
*/
private const LOG_POST_TYPE = 'robotstxt_smtp_log';
/**
* Retrieves the custom post type identifier used for SMTP logs.
*
* @since 1.1.1
*
* @return string
*/
public static function get_log_post_type(): string {
return self::LOG_POST_TYPE;
}
/**
* Cron hook used to trigger the log cleanup.
*/
private const CRON_HOOK = 'robotstxt_smtp_cleanup_logs';
/**
* Cron hook used to trigger statistics cleanup.
*/
private const STATS_CRON_HOOK = 'robotstxt_smtp_cleanup_stats';
/**
* Holds the class instance.
*
* @var Plugin|null
*/
private static ?Plugin $instance = null;
/**
* Settings page handler.
*
* @var Settings_Page|null
*/
private ?Settings_Page $settings_page = null;
/**
* Captures the SMTP debug output for the current email.
*
* @var array<int, string>
*/
private array $current_debug_log = array();
/**
* Holds rate limit error if checking failed.
*
* @since 1.2.1
*
* @var WP_Error|null
*/
private ?WP_Error $rate_limit_error = null;
/**
* Retrieves the plugin instance.
*
* @return Plugin Plugin instance.
*/
public static function get_instance(): Plugin {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Determines whether the Amazon SES integration plugin is active.
*
* @return bool
*/
public static function is_amazon_ses_integration_active(): bool {
/**
* Filters whether the Amazon SES integration should be considered active.
*
* @since 1.0.1
*
* @param bool $is_active True when the Amazon SES add-on is active.
*/
return (bool) \apply_filters( 'robotstxt_smtp_amazon_ses_active', false );
}
/**
* Sets up the plugin.
*
* @return void
*/
public function run(): void {
add_action( 'phpmailer_init', array( $this, 'configure_phpmailer' ) );
add_filter( 'pre_wp_mail', array( $this, 'pre_wp_mail_rate_limit_check' ), 1 );
add_action( 'phpmailer_init', array( $this, 'enforce_rate_limit_in_phpmailer' ), 5 );
add_filter( 'wp_mail_from', array( $this, 'filter_mail_from' ) );
add_filter( 'wp_mail_from_name', array( $this, 'filter_mail_from_name' ) );
add_action( 'phpmailer_init', array( $this, 'configure_reply_to' ), 20 );
add_action( 'init', array( $this, 'load_textdomain' ) );
add_action( 'init', array( $this, 'register_log_post_type' ) );
add_action( 'init', array( $this, 'maybe_schedule_cleanup' ) );
add_action( 'init', array( $this, 'maybe_schedule_stats_cleanup' ) );
add_action( 'wp_mail_succeeded', array( $this, 'handle_wp_mail_succeeded' ) );
add_action( 'wp_mail_failed', array( $this, 'handle_wp_mail_failed' ) );
add_action( self::CRON_HOOK, array( $this, 'cleanup_logs' ) );
add_action( self::STATS_CRON_HOOK, array( $this, 'cleanup_stats' ) );
// Initialize statistics table.
Statistics::get_instance();
if ( is_admin() ) {
add_action( 'admin_init', array( $this, 'migrate_plaintext_credentials' ) );
add_action( 'admin_init', array( $this, 'handle_encryption_notice_dismissal' ) );
add_action( 'admin_notices', array( $this, 'display_encryption_unavailable_notice' ) );
add_action( 'network_admin_notices', array( $this, 'display_encryption_unavailable_notice' ) );
$this->register_admin();
}
}
/**
* Loads the plugin text domain for translations.
*
* @since 2.2.1
*
* @return void
*/
public function load_textdomain(): void {
load_plugin_textdomain(
'robotstxt-smtp',
false,
dirname( ROBOTSTXT_SMTP_BASENAME ) . '/languages'
);
}
/**
* Registers the admin functionality.
*
* @return void
*/
private function register_admin(): void {
if ( null === $this->settings_page ) {
$this->settings_page = new Settings_Page();
}
$this->settings_page->register_hooks();
}
/**
* Registers the custom post type used to store email logs.
*
* @return void
*/
public function register_log_post_type(): void {
register_post_type(
self::LOG_POST_TYPE,
array(
'labels' => array(
'name' => esc_html__( 'SMTP Logs', 'robotstxt-smtp' ),
'singular_name' => esc_html__( 'SMTP Log', 'robotstxt-smtp' ),
),
'public' => false,
'show_ui' => false,
'show_in_menu' => false,
'show_in_nav_menus' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'supports' => array( 'title', 'editor' ),
'capability_type' => 'post',
'map_meta_cap' => true,
)
);
}
/**
* Schedules or clears the automatic log cleanup task based on settings.
*
* @return void
*/
public function maybe_schedule_cleanup(): void {
$logging = $this->get_logging_settings();
if ( ! $logging['enabled'] ) {
wp_clear_scheduled_hook( self::CRON_HOOK );
return;
}
if ( false === wp_next_scheduled( self::CRON_HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CRON_HOOK );
}
}
/**
* Schedules the automatic statistics cleanup task.
*
* @return void
*/
public function maybe_schedule_stats_cleanup(): void {
if ( false === wp_next_scheduled( self::STATS_CRON_HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::STATS_CRON_HOOK );
}
}
/**
* Filters the "From" email address used by WordPress.
*
* @param string $original_email Original email address provided by WordPress.
*
* @return string
*/
public function filter_mail_from( string $original_email ): string {
$settings = $this->get_mailer_settings();
$from_email = isset( $settings['from_email'] ) ? sanitize_email( is_string( $settings['from_email'] ) ? $settings['from_email'] : '' ) : '';
if ( empty( $from_email ) ) {
return sanitize_email( $original_email );
}
return $from_email;
}
/**
* Filters the "From" name used by WordPress.
*
* @param string $original_name Original name provided by WordPress.
*
* @return string
*/
public function filter_mail_from_name( string $original_name ): string {
$settings = $this->get_mailer_settings();
$from_name = isset( $settings['from_name'] ) ? sanitize_text_field( is_string( $settings['from_name'] ) ? $settings['from_name'] : '' ) : '';
if ( '' === $from_name ) {
return sanitize_text_field( $original_name );
}
return $from_name;
}
/**
* Configures Reply-To header if configured and not already set.
*
* This method runs with priority 20 on phpmailer_init to allow
* WordPress and other plugins to set Reply-To first. If no Reply-To
* exists and the settings include reply_to_email, it will be added.
*
* @param PHPMailer $phpmailer Mailer instance.
*
* @return void
*/
public function configure_reply_to( PHPMailer $phpmailer ): void {
$settings = $this->get_mailer_settings();
// Check if reply-to email is configured.
$reply_to_email = isset( $settings['reply_to_email'] ) ? sanitize_email( is_string( $settings['reply_to_email'] ) ? $settings['reply_to_email'] : '' ) : '';
// If no reply-to email configured, nothing to do.
if ( empty( $reply_to_email ) || ! is_email( $reply_to_email ) ) {
return;
}
// Check if Reply-To header already exists.
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( ! empty( $phpmailer->getReplyToAddresses() ) ) {
// Reply-To already set by wp_mail() or another plugin, don't override.
return;
}
// Get reply-to name (optional).
$reply_to_name = isset( $settings['reply_to_name'] ) ? sanitize_text_field( is_string( $settings['reply_to_name'] ) ? $settings['reply_to_name'] : '' ) : '';
// Add the Reply-To header.
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$phpmailer->addReplyTo( $reply_to_email, $reply_to_name );
}
/**
* Retrieves the stored mailer settings merged with defaults.
*
* @return array<string, mixed>
*/
private function get_mailer_settings(): array {
$defaults = Settings_Page::get_default_settings();
if ( Settings_Page::is_network_mode_enabled() ) {
$settings = get_site_option( Settings_Page::NETWORK_OPTION_NAME, array() );
} else {
$settings = get_option( Settings_Page::OPTION_NAME, array() );
}
if ( ! is_array( $settings ) ) {
$settings = array();
}
$settings = wp_parse_args( $settings, $defaults );
$settings['password'] = \Robotstxt_SMTP_Encryption::decrypt( is_string( $settings['password'] ?? '' ) ? ( $settings['password'] ?? '' ) : '' );
$settings['amazon_ses_access_key'] = \Robotstxt_SMTP_Encryption::decrypt( is_string( $settings['amazon_ses_access_key'] ?? '' ) ? ( $settings['amazon_ses_access_key'] ?? '' ) : '' );
$settings['amazon_ses_secret_key'] = \Robotstxt_SMTP_Encryption::decrypt( is_string( $settings['amazon_ses_secret_key'] ?? '' ) ? ( $settings['amazon_ses_secret_key'] ?? '' ) : '' );
/**
* Filters the SMTP settings before they are consumed by the mailer.
*
* @since 1.1.1
*
* @param array<string, mixed> $settings Sanitized settings merged with defaults.
*/
return (array) \apply_filters( 'robotstxt_smtp_mailer_settings', $settings );
}
/**
* Automatically migrates plaintext credentials to encrypted format.
*
* This method runs once during admin_init to detect and encrypt any
* credentials that were stored in plaintext (from pre-1.2.1 installations).
* Uses a transient to prevent repeated checks after migration is complete.
*
* @since 1.2.2
*
* @return void
*/
public function migrate_plaintext_credentials(): void {
// Check if migration has already been completed.
$migration_check_key = 'robotstxt_smtp_credentials_migration_checked';
if ( get_transient( $migration_check_key ) ) {
return;
}
// Check if encryption is available.
if ( ! \Robotstxt_SMTP_Encryption::is_encryption_available() ) {
// Set transient to retry in 1 hour if encryption becomes available.
set_transient( $migration_check_key, true, HOUR_IN_SECONDS );
return;
}
$needs_migration = false;
$is_network_mode = Settings_Page::is_network_mode_enabled();
// Load raw settings without decryption.
if ( $is_network_mode ) {
$settings = get_site_option( Settings_Page::NETWORK_OPTION_NAME, array() );
} else {
$settings = get_option( Settings_Page::OPTION_NAME, array() );
}
if ( ! is_array( $settings ) ) {
$settings = array();
}
// Check each credential field for plaintext values.
$credential_fields = array( 'password', 'amazon_ses_access_key', 'amazon_ses_secret_key' );
foreach ( $credential_fields as $field ) {
if ( ! isset( $settings[ $field ] ) || '' === $settings[ $field ] ) {
continue;
}
// If the value is not encrypted and not empty, it needs migration.
$field_value = is_string( $settings[ $field ] ) ? $settings[ $field ] : '';
if ( ! \Robotstxt_SMTP_Encryption::is_encrypted( $field_value ) ) {
$needs_migration = true;
$settings[ $field ] = \Robotstxt_SMTP_Encryption::encrypt( $field_value );
}
}
// Save migrated credentials if any were found.
if ( $needs_migration ) {
if ( $is_network_mode ) {
update_site_option( Settings_Page::NETWORK_OPTION_NAME, $settings );
} else {
update_option( Settings_Page::OPTION_NAME, $settings );
}
}
// Set transient to prevent future checks (valid for 30 days).
// After 30 days, it will check again in case new plaintext credentials were added.
set_transient( $migration_check_key, true, 30 * DAY_IN_SECONDS );
}
/**
* Displays an admin notice when encryption is unavailable.
*
* Shows a warning in the WordPress admin when encryption cannot be enabled,
* explaining what's missing and how to fix it. Only displays on plugin settings
* pages and can be dismissed for 7 days.
*
* @since 1.2.2
*
* @return void
*/
public function display_encryption_unavailable_notice(): void {
// Only show on plugin settings pages.
$screen = get_current_screen();
if ( null === $screen || false === strpos( $screen->id, 'robotstxt-smtp' ) ) {
return;
}
// Check if encryption is available.
if ( \Robotstxt_SMTP_Encryption::is_encryption_available() ) {
return;
}
// Check if notice has been dismissed.
$dismissed_key = 'robotstxt_smtp_encryption_notice_dismissed';
if ( get_transient( $dismissed_key ) ) {
return;
}
// Check if there are any stored credentials that need encryption.
$is_network_mode = Settings_Page::is_network_mode_enabled();
if ( $is_network_mode ) {
$settings = get_site_option( Settings_Page::NETWORK_OPTION_NAME, array() );
} else {
$settings = get_option( Settings_Page::OPTION_NAME, array() );
}
if ( ! is_array( $settings ) ) {
$settings = array();
}
// Check if there are any credentials stored.
$has_credentials = false;
$credential_fields = array( 'password', 'amazon_ses_access_key', 'amazon_ses_secret_key' );
foreach ( $credential_fields as $field ) {
if ( ! empty( $settings[ $field ] ) ) {
$has_credentials = true;
break;
}
}
// Only show notice if there are credentials to protect.
if ( ! $has_credentials ) {
return;
}
// Determine what's missing.
$missing_requirements = array();
if ( ! extension_loaded( 'openssl' ) ) {
$missing_requirements[] = __( 'OpenSSL PHP extension is not loaded', 'robotstxt-smtp' );
} elseif ( ! in_array( 'aes-256-gcm', openssl_get_cipher_methods(), true ) ) {
$missing_requirements[] = __( 'AES-256-GCM cipher is not supported by OpenSSL', 'robotstxt-smtp' );
}
if ( ! defined( 'AUTH_KEY' ) || '' === AUTH_KEY ) {
$missing_requirements[] = __( 'AUTH_KEY is not defined in wp-config.php', 'robotstxt-smtp' );
}
if ( ! defined( 'AUTH_SALT' ) || '' === AUTH_SALT ) {
$missing_requirements[] = __( 'AUTH_SALT is not defined in wp-config.php', 'robotstxt-smtp' );
}
if ( empty( $missing_requirements ) ) {
// Encryption should be available but check failed - don't show notice.
return;
}
// Generate dismiss URL.
$dismiss_url = add_query_arg(
array(
'robotstxt_smtp_dismiss_encryption_notice' => '1',
'_wpnonce' => wp_create_nonce( 'robotstxt_smtp_dismiss_encryption_notice' ),
)
);
?>
<div class="notice notice-warning is-dismissible">
<p>
<strong><?php esc_html_e( 'ROBOTSTXT SMTP: Credential Encryption Unavailable', 'robotstxt-smtp' ); ?></strong>
</p>
<p>
<?php esc_html_e( 'Your SMTP credentials are currently stored without encryption because the following requirements are not met:', 'robotstxt-smtp' ); ?>
</p>
<ul style="list-style: disc; margin-left: 20px;">
<?php foreach ( $missing_requirements as $requirement ) : ?>
<li><?php echo esc_html( $requirement ); ?></li>
<?php endforeach; ?>
</ul>
<p>
<?php
printf(
/* translators: %s: Link to WordPress security keys documentation */
esc_html__( 'To enable credential encryption, please ensure OpenSSL is installed and %s are defined in your wp-config.php file.', 'robotstxt-smtp' ),
'<a href="https://api.wordpress.org/secret-key/1.1/salt/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'WordPress authentication keys', 'robotstxt-smtp' ) . '</a>'
);
?>
</p>
<p>
<a href="<?php echo esc_url( $dismiss_url ); ?>" class="button button-secondary">
<?php esc_html_e( 'Dismiss for 7 days', 'robotstxt-smtp' ); ?>
</a>
</p>
</div>
<?php
}
/**
* Handles dismissal of the encryption unavailable notice.
*
* Sets a transient when the user clicks "Dismiss for 7 days" to prevent
* the notice from showing again for the specified period.
*
* @since 1.2.2
*
* @return void
*/
public function handle_encryption_notice_dismissal(): void {
// Check if this is a dismissal request.
$dismiss_action = filter_input( INPUT_GET, 'robotstxt_smtp_dismiss_encryption_notice', FILTER_UNSAFE_RAW );
if ( '1' !== $dismiss_action ) {
return;
}
// 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_smtp_dismiss_encryption_notice' ) ) {
return;
}
// Check capability.
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// Set transient to dismiss notice for 7 days.
set_transient( 'robotstxt_smtp_encryption_notice_dismissed', true, 7 * DAY_IN_SECONDS );
// Redirect to clean URL.
$redirect_url = remove_query_arg( array( 'robotstxt_smtp_dismiss_encryption_notice', '_wpnonce' ) );
wp_safe_redirect( $redirect_url );
exit;
}
/**
* Configures PHPMailer to use the stored SMTP settings.
*
* @param PHPMailer $phpmailer Mailer instance.
*
* @return void
*/
public function configure_phpmailer( PHPMailer $phpmailer ): void {
if ( self::is_amazon_ses_integration_active() ) {
return;
}
$this->current_debug_log = array();
$settings = $this->get_mailer_settings();
if ( empty( $settings['host'] ) ) {
return;
}
$phpmailer->isSMTP();
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$phpmailer->Host = is_string( $settings['host'] ) ? $settings['host'] : '';
$phpmailer->Port = isset( $settings['port'] ) && is_numeric( $settings['port'] ) ? (int) $settings['port'] : 25;
$phpmailer->SMTPAuth = ! empty( $settings['username'] ) || ! empty( $settings['password'] );
$phpmailer->Username = $phpmailer->SMTPAuth ? ( is_string( $settings['username'] ) ? $settings['username'] : '' ) : '';
$phpmailer->Password = $phpmailer->SMTPAuth ? ( is_string( $settings['password'] ) ? $settings['password'] : '' ) : '';
$phpmailer->SMTPAutoTLS = false;
$phpmailer->SMTPSecure = '';
// phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( 'ssl' === $settings['security'] ) {
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$phpmailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} elseif ( 'tls' === $settings['security'] ) {
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$phpmailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$phpmailer->SMTPAutoTLS = true;
// phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
$this->register_debug_logger( $phpmailer );
}
/**
* Enables SMTP debug logging for the current email.
*
* @param PHPMailer $phpmailer Mailer instance.
*
* @return void
*/
private function register_debug_logger( PHPMailer $phpmailer ): void {
$logging = $this->get_logging_settings();
if ( ! $logging['enabled'] ) {
return;
}
// phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$phpmailer->SMTPDebug = SMTP::DEBUG_SERVER;
$phpmailer->Debugoutput = function ( string $message, int $level ): void {
$this->current_debug_log[] = '[' . $level . '] ' . $message;
};
// phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
/**
* Stores the email data when WordPress reports a successful delivery.
*
* @param array<string, mixed> $mail_data Email data provided by wp_mail.
*
* @return void
*/
public function handle_wp_mail_succeeded( array $mail_data ): void {
// Track email for statistics.
Statistics::get_instance()->increment_today();
$logging = $this->get_logging_settings();
if ( ! $logging['enabled'] ) {
// Track email for rate limiting.
$this->track_email_sent();
return;
}
$settings = $this->get_mailer_settings();
$subject = isset( $mail_data['subject'] ) ? sanitize_text_field( is_string( $mail_data['subject'] ) ? $mail_data['subject'] : '' ) : '';
$message = isset( $mail_data['message'] ) ? ( is_string( $mail_data['message'] ) ? $mail_data['message'] : '' ) : '';
$headers = $this->normalize_headers( $mail_data['headers'] ?? array() );
$to = $this->normalize_recipients( $mail_data['to'] ?? array() );
$from = $this->determine_from_header( $headers, $settings );
$post_id = wp_insert_post(
array(
'post_type' => self::LOG_POST_TYPE,
'post_status' => 'publish',
'post_title' => $subject,
'post_content' => $message,
'post_date' => current_time( 'mysql' ),
),
true
);
if ( is_wp_error( $post_id ) ) {
return;
}
update_post_meta( $post_id, '_robotstxt_smtp_to', implode( ', ', $to ) );
update_post_meta( $post_id, '_robotstxt_smtp_from', $from );
update_post_meta( $post_id, '_robotstxt_smtp_headers', implode( "\n", $headers ) );
update_post_meta( $post_id, '_robotstxt_smtp_status', 'sent' );
update_post_meta( $post_id, '_robotstxt_smtp_error', '' );
if ( isset( $mail_data['attachments'] ) ) {
update_post_meta( $post_id, '_robotstxt_smtp_attachments', maybe_serialize( $mail_data['attachments'] ) );
}
$debug_log = $this->get_sanitized_debug_log();
if ( $debug_log ) {
update_post_meta( $post_id, '_robotstxt_smtp_debug_log', maybe_serialize( $debug_log ) );
}
if ( 'count' === $logging['mode'] ) {
$this->cleanup_logs_by_count( $logging['count'] );
return;
}
$this->cleanup_logs_by_days( $logging['days'] );
}
/**
* Stores the email data when WordPress reports a failed delivery.
*
* @param WP_Error $error Error object reported by wp_mail.
*
* @return void
*/
public function handle_wp_mail_failed( WP_Error $error ): void {
$logging = $this->get_logging_settings();
if ( ! $logging['enabled'] ) {
return;
}
$settings = $this->get_mailer_settings();
$data = $error->get_error_data();
if ( ! is_array( $data ) ) {
$data = array();
}
$subject = isset( $data['subject'] ) ? sanitize_text_field( is_string( $data['subject'] ) ? $data['subject'] : '' ) : '';
$message = isset( $data['message'] ) ? ( is_string( $data['message'] ) ? $data['message'] : '' ) : '';
$headers = $this->normalize_headers( $data['headers'] ?? array() );
$to = $this->normalize_recipients( $data['to'] ?? array() );
$from = $this->determine_from_header( $headers, $settings );
$error_msg = sanitize_text_field( $error->get_error_message() );
$post_id = wp_insert_post(
array(
'post_type' => self::LOG_POST_TYPE,
'post_status' => 'publish',
'post_title' => $subject,
'post_content' => $message,
'post_date' => current_time( 'mysql' ),
),
true
);
if ( is_wp_error( $post_id ) ) {
return;
}
update_post_meta( $post_id, '_robotstxt_smtp_to', implode( ', ', $to ) );
update_post_meta( $post_id, '_robotstxt_smtp_from', $from );
update_post_meta( $post_id, '_robotstxt_smtp_headers', implode( "\n", $headers ) );
update_post_meta( $post_id, '_robotstxt_smtp_status', 'error' );
update_post_meta( $post_id, '_robotstxt_smtp_error', $error_msg );
if ( isset( $data['attachments'] ) ) {
update_post_meta( $post_id, '_robotstxt_smtp_attachments', maybe_serialize( $data['attachments'] ) );
}
$debug_log = $this->get_sanitized_debug_log();
if ( $debug_log ) {
update_post_meta( $post_id, '_robotstxt_smtp_debug_log', maybe_serialize( $debug_log ) );
}
if ( 'count' === $logging['mode'] ) {
$this->cleanup_logs_by_count( $logging['count'] );
return;
}
$this->cleanup_logs_by_days( $logging['days'] );
}
/**
* Retrieves the sanitized SMTP debug output captured for the current email.
*
* @return array<int, string>
*/
/**
* Redacts sensitive authentication data from SMTP log messages.
*
* Removes or masks authentication credentials including:
* - AUTH PLAIN/LOGIN commands with base64-encoded credentials
* - Base64-encoded authentication responses
* - Server authentication challenges
*
* @since 1.2.1
*
* @param string $message Log message from PHPMailer SMTP debug output.
* @return string Sanitized message with credentials redacted.
*/
private function redact_smtp_credentials( string $message ): string {
// Redact AUTH PLAIN command with base64 credentials.
// Matches AUTH PLAIN anywhere in line, not just at start.
$message = preg_replace(
'/\bAUTH\s+PLAIN\s+[A-Za-z0-9+\/=]+/i',
'AUTH PLAIN [REDACTED]',
$message
) ?? $message;
// Redact AUTH LOGIN command with base64 credentials.
// Matches AUTH LOGIN anywhere in line.
$message = preg_replace(
'/\bAUTH\s+LOGIN\s+[A-Za-z0-9+\/=]+/i',
'AUTH LOGIN [REDACTED]',
$message
) ?? $message;
// Redact other AUTH mechanisms with credentials.
// Handles CRAM-MD5, DIGEST-MD5, XOAUTH2, NTLM, GSSAPI, EXTERNAL.
$message = preg_replace(
'/\bAUTH\s+(CRAM-MD5|DIGEST-MD5|XOAUTH2|NTLM|GSSAPI|EXTERNAL)\s+[A-Za-z0-9+\/=\-_\.]+/i',
'AUTH ${1} [REDACTED]',
$message
) ?? $message;
// Redact base64 challenge-response (server sends 334 + base64).
// The 334 code indicates server is awaiting authentication data.
$message = preg_replace(
'/\b334\s+[A-Za-z0-9+\/=]+/',
'334 [CHALLENGE REDACTED]',
$message
) ?? $message;
// Redact standalone base64 strings (likely auth responses).
// Matches lines that are predominantly base64 (20+ chars).
// Preserves optional timestamp prefix [123] or similar.
$message = preg_replace(
'/^(\[\d+\]\s*)?([A-Za-z0-9+\/=]{20,})\s*$/mi',
'${1}[CREDENTIAL REDACTED]',
$message
) ?? $message;
return $message;
}
/**
* Sanitizes and prepares debug log entries for storage or display.
*
* @since 1.0.0
*
* @return list<string> Sanitized debug log entries with credentials redacted.
*/
private function get_sanitized_debug_log(): array {
if ( empty( $this->current_debug_log ) ) {
return array();
}
$sanitized = array_map(
function ( $entry ): string {
$entry = sanitize_textarea_field( (string) $entry );
return $this->redact_smtp_credentials( $entry );
},
$this->current_debug_log
);
$sanitized = array_filter(
$sanitized,
static function ( string $line ): bool {
return '' !== trim( $line );
}
);
return array_values( $sanitized );
}
/**
* Performs log cleanup when triggered by cron.
*
* @return void
*/
public function cleanup_logs(): void {
$logging = $this->get_logging_settings();
if ( ! $logging['enabled'] ) {
return;
}
if ( 'count' === $logging['mode'] ) {
$this->cleanup_logs_by_count( $logging['count'] );
return;
}
$this->cleanup_logs_by_days( $logging['days'] );
}
/**
* Performs statistics cleanup when triggered by cron.
*
* @return void
*/
public function cleanup_stats(): void {
$settings = $this->get_mailer_settings();
$days = isset( $settings['stats_retention_days'] ) && is_numeric( $settings['stats_retention_days'] ) ? absint( $settings['stats_retention_days'] ) : 28;
if ( $days <= 0 ) {
return;
}
Statistics::get_instance()->cleanup_old_stats( $days );
}
/**
* Deletes all stored logs.
*
* @return void
*/
public function clear_all_logs(): void {
do {
$posts = get_posts(
array(
'post_type' => self::LOG_POST_TYPE,
'post_status' => 'any',
'fields' => 'ids',
'posts_per_page' => 100,
'orderby' => 'ID',
'order' => 'ASC',
)
);
foreach ( $posts as $post_id ) {
wp_delete_post( (int) $post_id, true );
}
} while ( ! empty( $posts ) );
}
/**
* Cleans up logs by enforcing a maximum number of stored records.
*
* @param int $limit Maximum number of logs to keep.
*
* @return void
*/
private function cleanup_logs_by_count( int $limit ): void {
if ( $limit <= 0 ) {
$this->clear_all_logs();
return;
}
$logs_to_delete = get_posts(
array(
'post_type' => self::LOG_POST_TYPE,
'post_status' => 'any',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => -1,
'offset' => $limit,
'no_found_rows' => true,
)
);
foreach ( $logs_to_delete as $post_id ) {
wp_delete_post( (int) $post_id, true );
}
}
/**
* Cleans up logs based on the maximum number of days to retain them.
*
* @param int $days Number of days to keep.
*
* @return void
*/
private function cleanup_logs_by_days( int $days ): void {
if ( $days <= 0 ) {
$this->clear_all_logs();
return;
}
$cutoff = time() - ( $days * DAY_IN_SECONDS );
$logs_to_delete = get_posts(
array(
'post_type' => self::LOG_POST_TYPE,
'post_status' => 'any',
'fields' => 'ids',
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => gmdate( 'Y-m-d H:i:s', $cutoff ),
),
),
'posts_per_page' => -1,
'no_found_rows' => true,
)
);
foreach ( $logs_to_delete as $post_id ) {
wp_delete_post( (int) $post_id, true );
}
}
/**
* Normalizes the headers array into a list of strings.
*
* @param mixed $headers Headers provided by wp_mail.
*
* @return array<int, string>
*/
private function normalize_headers( $headers ): array {
if ( empty( $headers ) ) {
return array();
}
if ( is_string( $headers ) ) {
$headers = preg_split( "/\r\n|\r|\n/", $headers );
}
if ( ! is_array( $headers ) ) {
return array();
}
$normalized = array();
foreach ( $headers as $header ) {
$line = trim( is_string( $header ) ? $header : '' );
if ( '' !== $line ) {
$normalized[] = $line;
}
}
return $normalized;
}
/**
* Normalizes the recipient list into an array of strings.
*
* @param mixed $recipients Recipient information from wp_mail.
*
* @return array<int, string>
*/
private function normalize_recipients( $recipients ): array {
if ( empty( $recipients ) ) {
return array();
}
if ( is_string( $recipients ) ) {
$recipients = explode( ',', $recipients );
}
if ( ! is_array( $recipients ) ) {
return array();
}
$normalized = array();
foreach ( $recipients as $recipient ) {
$normalized[] = sanitize_text_field( trim( is_string( $recipient ) ? $recipient : '' ) );
}
return array_filter( $normalized );
}
/**
* Determines the "From" header for the logged message.
*
* @param array<int, string> $headers Normalized header list.
* @param array<string, mixed> $settings Plugin settings.
*
* @return string
*/
private function determine_from_header( array $headers, array $settings ): string {
foreach ( $headers as $header ) {
if ( 0 === stripos( $header, 'from:' ) ) {
return sanitize_text_field( trim( substr( $header, 5 ) ) );
}
}
$from_email = isset( $settings['from_email'] ) ? sanitize_email( is_string( $settings['from_email'] ) ? $settings['from_email'] : '' ) : '';
$from_name = isset( $settings['from_name'] ) ? sanitize_text_field( is_string( $settings['from_name'] ) ? $settings['from_name'] : '' ) : '';
if ( $from_email && $from_name ) {
return $from_name . ' <' . $from_email . '>';
}
if ( $from_email ) {
return $from_email;
}
return get_bloginfo( 'name', 'display' );
}
/**
* Retrieves the logging-related settings from the option store.
*
* @return array{enabled: bool, mode: string, count: int, days: int}
*/
private function get_logging_settings(): array {
$settings = $this->get_mailer_settings();
return array(
'enabled' => ! empty( $settings['logs_enabled'] ),
'mode' => in_array( $settings['logs_retention_mode'], array( 'count', 'days' ), true )
? (string) $settings['logs_retention_mode']
: 'count',
'count' => isset( $settings['logs_retention_count'] ) && is_numeric( $settings['logs_retention_count'] ) ? (int) $settings['logs_retention_count'] : 0,
'days' => isset( $settings['logs_retention_days'] ) && is_numeric( $settings['logs_retention_days'] ) ? (int) $settings['logs_retention_days'] : 0,
);
}
/**
* Tracks that an email was sent for rate limiting purposes.
*
* Increments counters for per-second, per-hour, and per-day windows.
*
* @since 1.2.1
*
* @return void
*/
private function track_email_sent(): void {
$scope = $this->settings_page ? $this->settings_page->get_scope() : Settings_Page::SCOPE_SITE;
$key_second = $this->get_rate_limit_transient_key( $scope, 'second' );
$raw_second = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key_second ) : get_transient( $key_second );
$count = is_numeric( $raw_second ) ? (int) $raw_second : 0;
++$count;
if ( Settings_Page::SCOPE_NETWORK === $scope ) {
set_site_transient( $key_second, $count, 1 );
} else {
set_transient( $key_second, $count, 1 );
}
$key_hour = $this->get_rate_limit_transient_key( $scope, 'hour' );
$raw_hour = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key_hour ) : get_transient( $key_hour );
$count = is_numeric( $raw_hour ) ? (int) $raw_hour : 0;
++$count;
if ( Settings_Page::SCOPE_NETWORK === $scope ) {
set_site_transient( $key_hour, $count, HOUR_IN_SECONDS );
} else {
set_transient( $key_hour, $count, HOUR_IN_SECONDS );
}
$key_day = $this->get_rate_limit_transient_key( $scope, 'day' );
$raw_day = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key_day ) : get_transient( $key_day );
$count = is_numeric( $raw_day ) ? (int) $raw_day : 0;
++$count;
if ( Settings_Page::SCOPE_NETWORK === $scope ) {
set_site_transient( $key_day, $count, DAY_IN_SECONDS );
} else {
set_transient( $key_day, $count, DAY_IN_SECONDS );
}
}
/**
* Checks if sending an email would exceed configured rate limits.
*
* @since 1.2.1
*
* @return true|WP_Error True if sending is allowed, WP_Error if rate limit exceeded.
*/
private function check_rate_limit() {
if ( ! $this->settings_page ) {
return true;
}
$settings = $this->settings_page->get_settings();
$scope = $this->settings_page->get_scope();
if ( $settings['rate_limit_per_second'] > 0 ) {
$limit_second = (int) $settings['rate_limit_per_second'];
$key = $this->get_rate_limit_transient_key( $scope, 'second' );
$raw = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key ) : get_transient( $key );
$count = is_numeric( $raw ) ? (int) $raw : 0;
if ( $count >= $limit_second ) {
return new WP_Error(
'rate_limit_exceeded_second',
sprintf(
/* translators: %d: rate limit per second */
__( 'Rate limit exceeded: Maximum %d emails per second.', 'robotstxt-smtp' ),
$limit_second
)
);
}
}
if ( $settings['rate_limit_per_hour'] > 0 ) {
$limit_hour = (int) $settings['rate_limit_per_hour'];
$key = $this->get_rate_limit_transient_key( $scope, 'hour' );
$raw = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key ) : get_transient( $key );
$count = is_numeric( $raw ) ? (int) $raw : 0;
if ( $count >= $limit_hour ) {
return new WP_Error(
'rate_limit_exceeded_hour',
sprintf(
/* translators: %d: rate limit per hour */
__( 'Rate limit exceeded: Maximum %d emails per hour.', 'robotstxt-smtp' ),
$limit_hour
)
);
}
}
if ( $settings['rate_limit_per_day'] > 0 ) {
$limit_day = (int) $settings['rate_limit_per_day'];
$key = $this->get_rate_limit_transient_key( $scope, 'day' );
$raw = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $key ) : get_transient( $key );
$count = is_numeric( $raw ) ? (int) $raw : 0;
if ( $count >= $limit_day ) {
return new WP_Error(
'rate_limit_exceeded_day',
sprintf(
/* translators: %d: rate limit per day */
__( 'Rate limit exceeded: Maximum %d emails per 24 hours.', 'robotstxt-smtp' ),
$limit_day
)
);
}
}
return true;
}
/**
* Gets the transient key for rate limiting counters.
*
* @since 1.2.1
*
* @param string $scope Scope identifier (network or site).
* @param string $window Time window (second, hour, day).
* @return string Transient key.
*/
private function get_rate_limit_transient_key( string $scope, string $window ): string {
if ( Settings_Page::SCOPE_NETWORK === $scope ) {
return "robotstxt_smtp_rate_limit_{$window}_network";
}
return "robotstxt_smtp_rate_limit_{$window}_" . get_current_blog_id();
}
/**
* Gets current send counts for all time windows.
*
* Used for debugging and displaying current usage.
*
* @since 1.2.1
*
* @return array<string, int> Current counts keyed by window (second, hour, day).
*/
public function get_current_send_counts(): array {
if ( ! $this->settings_page ) {
return array(
'second' => 0,
'hour' => 0,
'day' => 0,
);
}
$scope = $this->settings_page->get_scope();
$raw_second = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $this->get_rate_limit_transient_key( $scope, 'second' ) ) : get_transient( $this->get_rate_limit_transient_key( $scope, 'second' ) );
$raw_hour = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $this->get_rate_limit_transient_key( $scope, 'hour' ) ) : get_transient( $this->get_rate_limit_transient_key( $scope, 'hour' ) );
$raw_day = Settings_Page::SCOPE_NETWORK === $scope ? get_site_transient( $this->get_rate_limit_transient_key( $scope, 'day' ) ) : get_transient( $this->get_rate_limit_transient_key( $scope, 'day' ) );
return array(
'second' => is_numeric( $raw_second ) ? (int) $raw_second : 0,
'hour' => is_numeric( $raw_hour ) ? (int) $raw_hour : 0,
'day' => is_numeric( $raw_day ) ? (int) $raw_day : 0,
);
}
/**
* Checks rate limits before sending an email.
*
* Hooks into 'pre_wp_mail' to prevent sending if rate limit is exceeded.
*
* @since 1.2.1
*
* @param null|bool $pre_wp_mail Short-circuit return value passed by the pre_wp_mail filter.
* @return null|bool Null to continue, false to abort (WP 5.7+ short-circuit).
*/
public function pre_wp_mail_rate_limit_check( $pre_wp_mail ) {
if ( null !== $pre_wp_mail ) {
return $pre_wp_mail;
}
$check = $this->check_rate_limit();
if ( is_wp_error( $check ) ) {
// Store error for the phpmailer_init hook (which fires after this filter).
// Return false to short-circuit wp_mail() immediately (WP 5.7+ behavior),
// avoiding the unnecessary PHPMailer instantiation and hook cascade.
$this->rate_limit_error = $check;
return false;
}
return null;
}
/**
* Enforces rate limits in phpmailer_init if check failed earlier.
*
* @since 1.2.1
*
* @param PHPMailer $phpmailer PHPMailer instance.
* @return void
* @throws \PHPMailer\PHPMailer\Exception If rate limit exceeded.
*
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.Found -- Required by WordPress action hook signature.
*/
public function enforce_rate_limit_in_phpmailer( PHPMailer $phpmailer ): void {
if ( isset( $this->rate_limit_error ) ) {
$error = $this->rate_limit_error;
unset( $this->rate_limit_error );
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception message not output to browser.
throw new \PHPMailer\PHPMailer\Exception( $error->get_error_message(), (int) $error->get_error_code() );
}
}
}