You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Mail.php

200 lines
5.9 KiB
PHP

<?php
namespace App\Services;
/***
* Mail Service
*/
use App\Models\Configurations;
use App\Models\EmailLog;
use App\Services\Mail\Mailgun;
use App\Services\Mail\Smtp;
use App\Services\Mail\NullMail;
use Smarty;
use Throwable;
class Mail
{
private const EMAIL_BLACKLIST_CACHE_KEY = 'email_blacklist';
/**
* @return Mailgun|Smtp|NullMail
*/
public static function getClient()
{
$driver = Config::get("mailDriver");
switch ($driver) {
case "mailgun":
return new Mailgun();
case "smtp":
return new Smtp();
default:
return new NullMail();
}
}
/**
* @param $template
* @param $ary
* @return mixed
*/
public static function genHtml($template, $ary)
{
$smarty = new smarty();
$smarty->settemplatedir(BASE_PATH . '/resources/email/');
$smarty->setcompiledir(BASE_PATH . '/storage/framework/smarty/compile/');
$smarty->setcachedir(BASE_PATH . '/storage/framework/smarty/cache/');
// add config
$smarty->assign('config', Config::getPublicConfig());
foreach ($ary as $key => $value) {
$smarty->assign($key, $value);
}
return $smarty->fetch($template);
}
/**
* @param $to
* @param $subject
* @param $template
* @param $ary
* @param $file
* @param $emailType
* @return bool Whether the mail provider accepted the message.
*/
public static function send($to, $subject, $template, $ary = [], $file = [], $emailType = null)
{
$sent = false;
try {
if (!self::isRecipientBlacklisted($to)) {
$text = self::genHtml($template, $ary);
$sent = self::getClient()->send($to, $subject, $text, $file) === true;
}
} catch (Throwable $exception) {
error_log('Email sending failed: ' . $exception->getMessage());
}
self::recordAttempt($to, $emailType ?? $subject, $sent);
return $sent;
}
private static function recordAttempt($to, $emailType, $sent)
{
try {
$log = new EmailLog();
$log->email = is_array($to) ? implode(', ', array_map('strval', $to)) : (string) $to;
$log->email_type = (string) $emailType;
$originalIp = defined('ORIGINAL_REMOTE_ADDR') ? (string) ORIGINAL_REMOTE_ADDR : '';
$log->ip = $originalIp !== ''
? $originalIp
: (!empty($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '127.0.0.1');
$log->request_domain = !empty($_SERVER['HTTP_HOST']) ? (string) $_SERVER['HTTP_HOST'] : null;
$log->date = time();
$log->status = $sent ? 1 : 0;
if (!$log->save()) {
error_log('Email attempt could not be recorded for ' . $log->email);
}
} catch (Throwable $exception) {
error_log('Email attempt could not be recorded: ' . $exception->getMessage());
}
}
public static function isRecipientBlacklisted($to)
{
return self::isRecipientBlacklistedByRules($to, self::emailBlacklistRules());
}
public static function isRecipientBlacklistedByRules($to, array $rules)
{
$emails = self::normalizeRecipients($to);
if (empty($emails)) {
return false;
}
if (empty($rules)) {
return false;
}
foreach ($emails as $email) {
$domain = substr(strrchr($email, '@'), 1);
foreach ($rules as $rule) {
if ($rule === $email) {
return true;
}
if (strpos($rule, '*@') === 0 && substr($rule, 1) === '@' . $domain) {
return true;
}
if (strpos($rule, '@') === 0 && $rule === '@' . $domain) {
return true;
}
}
}
return false;
}
public static function parseEmailBlacklistRules($raw)
{
$rules = [];
foreach (preg_split('/\r\n|\r|\n|,|;/', (string) $raw) as $line) {
$rule = strtolower(trim((string) $line));
if ($rule === '' || strpos($rule, '#') === 0) {
continue;
}
if (strpos($rule, '#') !== false) {
$rule = trim(explode('#', $rule, 2)[0]);
}
if ($rule === '') {
continue;
}
if (filter_var($rule, FILTER_VALIDATE_EMAIL) || strpos($rule, '@') === 0 || strpos($rule, '*@') === 0) {
$rules[] = $rule;
}
}
return array_values(array_unique($rules));
}
private static function normalizeRecipients($to)
{
$items = is_array($to) ? $to : preg_split('/[,;]+/', (string) $to);
$emails = [];
foreach ($items as $item) {
$email = strtolower(trim((string) $item));
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emails[] = $email;
}
}
return array_values(array_unique($emails));
}
private static function emailBlacklistRules()
{
$raw = '';
try {
$redis = new RedisClient();
$raw = (string) $redis->get(self::EMAIL_BLACKLIST_CACHE_KEY, 60, function () {
$value = Configurations::where('name', self::EMAIL_BLACKLIST_CACHE_KEY)->value('value');
return $value === null ? '' : $value;
});
} catch (\Exception $exception) {
try {
$value = Configurations::where('name', self::EMAIL_BLACKLIST_CACHE_KEY)->value('value');
$raw = $value === null ? '' : (string) $value;
} catch (\Exception $innerException) {
$raw = '';
}
}
return self::parseEmailBlacklistRules($raw);
}
}