` in front of the binary when the system has one. * 4. Puts every PHPMailer setting it changed (Timeout, SMTPKeepAlive, Mailer, Sendmail) back once the * send is over, because WordPress reuses the same PHPMailer for later mail in the request. */ final class MailGuard { /** Longest the mail transport may take, in seconds. Filterable with migratex_mail_deadline. */ public const DEADLINE = 15; /** @var string[] The PHPMailer settings bound() can change; each is put back after the send. */ private const RESTORED = array( 'Timeout', 'SMTPKeepAlive', 'Mailer', 'Sendmail' ); /** @var string Why the last send failed, for logs and the migratex_mail_failed action. Never shown to the user. */ private $detail = ''; /** * Why mail cannot work here at all, or null when it might. */ public static function unavailableReason(): ?string { $disabled = array_filter( array_map( 'trim', explode( ',', (string) ini_get( 'disable_functions' ) ) ) ); $mail_off = ! function_exists( 'mail' ) || in_array( 'mail', $disabled, true ); // Something else may deliver: a plugin that points PHPMailer at SMTP or an API, or one that // takes over wp_mail() through pre_wp_mail. Their presence is not proof they work, only that // mail() is not the only way, so the call is allowed and then guarded. $other = has_action( 'phpmailer_init' ) || has_filter( 'pre_wp_mail' ); return ( $mail_off && ! $other ) ? 'PHP mail() is disabled on this server and no SMTP or mail plugin is configured.' : null; } public static function deadline(): int { return max( 3, min( 60, (int) apply_filters( 'migratex_mail_deadline', self::DEADLINE ) ) ); } /** * The reason the last call to send() returned false. For logs; it can contain server details. */ public function detail(): string { return $this->detail; } /** * @param string[] $headers * @return bool True only when wp_mail() reported that the message was handed over. */ public function send( string $to, string $subject, string $body, array $headers = array() ): bool { $this->detail = ''; $unavailable = self::unavailableReason(); if ( null !== $unavailable ) { $this->detail = $unavailable; $this->report(); return false; } $deadline = self::deadline(); $failed = function ( $error ) { if ( is_wp_error( $error ) ) { $this->detail = $error->get_error_message(); } }; // WordPress keeps one PHPMailer in a global and reuses it for every later wp_mail() in the request, // so whatever is changed on it for this message must be put back afterwards. What the settings were // when our hook ran (after every other plugin's) is captured here, before bound() changes them. $captured = null; $configure = function ( $phpmailer ) use ( $deadline, &$captured ): void { $captured = self::capture( $phpmailer ); $this->bound( $phpmailer, $deadline ); }; add_action( 'wp_mail_failed', $failed ); add_action( 'phpmailer_init', $configure, PHP_INT_MAX ); $delivered = false; try { $delivered = (bool) wp_mail( $to, $subject, $body, $headers ); if ( ! $delivered && '' === $this->detail ) { $this->detail = 'wp_mail() returned false.'; } } catch ( \Throwable $e ) { $this->detail = sprintf( '%s: %s (%s:%d)', get_class( $e ), $e->getMessage(), basename( $e->getFile() ), $e->getLine() ); } finally { remove_action( 'wp_mail_failed', $failed ); remove_action( 'phpmailer_init', $configure, PHP_INT_MAX ); self::restore( $captured ); } if ( ! $delivered ) { $this->report(); } return $delivered; } /** * The settings bound() may change, with the PHPMailer object they belong to. * * @param object $phpmailer * @return array{mailer:object,values:array} */ private static function capture( $phpmailer ): array { $values = array(); foreach ( self::RESTORED as $property ) { if ( property_exists( $phpmailer, $property ) ) { $values[ $property ] = $phpmailer->$property; } } return array( 'mailer' => $phpmailer, 'values' => $values, ); } /** * Puts the captured settings back on the same PHPMailer, so a later email in this request behaves exactly * as if this one had never been sent. * * @param array{mailer:object,values:array}|null $captured Null when phpmailer_init never ran. */ private static function restore( ?array $captured ): void { if ( null === $captured ) { return; } foreach ( $captured['values'] as $property => $value ) { $captured['mailer']->$property = $value; } } /** * Tells the site owner why the email failed: an action for code that wants to react, and the * debug log when WordPress is set to keep one. */ private function report(): void { /** * Fires when the feedback email could not be sent. * * @param string $detail Technical reason. May contain server details; do not show it. */ do_action( 'migratex_mail_failed', $this->detail ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { error_log( 'MigrateX: feedback email failed: ' . $this->detail ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /** * Puts a ceiling on how long the chosen transport may take. Runs after every other plugin's * phpmailer_init, so it sees the transport that will actually be used. * * @param \PHPMailer\PHPMailer\PHPMailer $phpmailer * @throws \Exception When the transport cannot work at all. */ private function bound( $phpmailer, int $deadline ): void { // SMTP: connection and every read. The library's own default is 300 seconds. $phpmailer->Timeout = min( $deadline, (int) $phpmailer->Timeout > 0 ? (int) $phpmailer->Timeout : $deadline ); $phpmailer->SMTPKeepAlive = false; if ( 'mail' !== $phpmailer->Mailer ) { return; } // The default transport: PHP's mail(), which runs the server's sendmail and waits for it. if ( ! function_exists( 'mail' ) ) { throw new \Exception( 'PHP mail() is disabled on this server.' ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } $wrapped = self::boundedSendmail( $deadline ); if ( null !== $wrapped ) { // Same program and same message on stdin as mail() would use, but with a clock on it. $phpmailer->isSendmail(); $phpmailer->Sendmail = $wrapped; } } /** * " " for the server's configured sendmail, or null when it cannot be * built safely (no timeout program, no popen, a path with anything unusual in it). */ private static function boundedSendmail( int $deadline ): ?string { $disabled = array_filter( array_map( 'trim', explode( ',', (string) ini_get( 'disable_functions' ) ) ) ); if ( ! function_exists( 'popen' ) || in_array( 'popen', $disabled, true ) ) { return null; } // php.ini's sendmail_path is "program -flags"; only the program is kept. $parts = preg_split( '/\s+/', trim( (string) ini_get( 'sendmail_path' ) ) ); $binary = $parts ? (string) $parts[0] : ''; if ( '' === $binary || 1 !== preg_match( '#^/[A-Za-z0-9_./-]+$#', $binary ) || ! is_executable( $binary ) ) { return null; } foreach ( array( '/usr/bin/timeout', '/bin/timeout', '/usr/local/bin/timeout' ) as $timeout ) { if ( is_executable( $timeout ) ) { return $timeout . ' ' . $deadline . ' ' . $binary; } } return null; } }