initial commit

This commit is contained in:
rsgrinko committed 2026-09-12 23:55:44 +03:00
commit 3f64f4a49a
221 files changed
+26665

No files matched your search

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
/**
* Способ доставки письма. Новый драйвер — класс с этими двумя методами
* и строка в реестре Mail::DRIVERS (либо подмена через событие mail.driver).
*/
interface DriverInterface
{
/**
* Отправляет письмо. Не смог — бросает исключение: молча терять письмо нельзя.
*/
public function send(Message $message): void;
/**
* Короткое имя для логов и страницы состояния.
*/
public function name(): string;
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\Config;
/**
* Письмо не уходит никуда, а сохраняется файлом .eml в var/log/mail.
*
* Режим для разработки: письмо со ссылкой подтверждения можно открыть в любом
* почтовом клиенте и нажать кнопку, ничего никому не отправив.
*/
final class LogDriver implements DriverInterface
{
public function send(Message $message): void
{
$dir = (string) Config::get('paths.log', APP_ROOT . '/var/log') . '/mail';
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$name = date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.eml';
@file_put_contents($dir . '/' . $name, Mime::build($message));
}
public function name(): string
{
return 'log';
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Отправка через встроенную функцию mail() — то есть через sendmail хостинга.
*
* Драйвер по умолчанию: работает везде и не требует настроек. Очереди и повторов
* у него нет, ошибку он показывает одним булевым значением — для рабочего проекта
* лучше SMTP или почтовый сервис, но для старта этого достаточно.
*/
final class MailDriver implements DriverInterface
{
public function send(Message $message): void
{
$body = Mime::body($message);
$headers = array_merge(Mime::headers($message, false), $body['headers']);
// Получателей mail() принимает отдельным аргументом, в заголовках их быть
// не должно — иначе адресат увидит себя дважды
if ($message->copies() !== []) {
$headers['Cc'] = implode(', ', $message->copies());
}
if ($message->blindCopies() !== []) {
$headers['Bcc'] = implode(', ', $message->blindCopies());
}
$lines = [];
foreach ($headers as $name => $value) {
$lines[] = $name . ': ' . $value;
}
// Пятый аргумент задаёт обратный адрес конверта: без него письма уходят
// от пользователя веб-сервера и часто попадают в спам
$sent = @mail(
implode(', ', $message->recipients()),
Mime::encodeHeader($message->subjectLine()),
$body['body'],
implode("\r\n", $lines),
'-f' . $message->senderEmail()
);
if (!$sent) {
throw new ProtonException('Функция mail() не приняла письмо. Проверьте sendmail_path в php.ini');
}
}
public function name(): string
{
return 'mail';
}
}
@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
use Rsgrinko\Proton\Support\RequestId;
/**
* Отправка через внешний почтовый сервис по HTTP API.
*
* Письмо уходит одним запросом POST /api/v1/messages с ключом проекта в
* заголовке Authorization. Очередь, повторы, стоп-лист, DKIM и отчёты о доставке
* остаются на стороне сервиса — приложению нужно только отдать письмо.
*
* Адрес и ключ задаются настройками MAIL_SERVICE_URL и MAIL_SERVICE_KEY.
* curl не обязателен: если расширения нет, запрос уходит потоками.
*/
final class MailerServiceDriver implements DriverInterface
{
public function send(Message $message): void
{
$url = rtrim((string) Config::get('mail.service.url', ''), '/');
$key = (string) Config::get('mail.service.key', '');
if ($url === '' || $key === '') {
throw new ProtonException('Для драйвера mailer нужны MAIL_SERVICE_URL и MAIL_SERVICE_KEY');
}
$payload = $message->toArray();
// Сервис ждёт получателей строкой или списком — отдаём список,
// а пустые поля не шлём вовсе, чтобы не спорить с его валидацией
$body = array_filter([
'to' => $payload['to'],
'cc' => $payload['cc'],
'bcc' => $payload['bcc'],
'from' => $payload['from'],
'from_name' => $payload['from_name'],
'reply_to' => $payload['reply_to'],
'subject' => $payload['subject'],
'text' => $payload['text'],
'html' => $payload['html'],
'headers' => $payload['headers'],
'attachments' => $payload['attachments'],
], static fn (mixed $value): bool => $value !== '' && $value !== []);
$response = $this->post(
$url . '/api/v1/messages',
(string) json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
[
'Content-Type: application/json',
'Authorization: Bearer ' . $key,
// Своя цепочка запросов доезжает до сервиса и находится в его логах
RequestId::HEADER . ': ' . RequestId::current(),
]
);
if ($response['status'] < 200 || $response['status'] >= 300) {
$decoded = json_decode($response['body'], true);
$detail = is_array($decoded) ? (string) ($decoded['error']['message'] ?? '') : '';
throw new ProtonException(
'Почтовый сервис ответил ' . $response['status']
. ($detail !== '' ? ': ' . $detail : '')
);
}
}
public function name(): string
{
return 'mailer';
}
/**
* @param array<int, string> $headers
*
* @return array{status: int, body: string}
*/
private function post(string $url, string $body, array $headers): array
{
$timeout = max(2, (int) Config::get('mail.service.timeout', 10));
if (function_exists('curl_init')) {
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
]);
$response = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response === false) {
throw new ProtonException('Почтовый сервис недоступен: ' . $error);
}
return ['status' => $status, 'body' => (string) $response];
}
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $body,
'timeout' => $timeout,
// Нужен ответ, а не исключение: код разбираем сами
'ignore_errors' => true,
],
]);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
throw new ProtonException('Почтовый сервис недоступен: ' . $url);
}
$status = 0;
foreach ($http_response_header ?? [] as $header) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches) === 1) {
$status = (int) $matches[1];
}
}
return ['status' => $status, 'body' => $response];
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
/**
* Заглушка: письмо никуда не идёт и нигде не сохраняется.
* Нужна тестам — проверить, что письмо собралось, можно через Mail::sent().
*/
final class NullDriver implements DriverInterface
{
public function send(Message $message): void
{
// Ничего не делаем: письмо считается отправленным
}
public function name(): string
{
return 'null';
}
}
+259
View File
@@ -0,0 +1,259 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Mail\Drivers;
use Rsgrinko\Proton\Mail\Message;
use Rsgrinko\Proton\Mail\Mime;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Свой SMTP-клиент на потоках: ни composer, ни расширений, кроме openssl.
*
* Понимает голое соединение, SSL (порт 465) и STARTTLS (587), вход LOGIN и PLAIN —
* выбирается тот способ, который сервер объявил в ответе на EHLO. Соединение
* живёт от письма к письму: перед каждым следующим идёт RSET, он же проверка,
* что сервер не закрыл связь.
*/
final class SmtpDriver implements DriverInterface
{
/** @var resource|null */
private $socket = null;
/** @var array<int, string> Что сервер объявил в ответе на EHLO */
private array $capabilities = [];
private int $sentInSession = 0;
public function send(Message $message): void
{
$this->connect();
try {
$this->deliver($message);
} catch (ProtonException $e) {
// Сессию после ошибки не переиспользуем: состояние диалога уже неясно
$this->close();
throw $e;
}
$this->sentInSession++;
$limit = (int) Config::get('mail.smtp.session_limit', 100);
if ($limit > 0 && $this->sentInSession >= $limit) {
$this->close();
}
}
public function name(): string
{
return 'smtp';
}
public function __destruct()
{
$this->close();
}
/**
* Закрывает сессию — воркер зовёт это, когда очередь опустела.
*/
public function close(): void
{
if (is_resource($this->socket)) {
@fwrite($this->socket, "QUIT\r\n");
@fclose($this->socket);
}
$this->socket = null;
$this->capabilities = [];
$this->sentInSession = 0;
}
private function deliver(Message $message): void
{
$this->command('MAIL FROM:<' . $this->assertAddress($message->senderEmail()) . '>', [250]);
foreach ($message->envelopeRecipients() as $recipient) {
$this->command('RCPT TO:<' . $this->assertAddress($recipient) . '>', [250, 251]);
}
$this->command('DATA', [354]);
// Точка в начале строки — конец письма для SMTP, поэтому её удваивают
$body = preg_replace('/^\./m', '..', Mime::build($message)) ?? '';
$this->write($body . "\r\n.\r\n");
$this->expect([250]);
}
/**
* Поднимает соединение, если его ещё нет или сервер его закрыл.
*/
private function connect(): void
{
if (is_resource($this->socket)) {
// RSET заодно проверяет, жива ли связь
try {
$this->command('RSET', [250]);
return;
} catch (ProtonException) {
$this->close();
}
}
$host = (string) Config::get('mail.smtp.host', '127.0.0.1');
$port = (int) Config::get('mail.smtp.port', 25);
$encryption = strtolower((string) Config::get('mail.smtp.encryption', ''));
$timeout = max(5, (int) Config::get('mail.smtp.timeout', 30));
$address = ($encryption === 'ssl' ? 'ssl://' : 'tcp://') . $host . ':' . $port;
$context = stream_context_create([
'ssl' => [
'verify_peer' => (bool) Config::get('mail.smtp.verify_peer', true),
'verify_peer_name' => (bool) Config::get('mail.smtp.verify_peer', true),
'allow_self_signed' => !(bool) Config::get('mail.smtp.verify_peer', true),
],
]);
$socket = @stream_socket_client($address, $code, $error, $timeout, STREAM_CLIENT_CONNECT, $context);
if ($socket === false) {
throw new ProtonException('Не удалось подключиться к SMTP ' . $address . ': ' . $error . ' (' . $code . ')');
}
stream_set_timeout($socket, $timeout);
$this->socket = $socket;
$this->expect([220]);
$this->hello();
if ($encryption === 'tls') {
$this->command('STARTTLS', [220]);
if (!@stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
$last = error_get_last();
$this->close();
// Причина обычно не в сервере, а в самом PHP: не собран openssl.cafile
throw new ProtonException('Не удалось установить TLS: ' . (string) ($last['message'] ?? 'причина неизвестна'));
}
// После STARTTLS список возможностей объявляется заново
$this->hello();
}
$this->authenticate();
}
private function hello(): void
{
$name = (string) Config::get('mail.smtp.helo', '') ?: (string) (gethostname() ?: 'localhost');
$response = $this->command('EHLO ' . $name, [250], true);
$this->capabilities = array_map('strtoupper', explode("\n", $response));
}
private function authenticate(): void
{
$user = (string) Config::get('mail.smtp.username', '');
$password = (string) Config::get('mail.smtp.password', '');
if ($user === '') {
return;
}
$supports = static fn (array $lines, string $needle): bool => array_filter(
$lines,
static fn (string $line): bool => str_contains($line, $needle)
) !== [];
if ($supports($this->capabilities, 'AUTH') && $supports($this->capabilities, 'PLAIN')) {
$this->command('AUTH PLAIN ' . base64_encode("\0" . $user . "\0" . $password), [235]);
return;
}
$this->command('AUTH LOGIN', [334]);
$this->command(base64_encode($user), [334]);
$this->command(base64_encode($password), [235]);
}
/**
* Отправляет команду и проверяет код ответа.
*
* @param array<int, int> $expected
*/
private function command(string $command, array $expected, bool $multiline = false): string
{
$this->write($command . "\r\n");
return $this->expect($expected, $multiline);
}
private function write(string $data): void
{
if (!is_resource($this->socket) || @fwrite($this->socket, $data) === false) {
throw new ProtonException('Соединение с SMTP-сервером потеряно');
}
}
/**
* Читает ответ сервера и сверяет код.
*
* @param array<int, int> $expected
*/
private function expect(array $expected, bool $multiline = false): string
{
if (!is_resource($this->socket)) {
throw new ProtonException('Соединение с SMTP-сервером не открыто');
}
$lines = [];
do {
$line = fgets($this->socket, 1024);
if ($line === false) {
throw new ProtonException('SMTP-сервер закрыл соединение');
}
$lines[] = trim($line);
// Многострочный ответ: у всех строк, кроме последней, после кода стоит дефис
$more = strlen($line) > 3 && $line[3] === '-';
} while ($more);
$last = end($lines) ?: '';
$code = (int) substr($last, 0, 3);
if (!in_array($code, $expected, true)) {
throw new ProtonException('SMTP ответил «' . $last . '», ожидался код ' . implode(' или ', $expected));
}
return $multiline ? implode("\n", $lines) : $last;
}
/**
* Адрес конверта не должен содержать пробелов, скобок и управляющих символов:
* иначе в команду SMTP уезжает вторая строка.
*/
private function assertAddress(string $address): string
{
$address = trim($address);
if ($address === '' || preg_match('/^[^\s<>(),;:"\\\\\x00-\x1f]+@[^\s<>(),;:"\\\\\x00-\x1f]+$/', $address) !== 1) {
throw new ProtonException('Недопустимый адрес для SMTP: ' . $address);
}
return $address;
}
}