Sync global-autoresponder current state
This commit is contained in:
+60
-7
@@ -33,9 +33,10 @@ final class AppContext
|
||||
return $url;
|
||||
}
|
||||
|
||||
public function t(string $key): string
|
||||
/** @param array<string,string|int|float> $vars */
|
||||
public function t(string $key, array $vars = []): string
|
||||
{
|
||||
return $this->lang->t($key);
|
||||
return $this->lang->t($key, $vars);
|
||||
}
|
||||
|
||||
public function post(string $key, string $default = ''): string
|
||||
@@ -70,11 +71,8 @@ final class AppContext
|
||||
}
|
||||
}
|
||||
|
||||
public function syncActiveBackend(): void
|
||||
public function syncDirectAdminVacations(): void
|
||||
{
|
||||
if ($this->settings->backendMode() !== 'da') {
|
||||
return;
|
||||
}
|
||||
$service = new DirectAdminVacationSyncService(
|
||||
$this->rules,
|
||||
new DirectAdminSyncRepository(),
|
||||
@@ -98,7 +96,7 @@ final class AppContext
|
||||
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
|
||||
echo '<title>' . self::e($this->t($title)) . '</title><style>' . $this->styles() . '</style></head><body>';
|
||||
echo '<div class="wrap"><div class="breadcrumbs">' . self::e($this->t('Dashboard')) . ' <span>></span> ' . self::e($this->t('Global autoresponders')) . '</div>';
|
||||
echo '<header><h1>' . self::e($this->t($title)) . '</h1><p>' . self::e($this->t('Manage automatic replies for account mailboxes')) . '</p></header>';
|
||||
echo '<header><h1>' . self::e($this->t($title)) . '</h1></header>';
|
||||
echo '<div class="top-actions"><a class="btn amber' . ($this->action() === 'index' ? ' active' : '') . '" href="' . self::e($this->url('index.html')) . '">' . self::e($this->t('AUTORESPONDERS')) . '</a>';
|
||||
echo '<a class="btn amber' . ($this->action() === 'create' ? ' active' : '') . '" href="' . self::e($this->url('create.html')) . '">' . self::e($this->t('ADD AUTORESPONDER')) . '</a></div>';
|
||||
echo '<section class="main-section">' . $alerts . $body . '</section></div>';
|
||||
@@ -113,6 +111,12 @@ final class AppContext
|
||||
private function styles(): string
|
||||
{
|
||||
$skin = $this->daUser->skin();
|
||||
if ($skin === 'evolution') {
|
||||
$base = PLUGIN_ROOT . '/user/enhanced.css';
|
||||
$override = PLUGIN_ROOT . '/user/evolution.css';
|
||||
return (is_file($base) ? (string)file_get_contents($base) : '') . "\n" .
|
||||
(is_file($override) ? (string)file_get_contents($override) : '');
|
||||
}
|
||||
$path = PLUGIN_ROOT . '/user/' . $skin . '.css';
|
||||
if (!is_file($path)) {
|
||||
$path = PLUGIN_ROOT . '/user/enhanced.css';
|
||||
@@ -122,14 +126,39 @@ final class AppContext
|
||||
|
||||
private function scripts(): string
|
||||
{
|
||||
$skin = json_encode($this->daUser->skin(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
|
||||
$selectedLabel = json_encode($this->t('Selected'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
|
||||
$monthNames = json_encode($this->lang->code() === 'pl'
|
||||
? ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień']
|
||||
: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
|
||||
return <<<JS
|
||||
(function () {
|
||||
var pluginSkin = {$skin};
|
||||
var selectedLabel = {$selectedLabel};
|
||||
var monthNames = {$monthNames};
|
||||
function expandDirectAdminPluginContainers() {
|
||||
if (pluginSkin !== 'evolution') { return; }
|
||||
var wrap = document.querySelector('.wrap');
|
||||
if (!wrap) { return; }
|
||||
wrap.style.width = '100%';
|
||||
wrap.style.maxWidth = 'none';
|
||||
wrap.style.marginLeft = '0';
|
||||
wrap.style.marginRight = '0';
|
||||
var node = wrap.parentElement;
|
||||
var guard = 0;
|
||||
while (node && node !== document.body && guard < 12) {
|
||||
var id = node.id || '';
|
||||
var className = typeof node.className === 'string' ? node.className : '';
|
||||
var matchesDirectAdminContainer = id === 'content' || /(^|\\s)(container|container-fluid|main-content|page-content|content|content-wrapper|main-content-wrapper)(\\s|$)/.test(className);
|
||||
var computed = window.getComputedStyle ? window.getComputedStyle(node) : null;
|
||||
if (matchesDirectAdminContainer || (computed && computed.maxWidth && computed.maxWidth !== 'none')) {
|
||||
node.style.maxWidth = 'none';
|
||||
node.style.width = '100%';
|
||||
}
|
||||
node = node.parentElement;
|
||||
guard++;
|
||||
}
|
||||
}
|
||||
function pad(value) { return value < 10 ? '0' + value : String(value); }
|
||||
function updateCanonical(name) {
|
||||
var date = document.getElementById(name + '_date');
|
||||
@@ -195,6 +224,11 @@ final class AppContext
|
||||
document.querySelectorAll('[data-date-value]').forEach(function (btn) {
|
||||
bindDateButton(btn);
|
||||
});
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', expandDirectAdminPluginContainers);
|
||||
} else {
|
||||
expandDirectAdminPluginContainers();
|
||||
}
|
||||
document.querySelectorAll('[data-calendar-picker]').forEach(function (calendar) {
|
||||
var name = calendar.getAttribute('data-calendar-name');
|
||||
calendar.querySelectorAll('[data-calendar-prev],[data-calendar-next]').forEach(function (btn) {
|
||||
@@ -214,6 +248,25 @@ final class AppContext
|
||||
control.addEventListener('input', function () { updateCanonical(name); });
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('[data-modal-close]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var overlay = btn.closest('.br-overlay');
|
||||
if (overlay) {
|
||||
overlay.style.display = 'none';
|
||||
}
|
||||
document.body.classList.remove('modal-open');
|
||||
});
|
||||
});
|
||||
if (document.querySelector('.br-overlay')) {
|
||||
document.body.classList.add('modal-open');
|
||||
}
|
||||
document.addEventListener('keydown', function (event) {
|
||||
if (event.key !== 'Escape') { return; }
|
||||
document.querySelectorAll('.br-overlay').forEach(function (overlay) {
|
||||
overlay.style.display = 'none';
|
||||
});
|
||||
document.body.classList.remove('modal-open');
|
||||
});
|
||||
})();
|
||||
JS;
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class BackendRuntimeConfig
|
||||
{
|
||||
public static function sync(Settings $settings, string $backendScript, string $statePath = Settings::CONFIG_DIR . '/backend-state.json', string $errorLog = ''): void
|
||||
{
|
||||
$desired = $settings->backendMode();
|
||||
$current = self::currentBackend($statePath);
|
||||
if ($current === $desired) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_file($backendScript) || !is_executable($backendScript)) {
|
||||
self::log($errorLog, 'Backend script not executable: ' . $backendScript);
|
||||
return;
|
||||
}
|
||||
|
||||
$process = proc_open([$backendScript, $desired], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
||||
if (!is_resource($process)) {
|
||||
self::log($errorLog, 'Could not start backend script.');
|
||||
return;
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
stream_get_contents($pipes[1]);
|
||||
$stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
$code = proc_close($process);
|
||||
if ($code !== 0) {
|
||||
self::log($errorLog, 'Backend script failed with code ' . $code . ': ' . trim($stderr));
|
||||
}
|
||||
}
|
||||
|
||||
private static function currentBackend(string $statePath): string
|
||||
{
|
||||
if (!is_file($statePath)) {
|
||||
return '';
|
||||
}
|
||||
$data = json_decode((string)file_get_contents($statePath), true);
|
||||
return is_array($data) ? (string)($data['active_backend'] ?? '') : '';
|
||||
}
|
||||
|
||||
private static function log(string $errorLog, string $message): void
|
||||
{
|
||||
if ($errorLog === '') {
|
||||
return;
|
||||
}
|
||||
@error_log('[' . date('c') . '] BACKEND_SYNC ' . $message . "\n", 3, $errorLog);
|
||||
}
|
||||
}
|
||||
@@ -14,22 +14,23 @@ final class DirectAdminUser
|
||||
throw new InvalidArgumentException('Invalid username');
|
||||
}
|
||||
$this->username = $username;
|
||||
$this->skin = $skin !== '' ? $skin : 'enhanced';
|
||||
$this->skin = self::normalizeSkin($skin);
|
||||
$this->language = $language !== '' ? strtolower($language) : 'en';
|
||||
$this->configDir = $configDir;
|
||||
}
|
||||
|
||||
public static function fromEnvironment(Settings $settings): self
|
||||
{
|
||||
$username = getenv('USERNAME') ?: getenv('USER') ?: getenv('DA_USER') ?: '';
|
||||
if ($username === '' && isset($_SERVER['USERNAME'])) {
|
||||
$username = (string)$_SERVER['USERNAME'];
|
||||
}
|
||||
$username = self::environmentValue(['USERNAME', 'DA_USER', 'USER']);
|
||||
if ($username === '') {
|
||||
throw new RuntimeException('Cannot determine DirectAdmin user');
|
||||
}
|
||||
$skin = getenv('SKIN') ?: (string)($_SERVER['SKIN'] ?? 'enhanced');
|
||||
$lang = self::readLanguage($username) ?: $settings->defaultLanguage();
|
||||
$userConf = self::readUserConf($username);
|
||||
$skin = self::environmentValue(['SKIN', 'SESSION_SKIN', 'SESSION_SELECTED_SKIN', 'DA_SKIN', 'USER_SKIN', 'THEME']);
|
||||
if ($skin === '') {
|
||||
$skin = (string)($userConf['skin'] ?? 'enhanced');
|
||||
}
|
||||
$lang = self::languageFromUserConf($userConf) ?: $settings->defaultLanguage();
|
||||
return new self($username, $skin, $lang);
|
||||
}
|
||||
|
||||
@@ -58,21 +59,65 @@ final class DirectAdminUser
|
||||
return $settings->defaultEnable();
|
||||
}
|
||||
|
||||
private static function readLanguage(string $username): string
|
||||
private static function normalizeSkin(string $skin): string
|
||||
{
|
||||
$path = '/usr/local/directadmin/data/users/' . $username . '/user.conf';
|
||||
if (!is_file($path)) {
|
||||
return '';
|
||||
$normalizedSkin = strtolower(trim($skin));
|
||||
if ($normalizedSkin === '') {
|
||||
return 'enhanced';
|
||||
}
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines === false) {
|
||||
return '';
|
||||
if (str_contains($normalizedSkin, 'evolution')) {
|
||||
return 'evolution';
|
||||
}
|
||||
foreach ($lines as $line) {
|
||||
if (str_starts_with($line, 'language=')) {
|
||||
return strtolower(trim(substr($line, 9)));
|
||||
return $normalizedSkin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $keys
|
||||
*/
|
||||
private static function environmentValue(array $keys): string
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
$value = getenv($key);
|
||||
if ($value !== false && trim((string)$value) !== '') {
|
||||
return trim((string)$value);
|
||||
}
|
||||
if (isset($_SERVER[$key]) && trim((string)$_SERVER[$key]) !== '') {
|
||||
return trim((string)$_SERVER[$key]);
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private static function readUserConf(string $username): array
|
||||
{
|
||||
$path = '/usr/local/directadmin/data/users/' . $username . '/user.conf';
|
||||
if (!is_file($path)) {
|
||||
return [];
|
||||
}
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines === false) {
|
||||
return [];
|
||||
}
|
||||
$data = [];
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
|
||||
continue;
|
||||
}
|
||||
[$key, $value] = explode('=', $line, 2);
|
||||
$data[trim($key)] = trim($value);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string> $userConf
|
||||
*/
|
||||
private static function languageFromUserConf(array $userConf): string
|
||||
{
|
||||
return strtolower(trim((string)($userConf['language'] ?? $userConf['lang'] ?? '')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ class DirectAdminVacationApi
|
||||
return [$m[1], $m[2]];
|
||||
}
|
||||
if (!preg_match('/^([0-9]{4}-[0-9]{2}-[0-9]{2})\|(morning|afternoon|evening)$/', $value, $m)) {
|
||||
throw new InvalidArgumentException('DirectAdmin API backend requires exact date-time values');
|
||||
throw new InvalidArgumentException('DirectAdmin vacation sync requires exact date-time values');
|
||||
}
|
||||
$time = ['morning' => '08:00', 'afternoon' => '13:00', 'evening' => $start ? '18:00' : '23:59'][$m[2]];
|
||||
return [$m[1], $time];
|
||||
@@ -147,9 +147,6 @@ class DirectAdminVacationApi
|
||||
/** @param array<string,mixed> $rule */
|
||||
private function replyOnceTime(array $rule): string
|
||||
{
|
||||
if (!empty($rule['reply_every_message'])) {
|
||||
return '1m';
|
||||
}
|
||||
return match ((int)($rule['repeat_minutes'] ?? 1440)) {
|
||||
1 => '1m',
|
||||
10 => '10m',
|
||||
|
||||
@@ -28,6 +28,40 @@ final class DirectAdminVacationSyncService
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<int,array{domain:string,mailbox:string,email:string}> */
|
||||
public function untrackedNativeVacations(string $username): array
|
||||
{
|
||||
$tracked = $this->trackedEmails($username);
|
||||
$out = [];
|
||||
foreach ($this->mailboxes->domainsForUser($username) as $domain) {
|
||||
foreach ($this->api->listVacations($username, $domain) as $local) {
|
||||
$email = strtolower($local . '@' . $domain);
|
||||
if (isset($tracked[$email])) {
|
||||
continue;
|
||||
}
|
||||
$out[] = [
|
||||
'domain' => $domain,
|
||||
'mailbox' => $local,
|
||||
'email' => $email,
|
||||
];
|
||||
}
|
||||
}
|
||||
usort($out, static fn (array $a, array $b): int => strcmp($a['email'], $b['email']));
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @param array<int,array<string,mixed>> $entries */
|
||||
public function deleteNativeVacations(string $username, array $entries): void
|
||||
{
|
||||
foreach ($entries as $entry) {
|
||||
$email = strtolower((string)($entry['email'] ?? ''));
|
||||
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
continue;
|
||||
}
|
||||
$this->api->deleteVacation($username, $email);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,array<string,mixed>> */
|
||||
private function rulesById(string $username): array
|
||||
{
|
||||
@@ -47,12 +81,20 @@ final class DirectAdminVacationSyncService
|
||||
$existing = $this->indexedEntries($this->sync->entriesForRule($username, $ruleId));
|
||||
$targets = $this->targetMailboxes($username, $rule);
|
||||
$next = [];
|
||||
$conflicts = [];
|
||||
foreach ($targets as $mailbox) {
|
||||
$email = strtolower((string)$mailbox['email']);
|
||||
$isTracked = isset($existing[$email]);
|
||||
if (!$isTracked && $this->api->vacationExists($username, $email)) {
|
||||
throw new RuntimeException('Untracked DirectAdmin vacation already exists for ' . $email);
|
||||
$conflicts[] = $email;
|
||||
}
|
||||
}
|
||||
if ($conflicts !== []) {
|
||||
throw new RuntimeException('Untracked DirectAdmin vacation already exists for ' . implode(', ', $conflicts));
|
||||
}
|
||||
foreach ($targets as $mailbox) {
|
||||
$email = strtolower((string)$mailbox['email']);
|
||||
$isTracked = isset($existing[$email]);
|
||||
$this->api->saveVacation($username, $email, $rule, $isTracked);
|
||||
$next[] = [
|
||||
'rule_id' => $ruleId,
|
||||
@@ -95,6 +137,21 @@ final class DirectAdminVacationSyncService
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @return array<string,bool> */
|
||||
private function trackedEmails(string $username): array
|
||||
{
|
||||
$tracked = [];
|
||||
foreach ($this->sync->allRuleEntries($username) as $entries) {
|
||||
foreach ($entries as $entry) {
|
||||
$email = strtolower((string)($entry['email'] ?? $entry['api_key'] ?? ''));
|
||||
if ($email !== '') {
|
||||
$tracked[$email] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $tracked;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $rule @return array<int,array{domain:string,mailbox:string,email:string}> */
|
||||
private function targetMailboxes(string $username, array $rule): array
|
||||
{
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class MailSender
|
||||
{
|
||||
public static function buildMessage(string $from, string $to, string $subject, string $body): string
|
||||
{
|
||||
foreach ([$from, $to, $subject] as $value) {
|
||||
if (str_contains($value, "\r") || str_contains($value, "\n")) {
|
||||
throw new InvalidArgumentException('Invalid subject or address header');
|
||||
}
|
||||
}
|
||||
$encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
|
||||
$headers = [
|
||||
'From: ' . $from,
|
||||
'To: ' . $to,
|
||||
'Subject: ' . $encodedSubject,
|
||||
'Auto-Submitted: auto-replied',
|
||||
'Content-Type: text/plain; charset=UTF-8',
|
||||
'Content-Transfer-Encoding: 8bit',
|
||||
];
|
||||
return implode("\n", $headers) . "\n\n" . str_replace(["\r\n", "\r"], "\n", $body) . "\n";
|
||||
}
|
||||
|
||||
public function send(string $sendmail, string $from, string $to, string $subject, string $body): bool
|
||||
{
|
||||
$message = self::buildMessage($from, $to, $subject, $body);
|
||||
if (!is_file($sendmail) || !is_executable($sendmail)) {
|
||||
return false;
|
||||
}
|
||||
$process = proc_open([$sendmail, '-t', '-i'], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return false;
|
||||
}
|
||||
fwrite($pipes[0], $message);
|
||||
fclose($pipes[0]);
|
||||
stream_get_contents($pipes[1]);
|
||||
stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
return proc_close($process) === 0;
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ final class MailboxDirectory
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
private function domainsForUser(string $username): array
|
||||
public function domainsForUser(string $username): array
|
||||
{
|
||||
$domains = [];
|
||||
foreach ($this->domainOwners() as $domain => $owner) {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class MessageClassifier
|
||||
{
|
||||
/** @param array<string,string> $headers */
|
||||
public static function shouldSuppress(array $headers, string $sender): bool
|
||||
{
|
||||
$sender = strtolower(trim($sender));
|
||||
if ($sender === '' || str_starts_with($sender, 'mailer-daemon') || str_starts_with($sender, 'postmaster')) {
|
||||
return true;
|
||||
}
|
||||
$normalized = [];
|
||||
foreach ($headers as $key => $value) {
|
||||
$normalized[strtolower(trim($key))] = strtolower(trim($value));
|
||||
}
|
||||
if (($normalized['auto-submitted'] ?? 'no') !== 'no') {
|
||||
return true;
|
||||
}
|
||||
if (in_array($normalized['precedence'] ?? '', ['bulk', 'list', 'junk'], true)) {
|
||||
return true;
|
||||
}
|
||||
if (($normalized['list-id'] ?? '') !== '') {
|
||||
return true;
|
||||
}
|
||||
if (str_contains($normalized['content-type'] ?? '', 'delivery-status')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ final class PluginLogger
|
||||
public static function init(string $path): void
|
||||
{
|
||||
self::$path = $path;
|
||||
self::ensureLogFile();
|
||||
@ini_set('log_errors', '1');
|
||||
@ini_set('error_log', $path);
|
||||
|
||||
@@ -67,4 +68,21 @@ final class PluginLogger
|
||||
default => 'E_' . $severity,
|
||||
};
|
||||
}
|
||||
|
||||
private static function ensureLogFile(): void
|
||||
{
|
||||
if (self::$path === '') {
|
||||
return;
|
||||
}
|
||||
$dir = dirname(self::$path);
|
||||
if (!is_dir($dir) || !is_writable($dir)) {
|
||||
return;
|
||||
}
|
||||
if (!is_file(self::$path)) {
|
||||
@file_put_contents(self::$path, '');
|
||||
}
|
||||
if (is_file(self::$path)) {
|
||||
@chmod(self::$path, 0600);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class RepeatState
|
||||
{
|
||||
public function __construct(private string $baseDir = Settings::STATE_DIR, private ?int $now = null)
|
||||
{
|
||||
}
|
||||
|
||||
public function shouldSend(string $owner, string $ruleId, string $recipient, string $sender, int $repeatMinutes): bool
|
||||
{
|
||||
if ($repeatMinutes <= 0) {
|
||||
return true;
|
||||
}
|
||||
$path = $this->path($owner, $ruleId, $recipient, $sender);
|
||||
if (!is_file($path)) {
|
||||
return true;
|
||||
}
|
||||
$data = json_decode((string)file_get_contents($path), true);
|
||||
$last = is_array($data) ? (int)($data['last_sent_at'] ?? 0) : 0;
|
||||
return ($this->time() - $last) >= ($repeatMinutes * 60);
|
||||
}
|
||||
|
||||
public function record(string $owner, string $ruleId, string $recipient, string $sender): void
|
||||
{
|
||||
$path = $this->path($owner, $ruleId, $recipient, $sender);
|
||||
$dir = dirname($path);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0700, true);
|
||||
}
|
||||
file_put_contents($path, json_encode(['last_sent_at' => $this->time()], JSON_PRETTY_PRINT), LOCK_EX);
|
||||
@chmod($path, 0600);
|
||||
}
|
||||
|
||||
private function path(string $owner, string $ruleId, string $recipient, string $sender): string
|
||||
{
|
||||
if (!preg_match('/^[A-Za-z0-9._-]+$/', $owner)) {
|
||||
throw new InvalidArgumentException('Invalid owner');
|
||||
}
|
||||
$hash = hash('sha256', implode('|', [$owner, $ruleId, strtolower($recipient), strtolower($sender)]));
|
||||
return rtrim($this->baseDir, '/') . '/replies/' . $owner . '/' . $hash . '.json';
|
||||
}
|
||||
|
||||
private function time(): int
|
||||
{
|
||||
return $this->now ?? time();
|
||||
}
|
||||
}
|
||||
+21
-14
@@ -29,8 +29,16 @@ final class RuleValidator
|
||||
];
|
||||
|
||||
/** @param array<string,mixed> $input @return array<string,mixed> */
|
||||
public static function validate(array $input, Settings $settings): array
|
||||
public static function validate(array $input, Settings $settings, bool $allowPastSchedule = false): array
|
||||
{
|
||||
$name = trim(str_replace(["\r\n", "\r", "\0"], ["\n", "\n", ''], (string)($input['name'] ?? '')));
|
||||
if (str_contains($name, "\n")) {
|
||||
throw new InvalidArgumentException('Nazwa autorespondera nie może zawierać nowych linii.');
|
||||
}
|
||||
if (strlen($name) > 255) {
|
||||
throw new InvalidArgumentException('Nazwa autorespondera jest za długa.');
|
||||
}
|
||||
|
||||
$subjectPrefix = trim((string)($input['subject_prefix'] ?? $input['subject'] ?? ''));
|
||||
if (str_contains($subjectPrefix, "\r") || str_contains($subjectPrefix, "\n")) {
|
||||
throw new InvalidArgumentException('Przedrostek tematu nie może zawierać nowych linii.');
|
||||
@@ -52,15 +60,22 @@ final class RuleValidator
|
||||
$tz = new DateTimeZone($settings->timezone());
|
||||
[$startTs, $startValue] = self::parseScheduleValue((string)($input['start_value'] ?? ''), $mode, $tz, true);
|
||||
[$endTs, $endValue] = self::parseScheduleValue((string)($input['end_value'] ?? ''), $mode, $tz, false);
|
||||
if (substr($startValue, 0, 10) < (new DateTimeImmutable('today', $tz))->format('Y-m-d')) {
|
||||
throw new InvalidArgumentException('Data rozpoczęcia nie może być wcześniejsza niż aktualna data.');
|
||||
if (!$allowPastSchedule) {
|
||||
$today = (new DateTimeImmutable('today', $tz))->format('Y-m-d');
|
||||
if (substr($startValue, 0, 10) < $today) {
|
||||
throw new InvalidArgumentException('Data rozpoczęcia nie może być wcześniejsza niż aktualna data.');
|
||||
}
|
||||
if (substr($endValue, 0, 10) < $today) {
|
||||
throw new InvalidArgumentException('Data zakończenia nie może być wcześniejsza niż aktualna data.');
|
||||
}
|
||||
}
|
||||
if ($endTs <= $startTs) {
|
||||
throw new InvalidArgumentException('Data zakończenia musi być późniejsza niż data rozpoczęcia.');
|
||||
}
|
||||
[$replyEveryMessage, $repeatMinutes] = self::parseReplyFrequency((string)($input['reply_frequency'] ?? '1440'), $settings);
|
||||
$repeatMinutes = self::parseReplyFrequency((string)($input['reply_frequency'] ?? '1440'));
|
||||
|
||||
return [
|
||||
'name' => $name,
|
||||
'subject_prefix' => $subjectPrefix,
|
||||
'body' => $body,
|
||||
'schedule_mode' => $mode,
|
||||
@@ -70,24 +85,16 @@ final class RuleValidator
|
||||
'start_ts' => $startTs,
|
||||
'end_ts' => $endTs,
|
||||
'enabled' => self::truthy($input['enabled'] ?? false),
|
||||
'reply_every_message' => $replyEveryMessage,
|
||||
'repeat_minutes' => $repeatMinutes,
|
||||
'dynamic_scope' => $settings->dynamicMailboxScope(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{0:bool,1:int} */
|
||||
private static function parseReplyFrequency(string $value, Settings $settings): array
|
||||
private static function parseReplyFrequency(string $value): int
|
||||
{
|
||||
$value = trim(strtolower($value));
|
||||
if ($value === 'every') {
|
||||
if ($settings->backendMode() === 'da') {
|
||||
throw new InvalidArgumentException('Częstość odpowiedzi jest nieprawidłowa.');
|
||||
}
|
||||
return [true, 0];
|
||||
}
|
||||
if (isset(self::REPLY_FREQUENCIES[$value])) {
|
||||
return [false, self::REPLY_FREQUENCIES[$value]];
|
||||
return self::REPLY_FREQUENCIES[$value];
|
||||
}
|
||||
throw new InvalidArgumentException('Częstość odpowiedzi jest nieprawidłowa.');
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ final class Settings
|
||||
public const BASE_DIR = '/usr/local/hitme_plugins/global-autoresponders';
|
||||
public const CONFIG_DIR = self::BASE_DIR . '/config';
|
||||
public const DATA_DIR = self::BASE_DIR . '/data';
|
||||
public const STATE_DIR = self::BASE_DIR . '/state';
|
||||
public const LOG_DIR = self::BASE_DIR . '/logs';
|
||||
public const AUDIT_LOG = self::LOG_DIR . '/audit.log';
|
||||
public const EXTERNAL_SETTINGS = self::CONFIG_DIR . '/plugin-settings.conf';
|
||||
@@ -51,7 +50,6 @@ final class Settings
|
||||
'DEFAULT_PLUGIN_LANGUAGE' => 'pl',
|
||||
'DEFAULT_ENABLE' => 'true',
|
||||
'GLOBAL_AUTORESPONDER_TIMEZONE' => 'Europe/Warsaw',
|
||||
'GLOBAL_AUTORESPONDER_BACKEND' => 'da',
|
||||
'GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE' => 'true',
|
||||
'GLOBAL_AUTORESPONDER_MAX_SUBJECT_BYTES' => '255',
|
||||
'GLOBAL_AUTORESPONDER_MAX_BODY_BYTES' => '20000',
|
||||
@@ -91,11 +89,6 @@ final class Settings
|
||||
return $this->getString('GLOBAL_AUTORESPONDER_TIMEZONE', 'Europe/Warsaw');
|
||||
}
|
||||
|
||||
public function backendMode(): string
|
||||
{
|
||||
return $this->getString('GLOBAL_AUTORESPONDER_BACKEND', 'da');
|
||||
}
|
||||
|
||||
public function scheduleMode(): string
|
||||
{
|
||||
return 'exact_hour';
|
||||
@@ -141,9 +134,6 @@ final class Settings
|
||||
} catch (Throwable) {
|
||||
throw new InvalidArgumentException('Invalid timezone: ' . $this->timezone());
|
||||
}
|
||||
if (!in_array($this->backendMode(), ['da', 'exim'], true)) {
|
||||
throw new InvalidArgumentException('Invalid backend mode: ' . $this->backendMode());
|
||||
}
|
||||
if ($this->maxSubjectBytes() < 1 || $this->maxBodyBytes() < 1) {
|
||||
throw new InvalidArgumentException('Invalid size limits');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user