WebOrbiton
v1.0.1

AtheraStudio Database

139 lines · 5.8 KB
  1. <?php
  2. declare(strict_types=1);
  3. ​
  4. namespace Athera;
  5. ​
  6. defined('ATHERA') || exit;
  7. ​
  8. final class Mailer
  9. {
  10. public static string $lastError = '';
  11. ​
  12. public static function send(string $to, string $subject, string $body): bool
  13. {
  14. self::$lastError = '';
  15. $to = trim($to);
  16. if (!filter_var($to, FILTER_VALIDATE_EMAIL) || preg_match('/[\r\n,;]/', $to)) {
  17. self::$lastError = 'Invalid recipient';
  18. return false;
  19. }
  20. $subject = trim(preg_replace('/[\r\n\t]+/', ' ', $subject));
  21. $from = self::from();
  22. $body = str_replace(["\r\n", "\r"], "\n", $body);
  23. try {
  24. return Config::get('SMTP_HOST') !== '' ? self::smtp($to, $from, $subject, $body) : self::native($to, $from, $subject, $body);
  25. } catch (\Throwable $e) {
  26. self::$lastError = $e->getMessage();
  27. return false;
  28. }
  29. }
  30. ​
  31. private static function from(): string
  32. {
  33. $from = Config::get('MAIL_FROM');
  34. if (filter_var($from, FILTER_VALIDATE_EMAIL) && !preg_match('/[\r\n]/', $from)) return $from;
  35. $host = strtolower((string)($_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'] ?? 'localhost'));
  36. $host = preg_replace('/:\d+$/', '', $host);
  37. $host = preg_replace('/^www\./', '', $host);
  38. if (!preg_match('/^[a-z0-9.\-]+\.[a-z]{2,}$/', $host)) $host = 'localhost.localdomain';
  39. return 'no-reply@' . $host;
  40. }
  41. ​
  42. private static function headers(string $from, string $subject, bool $withSubject, string $to = ''): array
  43. {
  44. $domain = substr(strrchr($from, '@'), 1);
  45. $h = [
  46. 'Date: ' . date('r'),
  47. 'From: AtheraStudio Database <' . $from . '>',
  48. 'Message-ID: <' . bin2hex(random_bytes(12)) . '@' . $domain . '>',
  49. 'MIME-Version: 1.0',
  50. 'Content-Type: text/plain; charset=UTF-8',
  51. 'Content-Transfer-Encoding: base64',
  52. 'X-Auto-Response-Suppress: All',
  53. 'Auto-Submitted: auto-generated',
  54. ];
  55. if ($withSubject) {
  56. array_unshift($h, 'To: <' . $to . '>');
  57. array_unshift($h, 'Subject: ' . self::encode($subject));
  58. }
  59. return $h;
  60. }
  61. ​
  62. private static function encode(string $s): string
  63. {
  64. return preg_match('/[^\x20-\x7E]/', $s) ? '=?UTF-8?B?' . base64_encode($s) . '?=' : $s;
  65. }
  66. ​
  67. private static function native(string $to, string $from, string $subject, string $body): bool
  68. {
  69. if (!function_exists('mail')) {
  70. self::$lastError = 'mail() is disabled on this server';
  71. return false;
  72. }
  73. $headers = implode("\r\n", self::headers($from, $subject, false));
  74. $payload = rtrim(chunk_split(base64_encode($body), 76, "\r\n"));
  75. $ok = false;
  76. if (Config::get('MAIL_FROM') !== '') {
  77. $ok = @mail($to, self::encode($subject), $payload, $headers, '-f' . $from);
  78. }
  79. if (!$ok) $ok = @mail($to, self::encode($subject), $payload, $headers);
  80. if (!$ok) self::$lastError = 'mail() returned false';
  81. return $ok;
  82. }
  83. ​
  84. private static function smtp(string $to, string $from, string $subject, string $body): bool
  85. {
  86. $host = Config::get('SMTP_HOST');
  87. $port = Config::int('SMTP_PORT', 1, 65535);
  88. $secure = strtolower(Config::get('SMTP_SECURE'));
  89. $ctx = stream_context_create(['ssl' => ['verify_peer' => true, 'verify_peer_name' => true, 'peer_name' => $host]]);
  90. $target = ($secure === 'ssl' ? 'ssl://' : 'tcp://') . $host . ':' . $port;
  91. $s = @stream_socket_client($target, $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $ctx);
  92. if (!$s) throw new \RuntimeException('SMTP connect failed: ' . $errstr);
  93. stream_set_timeout($s, 20);
  94. $read = function () use ($s): array {
  95. $text = '';
  96. while (($line = fgets($s, 1024)) !== false) {
  97. $text .= $line;
  98. if (strlen($line) < 4 || $line[3] !== '-') break;
  99. }
  100. return [(int)substr($text, 0, 3), trim($text)];
  101. };
  102. $cmd = function (string $c, array $ok) use ($s, $read): array {
  103. fwrite($s, $c . "\r\n");
  104. $r = $read();
  105. if (!in_array($r[0], $ok, true)) throw new \RuntimeException('SMTP: ' . preg_replace('/\s+/', ' ', $r[1]));
  106. return $r;
  107. };
  108. try {
  109. $r = $read();
  110. if ($r[0] !== 220) throw new \RuntimeException('SMTP: ' . $r[1]);
  111. $ehlo = preg_replace('/[^a-z0-9.\-]/i', '', (string)($_SERVER['SERVER_NAME'] ?? 'localhost')) ?: 'localhost';
  112. $r = $cmd('EHLO ' . $ehlo, [250]);
  113. if ($secure === 'tls') {
  114. $cmd('STARTTLS', [220]);
  115. if (!stream_socket_enable_crypto($s, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT : 0))) {
  116. throw new \RuntimeException('SMTP: TLS negotiation failed');
  117. }
  118. $cmd('EHLO ' . $ehlo, [250]);
  119. }
  120. if (Config::get('SMTP_USER') !== '') {
  121. $cmd('AUTH LOGIN', [334]);
  122. $cmd(base64_encode(Config::get('SMTP_USER')), [334]);
  123. $cmd(base64_encode(Config::get('SMTP_PASS')), [235]);
  124. }
  125. $cmd('MAIL FROM:<' . $from . '>', [250]);
  126. $cmd('RCPT TO:<' . $to . '>', [250, 251]);
  127. $cmd('DATA', [354]);
  128. $msg = implode("\r\n", self::headers($from, $subject, true, $to)) . "\r\n\r\n" . chunk_split(base64_encode($body), 76, "\r\n");
  129. fwrite($s, $msg . ".\r\n");
  130. $r = $read();
  131. if ($r[0] !== 250) throw new \RuntimeException('SMTP: ' . $r[1]);
  132. fwrite($s, "QUIT\r\n");
  133. return true;
  134. } finally {
  135. fclose($s);
  136. }
  137. }
  138. }
  139. ​