diff --git a/config.dist.php b/config.dist.php index a6a486f..05b625a 100644 --- a/config.dist.php +++ b/config.dist.php @@ -149,6 +149,28 @@ return [ 'class' => Plugi\Modules\Router\DatabasePageRouter::class ], + /* + |-------------------------------------------------------------------------- + | Mail settings + |-------------------------------------------------------------------------- + | + | Configure the SMTP server used by Plugi mail actions. Leave credentials + | blank when the server does not require authentication. + | + */ + 'mail' => [ + 'class' => Plugi\Core\Mailer::class, + 'transport' => 'smtp', + 'host' => '', + 'port' => 587, + 'encryption' => 'tls', + 'username' => '', + 'password' => '', + 'from_address' => '', + 'from_name' => '', + 'timeout' => 10, + ], + /* |-------------------------------------------------------------------------- | Class replacements diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php index 023072c..7148247 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php @@ -38,6 +38,7 @@ class SendConfirmationEmailToSubmitter extends DefaultFinisher protected function sendMail(string $recipient, string $subject, string $message): bool { - return mail($recipient, $subject, $message); + $mailer = phpb_instance('mail'); + return $mailer !== null && $mailer->send($recipient, $subject, $message) === true; } } \ No newline at end of file diff --git a/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php b/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php index 5641400..d251607 100644 --- a/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php +++ b/extensions/plugi-ext-form/admin/Classes/Finishers/SendEmailToAdmin.php @@ -15,13 +15,8 @@ class SendEmailToAdmin extends DefaultFinisher $subject = 'Form submission: '.$this->getFormName(); $message = $this->getNiceFields(); - return mail( - $to, - $subject, - $message, - $additional_headers = [], - $additional_params = "" - ); + $mailer = phpb_instance('mail'); + return $mailer !== null && $mailer->send($to, $subject, $message) === true; } private function getNiceFields(): string { $text = ''; diff --git a/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php b/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php index ce8566d..42b6e74 100644 --- a/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php +++ b/extensions/plugi-ext-form/tests/SubmissionHandlerTest.php @@ -2,14 +2,27 @@ namespace FormExtensionTests { require_once dirname(__DIR__) . '/admin/Classes/Finishers/DefaultFinisher.php'; + require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendEmailToAdmin.php'; require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php'; + class TestMailer + { + public $calls = []; + public $result = true; + + public function send(string $to, string $subject, string $message): bool + { + $this->calls[] = [$to, $subject, $message]; + return $this->result; + } + } + class TestConfirmationFinisher extends \Plugi\Extensions\Form\Finishers\SendConfirmationEmailToSubmitter { protected function sendMail(string $recipient, string $subject, string $message): bool { $GLOBALS['confirmationEmails'][] = [$recipient, $subject, $message]; - return true; + return parent::sendMail($recipient, $subject, $message); } } @@ -69,6 +82,16 @@ namespace FormExtensionTests { } } +namespace Plugi { + class Extensions + { + public static function getSettings(string $name): array + { + return $GLOBALS['extensionSettings'][$name] ?? []; + } + } +} + namespace { require_once dirname(__DIR__) . '/admin/Classes/SubmissionHandler.php'; @@ -76,6 +99,13 @@ namespace { use FormExtensionTests\FinishersRepository as TestFinishersRepository; use Plugi\Extensions\Form\SubmissionHandler; + if (!function_exists('phpb_instance')) { + function phpb_instance(string $name, array $params = []): ?object + { + return $name === 'mail' ? ($GLOBALS['testMailer'] ?? null) : null; + } + } + function assertSameValue($expected, $actual, string $message): void { if ($expected !== $actual) { @@ -99,6 +129,8 @@ namespace { ]; } + $GLOBALS['testMailer'] = new \FormExtensionTests\TestMailer(); + $form = validForm([ ['type' => 'first', 'options' => ['marker' => 'passed']], ['type' => 'second'], @@ -180,6 +212,8 @@ namespace { 'message' => 'Thanks, Ada.', ]; $GLOBALS['confirmationEmails'] = []; + $GLOBALS['testMailer']->calls = []; + $GLOBALS['testMailer']->result = true; $confirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions); assertSameValue(true, $confirmationFinisher->execute(), 'A valid recipient should be sent a confirmation'); assertSameValue( @@ -187,18 +221,62 @@ namespace { $GLOBALS['confirmationEmails'], 'The configured recipient, subject, and message must be sent' ); + assertSameValue( + [['ada@example.com', 'We received your message', 'Thanks, Ada.']], + $GLOBALS['testMailer']->calls, + 'The confirmation finisher must use the configured core mailer' + ); + + $GLOBALS['testMailer']->result = false; + $failedConfirmationFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $confirmationOptions); + assertSameValue(false, $failedConfirmationFinisher->execute(), 'A failed core mail send must fail the confirmation action'); + assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed confirmation must be sent through the core mailer'); $invalidRecipientContext = $confirmationContext; $invalidRecipientContext['submission']['fields']['email'] = 'not-an-email'; $invalidRecipientFinisher = new \FormExtensionTests\TestConfirmationFinisher($invalidRecipientContext, $confirmationOptions); assertSameValue(false, $invalidRecipientFinisher->execute(), 'An invalid recipient must fail'); - assertSameValue(1, count($GLOBALS['confirmationEmails']), 'An invalid recipient must not send email'); + assertSameValue(2, count($GLOBALS['confirmationEmails']), 'An invalid recipient must not send email'); + assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid recipient must not call the core mailer'); $staleFieldOptions = $confirmationOptions; $staleFieldOptions['recipientField'] = 'removed_email'; $staleFieldFinisher = new \FormExtensionTests\TestConfirmationFinisher($confirmationContext, $staleFieldOptions); assertSameValue(false, $staleFieldFinisher->execute(), 'A stale recipient field selection must fail'); - assertSameValue(1, count($GLOBALS['confirmationEmails']), 'A stale field selection must not send email'); + assertSameValue(2, count($GLOBALS['confirmationEmails']), 'A stale field selection must not send email'); + assertSameValue(2, count($GLOBALS['testMailer']->calls), 'A stale field selection must not call the core mailer'); + + $GLOBALS['extensionSettings']['form'] = ['email' => ['value' => 'admin@example.com']]; + $adminContext = [ + 'formId' => 8, + 'form' => [ + 'name' => 'Contact form', + 'formFields' => [ + ['name' => 'name', 'label' => 'Name', 'type' => 'text'], + ['name' => 'email', 'label' => 'Email', 'type' => 'email'], + ], + ], + 'submission' => ['fields' => ['name' => 'Ada', 'email' => 'ada@example.com']], + ]; + $GLOBALS['testMailer']->calls = []; + $GLOBALS['testMailer']->result = true; + $adminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext); + assertSameValue(true, $adminFinisher->execute(), 'A successful core mail send must succeed for admin notifications'); + assertSameValue( + [['admin@example.com', 'Form submission: Contact form', "Name: Ada\nEmail: ada@example.com\n"]], + $GLOBALS['testMailer']->calls, + 'The admin finisher must preserve message composition and use the core mailer' + ); + + $GLOBALS['testMailer']->result = false; + $failedAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext); + assertSameValue(false, $failedAdminFinisher->execute(), 'A failed core mail send must fail the admin notification action'); + assertSameValue(2, count($GLOBALS['testMailer']->calls), 'The failed admin notification must be sent through the core mailer'); + + $GLOBALS['extensionSettings']['form']['email']['value'] = 'invalid-address'; + $invalidAdminFinisher = new \Plugi\Extensions\Form\Finishers\SendEmailToAdmin($adminContext); + assertSameValue(false, $invalidAdminFinisher->execute(), 'An invalid admin recipient must fail'); + assertSameValue(2, count($GLOBALS['testMailer']->calls), 'An invalid admin recipient must not call the core mailer'); $confirmationForm = [ 'name' => 'Contact form', @@ -209,6 +287,7 @@ namespace { ]]), ]; $GLOBALS['confirmationEmails'] = []; + $GLOBALS['testMailer']->result = true; $result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => 'ada@example.com']])); assertSameValue(true, $result['body']['success'], 'A valid confirmation action must report success'); $result = makeHandler($confirmationForm)->handle(8, json_encode(['fields' => ['email' => '']])); diff --git a/plugi-core/src/Core/Mailer.php b/plugi-core/src/Core/Mailer.php new file mode 100644 index 0000000..03d3a1b --- /dev/null +++ b/plugi-core/src/Core/Mailer.php @@ -0,0 +1,298 @@ +config = $config; + } + + public function send(string $to, string $subject, string $message): bool + { + $settings = $this->validatedSettings(); + if ($settings === null || !$this->isValidEmail($to) || !$this->isSafeHeader($subject) || strlen($subject) > 500) { + return false; + } + + $socket = $this->connect($settings); + if (!is_resource($socket)) { + return false; + } + + try { + if ($this->readResponse($socket) !== 220) { + return false; + } + if ($this->sendCommand($socket, 'EHLO localhost') !== 250) { + return false; + } + + if ($settings['encryption'] === 'tls') { + if ($this->sendCommand($socket, 'STARTTLS') !== 220) { + return false; + } + if (@stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) { + return false; + } + if ($this->sendCommand($socket, 'EHLO localhost') !== 250) { + return false; + } + } + + if ($settings['username'] !== '') { + if (!$this->authenticate($socket, $settings['username'], $settings['password'])) { + return false; + } + } + + if ($this->sendCommand($socket, 'MAIL FROM:<' . $settings['from_address'] . '>') !== 250) { + return false; + } + if (!in_array($this->sendCommand($socket, 'RCPT TO:<' . $to . '>'), [250, 251], true)) { + return false; + } + if ($this->sendCommand($socket, 'DATA') !== 354) { + return false; + } + + $messageData = $this->buildMessage($settings, $to, $subject, $message); + if (!$this->write($socket, $messageData)) { + return false; + } + + $delivered = $this->readResponse($socket) === 250; + $this->sendCommand($socket, 'QUIT'); + return $delivered; + } catch (\Throwable $exception) { + return false; + } finally { + fclose($socket); + } + } + + private function validatedSettings(): ?array + { + if (($this->config['transport'] ?? null) !== 'smtp') { + return null; + } + + $host = $this->config['host'] ?? null; + if (!is_string($host) || $host === '' || !$this->isValidHost($host)) { + return null; + } + + $port = filter_var($this->config['port'] ?? null, FILTER_VALIDATE_INT, [ + 'options' => ['min_range' => 1, 'max_range' => 65535], + ]); + if ($port === false) { + return null; + } + + $encryption = $this->config['encryption'] ?? null; + if (!is_string($encryption) || !in_array($encryption, ['tls', 'ssl', 'none'], true)) { + return null; + } + + $timeout = $this->config['timeout'] ?? null; + if ((!is_int($timeout) && !is_float($timeout) && !(is_string($timeout) && is_numeric($timeout))) || !is_finite((float) $timeout) || (float) $timeout <= 0 || (float) $timeout > 300) { + return null; + } + + $fromAddress = $this->config['from_address'] ?? null; + if (!is_string($fromAddress) || !$this->isValidEmail($fromAddress)) { + return null; + } + + $fromName = $this->config['from_name'] ?? ''; + if (!is_string($fromName) || !$this->isSafeHeader($fromName) || strlen($fromName) > 500) { + return null; + } + + $username = $this->config['username'] ?? ''; + $password = $this->config['password'] ?? ''; + if (!is_string($username) || !is_string($password) || (($username === '') !== ($password === '')) || strlen($username) > 250 || strlen($password) > 250) { + return null; + } + if ($username !== '' && strlen(base64_encode("\0" . $username . "\0" . $password)) > 500) { + return null; + } + + return [ + 'host' => $host, + 'port' => (int) $port, + 'encryption' => $encryption, + 'timeout' => (float) $timeout, + 'username' => $username, + 'password' => $password, + 'from_address' => $fromAddress, + 'from_name' => $fromName, + ]; + } + + private function isValidHost(string $host): bool + { + if (filter_var($host, FILTER_VALIDATE_IP) !== false) { + return true; + } + + return preg_match('/\A(?=.{1,253}\z)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?))*\z/', $host) === 1; + } + + private function isValidEmail(string $address): bool + { + return filter_var($address, FILTER_VALIDATE_EMAIL) !== false && preg_match('/[\r\n\x00-\x1F\x7F]/', $address) !== 1; + } + + private function isSafeHeader(string $value): bool + { + return preg_match('/[\r\n\x00-\x1F\x7F]/', $value) !== 1 && preg_match('//u', $value) === 1; + } + + private function connect(array $settings) + { + $host = $settings['host']; + $socketHost = filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false ? '[' . $host . ']' : $host; + $scheme = $settings['encryption'] === 'ssl' ? 'ssl' : 'tcp'; + $target = $scheme . '://' . $socketHost . ':' . $settings['port']; + $context = stream_context_create([ + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + 'peer_name' => $host, + 'SNI_enabled' => true, + ], + ]); + + $errno = 0; + $error = ''; + $socket = @stream_socket_client( + $target, + $errno, + $error, + $settings['timeout'], + STREAM_CLIENT_CONNECT, + $context + ); + if (is_resource($socket)) { + $seconds = (int) floor($settings['timeout']); + $microseconds = (int) ceil(($settings['timeout'] - $seconds) * 1000000); + if ($microseconds === 1000000) { + $seconds++; + $microseconds = 0; + } + stream_set_timeout($socket, $seconds, $microseconds); + } + + return $socket; + } + + private function authenticate($socket, string $username, string $password): bool + { + $response = $this->sendCommand($socket, 'AUTH PLAIN'); + if ($response === 235) { + return true; + } + if ($response !== 334) { + return false; + } + + $credentials = base64_encode("\0" . $username . "\0" . $password); + return $this->writeLine($socket, $credentials) && $this->readResponse($socket) === 235; + } + + private function sendCommand($socket, string $command): ?int + { + if (!$this->writeLine($socket, $command)) { + return null; + } + + return $this->readResponse($socket); + } + + private function writeLine($socket, string $line): bool + { + if (strlen($line) > 510 || preg_match('/[\r\n\x00-\x1F\x7F]/', $line) === 1) { + return false; + } + + return $this->write($socket, $line . "\r\n"); + } + + private function write($socket, string $data): bool + { + $length = strlen($data); + $written = 0; + while ($written < $length) { + $count = @fwrite($socket, substr($data, $written)); + if ($count === false || $count === 0) { + return false; + } + $written += $count; + } + + return true; + } + + private function readResponse($socket): ?int + { + $responseCode = null; + for ($lineNumber = 0; $lineNumber < 100; $lineNumber++) { + $line = @fgets($socket, 515); + if (!is_string($line) || !str_ends_with($line, "\r\n") || strlen($line) > 512 || preg_match('/\A([0-9]{3})([ -])/', $line, $matches) !== 1) { + return null; + } + + $code = (int) $matches[1]; + if ($responseCode !== null && $responseCode !== $code) { + return null; + } + $responseCode = $code; + if ($matches[2] === ' ') { + return $responseCode; + } + } + + return null; + } + + private function buildMessage(array $settings, string $to, string $subject, string $message): string + { + $from = $settings['from_name'] === '' + ? '<' . $settings['from_address'] . '>' + : $this->encodeHeader($settings['from_name']) . ' <' . $settings['from_address'] . '>'; + $headers = [ + 'From: ' . $from, + 'To: ' . $to, + 'Subject: ' . $this->encodeHeader($subject), + 'MIME-Version: 1.0', + 'Content-Type: text/plain; charset=UTF-8', + 'Content-Transfer-Encoding: quoted-printable', + ]; + + $normalizedMessage = str_replace(["\r\n", "\r"], "\n", $message); + $encodedMessage = str_replace(["\r\n", "\r"], "\n", quoted_printable_encode(str_replace("\n", "\r\n", $normalizedMessage))); + $messageLines = explode("\n", $encodedMessage); + foreach ($messageLines as &$line) { + if (str_starts_with($line, '.')) { + $line = '.' . $line; + } + } + unset($line); + + return implode("\r\n", $headers) . "\r\n\r\n" . implode("\r\n", $messageLines) . "\r\n.\r\n"; + } + + private function encodeHeader(string $value): string + { + return '=?UTF-8?B?' . base64_encode($value) . '?='; + } +} \ No newline at end of file diff --git a/plugi-core/tests/MailerTest.php b/plugi-core/tests/MailerTest.php new file mode 100644 index 0000000..50d24e3 --- /dev/null +++ b/plugi-core/tests/MailerTest.php @@ -0,0 +1,186 @@ +' && smtpReply($client, '250 sender accepted'); + } + if ($passed) { + $passed = smtpReadLine($client) === 'RCPT TO:'; + if ($passed && !empty($scenario['reject_recipient'])) { + $passed = smtpReply($client, '550 recipient rejected') && smtpReadLine($client) === null; + fclose($client); + exit($passed ? 0 : 1); + } + $passed = $passed && smtpReply($client, '250 recipient accepted'); + } + if ($passed) { + $passed = smtpReadLine($client) === 'DATA' && smtpReply($client, '354 send message'); + } + + $data = ''; + if ($passed) { + $terminated = false; + while (($line = smtpReadLine($client)) !== null) { + if ($line === '.') { + $terminated = true; + break; + } + $data .= $line . "\r\n"; + } + $passed = $terminated + && str_contains($data, 'From: =?UTF-8?B?UGx1Z2kgVGVzdA==?= ') + && str_contains($data, 'To: recipient@example.test') + && str_contains($data, 'Subject: =?UTF-8?B?U3RhdHVzIHVwZGF0ZQ==?=') + && str_contains($data, "..leading dot\r\n"); + } + if ($passed) { + $reply = !empty($scenario['reject_message']) ? '554 message rejected' : '250 message accepted'; + $passed = smtpReply($client, $reply) && smtpReadLine($client) === 'QUIT' && smtpReply($client, '221 closing'); + } + + fclose($client); + exit($passed ? 0 : 1); + } + + fclose($server); + $config = [ + 'transport' => 'smtp', + 'host' => '127.0.0.1', + 'port' => $port, + 'encryption' => 'none', + 'username' => !empty($scenario['auth']) ? 'test-user' : '', + 'password' => !empty($scenario['auth']) ? 'test-password' : '', + 'from_address' => 'sender@example.test', + 'from_name' => 'Plugi Test', + 'timeout' => 3, + ]; + $result = (new Mailer($config))->send('recipient@example.test', 'Status update', "First line\r\n.leading dot\r\nLast line"); + pcntl_waitpid($pid, $status); + if (!pcntl_wifexited($status) || pcntl_wexitstatus($status) !== 0) { + throw new RuntimeException('The scripted SMTP peer observed an unexpected protocol exchange.'); + } + + return [$result, $config]; +} + +function baseMailerConfig(): array +{ + return [ + 'transport' => 'smtp', + 'host' => '127.0.0.1', + 'port' => 587, + 'encryption' => 'tls', + 'username' => '', + 'password' => '', + 'from_address' => 'sender@example.test', + 'from_name' => 'Plugi Test', + 'timeout' => 1, + ]; +} + +[$success, $config] = runSmtpPeer(['auth' => true]); +assertMailerSame(true, $success, 'Authenticated SMTP delivery must succeed'); + +[$authFailure] = runSmtpPeer(['auth' => true, 'reject_auth' => true]); +assertMailerSame(false, $authFailure, 'Rejected SMTP authentication must fail'); + +[$recipientFailure] = runSmtpPeer(['reject_recipient' => true]); +assertMailerSame(false, $recipientFailure, 'A rejected SMTP recipient must fail'); + +[$messageFailure] = runSmtpPeer(['reject_message' => true]); +assertMailerSame(false, $messageFailure, 'A rejected SMTP message must fail'); + +$invalidConfig = baseMailerConfig(); +$invalidConfig['host'] = ''; +assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP configuration must fail safely'); + +$invalidConfig = baseMailerConfig(); +$invalidConfig['username'] = 'only-a-username'; +assertMailerSame(false, (new Mailer($invalidConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Incomplete SMTP authentication settings must fail safely'); + +assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('not-an-email', 'Subject', 'Body'), 'Invalid recipients must fail safely'); +assertMailerSame(false, (new Mailer(baseMailerConfig()))->send('recipient@example.test', "Subject\r\nBcc: other@example.test", 'Body'), 'Header injection must fail safely'); + +$unavailableServer = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage); +if (!is_resource($unavailableServer)) { + throw new RuntimeException('Could not allocate a port for the SMTP connection-failure check.'); +} +$unavailableAddress = stream_socket_get_name($unavailableServer, false); +$unavailablePort = (int) substr(strrchr($unavailableAddress, ':'), 1); +fclose($unavailableServer); +$unavailableConfig = baseMailerConfig(); +$unavailableConfig['host'] = '127.0.0.1'; +$unavailableConfig['port'] = $unavailablePort; +$unavailableConfig['encryption'] = 'none'; +assertMailerSame(false, (new Mailer($unavailableConfig))->send('recipient@example.test', 'Subject', 'Body'), 'Connection refusal must fail safely'); + +$rootConfig = require dirname(__DIR__, 2) . '/config.php'; +$templateConfig = require dirname(__DIR__, 2) . '/config.dist.php'; +$mailKeys = ['class', 'transport', 'host', 'port', 'encryption', 'username', 'password', 'from_address', 'from_name', 'timeout']; +assertMailerSame($mailKeys, array_keys($rootConfig['mail']), 'Root SMTP settings must expose the documented keys'); +assertMailerSame($mailKeys, array_keys($templateConfig['mail']), 'Template SMTP settings must expose the documented keys'); +assertMailerSame(Plugi\Core\Mailer::class, $rootConfig['mail']['class'], 'Root configuration must select the core mailer'); +assertMailerSame('', $templateConfig['mail']['username'], 'Template SMTP username must not contain credentials'); +assertMailerSame('', $templateConfig['mail']['password'], 'Template SMTP password must not contain credentials'); + +fwrite(STDOUT, "Mailer tests passed.\n"); \ No newline at end of file