Sync global-autoresponder current state

This commit is contained in:
Marek Miklewicz
2026-07-04 15:16:50 +02:00
parent 196ee224fe
commit af775ce976
47 changed files with 1165 additions and 1037 deletions
-2
View File
@@ -15,7 +15,6 @@ PluginLogger::init(PLUGIN_ROOT . '/plugin.log');
foreach ([
'Settings.php',
'BackendRuntimeConfig.php',
'Http.php',
'DirectAdminUser.php',
'Lang.php',
@@ -38,7 +37,6 @@ try {
Http::bootstrapGlobals();
$settings = Settings::load(Settings::EXTERNAL_SETTINGS);
BackendRuntimeConfig::sync($settings, PLUGIN_ROOT . '/scripts/backend.sh', Settings::CONFIG_DIR . '/backend-state.json');
$user = DirectAdminUser::fromEnvironment($settings);
$lang = Lang::load($user->language(), $settings);
if (!$user->hasPluginAccess($settings)) {
+244 -23
View File
@@ -5,6 +5,7 @@ function render_rule_form(AppContext $ctx, string $mode, ?array $rule): string
{
$isUpdate = $mode === 'update';
$id = $isUpdate ? (string)$rule['id'] : '';
$name = (string)($rule['name'] ?? '');
$subjectPrefix = $rule['subject_prefix'] ?? $rule['subject'] ?? '';
$replyFrequency = selected_reply_frequency($ctx, $rule);
$body = $rule['body'] ?? '';
@@ -17,16 +18,25 @@ function render_rule_form(AppContext $ctx, string $mode, ?array $rule): string
$hiddenId = $isUpdate ? '<input type="hidden" name="id" value="' . AppContext::e($id) . '">' : '';
return '<form method="post" action="' . AppContext::e($action) . '">' . $csrf . $hiddenId .
'<div class="panel"><h3>' . AppContext::e($ctx->t('Response content')) . '</h3><div class="row"><div><label>' . AppContext::e($ctx->t('Subject prefix')) . '</label><div class="subject-prefix-control"><input type="text" name="subject_prefix" value="' . AppContext::e((string)$subjectPrefix) . '"><span>' . AppContext::e($ctx->t('Original subject suffix')) . '</span></div></div>' .
'<div class="panel"><h3>' . AppContext::e($ctx->t('Response content')) . '</h3><div class="row"><div><label>' . AppContext::e($ctx->t('Autoresponder name')) . '</label><input type="text" name="name" value="' . AppContext::e($name) . '"><div class="field-help">' . AppContext::e($ctx->t('Autoresponder name help')) . '</div></div>' .
'<div><label>' . AppContext::e($ctx->t('Subject prefix')) . '</label><div class="subject-prefix-control"><input type="text" name="subject_prefix" value="' . AppContext::e((string)$subjectPrefix) . '"><span>' . AppContext::e($ctx->t('Original subject suffix')) . '</span></div></div>' .
'<div><label>' . AppContext::e($ctx->t('Response frequency')) . '</label>' . render_reply_frequency_select($ctx, $replyFrequency) . '</div>' .
'<div><label>' . AppContext::e($ctx->t('Status')) . '</label><label class="br-time-item"><input type="checkbox" name="enabled" value="1" ' . ($enabled ? 'checked' : '') . '> ' . AppContext::e($ctx->t('Enabled')) . '</label></div></div>' .
'<label>' . AppContext::e($ctx->t('Message body')) . '</label><textarea name="body">' . AppContext::e((string)$body) . '</textarea></div>' .
render_calendar_picker($ctx, 'start_value', $ctx->t('Start date'), $startValue) .
render_calendar_picker($ctx, 'end_value', $ctx->t('End date'), $endValue) .
render_schedule_panel($ctx, $startValue, $endValue, !$isUpdate) .
'<div class="panel"><div class="actions"><button class="primary" type="submit">' . AppContext::e($ctx->t($isUpdate ? 'Save changes' : 'Save autoresponder')) . '</button><a class="btn" href="' . AppContext::e($ctx->url('index.html')) . '">' . AppContext::e($ctx->t('Cancel')) . '</a></div></div>' .
'</form>';
}
function render_schedule_panel(AppContext $ctx, string $startValue, string $endValue, bool $enforceMinDate = true): string
{
return '<div class="panel schedule-panel"><h3>' . AppContext::e($ctx->t('Sending period')) . '</h3>' .
'<div class="schedule-scroll"><div class="schedule-grid">' .
render_calendar_picker($ctx, 'start_value', $ctx->t('Start date'), $startValue, $enforceMinDate) .
render_calendar_picker($ctx, 'end_value', $ctx->t('End date'), $endValue, $enforceMinDate) .
'</div></div></div>';
}
function default_schedule_value(AppContext $ctx, bool $start): string
{
$today = new DateTimeImmutable('today', new DateTimeZone($ctx->settings->timezone()));
@@ -39,9 +49,6 @@ function selected_reply_frequency(AppContext $ctx, ?array $rule): string
if ($rule === null) {
return '1440';
}
if (!empty($rule['reply_every_message'])) {
return $ctx->settings->backendMode() === 'da' ? '1' : 'every';
}
$minutes = (string)(int)($rule['repeat_minutes'] ?? 1440);
return array_key_exists($minutes, reply_frequency_options($ctx)) ? $minutes : '1440';
}
@@ -60,11 +67,7 @@ function render_reply_frequency_select(AppContext $ctx, string $selected): strin
/** @return array<string,string> */
function reply_frequency_options(AppContext $ctx): array
{
$options = [];
if ($ctx->settings->backendMode() !== 'da') {
$options['every'] = 'Send automatic reply for every message';
}
return $options + [
return [
'1' => '1 minute',
'10' => '10 minutes',
'30' => '30 minutes',
@@ -114,12 +117,9 @@ function attach_rule_scope(AppContext $ctx, array $rule): array
return $rule;
}
/** @param array<string,mixed> $rule */
function enforce_rule_backend_constraints(AppContext $ctx, ?string $currentId, array $rule): void
/** @return array<string,mixed>|null */
function find_active_rule_conflict(AppContext $ctx, ?string $currentId): ?array
{
if ($ctx->settings->backendMode() !== 'da' || empty($rule['enabled'])) {
return;
}
foreach ($ctx->rules->all($ctx->daUser->username()) as $existing) {
if (empty($existing['enabled'])) {
continue;
@@ -127,13 +127,234 @@ function enforce_rule_backend_constraints(AppContext $ctx, ?string $currentId, a
if ($currentId !== null && (string)($existing['id'] ?? '') === $currentId) {
continue;
}
throw new RuntimeException($ctx->t('DirectAdmin backend supports only one enabled global rule.'));
return $existing;
}
return null;
}
/** @param array<string,mixed> $rule */
function enforce_rule_directadmin_constraints(AppContext $ctx, ?string $currentId, array $rule): void
{
if (empty($rule['enabled'])) {
return;
}
if (find_active_rule_conflict($ctx, $currentId) !== null) {
throw new RuntimeException($ctx->t('Only one global autoresponder can be active per user.'));
}
}
function render_calendar_picker(AppContext $ctx, string $name, string $title, string $value): string
/** @param array<string,mixed> $rule */
function display_rule_name(AppContext $ctx, array $rule): string
{
$name = trim((string)($rule['name'] ?? ''));
if ($name !== '') {
return $name;
}
$subjectPrefix = trim((string)($rule['subject_prefix'] ?? $rule['subject'] ?? ''));
return $subjectPrefix !== '' ? $subjectPrefix : $ctx->t('Unnamed autoresponder');
}
/** @param array<string,mixed> $rule */
function format_rule_created_at(AppContext $ctx, array $rule): string
{
$timestamp = (int)($rule['created_at'] ?? $rule['updated_at'] ?? time());
return format_rule_timestamp($ctx, $timestamp);
}
function format_rule_timestamp(AppContext $ctx, int $timestamp): string
{
return (new DateTimeImmutable('@' . $timestamp))
->setTimezone(new DateTimeZone($ctx->settings->timezone()))
->format('Y-m-d H:i');
}
/** @param array<string,mixed> $rule */
/** @param array<string,string> $extra */
function render_hidden_rule_inputs(AppContext $ctx, array $rule, bool $enabled, array $extra = []): string
{
$fields = [
'name' => display_rule_name_for_input($rule),
'subject_prefix' => (string)($rule['subject_prefix'] ?? $rule['subject'] ?? ''),
'reply_frequency' => selected_reply_frequency($ctx, $rule),
'body' => (string)($rule['body'] ?? ''),
'start_value' => (string)($rule['start_value'] ?? ''),
'end_value' => (string)($rule['end_value'] ?? ''),
];
$html = '';
foreach ($fields as $name => $value) {
$html .= '<input type="hidden" name="' . AppContext::e($name) . '" value="' . AppContext::e($value) . '">';
}
if ($enabled) {
$html .= '<input type="hidden" name="enabled" value="1">';
}
foreach ($extra as $name => $value) {
$html .= '<input type="hidden" name="' . AppContext::e($name) . '" value="' . AppContext::e($value) . '">';
}
return $html;
}
/** @param array<string,mixed> $rule */
function display_rule_name_for_input(array $rule): string
{
return trim((string)($rule['name'] ?? ''));
}
/** @param array<string,mixed> $pending @param array<string,mixed> $active */
function render_create_conflict_modal(AppContext $ctx, array $pending, array $active): string
{
$newName = display_rule_name($ctx, $pending);
$oldName = display_rule_name($ctx, $active);
$created = format_rule_created_at($ctx, $active);
$action = $ctx->url('create.html');
$html = '<div class="br-overlay" role="dialog" aria-modal="true"><div class="br-modal">';
$html .= '<h3>' . AppContext::e($ctx->t('Only one active autoresponder')) . '</h3>';
$html .= '<p>' . AppContext::e($ctx->t('Active autoresponder exists for user.', [
'user' => $ctx->daUser->username(),
'name' => $oldName,
'created' => $created,
])) . '</p>';
$html .= '<p>' . AppContext::e($ctx->t('Only one global autoresponder can be active per user.')) . '</p>';
$html .= '<div class="br-modal-actions">';
$html .= '<form method="post" action="' . AppContext::e($action) . '">' . $ctx->csrfField('create') . render_hidden_rule_inputs($ctx, $pending, true) .
'<input type="hidden" name="conflict_action" value="replace"><input type="hidden" name="conflict_rule_id" value="' . AppContext::e((string)($active['id'] ?? '')) . '">' .
'<button class="success" type="submit">' . AppContext::e($ctx->t('Enable new and disable previous', ['new' => $newName, 'old' => $oldName])) . '</button></form>';
$html .= '<form method="post" action="' . AppContext::e($action) . '">' . $ctx->csrfField('create') . render_hidden_rule_inputs($ctx, $pending, false) .
'<input type="hidden" name="conflict_action" value="create_disabled"><input type="hidden" name="conflict_rule_id" value="' . AppContext::e((string)($active['id'] ?? '')) . '">' .
'<button type="submit">' . AppContext::e($ctx->t('Add as disabled', ['name' => $newName])) . '</button></form>';
$html .= '<button class="danger-fill" type="button" data-modal-close>' . AppContext::e($ctx->t('Cancel')) . '</button>';
$html .= '</div></div></div>';
return $html;
}
/** @param array<string,mixed> $pending @param array<int,array<string,mixed>> $nativeEntries @param array<string,string> $extra */
function render_native_vacation_conflict_modal(AppContext $ctx, array $pending, array $nativeEntries, array $extra = []): string
{
$rows = '';
foreach ($nativeEntries as $entry) {
$email = (string)($entry['email'] ?? '');
$domain = (string)($entry['domain'] ?? '');
$mailbox = (string)($entry['mailbox'] ?? '');
$rows .= '<tr><td>' . AppContext::e($email) . '</td><td>' . AppContext::e($domain) . '</td><td>' . AppContext::e($mailbox) . '</td></tr>';
}
$html = '<div class="br-overlay" role="dialog" aria-modal="true"><div class="br-modal">';
$html .= '<h3>' . AppContext::e($ctx->t('Native autoresponders already exist')) . '</h3>';
$html .= '<p>' . AppContext::e($ctx->t('Native autoresponders exist for user.', ['user' => $ctx->daUser->username()])) . '</p>';
$html .= '<p><strong>' . AppContext::e($ctx->t('Native autoresponders removal warning')) . '</strong></p>';
$html .= '<table><thead><tr><th>' . AppContext::e($ctx->t('Email address')) . '</th><th>' . AppContext::e($ctx->t('Domain')) . '</th><th>' . AppContext::e($ctx->t('Mailbox')) . '</th></tr></thead><tbody>' . $rows . '</tbody></table>';
$html .= '<div class="br-modal-actions">';
$html .= '<form method="post" action="' . AppContext::e($ctx->url('create.html')) . '">' . $ctx->csrfField('create') . render_hidden_rule_inputs($ctx, $pending, !empty($pending['enabled']), $extra + ['native_conflict_action' => 'disable_native']) .
'<button class="danger-fill" type="submit">' . AppContext::e($ctx->t('Remove existing autoresponders')) . '</button></form>';
$html .= '<button type="button" data-modal-close>' . AppContext::e($ctx->t('Cancel')) . '</button>';
$html .= '</div></div></div>';
return $html;
}
function directadmin_vacation_sync_service(AppContext $ctx): DirectAdminVacationSyncService
{
return new DirectAdminVacationSyncService(
$ctx->rules,
new DirectAdminSyncRepository(),
new MailboxDirectory(),
new DirectAdminVacationApi()
);
}
/** @return array<int,array{domain:string,mailbox:string,email:string}> */
function list_untracked_native_da_vacations(AppContext $ctx): array
{
return directadmin_vacation_sync_service($ctx)->untrackedNativeVacations($ctx->daUser->username());
}
function delete_untracked_native_da_vacations(AppContext $ctx): void
{
$service = directadmin_vacation_sync_service($ctx);
$service->deleteNativeVacations($ctx->daUser->username(), $service->untrackedNativeVacations($ctx->daUser->username()));
}
/** @param array<string,mixed> $target @param array<string,mixed> $active */
function render_toggle_conflict_modal(AppContext $ctx, array $target, array $active): string
{
$targetName = display_rule_name($ctx, $target);
$oldName = display_rule_name($ctx, $active);
$created = format_rule_created_at($ctx, $active);
$id = (string)($target['id'] ?? '');
$html = '<div class="br-overlay" role="dialog" aria-modal="true"><div class="br-modal">';
$html .= '<h3>' . AppContext::e($ctx->t('Only one active autoresponder')) . '</h3>';
$html .= '<p>' . AppContext::e($ctx->t('Active autoresponder exists for user.', [
'user' => $ctx->daUser->username(),
'name' => $oldName,
'created' => $created,
])) . '</p>';
$html .= '<p>' . AppContext::e($ctx->t('Only one global autoresponder can be active per user.')) . '</p>';
$html .= '<div class="br-modal-actions">';
$html .= '<form method="post" action="' . AppContext::e($ctx->url('toggle.html')) . '">' . $ctx->csrfField('toggle:' . $id) .
'<input type="hidden" name="id" value="' . AppContext::e($id) . '">' .
'<input type="hidden" name="conflict_action" value="replace"><input type="hidden" name="conflict_rule_id" value="' . AppContext::e((string)($active['id'] ?? '')) . '">' .
'<button class="success" type="submit">' . AppContext::e($ctx->t('Enable autoresponder', ['name' => $targetName])) . '</button></form>';
$html .= '<button class="danger-fill" type="button" data-modal-close>' . AppContext::e($ctx->t('Cancel')) . '</button>';
$html .= '</div></div></div>';
return $html;
}
function render_delete_confirmation_body(AppContext $ctx, array $rule): string
{
$id = (string)($rule['id'] ?? '');
$name = display_rule_name($ctx, $rule);
$created = format_rule_created_at($ctx, $rule);
$message = $ctx->t('Delete confirmation question', [
'name' => $name,
'created' => $created,
]);
return '<div class="panel"><p class="confirm-question">' . AppContext::e($message) . '</p>' .
'<form method="post" action="' . AppContext::e($ctx->url('delete.html')) . '">' . $ctx->csrfField('delete:' . $id) .
'<input type="hidden" name="id" value="' . AppContext::e($id) . '">' .
'<div class="actions"><button class="danger-fill" type="submit">' . AppContext::e($ctx->t('Yes')) . '</button>' .
'<a class="btn" href="' . AppContext::e($ctx->url('index.html')) . '">' . AppContext::e($ctx->t('No')) . '</a></div></form></div>';
}
function render_rules_index_body(AppContext $ctx, string $extraHtml = ''): string
{
$rules = $ctx->rules->all($ctx->daUser->username());
if ($rules === []) {
return '<div class="panel"><div class="empty-state"><div><h3>' . AppContext::e($ctx->t('No global autoresponders')) . '</h3></div></div></div>' . $extraHtml;
}
$rows = '';
foreach ($rules as $rule) {
$id = (string)$rule['id'];
$enabled = !empty($rule['enabled']);
$subjectPrefix = (string)($rule['subject_prefix'] ?? $rule['subject'] ?? '');
$rows .= '<tr><td><span class="badge ' . ($enabled ? 'ok' : 'off') . '">' . AppContext::e($ctx->t($enabled ? 'Enabled' : 'Disabled')) . '</span></td>';
$rows .= '<td>' . AppContext::e(display_rule_name($ctx, $rule)) . '</td>';
$rows .= '<td>' . AppContext::e($subjectPrefix) . '</td>';
$rows .= '<td>' . AppContext::e(format_rule_created_at($ctx, $rule)) . '</td>';
$rows .= '<td>' . AppContext::e(format_rule_timestamp($ctx, (int)$rule['start_ts'])) . '<br><span class="muted">' . AppContext::e($ctx->t('To')) . ' ' . AppContext::e(format_rule_timestamp($ctx, (int)$rule['end_ts'])) . '</span></td>';
$rows .= '<td><span class="table-actions">';
$rows .= '<a class="btn" href="' . AppContext::e($ctx->url('update.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Edit')) . '</a>';
$rows .= '<a class="btn" href="' . AppContext::e($ctx->url('preview.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Preview')) . '</a>';
$rows .= '<form method="post" action="' . AppContext::e($ctx->url('toggle.html')) . '">' . $ctx->csrfField('toggle:' . $id) . '<input type="hidden" name="id" value="' . AppContext::e($id) . '"><button>' . AppContext::e($ctx->t($enabled ? 'Disable' : 'Enable')) . '</button></form>';
$rows .= '<a class="btn danger" href="' . AppContext::e($ctx->url('delete.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Delete')) . '</a>';
$rows .= '</span></td></tr>';
}
return '<div class="panel"><div class="panel-head"><div><h3>' . AppContext::e($ctx->t('Global autoresponders')) . '</h3></div>' .
'</div><table><thead><tr><th>' . AppContext::e($ctx->t('Status')) . '</th><th>' . AppContext::e($ctx->t('Autoresponder name')) . '</th><th>' . AppContext::e($ctx->t('Subject prefix')) . '</th><th>' . AppContext::e($ctx->t('Created')) . '</th><th>' . AppContext::e($ctx->t('Sending period')) . '</th><th>' . AppContext::e($ctx->t('Actions')) . '</th></tr></thead><tbody>' . $rows . '</tbody></table></div>' . $extraHtml;
}
function render_rules_index(AppContext $ctx, array $ok = [], array $errors = [], string $extraHtml = ''): void
{
$ctx->render('Global autoresponders', render_rules_index_body($ctx, $extraHtml), $ok, $errors);
}
function render_calendar_picker(AppContext $ctx, string $name, string $title, string $value, bool $enforceMinDate = true): string
{
$mode = $ctx->settings->scheduleMode();
$columnClass = $name === 'start_value' ? 'schedule-start' : 'schedule-end';
$timeLabel = $ctx->t($name === 'start_value' ? 'Start hour' : 'End hour');
$selectedDate = substr($value, 0, 10);
if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $selectedDate)) {
$selectedDate = date('Y-m-d');
@@ -147,12 +368,12 @@ function render_calendar_picker(AppContext $ctx, string $name, string $title, st
}
$selectedDt = DateTimeImmutable::createFromFormat('!Y-m-d', $selectedDate) ?: new DateTimeImmutable('today');
$monthStart = $selectedDt->modify('first day of this month');
$minDate = (new DateTimeImmutable('today', new DateTimeZone($ctx->settings->timezone())))->format('Y-m-d');
$minDate = $enforceMinDate ? (new DateTimeImmutable('today', new DateTimeZone($ctx->settings->timezone())))->format('Y-m-d') : '';
$days = render_calendar_days($name, $selectedDate, $monthStart, $minDate);
$visibleMonth = $monthStart->format('Y-m');
$monthLabel = calendar_month_label($ctx, $monthStart);
if ($mode === 'exact_hour') {
$timeControl = '<label>' . AppContext::e($ctx->t('Time')) . '</label><input type="time" name="' . AppContext::e($name . '_time') . '" value="' . AppContext::e($selectedTime) . '" step="60" data-time-for="' . AppContext::e($name) . '">';
$timeControl = '<label>' . AppContext::e($timeLabel) . '</label><input type="time" name="' . AppContext::e($name . '_time') . '" value="' . AppContext::e($selectedTime) . '" step="60" data-time-for="' . AppContext::e($name) . '">';
} else {
$timeControl = '<label>' . AppContext::e($ctx->t('Time of day')) . '</label><select name="' . AppContext::e($name . '_period') . '" data-period-for="' . AppContext::e($name) . '">' .
'<option value="morning"' . ($selectedPeriod === 'morning' ? ' selected' : '') . '>' . AppContext::e($ctx->t('Morning')) . '</option>' .
@@ -160,10 +381,10 @@ function render_calendar_picker(AppContext $ctx, string $name, string $title, st
'<option value="evening"' . ($selectedPeriod === 'evening' ? ' selected' : '') . '>' . AppContext::e($ctx->t('Evening')) . '</option>' .
'</select>';
}
return '<div class="panel"><h3>' . AppContext::e($title) . '</h3><div class="br-restore-layout"><div class="br-restore-calendar" data-calendar-picker data-schedule-mode="' . AppContext::e($mode) . '" data-calendar-name="' . AppContext::e($name) . '" data-visible-month="' . AppContext::e($visibleMonth) . '" data-selected-date="' . AppContext::e($selectedDate) . '" data-min-date="' . AppContext::e($minDate) . '"><h4>' . AppContext::e($title) . '</h4><div class="br-month-nav"><button type="button" class="br-month-btn" data-calendar-prev>&lsaquo;</button><span class="br-month-label" data-calendar-month-label>' . AppContext::e($monthLabel) . '</span><button type="button" class="br-month-btn" data-calendar-next>&rsaquo;</button></div>' .
return '<div class="schedule-column ' . AppContext::e($columnClass) . '"><div class="br-restore-calendar" data-calendar-picker data-schedule-mode="' . AppContext::e($mode) . '" data-calendar-name="' . AppContext::e($name) . '" data-visible-month="' . AppContext::e($visibleMonth) . '" data-selected-date="' . AppContext::e($selectedDate) . '" data-min-date="' . AppContext::e($minDate) . '"><h4>' . AppContext::e($title) . '</h4><div class="br-month-nav"><button type="button" class="br-month-btn" data-calendar-prev>&lsaquo;</button><span class="br-month-label" data-calendar-month-label>' . AppContext::e($monthLabel) . '</span><button type="button" class="br-month-btn" data-calendar-next>&rsaquo;</button></div>' .
'<table class="br-calendar-grid"><thead><tr>' . render_weekday_headers($ctx) . '</tr></thead><tbody data-calendar-days>' . $days . '</tbody></table>' .
'<div class="br-date-label" id="' . AppContext::e($name . '_label') . '">' . AppContext::e($ctx->t('Selected')) . ': ' . AppContext::e($selectedDate) . '</div><input type="hidden" id="' . AppContext::e($name . '_date') . '" name="' . AppContext::e($name . '_date') . '" value="' . AppContext::e($selectedDate) . '"></div>' .
'<div class="br-restore-calendar"><h4>' . AppContext::e($ctx->t('Time')) . '</h4>' . $timeControl . '</div></div>' .
'<div class="br-time-picker">' . $timeControl . '</div>' .
'<input type="hidden" id="' . AppContext::e($name) . '" name="' . AppContext::e($name) . '" value="' . AppContext::e($value) . '" data-canonical-value="' . AppContext::e($name) . '"></div>';
}
@@ -196,7 +417,7 @@ function render_calendar_days(string $name, string $selectedDate, DateTimeImmuta
continue;
}
$date = $monthStart->setDate((int)$monthStart->format('Y'), (int)$monthStart->format('m'), $day)->format('Y-m-d');
if ($date < $minDate) {
if ($minDate !== '' && $date < $minDate) {
$html .= '<td><span class="br-cal-day-disabled">' . $day . '</span></td>';
$day++;
continue;
+69 -9
View File
@@ -3,24 +3,84 @@ declare(strict_types=1);
return static function (AppContext $ctx): void {
$errors = [];
$formRule = null;
$modal = '';
if (Http::isPost()) {
try {
$ctx->requireCsrf('create');
$input = normalize_rule_post($_POST);
$rule = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings));
enforce_rule_backend_constraints($ctx, null, $rule);
$created = $ctx->rules->create($ctx->daUser->username(), $rule);
try {
$ctx->syncActiveBackend();
} catch (Throwable $syncError) {
$ctx->rules->delete($ctx->daUser->username(), (string)$created['id']);
throw $syncError;
$formRule = $rule;
$conflict = !empty($rule['enabled']) ? find_active_rule_conflict($ctx, null) : null;
$conflictAction = $ctx->post('conflict_action');
$conflictRuleId = $ctx->post('conflict_rule_id');
if ($conflict !== null && ($conflictAction !== 'replace' || $conflictRuleId !== (string)($conflict['id'] ?? ''))) {
$modal = render_create_conflict_modal($ctx, $rule, $conflict);
} else {
if (!empty($rule['enabled'])) {
$nativeAction = $ctx->post('native_conflict_action');
if ($nativeAction === 'disable_native') {
delete_untracked_native_da_vacations($ctx);
} else {
$nativeEntries = list_untracked_native_da_vacations($ctx);
if ($nativeEntries !== []) {
$extra = [];
if ($conflict !== null) {
$extra = [
'conflict_action' => 'replace',
'conflict_rule_id' => (string)($conflict['id'] ?? ''),
];
}
$modal = render_native_vacation_conflict_modal($ctx, $rule, $nativeEntries, $extra);
$ctx->render('Add autoresponder', render_rule_form($ctx, 'create', $formRule) . $modal, [], $errors);
return;
}
}
}
if ($conflict !== null) {
create_rule_replacing_active($ctx, $rule, $conflict);
} else {
create_rule_with_sync($ctx, $rule);
}
Http::redirect($ctx->url('index.html', ['status' => 'created']));
}
Http::redirect($ctx->url('index.html', ['status' => 'created']));
} catch (Throwable $e) {
PluginLogger::exception($e, 'CREATE');
$errors[] = $e->getMessage();
}
}
$ctx->render('Add autoresponder', render_rule_form($ctx, 'create', null), [], $errors);
$ctx->render('Add autoresponder', render_rule_form($ctx, 'create', $formRule) . $modal, [], $errors);
};
/** @param array<string,mixed> $rule */
function create_rule_with_sync(AppContext $ctx, array $rule): array
{
$created = $ctx->rules->create($ctx->daUser->username(), $rule);
try {
$ctx->syncDirectAdminVacations();
} catch (Throwable $syncError) {
$ctx->rules->delete($ctx->daUser->username(), (string)$created['id']);
throw $syncError;
}
return $created;
}
/** @param array<string,mixed> $rule @param array<string,mixed> $active */
function create_rule_replacing_active(AppContext $ctx, array $rule, array $active): array
{
$activeId = (string)($active['id'] ?? '');
if ($activeId === '') {
throw new RuntimeException($ctx->t('Rule not found'));
}
$ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => false]);
$created = $ctx->rules->create($ctx->daUser->username(), $rule);
try {
$ctx->syncDirectAdminVacations();
} catch (Throwable $syncError) {
$ctx->rules->delete($ctx->daUser->username(), (string)$created['id']);
$ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => true]);
throw $syncError;
}
return $created;
}
+4 -7
View File
@@ -11,19 +11,16 @@ return static function (AppContext $ctx): void {
if (Http::isPost()) {
try {
$ctx->requireCsrf('delete:' . $id);
$deletedName = display_rule_name($ctx, $rule);
$ctx->rules->delete($ctx->daUser->username(), $id);
$ctx->syncActiveBackend();
$ctx->syncDirectAdminVacations();
$ctx->audit->record('delete', $ctx->daUser->username(), ['rule_id' => $id, 'subject_prefix' => (string)($rule['subject_prefix'] ?? $rule['subject'] ?? '')]);
Http::redirect($ctx->url('index.html', ['status' => 'deleted']));
Http::redirect($ctx->url('index.html', ['status' => 'deleted', 'name' => $deletedName]));
} catch (Throwable $e) {
PluginLogger::exception($e, 'DELETE');
$ctx->render('Confirm deletion', '<div class="alert alert-err">' . AppContext::e($e->getMessage()) . '</div>');
return;
}
}
$body = '<div class="grid grid-2"><div class="panel"><h3>' . AppContext::e($ctx->t('Preview autoresponder')) . '</h3>' . render_preview_box($ctx, $rule) . '</div>' .
'<div class="panel"><h3>' . AppContext::e($ctx->t('Confirm deletion')) . '</h3><div class="alert alert-err">' . AppContext::e($ctx->t('Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.')) . '</div>' .
'<form method="post" action="' . AppContext::e($ctx->url('delete.html')) . '">' . $ctx->csrfField('delete:' . $id) . '<input type="hidden" name="id" value="' . AppContext::e($id) . '">' .
'<div class="actions"><button class="danger-fill" type="submit">' . AppContext::e($ctx->t('Delete autoresponder')) . '</button><a class="btn" href="' . AppContext::e($ctx->url('index.html')) . '">' . AppContext::e($ctx->t('Do not delete')) . '</a></div></form></div></div>';
$ctx->render('Confirm deletion', $body);
$ctx->render('Confirm deletion', render_delete_confirmation_body($ctx, $rule));
};
+5 -28
View File
@@ -2,38 +2,15 @@
declare(strict_types=1);
return static function (AppContext $ctx): void {
$rules = $ctx->rules->all($ctx->daUser->username());
$ok = [];
$status = $ctx->query('status');
if ($status === 'created') { $ok[] = $ctx->t('Rule created.'); }
if ($status === 'updated') { $ok[] = $ctx->t('Rule updated.'); }
if ($status === 'deleted') { $ok[] = $ctx->t('Rule deleted.'); }
if ($status === 'deleted') {
$name = $ctx->query('name');
$ok[] = $name !== '' ? $ctx->t('Global autoresponder deleted.', ['name' => $name]) : $ctx->t('Rule deleted.');
}
if ($status === 'toggled') { $ok[] = $ctx->t('Rule status changed.'); }
if ($rules === []) {
$body = '<div class="panel"><div class="empty-state"><div><h3>' . AppContext::e($ctx->t('No global autoresponders')) . '</h3>' .
'<p class="muted">' . AppContext::e($ctx->t('All valid POP/IMAP mailboxes in this account')) . '</p></div></div></div>';
$ctx->render('Global autoresponders', $body, $ok);
return;
}
$rows = '';
foreach ($rules as $rule) {
$id = (string)$rule['id'];
$enabled = !empty($rule['enabled']);
$subjectPrefix = (string)($rule['subject_prefix'] ?? $rule['subject'] ?? '');
$rows .= '<tr><td><span class="badge ' . ($enabled ? 'ok' : 'off') . '">' . AppContext::e($ctx->t($enabled ? 'Enabled' : 'Disabled')) . '</span></td>';
$rows .= '<td>' . AppContext::e($subjectPrefix) . '<br><span class="muted">' . date('Y-m-d H:i', (int)($rule['updated_at'] ?? time())) . '</span></td>';
$rows .= '<td>' . AppContext::e(date('Y-m-d H:i', (int)$rule['start_ts'])) . '<br><span class="muted">' . AppContext::e($ctx->t('To')) . ' ' . AppContext::e(date('Y-m-d H:i', (int)$rule['end_ts'])) . '</span></td>';
$rows .= '<td><span class="table-actions">';
$rows .= '<a class="btn" href="' . AppContext::e($ctx->url('update.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Edit')) . '</a>';
$rows .= '<a class="btn" href="' . AppContext::e($ctx->url('preview.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Preview')) . '</a>';
$rows .= '<form method="post" action="' . AppContext::e($ctx->url('toggle.html')) . '">' . $ctx->csrfField('toggle:' . $id) . '<input type="hidden" name="id" value="' . AppContext::e($id) . '"><button>' . AppContext::e($ctx->t($enabled ? 'Disable' : 'Enable')) . '</button></form>';
$rows .= '<a class="btn danger" href="' . AppContext::e($ctx->url('delete.html', ['id' => $id])) . '">' . AppContext::e($ctx->t('Delete')) . '</a>';
$rows .= '</span></td></tr>';
}
$body = '<div class="panel"><div class="panel-head"><div><h3>' . AppContext::e($ctx->t('Global autoresponders')) . '</h3><p class="muted">' . AppContext::e($ctx->t('All valid POP/IMAP mailboxes in this account')) . '</p></div>' .
'</div><table><thead><tr><th>' . AppContext::e($ctx->t('Status')) . '</th><th>' . AppContext::e($ctx->t('Subject prefix')) . '</th><th>' . AppContext::e($ctx->t('Sending period')) . '</th><th>' . AppContext::e($ctx->t('Actions')) . '</th></tr></thead><tbody>' . $rows . '</tbody></table></div>';
$ctx->render('Global autoresponders', $body, $ok);
render_rules_index($ctx, $ok);
};
+31 -2
View File
@@ -11,12 +11,41 @@ return static function (AppContext $ctx): void {
throw new RuntimeException($ctx->t('Rule not found'));
}
$next = ['enabled' => empty($rule['enabled'])];
enforce_rule_backend_constraints($ctx, $id, $next);
if (!empty($next['enabled'])) {
$conflict = find_active_rule_conflict($ctx, $id);
$conflictAction = $ctx->post('conflict_action');
$conflictRuleId = $ctx->post('conflict_rule_id');
if ($conflict !== null && ($conflictAction !== 'replace' || $conflictRuleId !== (string)($conflict['id'] ?? ''))) {
render_rules_index($ctx, [], [], render_toggle_conflict_modal($ctx, $rule, $conflict));
return;
}
if ($conflict !== null) {
toggle_rule_replacing_active($ctx, $id, (string)($conflict['id'] ?? ''));
Http::redirect($ctx->url('index.html', ['status' => 'toggled']));
return;
}
}
$ctx->rules->update($ctx->daUser->username(), $id, $next);
$ctx->syncActiveBackend();
$ctx->syncDirectAdminVacations();
Http::redirect($ctx->url('index.html', ['status' => 'toggled']));
} catch (Throwable $e) {
PluginLogger::exception($e, 'TOGGLE');
throw $e;
}
};
function toggle_rule_replacing_active(AppContext $ctx, string $targetId, string $activeId): void
{
if ($activeId === '') {
throw new RuntimeException($ctx->t('Rule not found'));
}
$ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => false]);
$ctx->rules->update($ctx->daUser->username(), $targetId, ['enabled' => true]);
try {
$ctx->syncDirectAdminVacations();
} catch (Throwable $syncError) {
$ctx->rules->update($ctx->daUser->username(), $targetId, ['enabled' => false]);
$ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => true]);
throw $syncError;
}
}
+3 -3
View File
@@ -13,10 +13,10 @@ return static function (AppContext $ctx): void {
try {
$ctx->requireCsrf('update:' . $id);
$input = normalize_rule_post($_POST);
$patch = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings));
enforce_rule_backend_constraints($ctx, $id, $patch);
$patch = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings, true));
enforce_rule_directadmin_constraints($ctx, $id, $patch);
$ctx->rules->update($ctx->daUser->username(), $id, $patch);
$ctx->syncActiveBackend();
$ctx->syncDirectAdminVacations();
Http::redirect($ctx->url('index.html', ['status' => 'updated']));
} catch (Throwable $e) {
PluginLogger::exception($e, 'UPDATE');
+60 -7
View File
@@ -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>&gt;</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;
}
-51
View File
@@ -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);
}
}
+62 -17
View File
@@ -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'] ?? '')));
}
}
+1 -4
View File
@@ -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',
+58 -1
View File
@@ -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
{
-43
View File
@@ -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;
}
}
+1 -1
View File
@@ -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) {
-31
View File
@@ -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;
}
}
+18
View File
@@ -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);
}
}
}
-48
View File
@@ -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
View File
@@ -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.');
}
-10
View File
@@ -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');
}