Compare commits

..

11 Commits

Author SHA1 Message Date
Marek Miklewicz 1cec1aec81 Bump global-autoresponder to 1.4.12 2026-07-04 15:19:34 +02:00
Marek Miklewicz af775ce976 Sync global-autoresponder current state 2026-07-04 15:16:50 +02:00
Marek Miklewicz 196ee224fe fix: simplify autoresponder list actions 2026-06-03 15:31:03 +02:00
Marek Miklewicz 9174d62706 fix: match directadmin vacation controls 2026-06-03 09:21:51 +02:00
Marek Miklewicz 0617798821 fix: render redirects in cli runtime 2026-06-03 08:39:33 +02:00
Marek Miklewicz 27d95e1baf fix: align directadmin vacation api payload 2026-06-02 23:10:01 +02:00
Marek Miklewicz 86eb1dddbd feat: log plugin runtime errors 2026-06-02 22:57:23 +02:00
Marek Miklewicz 7561077eee fix: use documented directadmin binary 2026-06-02 22:23:27 +02:00
Marek Miklewicz 7e392e4ee7 fix: parse directadmin cli post data 2026-06-02 22:14:33 +02:00
Marek Miklewicz c0b007d25d fix: default autoresponder dates to today 2026-06-02 22:01:32 +02:00
Marek Miklewicz 767016c659 fix: scope csrf fields and block past dates 2026-06-02 21:54:56 +02:00
50 changed files with 1865 additions and 1073 deletions
+5
View File
@@ -0,0 +1,5 @@
*.log
logs/
state/
data/
.DS_Store
+6 -2
View File
@@ -10,9 +10,11 @@ if (!defined('IN_DA_PLUGIN') || IN_DA_PLUGIN !== true) {
define('PLUGIN_ROOT', dirname(__DIR__)); define('PLUGIN_ROOT', dirname(__DIR__));
define('PLUGIN_EXEC_DIR', __DIR__); define('PLUGIN_EXEC_DIR', __DIR__);
require_once PLUGIN_EXEC_DIR . '/lib/PluginLogger.php';
PluginLogger::init(PLUGIN_ROOT . '/plugin.log');
foreach ([ foreach ([
'Settings.php', 'Settings.php',
'BackendRuntimeConfig.php',
'Http.php', 'Http.php',
'DirectAdminUser.php', 'DirectAdminUser.php',
'Lang.php', 'Lang.php',
@@ -32,8 +34,9 @@ foreach ([
require_once PLUGIN_EXEC_DIR . '/handlers/_form_helpers.php'; require_once PLUGIN_EXEC_DIR . '/handlers/_form_helpers.php';
try { try {
Http::bootstrapGlobals();
$settings = Settings::load(Settings::EXTERNAL_SETTINGS); $settings = Settings::load(Settings::EXTERNAL_SETTINGS);
BackendRuntimeConfig::sync($settings, PLUGIN_ROOT . '/scripts/backend.sh', Settings::CONFIG_DIR . '/backend-state.json');
$user = DirectAdminUser::fromEnvironment($settings); $user = DirectAdminUser::fromEnvironment($settings);
$lang = Lang::load($user->language(), $settings); $lang = Lang::load($user->language(), $settings);
if (!$user->hasPluginAccess($settings)) { if (!$user->hasPluginAccess($settings)) {
@@ -56,6 +59,7 @@ try {
} }
$handler($ctx); $handler($ctx);
} catch (Throwable $e) { } catch (Throwable $e) {
PluginLogger::exception($e, 'BOOTSTRAP');
http_response_code(500); http_response_code(500);
header('Content-Type: text/html; charset=UTF-8'); header('Content-Type: text/html; charset=UTF-8');
echo '<!doctype html><html><head><meta charset="utf-8"><title>Błąd</title></head><body>'; echo '<!doctype html><html><head><meta charset="utf-8"><title>Błąd</title></head><body>';
+286 -31
View File
@@ -5,45 +5,71 @@ function render_rule_form(AppContext $ctx, string $mode, ?array $rule): string
{ {
$isUpdate = $mode === 'update'; $isUpdate = $mode === 'update';
$id = $isUpdate ? (string)$rule['id'] : ''; $id = $isUpdate ? (string)$rule['id'] : '';
$name = (string)($rule['name'] ?? '');
$subjectPrefix = $rule['subject_prefix'] ?? $rule['subject'] ?? ''; $subjectPrefix = $rule['subject_prefix'] ?? $rule['subject'] ?? '';
$replyFrequency = selected_reply_frequency($rule); $replyFrequency = selected_reply_frequency($ctx, $rule);
$body = $rule['body'] ?? ''; $body = $rule['body'] ?? '';
$enabled = $rule === null || !empty($rule['enabled']); $enabled = $rule === null || !empty($rule['enabled']);
$startValue = (string)($rule['start_value'] ?? '2026-06-10T09:00'); $startValue = (string)($rule['start_value'] ?? default_schedule_value($ctx, true));
$endValue = (string)($rule['end_value'] ?? '2026-06-24T17:00'); $endValue = (string)($rule['end_value'] ?? default_schedule_value($ctx, false));
$action = $ctx->url($isUpdate ? 'update.html' : 'create.html'); $action = $ctx->url($isUpdate ? 'update.html' : 'create.html');
$intent = $isUpdate ? 'update:' . $id : 'create'; $intent = $isUpdate ? 'update:' . $id : 'create';
$csrf = $ctx->csrfField($intent); $csrf = $ctx->csrfField($intent);
$hiddenId = $isUpdate ? '<input type="hidden" name="id" value="' . AppContext::e($id) . '">' : ''; $hiddenId = $isUpdate ? '<input type="hidden" name="id" value="' . AppContext::e($id) . '">' : '';
return '<form method="post" action="' . AppContext::e($action) . '">' . $csrf . $hiddenId . 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('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>' . '<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>' . '<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_schedule_panel($ctx, $startValue, $endValue, !$isUpdate) .
render_calendar_picker($ctx, 'end_value', $ctx->t('End date'), $endValue) .
'<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>' . '<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>'; '</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()));
return $today->format('Y-m-d') . 'T' . ($start ? '00:00' : '23:59');
}
/** @param array<string,mixed>|null $rule */ /** @param array<string,mixed>|null $rule */
function selected_reply_frequency(?array $rule): string function selected_reply_frequency(AppContext $ctx, ?array $rule): string
{ {
if ($rule === null) { if ($rule === null) {
return '1440'; return '1440';
} }
if (!empty($rule['reply_every_message'])) {
return 'every';
}
$minutes = (string)(int)($rule['repeat_minutes'] ?? 1440); $minutes = (string)(int)($rule['repeat_minutes'] ?? 1440);
return in_array($minutes, ['30', '60', '120', '360', '720', '1440', '2880', '10080'], true) ? $minutes : '1440'; return array_key_exists($minutes, reply_frequency_options($ctx)) ? $minutes : '1440';
} }
function render_reply_frequency_select(AppContext $ctx, string $selected): string function render_reply_frequency_select(AppContext $ctx, string $selected): string
{ {
$options = [ $options = reply_frequency_options($ctx);
'every' => 'Send automatic reply for every message', $html = '<select name="reply_frequency">';
foreach ($options as $value => $label) {
$value = (string)$value;
$html .= '<option value="' . AppContext::e($value) . '"' . ($selected === $value ? ' selected' : '') . '>' . AppContext::e($ctx->t($label)) . '</option>';
}
return $html . '</select>';
}
/** @return array<string,string> */
function reply_frequency_options(AppContext $ctx): array
{
return [
'1' => '1 minute',
'10' => '10 minutes',
'30' => '30 minutes', '30' => '30 minutes',
'60' => '1 hour', '60' => '1 hour',
'120' => '2 hours', '120' => '2 hours',
@@ -51,14 +77,19 @@ function render_reply_frequency_select(AppContext $ctx, string $selected): strin
'720' => '12 hours', '720' => '12 hours',
'1440' => '1 day', '1440' => '1 day',
'2880' => '2 days', '2880' => '2 days',
'4320' => '3 days',
'5760' => '4 days',
'7200' => '5 days',
'8640' => '6 days',
'10080' => '7 days', '10080' => '7 days',
'11520' => '8 days',
'12960' => '9 days',
'14400' => '10 days',
'15840' => '11 days',
'17280' => '12 days',
'18720' => '13 days',
'20160' => '14 days',
]; ];
$html = '<select name="reply_frequency">';
foreach ($options as $value => $label) {
$value = (string)$value;
$html .= '<option value="' . AppContext::e($value) . '"' . ($selected === $value ? ' selected' : '') . '>' . AppContext::e($ctx->t($label)) . '</option>';
}
return $html . '</select>';
} }
/** @param array<string,mixed> $post @return array<string,mixed> */ /** @param array<string,mixed> $post @return array<string,mixed> */
@@ -86,12 +117,9 @@ function attach_rule_scope(AppContext $ctx, array $rule): array
return $rule; return $rule;
} }
/** @param array<string,mixed> $rule */ /** @return array<string,mixed>|null */
function enforce_rule_backend_constraints(AppContext $ctx, ?string $currentId, array $rule): void 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) { foreach ($ctx->rules->all($ctx->daUser->username()) as $existing) {
if (empty($existing['enabled'])) { if (empty($existing['enabled'])) {
continue; continue;
@@ -99,13 +127,234 @@ function enforce_rule_backend_constraints(AppContext $ctx, ?string $currentId, a
if ($currentId !== null && (string)($existing['id'] ?? '') === $currentId) { if ($currentId !== null && (string)($existing['id'] ?? '') === $currentId) {
continue; 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(); $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); $selectedDate = substr($value, 0, 10);
if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $selectedDate)) { if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $selectedDate)) {
$selectedDate = date('Y-m-d'); $selectedDate = date('Y-m-d');
@@ -119,11 +368,12 @@ function render_calendar_picker(AppContext $ctx, string $name, string $title, st
} }
$selectedDt = DateTimeImmutable::createFromFormat('!Y-m-d', $selectedDate) ?: new DateTimeImmutable('today'); $selectedDt = DateTimeImmutable::createFromFormat('!Y-m-d', $selectedDate) ?: new DateTimeImmutable('today');
$monthStart = $selectedDt->modify('first day of this month'); $monthStart = $selectedDt->modify('first day of this month');
$days = render_calendar_days($name, $selectedDate, $monthStart); $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'); $visibleMonth = $monthStart->format('Y-m');
$monthLabel = calendar_month_label($ctx, $monthStart); $monthLabel = calendar_month_label($ctx, $monthStart);
if ($mode === 'exact_hour') { 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 { } else {
$timeControl = '<label>' . AppContext::e($ctx->t('Time of day')) . '</label><select name="' . AppContext::e($name . '_period') . '" data-period-for="' . AppContext::e($name) . '">' . $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>' . '<option value="morning"' . ($selectedPeriod === 'morning' ? ' selected' : '') . '>' . AppContext::e($ctx->t('Morning')) . '</option>' .
@@ -131,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>' . '<option value="evening"' . ($selectedPeriod === 'evening' ? ' selected' : '') . '>' . AppContext::e($ctx->t('Evening')) . '</option>' .
'</select>'; '</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) . '"><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>' . '<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-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>'; '<input type="hidden" id="' . AppContext::e($name) . '" name="' . AppContext::e($name) . '" value="' . AppContext::e($value) . '" data-canonical-value="' . AppContext::e($name) . '"></div>';
} }
@@ -153,7 +403,7 @@ function render_weekday_headers(AppContext $ctx): string
return $html; return $html;
} }
function render_calendar_days(string $name, string $selectedDate, DateTimeImmutable $monthStart): string function render_calendar_days(string $name, string $selectedDate, DateTimeImmutable $monthStart, string $minDate): string
{ {
$offset = ((int)$monthStart->format('N')) - 1; $offset = ((int)$monthStart->format('N')) - 1;
$daysInMonth = (int)$monthStart->format('t'); $daysInMonth = (int)$monthStart->format('t');
@@ -167,6 +417,11 @@ function render_calendar_days(string $name, string $selectedDate, DateTimeImmuta
continue; continue;
} }
$date = $monthStart->setDate((int)$monthStart->format('Y'), (int)$monthStart->format('m'), $day)->format('Y-m-d'); $date = $monthStart->setDate((int)$monthStart->format('Y'), (int)$monthStart->format('m'), $day)->format('Y-m-d');
if ($minDate !== '' && $date < $minDate) {
$html .= '<td><span class="br-cal-day-disabled">' . $day . '</span></td>';
$day++;
continue;
}
$class = $date === $selectedDate ? ' is-selected' : ''; $class = $date === $selectedDate ? ' is-selected' : '';
$html .= '<td><button type="button" class="br-cal-day' . $class . '" data-date-target="' . AppContext::e($name . '_date') . '" data-date-label="' . AppContext::e($name . '_label') . '" data-date-value="' . AppContext::e($date) . '">' . $day . '</button></td>'; $html .= '<td><button type="button" class="br-cal-day' . $class . '" data-date-target="' . AppContext::e($name . '_date') . '" data-date-label="' . AppContext::e($name . '_label') . '" data-date-value="' . AppContext::e($date) . '">' . $day . '</button></td>';
$day++; $day++;
+70 -9
View File
@@ -3,23 +3,84 @@ declare(strict_types=1);
return static function (AppContext $ctx): void { return static function (AppContext $ctx): void {
$errors = []; $errors = [];
$formRule = null;
$modal = '';
if (Http::isPost()) { if (Http::isPost()) {
try { try {
$ctx->requireCsrf('create'); $ctx->requireCsrf('create');
$input = normalize_rule_post($_POST); $input = normalize_rule_post($_POST);
$rule = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings)); $rule = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings));
enforce_rule_backend_constraints($ctx, null, $rule); $formRule = $rule;
$created = $ctx->rules->create($ctx->daUser->username(), $rule); $conflict = !empty($rule['enabled']) ? find_active_rule_conflict($ctx, null) : null;
try { $conflictAction = $ctx->post('conflict_action');
$ctx->syncActiveBackend(); $conflictRuleId = $ctx->post('conflict_rule_id');
} catch (Throwable $syncError) {
$ctx->rules->delete($ctx->daUser->username(), (string)$created['id']); if ($conflict !== null && ($conflictAction !== 'replace' || $conflictRuleId !== (string)($conflict['id'] ?? ''))) {
throw $syncError; $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) { } catch (Throwable $e) {
PluginLogger::exception($e, 'CREATE');
$errors[] = $e->getMessage(); $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;
}
+5 -7
View File
@@ -11,18 +11,16 @@ return static function (AppContext $ctx): void {
if (Http::isPost()) { if (Http::isPost()) {
try { try {
$ctx->requireCsrf('delete:' . $id); $ctx->requireCsrf('delete:' . $id);
$deletedName = display_rule_name($ctx, $rule);
$ctx->rules->delete($ctx->daUser->username(), $id); $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'] ?? '')]); $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) { } catch (Throwable $e) {
PluginLogger::exception($e, 'DELETE');
$ctx->render('Confirm deletion', '<div class="alert alert-err">' . AppContext::e($e->getMessage()) . '</div>'); $ctx->render('Confirm deletion', '<div class="alert alert-err">' . AppContext::e($e->getMessage()) . '</div>');
return; return;
} }
} }
$body = '<div class="grid grid-2"><div class="panel"><h3>' . AppContext::e($ctx->t('Preview autoresponder')) . '</h3>' . render_preview_box($ctx, $rule) . '</div>' . $ctx->render('Confirm deletion', render_delete_confirmation_body($ctx, $rule));
'<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);
}; };
+5 -30
View File
@@ -2,40 +2,15 @@
declare(strict_types=1); declare(strict_types=1);
return static function (AppContext $ctx): void { return static function (AppContext $ctx): void {
$rules = $ctx->rules->all($ctx->daUser->username());
$ok = []; $ok = [];
$status = $ctx->query('status'); $status = $ctx->query('status');
if ($status === 'created') { $ok[] = $ctx->t('Rule created.'); } if ($status === 'created') { $ok[] = $ctx->t('Rule created.'); }
if ($status === 'updated') { $ok[] = $ctx->t('Rule updated.'); } 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 ($status === 'toggled') { $ok[] = $ctx->t('Rule status changed.'); }
if ($rules === []) { render_rules_index($ctx, $ok);
$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>' .
'<a class="btn amber" href="' . AppContext::e($ctx->url('create.html')) . '">' . AppContext::e($ctx->t('Add autoresponder')) . '</a></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>' . AppContext::e($ctx->t($rule['dynamic_scope'] ? 'Dynamic' : 'Snapshot')) . '</td><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>' .
'<a class="btn amber" href="' . AppContext::e($ctx->url('create.html')) . '">' . AppContext::e($ctx->t('Add autoresponder')) . '</a></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('Scope')) . '</th><th>' . AppContext::e($ctx->t('Actions')) . '</th></tr></thead><tbody>' . $rows . '</tbody></table></div>';
$ctx->render('Global autoresponders', $body, $ok);
}; };
+45 -11
View File
@@ -2,16 +2,50 @@
declare(strict_types=1); declare(strict_types=1);
return static function (AppContext $ctx): void { return static function (AppContext $ctx): void {
$ctx->requirePost(); try {
$id = $ctx->post('id'); $ctx->requirePost();
$ctx->requireCsrf('toggle:' . $id); $id = $ctx->post('id');
$rule = $ctx->rules->find($ctx->daUser->username(), $id); $ctx->requireCsrf('toggle:' . $id);
if ($rule === null) { $rule = $ctx->rules->find($ctx->daUser->username(), $id);
if ($rule === null) {
throw new RuntimeException($ctx->t('Rule not found'));
}
$next = ['enabled' => empty($rule['enabled'])];
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->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')); throw new RuntimeException($ctx->t('Rule not found'));
} }
$next = ['enabled' => empty($rule['enabled'])]; $ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => false]);
enforce_rule_backend_constraints($ctx, $id, $next); $ctx->rules->update($ctx->daUser->username(), $targetId, ['enabled' => true]);
$ctx->rules->update($ctx->daUser->username(), $id, $next); try {
$ctx->syncActiveBackend(); $ctx->syncDirectAdminVacations();
Http::redirect($ctx->url('index.html', ['status' => 'toggled'])); } catch (Throwable $syncError) {
}; $ctx->rules->update($ctx->daUser->username(), $targetId, ['enabled' => false]);
$ctx->rules->update($ctx->daUser->username(), $activeId, ['enabled' => true]);
throw $syncError;
}
}
+4 -3
View File
@@ -13,12 +13,13 @@ return static function (AppContext $ctx): void {
try { try {
$ctx->requireCsrf('update:' . $id); $ctx->requireCsrf('update:' . $id);
$input = normalize_rule_post($_POST); $input = normalize_rule_post($_POST);
$patch = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings)); $patch = attach_rule_scope($ctx, RuleValidator::validate($input, $ctx->settings, true));
enforce_rule_backend_constraints($ctx, $id, $patch); enforce_rule_directadmin_constraints($ctx, $id, $patch);
$ctx->rules->update($ctx->daUser->username(), $id, $patch); $ctx->rules->update($ctx->daUser->username(), $id, $patch);
$ctx->syncActiveBackend(); $ctx->syncDirectAdminVacations();
Http::redirect($ctx->url('index.html', ['status' => 'updated'])); Http::redirect($ctx->url('index.html', ['status' => 'updated']));
} catch (Throwable $e) { } catch (Throwable $e) {
PluginLogger::exception($e, 'UPDATE');
$errors[] = $e->getMessage(); $errors[] = $e->getMessage();
} }
} }
+70 -11
View File
@@ -33,9 +33,10 @@ final class AppContext
return $url; 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 public function post(string $key, string $default = ''): string
@@ -58,23 +59,20 @@ final class AppContext
public function csrfField(string $intent): string public function csrfField(string $intent): string
{ {
$issued = $this->csrf->issue($intent); $issued = $this->csrf->issue($intent);
return '<input type="hidden" name="csrf_ts" value="' . self::e((string)$issued['ts']) . '">' . return '<input type="hidden" name="gar_csrf_ts" value="' . self::e((string)$issued['ts']) . '">' .
'<input type="hidden" name="csrf_sid" value="' . self::e($issued['sid']) . '">' . '<input type="hidden" name="gar_csrf_sid" value="' . self::e($issued['sid']) . '">' .
'<input type="hidden" name="csrf_token" value="' . self::e($issued['token']) . '">'; '<input type="hidden" name="gar_csrf_token" value="' . self::e($issued['token']) . '">';
} }
public function requireCsrf(string $intent): void public function requireCsrf(string $intent): void
{ {
if (!$this->csrf->validate($intent, $this->post('csrf_ts'), $this->post('csrf_token'), 3600, $this->post('csrf_sid'))) { if (!$this->csrf->validate($intent, $this->post('gar_csrf_ts'), $this->post('gar_csrf_token'), 3600, $this->post('gar_csrf_sid'))) {
throw new RuntimeException('Nieprawidłowy lub wygasły token CSRF.'); throw new RuntimeException('Nieprawidłowy lub wygasły token CSRF.');
} }
} }
public function syncActiveBackend(): void public function syncDirectAdminVacations(): void
{ {
if ($this->settings->backendMode() !== 'da') {
return;
}
$service = new DirectAdminVacationSyncService( $service = new DirectAdminVacationSyncService(
$this->rules, $this->rules,
new DirectAdminSyncRepository(), new DirectAdminSyncRepository(),
@@ -98,7 +96,7 @@ final class AppContext
echo '<meta name="viewport" content="width=device-width, initial-scale=1">'; 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 '<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 '<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 '<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 '<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>'; echo '<section class="main-section">' . $alerts . $body . '</section></div>';
@@ -113,6 +111,12 @@ final class AppContext
private function styles(): string private function styles(): string
{ {
$skin = $this->daUser->skin(); $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'; $path = PLUGIN_ROOT . '/user/' . $skin . '.css';
if (!is_file($path)) { if (!is_file($path)) {
$path = PLUGIN_ROOT . '/user/enhanced.css'; $path = PLUGIN_ROOT . '/user/enhanced.css';
@@ -122,14 +126,39 @@ final class AppContext
private function scripts(): string 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); $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' $monthNames = json_encode($this->lang->code() === 'pl'
? ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'] ? ['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); : ['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 return <<<JS
(function () { (function () {
var pluginSkin = {$skin};
var selectedLabel = {$selectedLabel}; var selectedLabel = {$selectedLabel};
var monthNames = {$monthNames}; 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 pad(value) { return value < 10 ? '0' + value : String(value); }
function updateCanonical(name) { function updateCanonical(name) {
var date = document.getElementById(name + '_date'); var date = document.getElementById(name + '_date');
@@ -158,6 +187,7 @@ final class AppContext
} }
function renderMonth(calendar, year, month) { function renderMonth(calendar, year, month) {
var selected = calendar.getAttribute('data-selected-date') || ''; var selected = calendar.getAttribute('data-selected-date') || '';
var minDate = calendar.getAttribute('data-min-date') || '';
var tbody = calendar.querySelector('[data-calendar-days]'); var tbody = calendar.querySelector('[data-calendar-days]');
var label = calendar.querySelector('[data-calendar-month-label]'); var label = calendar.querySelector('[data-calendar-month-label]');
if (!tbody || !label) { return; } if (!tbody || !label) { return; }
@@ -174,6 +204,11 @@ final class AppContext
continue; continue;
} }
var value = year + '-' + pad(month) + '-' + pad(day); var value = year + '-' + pad(month) + '-' + pad(day);
if (minDate && value < minDate) {
html += '<td><span class="br-cal-day-disabled">' + day + '</span></td>';
day++;
continue;
}
var cls = value === selected ? ' is-selected' : ''; var cls = value === selected ? ' is-selected' : '';
html += '<td><button type="button" class="br-cal-day' + cls + '" data-date-target="' + calendar.getAttribute('data-calendar-name') + '_date" data-date-label="' + calendar.getAttribute('data-calendar-name') + '_label" data-date-value="' + value + '">' + day + '</button></td>'; html += '<td><button type="button" class="br-cal-day' + cls + '" data-date-target="' + calendar.getAttribute('data-calendar-name') + '_date" data-date-label="' + calendar.getAttribute('data-calendar-name') + '_label" data-date-value="' + value + '">' + day + '</button></td>';
day++; day++;
@@ -189,6 +224,11 @@ final class AppContext
document.querySelectorAll('[data-date-value]').forEach(function (btn) { document.querySelectorAll('[data-date-value]').forEach(function (btn) {
bindDateButton(btn); bindDateButton(btn);
}); });
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', expandDirectAdminPluginContainers);
} else {
expandDirectAdminPluginContainers();
}
document.querySelectorAll('[data-calendar-picker]').forEach(function (calendar) { document.querySelectorAll('[data-calendar-picker]').forEach(function (calendar) {
var name = calendar.getAttribute('data-calendar-name'); var name = calendar.getAttribute('data-calendar-name');
calendar.querySelectorAll('[data-calendar-prev],[data-calendar-next]').forEach(function (btn) { calendar.querySelectorAll('[data-calendar-prev],[data-calendar-next]').forEach(function (btn) {
@@ -208,6 +248,25 @@ final class AppContext
control.addEventListener('input', function () { updateCanonical(name); }); 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; 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'); throw new InvalidArgumentException('Invalid username');
} }
$this->username = $username; $this->username = $username;
$this->skin = $skin !== '' ? $skin : 'enhanced'; $this->skin = self::normalizeSkin($skin);
$this->language = $language !== '' ? strtolower($language) : 'en'; $this->language = $language !== '' ? strtolower($language) : 'en';
$this->configDir = $configDir; $this->configDir = $configDir;
} }
public static function fromEnvironment(Settings $settings): self public static function fromEnvironment(Settings $settings): self
{ {
$username = getenv('USERNAME') ?: getenv('USER') ?: getenv('DA_USER') ?: ''; $username = self::environmentValue(['USERNAME', 'DA_USER', 'USER']);
if ($username === '' && isset($_SERVER['USERNAME'])) {
$username = (string)$_SERVER['USERNAME'];
}
if ($username === '') { if ($username === '') {
throw new RuntimeException('Cannot determine DirectAdmin user'); throw new RuntimeException('Cannot determine DirectAdmin user');
} }
$skin = getenv('SKIN') ?: (string)($_SERVER['SKIN'] ?? 'enhanced'); $userConf = self::readUserConf($username);
$lang = self::readLanguage($username) ?: $settings->defaultLanguage(); $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); return new self($username, $skin, $lang);
} }
@@ -58,21 +59,65 @@ final class DirectAdminUser
return $settings->defaultEnable(); 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'; $normalizedSkin = strtolower(trim($skin));
if (!is_file($path)) { if ($normalizedSkin === '') {
return ''; return 'enhanced';
} }
$lines = file($path, FILE_IGNORE_NEW_LINES); if (str_contains($normalizedSkin, 'evolution')) {
if ($lines === false) { return 'evolution';
return '';
} }
foreach ($lines as $line) { return $normalizedSkin;
if (str_starts_with($line, 'language=')) { }
return strtolower(trim(substr($line, 9)));
/**
* @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 '';
} }
/**
* @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'] ?? '')));
}
} }
+142 -18
View File
@@ -5,12 +5,20 @@ class DirectAdminVacationApi
{ {
/** @var callable|null */ /** @var callable|null */
private $request; private $request;
private string $daBinary = '/usr/local/bin/da'; /** @var callable|null */
private $runner;
private string $daBinary = '/usr/local/directadmin/directadmin';
public function __construct(string $daBinary = '/usr/local/bin/da', ?callable $request = null) public function __construct(string $daBinary = '/usr/local/directadmin/directadmin', ?callable $request = null, ?callable $runner = null)
{ {
$this->daBinary = $daBinary; $this->daBinary = $daBinary;
$this->request = $request; $this->request = $request;
$this->runner = $runner;
}
public function directAdminBinary(): string
{
return $this->daBinary;
} }
/** @param array<string,mixed> $rule @return array<string,string> */ /** @param array<string,mixed> $rule @return array<string,string> */
@@ -20,22 +28,20 @@ class DirectAdminVacationApi
throw new InvalidArgumentException('Invalid mailbox email'); throw new InvalidArgumentException('Invalid mailbox email');
} }
[$local, $domain] = explode('@', strtolower($email), 2); [$local, $domain] = explode('@', strtolower($email), 2);
[$startDate, $startTime] = $this->splitPeriod((string)($rule['start_value'] ?? '')); [$startDate, $startTime] = $this->splitScheduleValue((string)($rule['start_value'] ?? ''), true);
[$endDate, $endTime] = $this->splitPeriod((string)($rule['end_value'] ?? '')); [$endDate, $endTime] = $this->splitScheduleValue((string)($rule['end_value'] ?? ''), false);
[$startYear, $startMonth, $startDay] = explode('-', $startDate); [$startYear, $startMonth, $startDay] = explode('-', $startDate);
[$endYear, $endMonth, $endDay] = explode('-', $endDate); [$endYear, $endMonth, $endDay] = explode('-', $endDate);
$subjectPrefix = (string)($rule['subject_prefix'] ?? $rule['subject'] ?? ''); $subjectPrefix = (string)($rule['subject_prefix'] ?? $rule['subject'] ?? '');
$replyFrequency = !empty($rule['reply_every_message']) ? '0' : (string)max(0, (int)($rule['repeat_minutes'] ?? 1440)); $payload = [
return [
'action' => $exists ? 'modify' : 'create', 'action' => $exists ? 'modify' : 'create',
'domain' => $domain, 'domain' => $domain,
'user' => $local, 'user' => $local,
'email' => $email,
'text' => (string)($rule['body'] ?? ''), 'text' => (string)($rule['body'] ?? ''),
'subject_prefix' => $subjectPrefix,
'subject' => $subjectPrefix, 'subject' => $subjectPrefix,
'reply_frequency' => $replyFrequency, 'reply_encoding' => 'UTF-8',
'reply_once_time' => $replyFrequency, 'reply_content_type' => 'text/plain',
'reply_once_time' => $this->replyOnceTime($rule),
'starttime' => $startTime, 'starttime' => $startTime,
'startyear' => $startYear, 'startyear' => $startYear,
'startmonth' => $startMonth, 'startmonth' => $startMonth,
@@ -44,8 +50,11 @@ class DirectAdminVacationApi
'endyear' => $endYear, 'endyear' => $endYear,
'endmonth' => $endMonth, 'endmonth' => $endMonth,
'endday' => $endDay, 'endday' => $endDay,
'create' => $exists ? '' : 'Create',
]; ];
if (!$exists) {
$payload['create'] = 'Create';
}
return $payload;
} }
/** @param array<string,mixed> $rule */ /** @param array<string,mixed> $rule */
@@ -99,12 +108,16 @@ class DirectAdminVacationApi
} }
/** @return array{0:string,1:string} */ /** @return array{0:string,1:string} */
private function splitPeriod(string $value): array private function splitScheduleValue(string $value, bool $start): array
{ {
if (!preg_match('/^([0-9]{4}-[0-9]{2}-[0-9]{2})\|(morning|afternoon|evening)$/', $value, $m)) { if (preg_match('/^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2})$/', $value, $m)) {
throw new InvalidArgumentException('DirectAdmin API backend requires directadmin_period values'); return [$m[1], $m[2]];
} }
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 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];
} }
/** @param array<string,string> $payload */ /** @param array<string,string> $payload */
@@ -122,18 +135,107 @@ class DirectAdminVacationApi
} }
$baseUrl = $this->apiUrl($owner); $baseUrl = $this->apiUrl($owner);
$url = rtrim($baseUrl, '/') . '/' . $endpoint; $url = rtrim($baseUrl, '/') . '/' . $endpoint;
$args = ['curl', '-fsS', '-X', 'POST']; $args = ['curl', '-sS', '-X', 'POST', '-w', "\n%{http_code}"];
foreach ($payload as $key => $value) { foreach ($payload as $key => $value) {
$args[] = '--data-urlencode'; $args[] = '--data-urlencode';
$args[] = $key . '=' . $value; $args[] = $key . '=' . $value;
} }
$args[] = $url; $args[] = $url;
return $this->run($args, ''); return $this->parseHttpResponse($this->run($args, ''));
}
/** @param array<string,mixed> $rule */
private function replyOnceTime(array $rule): string
{
return match ((int)($rule['repeat_minutes'] ?? 1440)) {
1 => '1m',
10 => '10m',
30 => '30m',
60 => '1h',
120 => '2h',
360 => '6h',
720 => '12h',
1440 => '1d',
2880 => '2d',
4320 => '3d',
5760 => '4d',
7200 => '5d',
8640 => '6d',
10080 => '1w',
11520 => '8d',
12960 => '9d',
14400 => '10d',
15840 => '11d',
17280 => '12d',
18720 => '13d',
20160 => '14d',
default => '1d',
};
}
private function parseHttpResponse(string $output): string
{
if (!preg_match("/\n([0-9]{3})$/", $output, $m, PREG_OFFSET_CAPTURE)) {
return $output;
}
$code = (int)$m[1][0];
$body = substr($output, 0, (int)$m[0][1]);
if ($code < 200 || $code >= 400) {
throw new RuntimeException('DirectAdmin API HTTP ' . $code . ': ' . $this->compactBody($body));
}
$this->throwIfApiError($body);
return $body;
}
private function throwIfApiError(string $body): void
{
$trimmed = trim($body);
if ($trimmed === '') {
return;
}
$json = json_decode($trimmed, true);
if (is_array($json) && isset($json['error']) && $this->truthyError($json['error'])) {
throw new RuntimeException('DirectAdmin API error: ' . $this->compactBody(implode(' ', array_filter([
(string)($json['text'] ?? ''),
(string)($json['details'] ?? ''),
(string)($json['result'] ?? ''),
(string)($json['error'] ?? ''),
]))));
}
$fields = [];
parse_str($trimmed, $fields);
if (isset($fields['error']) && $this->truthyError($fields['error'])) {
throw new RuntimeException('DirectAdmin API error: ' . $this->compactBody(implode(' ', array_filter([
is_scalar($fields['text'] ?? null) ? (string)$fields['text'] : '',
is_scalar($fields['details'] ?? null) ? (string)$fields['details'] : '',
is_scalar($fields['result'] ?? null) ? (string)$fields['result'] : '',
is_scalar($fields['error'] ?? null) ? (string)$fields['error'] : '',
]))));
}
}
private function truthyError(mixed $value): bool
{
return in_array(strtolower(trim((string)$value)), ['1', 'yes', 'true', 'error'], true);
}
private function compactBody(string $body): string
{
$body = trim(preg_replace('/[[:cntrl:]]+/', ' ', $body) ?? $body);
if ($body === '') {
return 'empty response body';
}
if (strlen($body) > 1200) {
return substr($body, 0, 1200) . '...';
}
return $body;
} }
private function apiUrl(string $owner): string private function apiUrl(string $owner): string
{ {
$output = $this->run([$this->daBinary, 'api-url', '--user=' . $owner], ''); $output = $this->run([$this->resolveDirectAdminBinary(), 'api-url', '--user=' . $owner], '');
$url = trim($output); $url = trim($output);
if ($url === '' || !preg_match('#^https?://#', $url)) { if ($url === '' || !preg_match('#^https?://#', $url)) {
throw new RuntimeException('Cannot determine DirectAdmin API URL for user'); throw new RuntimeException('Cannot determine DirectAdmin API URL for user');
@@ -141,9 +243,31 @@ class DirectAdminVacationApi
return $url; return $url;
} }
private function resolveDirectAdminBinary(): string
{
$candidates = array_values(array_unique([
$this->daBinary,
'/usr/local/directadmin/directadmin',
'/usr/bin/da',
]));
foreach ($candidates as $candidate) {
if ($candidate !== '' && is_executable($candidate)) {
return $candidate;
}
}
throw new RuntimeException('DirectAdmin binary is not executable. Checked: ' . implode(', ', $candidates));
}
/** @param string[] $args */ /** @param string[] $args */
private function run(array $args, string $stdin): string private function run(array $args, string $stdin): string
{ {
if ($this->runner !== null) {
$result = call_user_func($this->runner, $args, $stdin);
return (string)$result;
}
if (($args[0] ?? '') !== '' && str_contains($args[0], '/') && !is_executable($args[0])) {
throw new RuntimeException('DirectAdmin API command is not executable: ' . $args[0]);
}
$process = proc_open($args, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes); $process = proc_open($args, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
if (!is_resource($process)) { if (!is_resource($process)) {
throw new RuntimeException('Cannot start DirectAdmin API command'); throw new RuntimeException('Cannot start DirectAdmin API command');
+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>> */ /** @return array<string,array<string,mixed>> */
private function rulesById(string $username): array private function rulesById(string $username): array
{ {
@@ -47,12 +81,20 @@ final class DirectAdminVacationSyncService
$existing = $this->indexedEntries($this->sync->entriesForRule($username, $ruleId)); $existing = $this->indexedEntries($this->sync->entriesForRule($username, $ruleId));
$targets = $this->targetMailboxes($username, $rule); $targets = $this->targetMailboxes($username, $rule);
$next = []; $next = [];
$conflicts = [];
foreach ($targets as $mailbox) { foreach ($targets as $mailbox) {
$email = strtolower((string)$mailbox['email']); $email = strtolower((string)$mailbox['email']);
$isTracked = isset($existing[$email]); $isTracked = isset($existing[$email]);
if (!$isTracked && $this->api->vacationExists($username, $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); $this->api->saveVacation($username, $email, $rule, $isTracked);
$next[] = [ $next[] = [
'rule_id' => $ruleId, 'rule_id' => $ruleId,
@@ -95,6 +137,21 @@ final class DirectAdminVacationSyncService
return $out; 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}> */ /** @param array<string,mixed> $rule @return array<int,array{domain:string,mailbox:string,email:string}> */
private function targetMailboxes(string $username, array $rule): array private function targetMailboxes(string $username, array $rule): array
{ {
+84
View File
@@ -3,6 +3,72 @@ declare(strict_types=1);
final class Http final class Http
{ {
public static function bootstrapGlobals(): void
{
if (PHP_SAPI !== 'cli') {
return;
}
$query = getenv('QUERY_STRING') ?: '';
$method = strtoupper((string)(getenv('REQUEST_METHOD') ?: 'GET'));
$_GET = [];
if ($query !== '') {
parse_str($query, $_GET);
}
$_POST = [];
if ($method === 'POST') {
$rawPost = (string)(getenv('POST') ?: '');
if ($rawPost === '') {
$rawPost = (string)(getenv('HTTP_POST') ?: '');
}
$contentType = strtolower((string)(getenv('CONTENT_TYPE') ?: ''));
$isUrlEncoded = ($contentType === '' || str_contains($contentType, 'application/x-www-form-urlencoded'));
if ($rawPost === '' && $isUrlEncoded) {
$stdin = @file_get_contents('php://stdin');
if (is_string($stdin) && $stdin !== '') {
$rawPost = $stdin;
}
}
if ($rawPost !== '') {
parse_str($rawPost, $_POST);
}
}
$_REQUEST = array_merge($_GET, $_POST);
$_SERVER['REQUEST_METHOD'] = $method;
$_SERVER['QUERY_STRING'] = $query;
foreach ([
'USER',
'USERNAME',
'HOME',
'LANGUAGE',
'SESSION_ID',
'REQUEST_URI',
'HTTP_HOST',
'HTTPS',
'HTTP_USER_AGENT',
'HTTP_X_FORWARDED_PROTO',
'HTTP_FRONT_END_HTTPS',
'REQUEST_SCHEME',
'SERVER_NAME',
'SERVER_PORT',
'REMOTE_ADDR',
'SKIN',
] as $key) {
if (!isset($_SERVER[$key])) {
$value = getenv($key);
if ($value !== false) {
$_SERVER[$key] = $value;
}
}
}
}
public static function method(): string public static function method(): string
{ {
return strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')); return strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
@@ -24,7 +90,25 @@ final class Http
public static function redirect(string $url): void public static function redirect(string $url): void
{ {
if (PHP_SAPI === 'cli') {
header('Content-Type: text/html; charset=UTF-8');
echo self::redirectDocument($url);
exit;
}
header('Location: ' . $url, true, 302); header('Location: ' . $url, true, 302);
exit; exit;
} }
public static function redirectDocument(string $url): string
{
$safeUrl = htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$jsonUrl = json_encode($url, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
return '<!doctype html><html lang="pl"><head><meta charset="utf-8">' .
'<meta name="viewport" content="width=device-width, initial-scale=1">' .
'<meta http-equiv="refresh" content="0;url=' . $safeUrl . '">' .
'<title>Przekierowanie</title></head><body>' .
'<p>Przekierowanie... <a href="' . $safeUrl . '">Kontynuuj</a></p>' .
'<script>window.location.replace(' . $jsonUrl . ');</script>' .
'</body></html>';
}
} }
-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[] */ /** @return string[] */
private function domainsForUser(string $username): array public function domainsForUser(string $username): array
{ {
$domains = []; $domains = [];
foreach ($this->domainOwners() as $domain => $owner) { 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;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
final class PluginLogger
{
private static string $path = '';
public static function init(string $path): void
{
self::$path = $path;
self::ensureLogFile();
@ini_set('log_errors', '1');
@ini_set('error_log', $path);
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) === 0) {
return false;
}
self::log('PHP_ERROR', self::severityName($severity) . ': ' . $message . ' in ' . $file . ':' . $line);
return false;
});
register_shutdown_function(static function (): void {
$error = error_get_last();
if (!is_array($error)) {
return;
}
$fatal = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR];
if (in_array((int)($error['type'] ?? 0), $fatal, true)) {
self::log('PHP_FATAL', self::severityName((int)$error['type']) . ': ' . (string)$error['message'] . ' in ' . (string)$error['file'] . ':' . (string)$error['line']);
}
});
}
public static function exception(Throwable $e, string $context = 'UNCAUGHT'): void
{
self::log($context, get_class($e) . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . "\n" . $e->getTraceAsString());
}
public static function log(string $level, string $message): void
{
$path = self::$path !== '' ? self::$path : (defined('PLUGIN_ROOT') ? PLUGIN_ROOT . '/plugin.log' : __DIR__ . '/../../plugin.log');
$line = '[' . gmdate('c') . '] ' . $level . ' ' . str_replace(["\r\n", "\r"], "\n", $message) . "\n";
$ok = @file_put_contents($path, $line, FILE_APPEND | LOCK_EX);
if ($ok !== false && is_file($path)) {
@chmod($path, 0600);
}
}
private static function severityName(int $severity): string
{
return match ($severity) {
E_ERROR => 'E_ERROR',
E_WARNING => 'E_WARNING',
E_PARSE => 'E_PARSE',
E_NOTICE => 'E_NOTICE',
E_CORE_ERROR => 'E_CORE_ERROR',
E_CORE_WARNING => 'E_CORE_WARNING',
E_COMPILE_ERROR => 'E_COMPILE_ERROR',
E_COMPILE_WARNING => 'E_COMPILE_WARNING',
E_USER_ERROR => 'E_USER_ERROR',
E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE',
E_STRICT => 'E_STRICT',
E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
E_DEPRECATED => 'E_DEPRECATED',
E_USER_DEPRECATED => 'E_USER_DEPRECATED',
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();
}
}
+35 -9
View File
@@ -5,6 +5,8 @@ final class RuleValidator
{ {
/** @var array<string,int> */ /** @var array<string,int> */
private const REPLY_FREQUENCIES = [ private const REPLY_FREQUENCIES = [
'1' => 1,
'10' => 10,
'30' => 30, '30' => 30,
'60' => 60, '60' => 60,
'120' => 120, '120' => 120,
@@ -12,12 +14,31 @@ final class RuleValidator
'720' => 720, '720' => 720,
'1440' => 1440, '1440' => 1440,
'2880' => 2880, '2880' => 2880,
'4320' => 4320,
'5760' => 5760,
'7200' => 7200,
'8640' => 8640,
'10080' => 10080, '10080' => 10080,
'11520' => 11520,
'12960' => 12960,
'14400' => 14400,
'15840' => 15840,
'17280' => 17280,
'18720' => 18720,
'20160' => 20160,
]; ];
/** @param array<string,mixed> $input @return array<string,mixed> */ /** @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'] ?? '')); $subjectPrefix = trim((string)($input['subject_prefix'] ?? $input['subject'] ?? ''));
if (str_contains($subjectPrefix, "\r") || str_contains($subjectPrefix, "\n")) { if (str_contains($subjectPrefix, "\r") || str_contains($subjectPrefix, "\n")) {
throw new InvalidArgumentException('Przedrostek tematu nie może zawierać nowych linii.'); throw new InvalidArgumentException('Przedrostek tematu nie może zawierać nowych linii.');
@@ -39,12 +60,22 @@ final class RuleValidator
$tz = new DateTimeZone($settings->timezone()); $tz = new DateTimeZone($settings->timezone());
[$startTs, $startValue] = self::parseScheduleValue((string)($input['start_value'] ?? ''), $mode, $tz, true); [$startTs, $startValue] = self::parseScheduleValue((string)($input['start_value'] ?? ''), $mode, $tz, true);
[$endTs, $endValue] = self::parseScheduleValue((string)($input['end_value'] ?? ''), $mode, $tz, false); [$endTs, $endValue] = self::parseScheduleValue((string)($input['end_value'] ?? ''), $mode, $tz, false);
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) { if ($endTs <= $startTs) {
throw new InvalidArgumentException('Data zakończenia musi być późniejsza niż data rozpoczęcia.'); throw new InvalidArgumentException('Data zakończenia musi być późniejsza niż data rozpoczęcia.');
} }
[$replyEveryMessage, $repeatMinutes] = self::parseReplyFrequency((string)($input['reply_frequency'] ?? '1440')); $repeatMinutes = self::parseReplyFrequency((string)($input['reply_frequency'] ?? '1440'));
return [ return [
'name' => $name,
'subject_prefix' => $subjectPrefix, 'subject_prefix' => $subjectPrefix,
'body' => $body, 'body' => $body,
'schedule_mode' => $mode, 'schedule_mode' => $mode,
@@ -54,21 +85,16 @@ final class RuleValidator
'start_ts' => $startTs, 'start_ts' => $startTs,
'end_ts' => $endTs, 'end_ts' => $endTs,
'enabled' => self::truthy($input['enabled'] ?? false), 'enabled' => self::truthy($input['enabled'] ?? false),
'reply_every_message' => $replyEveryMessage,
'repeat_minutes' => $repeatMinutes, 'repeat_minutes' => $repeatMinutes,
'dynamic_scope' => $settings->dynamicMailboxScope(), 'dynamic_scope' => $settings->dynamicMailboxScope(),
]; ];
} }
/** @return array{0:bool,1:int} */ private static function parseReplyFrequency(string $value): int
private static function parseReplyFrequency(string $value): array
{ {
$value = trim(strtolower($value)); $value = trim(strtolower($value));
if ($value === 'every') {
return [true, 0];
}
if (isset(self::REPLY_FREQUENCIES[$value])) { 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.'); throw new InvalidArgumentException('Częstość odpowiedzi jest nieprawidłowa.');
} }
+1 -11
View File
@@ -6,7 +6,6 @@ final class Settings
public const BASE_DIR = '/usr/local/hitme_plugins/global-autoresponders'; public const BASE_DIR = '/usr/local/hitme_plugins/global-autoresponders';
public const CONFIG_DIR = self::BASE_DIR . '/config'; public const CONFIG_DIR = self::BASE_DIR . '/config';
public const DATA_DIR = self::BASE_DIR . '/data'; 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 LOG_DIR = self::BASE_DIR . '/logs';
public const AUDIT_LOG = self::LOG_DIR . '/audit.log'; public const AUDIT_LOG = self::LOG_DIR . '/audit.log';
public const EXTERNAL_SETTINGS = self::CONFIG_DIR . '/plugin-settings.conf'; public const EXTERNAL_SETTINGS = self::CONFIG_DIR . '/plugin-settings.conf';
@@ -51,7 +50,6 @@ final class Settings
'DEFAULT_PLUGIN_LANGUAGE' => 'pl', 'DEFAULT_PLUGIN_LANGUAGE' => 'pl',
'DEFAULT_ENABLE' => 'true', 'DEFAULT_ENABLE' => 'true',
'GLOBAL_AUTORESPONDER_TIMEZONE' => 'Europe/Warsaw', 'GLOBAL_AUTORESPONDER_TIMEZONE' => 'Europe/Warsaw',
'GLOBAL_AUTORESPONDER_BACKEND' => 'da',
'GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE' => 'true', 'GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE' => 'true',
'GLOBAL_AUTORESPONDER_MAX_SUBJECT_BYTES' => '255', 'GLOBAL_AUTORESPONDER_MAX_SUBJECT_BYTES' => '255',
'GLOBAL_AUTORESPONDER_MAX_BODY_BYTES' => '20000', 'GLOBAL_AUTORESPONDER_MAX_BODY_BYTES' => '20000',
@@ -91,14 +89,9 @@ final class Settings
return $this->getString('GLOBAL_AUTORESPONDER_TIMEZONE', 'Europe/Warsaw'); return $this->getString('GLOBAL_AUTORESPONDER_TIMEZONE', 'Europe/Warsaw');
} }
public function backendMode(): string
{
return $this->getString('GLOBAL_AUTORESPONDER_BACKEND', 'da');
}
public function scheduleMode(): string public function scheduleMode(): string
{ {
return $this->backendMode() === 'da' ? 'directadmin_period' : 'exact_hour'; return 'exact_hour';
} }
public function dynamicMailboxScope(): bool public function dynamicMailboxScope(): bool
@@ -141,9 +134,6 @@ final class Settings
} catch (Throwable) { } catch (Throwable) {
throw new InvalidArgumentException('Invalid timezone: ' . $this->timezone()); 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) { if ($this->maxSubjectBytes() < 1 || $this->maxBodyBytes() < 1) {
throw new InvalidArgumentException('Invalid size limits'); throw new InvalidArgumentException('Invalid size limits');
} }
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"
fill="none" stroke="currentColor" stroke-width="1.7"
stroke-linecap="round" stroke-linejoin="round"
role="img" aria-label="Autoresponder">
<!-- PL: Koperta (treść maila). EN: Envelope (mail body). -->
<rect x="4" y="3" width="16" height="9.5" rx="2.25"/>
<!-- PL: Klapka koperty. EN: Envelope flap. -->
<path d="M5.25 4.75 12 9l6.75-4.25"/>
<!-- PL: Strzalka auto-odpowiedzi wychodzaca z koperty. EN: Auto-reply return arrow. -->
<path d="M19 12.5V14a4 4 0 0 1-4 4H7.5"/>
<path d="M10.5 15 7.5 18l3 3"/>
</svg>

After

Width:  |  Height:  |  Size: 625 B

+37 -6
View File
@@ -3,20 +3,23 @@ declare(strict_types=1);
return [ return [
'Global autoresponders' => 'Global autoresponders', 'Global autoresponders' => 'Global autoresponders',
'Manage automatic replies for account mailboxes' => 'Manage automatic replies for account mailboxes',
'Dashboard' => 'Dashboard', 'Dashboard' => 'Dashboard',
'AUTORESPONDERS' => 'AUTORESPONDERS', 'AUTORESPONDERS' => 'Global autoresponder list',
'ADD AUTORESPONDER' => 'ADD AUTORESPONDER', 'ADD AUTORESPONDER' => 'Add global autoresponder',
'Add autoresponder' => 'Add autoresponder', 'Add autoresponder' => 'Add autoresponder',
'Edit autoresponder' => 'Edit autoresponder', 'Edit autoresponder' => 'Edit autoresponder',
'Preview autoresponder' => 'Preview autoresponder', 'Preview autoresponder' => 'Preview autoresponder',
'Autoresponder name' => 'Autoresponder name',
'Autoresponder name help' => 'This name is used only for description and is not used by the autoresponder itself.',
'Unnamed autoresponder' => 'Unnamed autoresponder',
'Subject' => 'Subject', 'Subject' => 'Subject',
'Subject prefix' => 'Subject prefix', 'Subject prefix' => 'Subject prefix',
'Original subject suffix' => ': original subject', 'Original subject suffix' => ': original subject',
'Message body' => 'Message body', 'Message body' => 'Message body',
'Response content' => 'Response content', 'Response content' => 'Response content',
'Response frequency' => 'Response frequency', 'Response frequency' => 'Response frequency',
'Send automatic reply for every message' => 'Send automatic reply for every message', '1 minute' => '1 minute',
'10 minutes' => '10 minutes',
'30 minutes' => '30 minutes', '30 minutes' => '30 minutes',
'1 hour' => '1 hour', '1 hour' => '1 hour',
'2 hours' => '2 hours', '2 hours' => '2 hours',
@@ -24,7 +27,18 @@ return [
'12 hours' => '12 hours', '12 hours' => '12 hours',
'1 day' => '1 day', '1 day' => '1 day',
'2 days' => '2 days', '2 days' => '2 days',
'3 days' => '3 days',
'4 days' => '4 days',
'5 days' => '5 days',
'6 days' => '6 days',
'7 days' => '7 days', '7 days' => '7 days',
'8 days' => '8 days',
'9 days' => '9 days',
'10 days' => '10 days',
'11 days' => '11 days',
'12 days' => '12 days',
'13 days' => '13 days',
'14 days' => '14 days',
'Status' => 'Status', 'Status' => 'Status',
'Enabled' => 'Enabled', 'Enabled' => 'Enabled',
'Disabled' => 'Disabled', 'Disabled' => 'Disabled',
@@ -48,14 +62,19 @@ return [
'Confirm deletion' => 'Confirm deletion', 'Confirm deletion' => 'Confirm deletion',
'Delete autoresponder' => 'Delete autoresponder', 'Delete autoresponder' => 'Delete autoresponder',
'Do not delete' => 'Do not delete', 'Do not delete' => 'Do not delete',
'Delete confirmation question' => 'Are you sure you want to delete global autoresponder {name} created on {created}?',
'Yes' => 'Yes',
'No' => 'No',
'No global autoresponders' => 'No global autoresponders', 'No global autoresponders' => 'No global autoresponders',
'Rule created.' => 'Rule created.', 'Rule created.' => 'Rule created.',
'Rule updated.' => 'Rule updated.', 'Rule updated.' => 'Rule updated.',
'Rule deleted.' => 'Rule deleted.', 'Rule deleted.' => 'Rule deleted.',
'Global autoresponder deleted.' => 'Global autoresponder {name} has been deleted.',
'Rule status changed.' => 'Rule status changed.', 'Rule status changed.' => 'Rule status changed.',
'All valid POP/IMAP mailboxes in this account' => 'All valid POP/IMAP mailboxes in this account',
'Rule not found' => 'Rule not found', 'Rule not found' => 'Rule not found',
'Sending period' => 'Sending period', 'Sending period' => 'Sending period',
'Created' => 'Created',
'Updated' => 'Updated',
'Scope' => 'Scope', 'Scope' => 'Scope',
'Actions' => 'Actions', 'Actions' => 'Actions',
'Dynamic' => 'Dynamic', 'Dynamic' => 'Dynamic',
@@ -71,6 +90,18 @@ return [
'Fri' => 'Fri', 'Fri' => 'Fri',
'Sat' => 'Sat', 'Sat' => 'Sat',
'Sun' => 'Sun', 'Sun' => 'Sun',
'DirectAdmin backend supports only one enabled global rule.' => 'DirectAdmin backend supports only one enabled global rule.', 'Only one active autoresponder' => 'Only one active autoresponder',
'Active autoresponder exists for user.' => 'A global autoresponder named {name}, created on {created}, already exists for user {user}.',
'Only one global autoresponder can be active per user.' => 'Only one global autoresponder can be active in one user account.',
'Enable new and disable previous' => 'Enable autoresponder ({new}) and disable previous ({old})',
'Add as disabled' => 'Add autoresponder ({name}) as disabled',
'Enable autoresponder' => 'Enable autoresponder',
'Native autoresponders already exist' => 'Native autoresponders already exist',
'Native autoresponders exist for user.' => 'User {user} already has native autoresponders / vacation messages created with DirectAdmin autoresponder / vacation message options.',
'Email address' => 'Email address',
'Domain' => 'Domain',
'Mailbox' => 'Mailbox',
'Native autoresponders removal warning' => 'Existing autoresponders / vacation messages will be removed if you continue.',
'Remove existing autoresponders' => 'REMOVE EXISTING AUTORESPONDERS',
'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.' => 'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.', 'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.' => 'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.',
]; ];
+37 -6
View File
@@ -3,20 +3,23 @@ declare(strict_types=1);
return [ return [
'Global autoresponders' => 'Globalne autorespondery', 'Global autoresponders' => 'Globalne autorespondery',
'Manage automatic replies for account mailboxes' => 'Zarządzanie odpowiedziami dla skrzynek pocztowych konta',
'Dashboard' => 'Pulpit', 'Dashboard' => 'Pulpit',
'AUTORESPONDERS' => 'AUTORESPONDERY', 'AUTORESPONDERS' => 'Lista globalnych autoresponderów',
'ADD AUTORESPONDER' => 'DODAJ AUTORESPONDER', 'ADD AUTORESPONDER' => 'Dodaj Globalny autoresponder',
'Add autoresponder' => 'Dodaj autoresponder', 'Add autoresponder' => 'Dodaj autoresponder',
'Edit autoresponder' => 'Edytuj autoresponder', 'Edit autoresponder' => 'Edytuj autoresponder',
'Preview autoresponder' => 'Podgląd autorespondera', 'Preview autoresponder' => 'Podgląd autorespondera',
'Autoresponder name' => 'Nazwa autorespondera',
'Autoresponder name help' => 'Ta nazwa jest wykorzystywana tylko w celach opisowych i nie jest używana do pracy autorespondera.',
'Unnamed autoresponder' => 'Autoresponder bez nazwy',
'Subject' => 'Temat', 'Subject' => 'Temat',
'Subject prefix' => 'Przedrostek tematu', 'Subject prefix' => 'Przedrostek tematu',
'Original subject suffix' => ': pierwotny temat', 'Original subject suffix' => ': pierwotny temat',
'Message body' => 'Treść wiadomości', 'Message body' => 'Treść wiadomości',
'Response content' => 'Treść odpowiedzi', 'Response content' => 'Treść odpowiedzi',
'Response frequency' => 'Częstość odpowiedzi', 'Response frequency' => 'Częstość odpowiedzi',
'Send automatic reply for every message' => 'Wysyłaj automatyczną odpowiedź dla każdej wiadomości', '1 minute' => '1 minuta',
'10 minutes' => '10 minut',
'30 minutes' => '30 minut', '30 minutes' => '30 minut',
'1 hour' => '1 godzina', '1 hour' => '1 godzina',
'2 hours' => '2 godziny', '2 hours' => '2 godziny',
@@ -24,7 +27,18 @@ return [
'12 hours' => '12 godzin', '12 hours' => '12 godzin',
'1 day' => '1 dzień', '1 day' => '1 dzień',
'2 days' => '2 dni', '2 days' => '2 dni',
'3 days' => '3 dni',
'4 days' => '4 dni',
'5 days' => '5 dni',
'6 days' => '6 dni',
'7 days' => '7 dni', '7 days' => '7 dni',
'8 days' => '8 dni',
'9 days' => '9 dni',
'10 days' => '10 dni',
'11 days' => '11 dni',
'12 days' => '12 dni',
'13 days' => '13 dni',
'14 days' => '14 dni',
'Status' => 'Status', 'Status' => 'Status',
'Enabled' => 'Włączony', 'Enabled' => 'Włączony',
'Disabled' => 'Wyłączony', 'Disabled' => 'Wyłączony',
@@ -48,14 +62,19 @@ return [
'Confirm deletion' => 'Potwierdź usunięcie', 'Confirm deletion' => 'Potwierdź usunięcie',
'Delete autoresponder' => 'Usuń autoresponder', 'Delete autoresponder' => 'Usuń autoresponder',
'Do not delete' => 'Nie usuwaj', 'Do not delete' => 'Nie usuwaj',
'Delete confirmation question' => 'Czy napewno chcesz usunąć globalny autoresponder {name} utworzony {created}?',
'Yes' => 'Tak',
'No' => 'Nie',
'No global autoresponders' => 'Brak globalnych autoresponderów', 'No global autoresponders' => 'Brak globalnych autoresponderów',
'Rule created.' => 'Reguła została utworzona.', 'Rule created.' => 'Reguła została utworzona.',
'Rule updated.' => 'Reguła została zaktualizowana.', 'Rule updated.' => 'Reguła została zaktualizowana.',
'Rule deleted.' => 'Reguła została usunięta.', 'Rule deleted.' => 'Reguła została usunięta.',
'Global autoresponder deleted.' => 'Globalny autoresponder {name} został usunięty.',
'Rule status changed.' => 'Status reguły został zmieniony.', 'Rule status changed.' => 'Status reguły został zmieniony.',
'All valid POP/IMAP mailboxes in this account' => 'Wszystkie prawidłowe skrzynki POP/IMAP konta',
'Rule not found' => 'Nie znaleziono reguły', 'Rule not found' => 'Nie znaleziono reguły',
'Sending period' => 'Okres wysyłki', 'Sending period' => 'Okres wysyłki',
'Created' => 'Utworzono',
'Updated' => 'Zaktualizowano',
'Scope' => 'Zakres', 'Scope' => 'Zakres',
'Actions' => 'Akcje', 'Actions' => 'Akcje',
'Dynamic' => 'Dynamiczny', 'Dynamic' => 'Dynamiczny',
@@ -71,6 +90,18 @@ return [
'Fri' => 'Pt', 'Fri' => 'Pt',
'Sat' => 'Sb', 'Sat' => 'Sb',
'Sun' => 'Nd', 'Sun' => 'Nd',
'DirectAdmin backend supports only one enabled global rule.' => 'Backend DirectAdmin obsługuje tylko jedną aktywną regułę globalną.', 'Only one active autoresponder' => 'Tylko jeden aktywny autoresponder',
'Active autoresponder exists for user.' => 'Dla użytkownika {user} istnieje już globalny autoresponder o nazwie {name}, utworzony dnia {created}.',
'Only one global autoresponder can be active per user.' => 'W ramach użytkownika może być aktywny tylko jeden globalny autoresponder.',
'Enable new and disable previous' => 'Włącz autoresponder ({new}) i wyłącz poprzedni ({old})',
'Add as disabled' => 'Dodaj autoresponder ({name}) jako wyłączony',
'Enable autoresponder' => 'Włącz autoresponder',
'Native autoresponders already exist' => 'Istnieją natywne autorespondery',
'Native autoresponders exist for user.' => 'użytkownik {user} ma już utworzone natywne autorespondery / wiadomości przy użyciu opcji autorespondery / wiadomość urlopowa w DirectAdminie.',
'Email address' => 'Adres e-mail',
'Domain' => 'Domena',
'Mailbox' => 'Skrzynka',
'Native autoresponders removal warning' => 'Istniejące autorespondery / wiadomości urlopowe zostaną usunięte w przypadku kontynuacji.',
'Remove existing autoresponders' => 'USUŃ ISTNIEJĄCE AUTORESPONDERY',
'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.' => 'Usunięcie reguły wyłączy odpowiedź automatyczną utworzoną przez tę regułę dla objętych skrzynek.', 'Deleting this rule will disable the automatic reply created by this rule for covered mailboxes.' => 'Usunięcie reguły wyłączy odpowiedź automatyczną utworzoną przez tę regułę dla objętych skrzynek.',
]; ];
-5
View File
@@ -8,11 +8,6 @@ DEFAULT_ENABLE=true
# Strefa czasu używana do interpretacji i wyświetlania dat rozpoczęcia oraz zakończenia. # Strefa czasu używana do interpretacji i wyświetlania dat rozpoczęcia oraz zakończenia.
GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw
# Tryb pracy pluginu.
# da = użycie natywnych autoresponderów DirectAdmin.
# exim = własna obsługa z możliwością podania dokładnej godziny i minuty.
GLOBAL_AUTORESPONDER_BACKEND=da
# Czy reguła obejmuje także skrzynki POP/IMAP dodane po utworzeniu reguły. # Czy reguła obejmuje także skrzynki POP/IMAP dodane po utworzeniu reguły.
# true = zakres dynamiczny, false = snapshot skrzynek przy tworzeniu/edycji. # true = zakres dynamiczny, false = snapshot skrzynek przy tworzeniu/edycji.
GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE=true GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE=true
+1 -1
View File
@@ -2,7 +2,7 @@ name=global-autoresponder
id=global-autoresponder id=global-autoresponder
type=user type=user
author=HITME.PL author=HITME.PL
version=1.0.8 version=1.4.12
active=no active=no
installed=no installed=no
user_run_as=root user_run_as=root
-186
View File
@@ -1,186 +0,0 @@
#!/bin/sh
set -eu
BASE_DIR="/usr/local/hitme_plugins/global-autoresponders"
STATE_FILE="$BASE_DIR/config/backend-state.json"
PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder"
CUSTOM_DIR="/usr/local/directadmin/custombuild/custom/exim"
CUSTOM_CONF="$CUSTOM_DIR/exim.conf"
SOURCE_CONF="/usr/local/directadmin/custombuild/configure/exim/exim.conf"
ROUTER_SNIPPET="$PLUGIN_DIR/scripts/exim/global_autoresponder_router.conf"
TRANSPORT_SNIPPET="$PLUGIN_DIR/scripts/exim/global_autoresponder_transport.conf"
ROLLBACK_ACTIVE=0
ROLLBACK_CREATED=0
ROLLBACK_REBUILD=0
ROLLBACK_FILE=
usage() {
echo "Usage: scripts/backend.sh da|exim" >&2
}
if [ "${1:-}" != "da" ] && [ "${1:-}" != "exim" ]; then
usage
exit 2
fi
mkdir -p "$BASE_DIR/config" "$BASE_DIR/data" "$BASE_DIR/state" "$BASE_DIR/logs"
chmod 700 "$BASE_DIR/config" "$BASE_DIR/logs"
write_state() {
backend="$1"
printf '{"active_backend":"%s","migration_status":"complete"}\n' "$backend" > "$STATE_FILE"
chmod 600 "$STATE_FILE"
}
remove_marked_block() {
marker="$1"
file="$2"
tmp="${file}.global-autoresponder.$$"
awk -v marker="$marker" '
$0 == "# BEGIN global-autoresponder " marker { skip=1; next }
$0 == "# END global-autoresponder " marker { skip=0; next }
skip != 1 { print }
' "$file" > "$tmp"
mv "$tmp" "$file"
}
insert_after_section() {
section="$1"
snippet="$2"
file="$3"
tmp="${file}.global-autoresponder.$$"
if ! awk -v section="$section" -v snippet="$snippet" '
BEGIN {
while ((getline line < snippet) > 0) {
block = block line "\n"
}
close(snippet)
}
{ print }
$0 == section && inserted != 1 {
printf "\n%s\n", block
inserted = 1
}
END {
if (inserted != 1) {
exit 3
}
}
' "$file" > "$tmp"; then
rm -f "$tmp"
echo "Cannot install exim backend: section $section not found in custom exim.conf." >&2
exit 1
fi
mv "$tmp" "$file"
}
backup_custom_conf() {
mkdir -p "$CUSTOM_DIR"
ROLLBACK_FILE="${CUSTOM_CONF}.global-autoresponder.backup.$$"
if [ -f "$CUSTOM_CONF" ]; then
cp "$CUSTOM_CONF" "$ROLLBACK_FILE"
ROLLBACK_CREATED=0
else
: > "$ROLLBACK_FILE"
ROLLBACK_CREATED=1
fi
ROLLBACK_ACTIVE=1
}
restore_custom_conf() {
if [ "$ROLLBACK_ACTIVE" != "1" ]; then
return
fi
set +e
if [ "$ROLLBACK_CREATED" = "1" ]; then
rm -f "$CUSTOM_CONF"
else
cp "$ROLLBACK_FILE" "$CUSTOM_CONF"
fi
rm -f "$ROLLBACK_FILE"
if [ "$ROLLBACK_REBUILD" = "1" ]; then
rebuild_and_reload_exim >/dev/null 2>&1
fi
ROLLBACK_ACTIVE=0
}
commit_custom_conf() {
rm -f "$ROLLBACK_FILE"
ROLLBACK_ACTIVE=0
ROLLBACK_CREATED=0
ROLLBACK_REBUILD=0
}
trap 'restore_custom_conf' EXIT
trap 'restore_custom_conf; exit 1' HUP INT TERM
validate_exim_conf() {
if command -v exim >/dev/null 2>&1; then
exim -C "$CUSTOM_CONF" -bV >/dev/null
elif command -v exim4 >/dev/null 2>&1; then
exim4 -C "$CUSTOM_CONF" -bV >/dev/null
else
echo "Cannot validate exim backend: exim binary not found." >&2
exit 1
fi
}
rebuild_and_reload_exim() {
if command -v da >/dev/null 2>&1; then
da build exim_conf
elif [ -x /usr/local/directadmin/custombuild/build ]; then
/usr/local/directadmin/custombuild/build exim_conf
else
echo "Cannot rebuild exim configuration: da/build command not found." >&2
exit 1
fi
if command -v systemctl >/dev/null 2>&1; then
systemctl reload exim 2>/dev/null || systemctl restart exim
else
service exim reload 2>/dev/null || service exim restart
fi
}
if [ "$1" = "da" ]; then
if [ -f "$CUSTOM_CONF" ]; then
backup_custom_conf
remove_marked_block "router" "$CUSTOM_CONF"
remove_marked_block "transport" "$CUSTOM_CONF"
if grep -Fq "global_autoresponder_" "$CUSTOM_CONF"; then
echo "Cannot switch to da: plugin Exim markers were not removed cleanly." >&2
exit 1
fi
validate_exim_conf
ROLLBACK_REBUILD=1
rebuild_and_reload_exim
commit_custom_conf
fi
write_state "da"
echo "Backend set to da"
exit 0
fi
if [ ! -d "$(dirname "$SOURCE_CONF")" ]; then
echo "Cannot enable exim backend: DirectAdmin CustomBuild exim source config not found." >&2
exit 1
fi
if [ ! -f "$ROUTER_SNIPPET" ] || [ ! -f "$TRANSPORT_SNIPPET" ]; then
echo "Cannot enable exim backend: plugin Exim snippets are missing." >&2
exit 1
fi
backup_custom_conf
if [ ! -f "$CUSTOM_CONF" ]; then
cp "$SOURCE_CONF" "$CUSTOM_CONF"
fi
remove_marked_block "router" "$CUSTOM_CONF"
remove_marked_block "transport" "$CUSTOM_CONF"
insert_after_section "begin routers" "$ROUTER_SNIPPET" "$CUSTOM_CONF"
insert_after_section "begin transports" "$TRANSPORT_SNIPPET" "$CUSTOM_CONF"
validate_exim_conf
ROLLBACK_REBUILD=1
rebuild_and_reload_exim
commit_custom_conf
write_state "exim"
echo "Backend set to exim"
@@ -1,11 +0,0 @@
# BEGIN global-autoresponder router
# Runs an unseen delivery to the plugin worker for local recipients. Normal mailbox
# delivery continues because unseen is enabled and the worker suppresses ineligible mail.
global_autoresponder_router:
driver = accept
domains = +local_domains
condition = ${if exists{/usr/local/directadmin/plugins/global-autoresponder/scripts/global_autoresponder_worker.php}{yes}{no}}
transport = global_autoresponder_transport
unseen
no_verify
# END global-autoresponder router
@@ -1,13 +0,0 @@
# BEGIN global-autoresponder transport
# The worker receives the original message on stdin and Exim-provided envelope
# variables such as SENDER, RECIPIENT, LOCAL_PART, and DOMAIN in the environment.
global_autoresponder_transport:
driver = pipe
command = /usr/local/directadmin/plugins/global-autoresponder/scripts/global_autoresponder_worker.php
user = root
group = root
return_fail_output = false
log_output = true
message_prefix =
message_suffix =
# END global-autoresponder transport
-199
View File
@@ -1,199 +0,0 @@
#!/usr/local/bin/php
<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/exec/lib/Settings.php';
require_once dirname(__DIR__) . '/exec/lib/MessageClassifier.php';
require_once dirname(__DIR__) . '/exec/lib/RepeatState.php';
require_once dirname(__DIR__) . '/exec/lib/MailSender.php';
require_once dirname(__DIR__) . '/exec/lib/MailboxDirectory.php';
require_once dirname(__DIR__) . '/exec/lib/RuleRepository.php';
final class GlobalAutoresponderWorker
{
/** @param callable(string,string,string,string):bool $send */
public function __construct(
private Settings $settings,
private RuleRepository $rules,
private MailboxDirectory $mailboxes,
private RepeatState $repeat,
private $send,
private ?int $now = null
) {
}
/** @param array<string,string> $env */
public function handle(array $env, string $message): int
{
if ($this->settings->backendMode() !== 'exim') {
return 0;
}
$sender = self::firstEnv($env, ['SENDER_ADDRESS', 'sender_address', 'SENDER', 'sender']);
$recipient = self::recipientFromEnv($env);
if ($sender === '' || $recipient === '' || !self::isEmail($sender) || !self::isEmail($recipient)) {
return 0;
}
$headers = self::parseHeaders($message);
if (MessageClassifier::shouldSuppress($headers, $sender)) {
return 0;
}
$resolved = $this->mailboxes->resolveRecipient($recipient);
if ($resolved === null) {
return 0;
}
$sent = 0;
$owner = $resolved['owner'];
$recipient = $resolved['email'];
foreach ($this->rules->all($owner) as $rule) {
if (!$this->isActiveRule($rule)) {
continue;
}
if (!$this->ruleIncludesRecipient($rule, $recipient)) {
continue;
}
$ruleId = (string)($rule['id'] ?? '');
if ($ruleId === '') {
continue;
}
$repeatMinutes = !empty($rule['reply_every_message']) ? 0 : max(0, (int)($rule['repeat_minutes'] ?? 1440));
if (!$this->repeat->shouldSend($owner, $ruleId, $recipient, $sender, $repeatMinutes)) {
continue;
}
$replySubject = self::replySubject(
(string)($rule['subject_prefix'] ?? $rule['subject'] ?? ''),
self::headerValue($headers, 'subject')
);
$ok = (bool)call_user_func(
$this->send,
$recipient,
strtolower($sender),
$replySubject,
(string)$rule['body']
);
if ($ok) {
$this->repeat->record($owner, $ruleId, $recipient, $sender);
$sent++;
}
}
return $sent;
}
/** @param array<string,mixed> $rule */
private function isActiveRule(array $rule): bool
{
if (empty($rule['enabled'])) {
return false;
}
$now = $this->now ?? time();
return (int)($rule['start_ts'] ?? 0) <= $now && (int)($rule['end_ts'] ?? 0) >= $now;
}
/** @param array<string,mixed> $rule */
private function ruleIncludesRecipient(array $rule, string $recipient): bool
{
if (!array_key_exists('dynamic_scope', $rule) || !empty($rule['dynamic_scope'])) {
return true;
}
$snapshot = $rule['mailbox_snapshot'] ?? [];
if (!is_array($snapshot)) {
return false;
}
foreach ($snapshot as $mailbox) {
if (is_array($mailbox) && strtolower((string)($mailbox['email'] ?? '')) === strtolower($recipient)) {
return true;
}
}
return false;
}
/** @param array<string,string> $env @param string[] $keys */
private static function firstEnv(array $env, array $keys): string
{
foreach ($keys as $key) {
$value = trim((string)($env[$key] ?? ''));
if ($value !== '') {
return strtolower($value);
}
}
return '';
}
/** @param array<string,string> $env */
private static function recipientFromEnv(array $env): string
{
$direct = self::firstEnv($env, ['LOCAL_PART_DOMAIN', 'RECIPIENT', 'ORIGINAL_RECIPIENT', 'local_part_domain']);
if ($direct !== '') {
return $direct;
}
$local = self::firstEnv($env, ['LOCAL_PART', 'local_part']);
$domain = self::firstEnv($env, ['DOMAIN', 'domain']);
return ($local !== '' && $domain !== '') ? $local . '@' . $domain : '';
}
private static function isEmail(string $value): bool
{
return (bool)preg_match('/^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+$/', $value);
}
/** @return array<string,string> */
public static function parseHeaders(string $message): array
{
$headers = [];
$current = '';
foreach (preg_split('/\r\n|\n|\r/', $message) ?: [] as $line) {
if ($line === '') {
break;
}
if ($current !== '' && preg_match('/^[ \t]/', $line)) {
$headers[$current] .= ' ' . trim($line);
continue;
}
if (!str_contains($line, ':')) {
continue;
}
[$key, $value] = explode(':', $line, 2);
$current = trim($key);
if ($current !== '') {
$headers[$current] = trim($value);
}
}
return $headers;
}
/** @param array<string,string> $headers */
private static function headerValue(array $headers, string $name): string
{
foreach ($headers as $key => $value) {
if (strcasecmp($key, $name) === 0) {
return trim($value);
}
}
return '';
}
private static function replySubject(string $prefix, string $originalSubject): string
{
$prefix = trim($prefix);
$originalSubject = trim($originalSubject);
if ($prefix !== '' && $originalSubject !== '') {
return str_ends_with($prefix, ':') ? $prefix . ' ' . $originalSubject : $prefix . ': ' . $originalSubject;
}
if ($prefix !== '') {
return $prefix;
}
return $originalSubject !== '' ? $originalSubject : 'Automatic reply';
}
}
if (PHP_SAPI === 'cli' && realpath((string)($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
$settings = Settings::load(Settings::EXTERNAL_SETTINGS);
$sender = new MailSender();
$worker = new GlobalAutoresponderWorker(
$settings,
new RuleRepository(),
new MailboxDirectory(),
new RepeatState(),
static fn (string $from, string $to, string $subject, string $body): bool => $sender->send('/usr/sbin/sendmail', $from, $to, $subject, $body)
);
$worker->handle(getenv(), stream_get_contents(STDIN) ?: '');
}
+2 -7
View File
@@ -5,20 +5,15 @@ BASE_DIR="/usr/local/hitme_plugins/global-autoresponders"
PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder" PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder"
CRON_FILE="/etc/cron.d/global-autoresponder" CRON_FILE="/etc/cron.d/global-autoresponder"
mkdir -p "$BASE_DIR/config/users" "$BASE_DIR/data/users" "$BASE_DIR/state/replies" "$BASE_DIR/logs" mkdir -p "$BASE_DIR/config/users" "$BASE_DIR/data/users" "$BASE_DIR/logs"
chmod 700 "$BASE_DIR/config" "$BASE_DIR/logs" chmod 700 "$BASE_DIR/config" "$BASE_DIR/logs"
chmod 711 "$BASE_DIR/data" "$BASE_DIR/state" chmod 711 "$BASE_DIR/data"
if [ ! -f "$BASE_DIR/config/plugin-settings.conf" ]; then if [ ! -f "$BASE_DIR/config/plugin-settings.conf" ]; then
cp "$PLUGIN_DIR/plugin-settings.conf" "$BASE_DIR/config/plugin-settings.conf" cp "$PLUGIN_DIR/plugin-settings.conf" "$BASE_DIR/config/plugin-settings.conf"
chmod 600 "$BASE_DIR/config/plugin-settings.conf" chmod 600 "$BASE_DIR/config/plugin-settings.conf"
fi fi
if [ ! -f "$BASE_DIR/config/backend-state.json" ]; then
printf '%s\n' '{"active_backend":"da","migration_status":"complete"}' > "$BASE_DIR/config/backend-state.json"
chmod 600 "$BASE_DIR/config/backend-state.json"
fi
touch "$BASE_DIR/logs/audit.log" touch "$BASE_DIR/logs/audit.log"
chmod 600 "$BASE_DIR/logs/audit.log" chmod 600 "$BASE_DIR/logs/audit.log"
+1 -5
View File
@@ -38,11 +38,7 @@ try {
throw new InvalidArgumentException('Invalid username'); throw new InvalidArgumentException('Invalid username');
} }
$settings = Settings::load(Settings::EXTERNAL_SETTINGS); Settings::load(Settings::EXTERNAL_SETTINGS);
if ($settings->backendMode() !== 'da') {
echo "DirectAdmin backend is not active; nothing to sync.\n";
exit(0);
}
$users = $targetUser !== '' ? [$targetUser] : users_with_rules(Settings::DATA_DIR); $users = $targetUser !== '' ? [$targetUser] : users_with_rules(Settings::DATA_DIR);
$service = new DirectAdminVacationSyncService( $service = new DirectAdminVacationSyncService(
-4
View File
@@ -2,12 +2,8 @@
set -eu set -eu
BASE_DIR="/usr/local/hitme_plugins/global-autoresponders" BASE_DIR="/usr/local/hitme_plugins/global-autoresponders"
PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder"
CRON_FILE="/etc/cron.d/global-autoresponder" CRON_FILE="/etc/cron.d/global-autoresponder"
if [ -x "$PLUGIN_DIR/scripts/backend.sh" ]; then
"$PLUGIN_DIR/scripts/backend.sh" da || true
fi
rm -f "$CRON_FILE" rm -f "$CRON_FILE"
if [ "${PURGE_GLOBAL_AUTORESPONDER_DATA:-0}" = "1" ]; then if [ "${PURGE_GLOBAL_AUTORESPONDER_DATA:-0}" = "1" ]; then
+1 -1
View File
@@ -4,7 +4,7 @@ set -eu
BASE_DIR="/usr/local/hitme_plugins/global-autoresponders" BASE_DIR="/usr/local/hitme_plugins/global-autoresponders"
PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder" PLUGIN_DIR="/usr/local/directadmin/plugins/global-autoresponder"
CRON_FILE="/etc/cron.d/global-autoresponder" CRON_FILE="/etc/cron.d/global-autoresponder"
mkdir -p "$BASE_DIR/config/users" "$BASE_DIR/data/users" "$BASE_DIR/state/replies" "$BASE_DIR/logs" mkdir -p "$BASE_DIR/config/users" "$BASE_DIR/data/users" "$BASE_DIR/logs"
printf '%s\n' "*/15 * * * * root $PLUGIN_DIR/scripts/sync_directadmin_vacations.php >/dev/null 2>&1" > "$CRON_FILE" printf '%s\n' "*/15 * * * * root $PLUGIN_DIR/scripts/sync_directadmin_vacations.php >/dev/null 2>&1" > "$CRON_FILE"
chmod 644 "$CRON_FILE" chmod 644 "$CRON_FILE"
echo "global-autoresponder updated; external configuration preserved" echo "global-autoresponder updated; external configuration preserved"
-21
View File
@@ -1,21 +0,0 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/Settings.php';
require_once PLUGIN_ROOT . '/exec/lib/BackendRuntimeConfig.php';
test('backend runtime sync invokes backend script when setting changes', function (): void {
$settingsPath = TEST_TMP . '/backend-runtime.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_BACKEND=exim\n");
$settings = Settings::load($settingsPath);
$script = TEST_TMP . '/backend.sh';
test_write($script, "#!/bin/sh\necho \"$1\" >> " . escapeshellarg(TEST_TMP . '/called.log') . "\nmkdir -p " . escapeshellarg(TEST_TMP . '/config') . "\nprintf '{\"active_backend\":\"%s\"}\\n' \"$1\" > " . escapeshellarg(TEST_TMP . '/config/backend-state.json') . "\n");
chmod($script, 0700);
BackendRuntimeConfig::sync($settings, $script, TEST_TMP . '/config/backend-state.json');
assert_same("exim\n", file_get_contents(TEST_TMP . '/called.log'));
BackendRuntimeConfig::sync($settings, $script, TEST_TMP . '/config/backend-state.json');
assert_same("exim\n", file_get_contents(TEST_TMP . '/called.log'), 'Script should not run again when backend is already active');
});
+19 -13
View File
@@ -10,7 +10,6 @@ test('settings validate defaults and external paths', function (): void {
'DEFAULT_PLUGIN_LANGUAGE=pl', 'DEFAULT_PLUGIN_LANGUAGE=pl',
'DEFAULT_ENABLE=false', 'DEFAULT_ENABLE=false',
'GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw', 'GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw',
'GLOBAL_AUTORESPONDER_BACKEND=exim',
'GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE=true', 'GLOBAL_AUTORESPONDER_DYNAMIC_MAILBOX_SCOPE=true',
'GLOBAL_AUTORESPONDER_MAX_SUBJECT_BYTES=255', 'GLOBAL_AUTORESPONDER_MAX_SUBJECT_BYTES=255',
'GLOBAL_AUTORESPONDER_MAX_BODY_BYTES=20000', 'GLOBAL_AUTORESPONDER_MAX_BODY_BYTES=20000',
@@ -21,7 +20,6 @@ test('settings validate defaults and external paths', function (): void {
assert_false($settings->defaultEnable()); assert_false($settings->defaultEnable());
assert_same('Europe/Warsaw', $settings->timezone()); assert_same('Europe/Warsaw', $settings->timezone());
assert_same('exact_hour', $settings->scheduleMode()); assert_same('exact_hour', $settings->scheduleMode());
assert_same('exim', $settings->backendMode());
assert_same('/usr/local/hitme_plugins/global-autoresponders/config', Settings::CONFIG_DIR); assert_same('/usr/local/hitme_plugins/global-autoresponders/config', Settings::CONFIG_DIR);
assert_same('/usr/local/hitme_plugins/global-autoresponders/data', Settings::DATA_DIR); assert_same('/usr/local/hitme_plugins/global-autoresponders/data', Settings::DATA_DIR);
}); });
@@ -34,7 +32,7 @@ test('settings template does not contain global repeat policy settings', functio
test('settings reject invalid timezone and schedule mode', function (): void { test('settings reject invalid timezone and schedule mode', function (): void {
$path = TEST_TMP . '/bad-settings.conf'; $path = TEST_TMP . '/bad-settings.conf';
test_write($path, "GLOBAL_AUTORESPONDER_TIMEZONE=Not/AZone\nGLOBAL_AUTORESPONDER_BACKEND=bad\n"); test_write($path, "GLOBAL_AUTORESPONDER_TIMEZONE=Not/AZone\n");
try { try {
Settings::load($path); Settings::load($path);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
@@ -44,16 +42,8 @@ test('settings reject invalid timezone and schedule mode', function (): void {
throw new RuntimeException('Expected invalid settings to fail'); throw new RuntimeException('Expected invalid settings to fail');
}); });
test('backend mode derives schedule mode', function (): void { test('settings keep exact schedule mode', function (): void {
$path = TEST_TMP . '/backend.conf'; $settings = Settings::load(TEST_TMP . '/schedule.conf');
test_write($path, "GLOBAL_AUTORESPONDER_BACKEND=da\n");
$settings = Settings::load($path);
assert_same('da', $settings->backendMode());
assert_same('directadmin_period', $settings->scheduleMode());
test_write($path, "GLOBAL_AUTORESPONDER_BACKEND=exim\n");
$settings = Settings::load($path);
assert_same('exim', $settings->backendMode());
assert_same('exact_hour', $settings->scheduleMode()); assert_same('exact_hour', $settings->scheduleMode());
}); });
@@ -67,3 +57,19 @@ test('directadmin user access follows DEFAULT_ENABLE and per-user overrides', fu
test_write(TEST_TMP . '/config/users/marek.conf', "enabled=true\n"); test_write(TEST_TMP . '/config/users/marek.conf', "enabled=true\n");
assert_true($user->hasPluginAccess($settings)); assert_true($user->hasPluginAccess($settings));
}); });
test('directadmin user normalizes evolution skin variants', function (): void {
assert_same('evolution', (new DirectAdminUser('marek', 'Evolution', 'en', TEST_TMP . '/config'))->skin());
assert_same('evolution', (new DirectAdminUser('marek', 'evolution-ui', 'en', TEST_TMP . '/config'))->skin());
assert_same('enhanced', (new DirectAdminUser('marek', '', 'en', TEST_TMP . '/config'))->skin());
});
test('directadmin user checks common skin environment variables', function (): void {
$source = file_get_contents(PLUGIN_ROOT . '/exec/lib/DirectAdminUser.php') ?: '';
assert_contains('SESSION_SKIN', $source);
assert_contains('SESSION_SELECTED_SKIN', $source);
assert_contains('DA_SKIN', $source);
assert_contains("['skin']", $source);
assert_contains('readUserConf', $source);
});
+53
View File
@@ -2,6 +2,13 @@
declare(strict_types=1); declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/CsrfGuard.php'; require_once PLUGIN_ROOT . '/exec/lib/CsrfGuard.php';
require_once PLUGIN_ROOT . '/exec/lib/Http.php';
require_once PLUGIN_ROOT . '/exec/lib/Settings.php';
require_once PLUGIN_ROOT . '/exec/lib/Lang.php';
require_once PLUGIN_ROOT . '/exec/lib/DirectAdminUser.php';
require_once PLUGIN_ROOT . '/exec/lib/RuleRepository.php';
require_once PLUGIN_ROOT . '/exec/lib/AuditLog.php';
require_once PLUGIN_ROOT . '/exec/lib/AppContext.php';
test('csrf token is bound to user session action and time', function (): void { test('csrf token is bound to user session action and time', function (): void {
$guard = new CsrfGuard('secret', 'alice', 'session-1'); $guard = new CsrfGuard('secret', 'alice', 'session-1');
@@ -13,3 +20,49 @@ test('csrf token is bound to user session action and time', function (): void {
assert_false($guard->validate('create', (string)($issued['ts'] - 7200), $issued['token'], 3600, 'session-1')); assert_false($guard->validate('create', (string)($issued['ts'] - 7200), $issued['token'], 3600, 'session-1'));
assert_false($guard->validate('create', 'bad', $issued['token'], 3600, 'session-1')); assert_false($guard->validate('create', 'bad', $issued['token'], 3600, 'session-1'));
}); });
test('csrf form fields use plugin scoped names to avoid directadmin token collisions', function (): void {
$settings = Settings::load(TEST_TMP . '/missing-csrf-form.conf');
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = $ctx->csrfField('create');
assert_contains('name="gar_csrf_ts"', $html);
assert_contains('name="gar_csrf_sid"', $html);
assert_contains('name="gar_csrf_token"', $html);
assert_false(str_contains($html, 'name="csrf_token"'));
});
test('http bootstrap populates post data from directadmin cli environment', function (): void {
$oldGet = $_GET;
$oldPost = $_POST;
$oldRequest = $_REQUEST;
$oldServer = $_SERVER;
putenv('REQUEST_METHOD=POST');
putenv('QUERY_STRING=id=abc');
putenv('POST=gar_csrf_ts=123&gar_csrf_sid=sid&gar_csrf_token=token&body=Hello+World');
try {
Http::bootstrapGlobals();
assert_same('POST', Http::method());
assert_same('abc', Http::getString($_GET, 'id'));
assert_same('123', Http::getString($_POST, 'gar_csrf_ts'));
assert_same('token', Http::getString($_POST, 'gar_csrf_token'));
assert_same('Hello World', Http::getString($_POST, 'body'));
} finally {
putenv('REQUEST_METHOD');
putenv('QUERY_STRING');
putenv('POST');
$_GET = $oldGet;
$_POST = $oldPost;
$_REQUEST = $oldRequest;
$_SERVER = $oldServer;
}
});
+68 -8
View File
@@ -3,24 +3,84 @@ declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/DirectAdminVacationApi.php'; require_once PLUGIN_ROOT . '/exec/lib/DirectAdminVacationApi.php';
test('directadmin vacation api default binary follows documented directadmin path', function (): void {
$api = new DirectAdminVacationApi();
assert_same('/usr/local/directadmin/directadmin', $api->directAdminBinary());
});
test('directadmin vacation api builds scoped payload for one mailbox', function (): void { test('directadmin vacation api builds scoped payload for one mailbox', function (): void {
$api = new DirectAdminVacationApi('/usr/local/directadmin/directadmin'); $api = new DirectAdminVacationApi('/usr/local/directadmin/directadmin');
$payload = $api->buildSavePayload('info@example.com', [ $payload = $api->buildSavePayload('info@example.com', [
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_every_message' => false, 'repeat_minutes' => 1,
'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => '2026-06-10T00:00',
'end_value' => '2026-06-24|evening', 'end_value' => '2026-06-24T23:59',
]); ]);
assert_same('info', $payload['user']); assert_same('info', $payload['user']);
assert_same('example.com', $payload['domain']); assert_same('example.com', $payload['domain']);
assert_same('Body', $payload['text']); assert_same('Body', $payload['text']);
assert_same('Urlop', $payload['subject_prefix']); assert_same('Urlop', $payload['subject']);
assert_same('1440', $payload['reply_frequency']); assert_same('1m', $payload['reply_once_time']);
assert_same('morning', $payload['starttime']); assert_false(isset($payload['email']));
assert_same('evening', $payload['endtime']); assert_false(isset($payload['subject_prefix']));
assert_false(isset($payload['reply_frequency']));
assert_same('00:00', $payload['starttime']);
assert_same('23:59', $payload['endtime']);
});
test('directadmin vacation api reports http error response bodies', function (): void {
$runner = static function (array $args, string $stdin): string {
if ($args[0] === '/bin/echo') {
return 'https://directadmin.invalid/CMD_LOGIN_KEY';
}
assert_same('curl', $args[0]);
return "error=1&text=Unable to set vacation&details=Invalid repeat value\n500";
};
$api = new DirectAdminVacationApi('/bin/echo', null, $runner);
try {
$api->saveVacation('alice', 'info@example.com', [
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'start_value' => '2026-06-10|morning',
'end_value' => '2026-06-24|evening',
], false);
} catch (RuntimeException $e) {
assert_contains('DirectAdmin API HTTP 500', $e->getMessage());
assert_contains('Invalid repeat value', $e->getMessage());
return;
}
throw new RuntimeException('Expected HTTP error to fail');
});
test('directadmin vacation api reports legacy api error payloads', function (): void {
$runner = static function (array $args, string $stdin): string {
if ($args[0] === '/bin/echo') {
return 'https://directadmin.invalid/CMD_LOGIN_KEY';
}
return "error=1&text=Unable%20to%20set%20vacation&details=Bad%20mailbox\n200";
};
$api = new DirectAdminVacationApi('/bin/echo', null, $runner);
try {
$api->saveVacation('alice', 'info@example.com', [
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'start_value' => '2026-06-10|morning',
'end_value' => '2026-06-24|evening',
], false);
} catch (RuntimeException $e) {
assert_contains('DirectAdmin API error', $e->getMessage());
assert_contains('Bad mailbox', $e->getMessage());
return;
}
throw new RuntimeException('Expected legacy API error to fail');
}); });
test('directadmin vacation api detects existing native vacation by mailbox', function (): void { test('directadmin vacation api detects existing native vacation by mailbox', function (): void {
@@ -16,7 +16,6 @@ test('directadmin vacation sync creates tracked entries for enabled rule mailbox
$repo = new RuleRepository(TEST_TMP . '/da-sync-data'); $repo = new RuleRepository(TEST_TMP . '/da-sync-data');
$rule = $repo->create('alice', [ $rule = $repo->create('alice', [
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_every_message' => false,
'repeat_minutes' => 1440, 'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => '2026-06-10|morning',
@@ -71,7 +70,6 @@ test('directadmin vacation sync deletes stale tracked entries after rule removal
$syncRepo = new DirectAdminSyncRepository($dataDir); $syncRepo = new DirectAdminSyncRepository($dataDir);
$rule = $repo->create('alice', [ $rule = $repo->create('alice', [
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_every_message' => false,
'repeat_minutes' => 1440, 'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => '2026-06-10|morning',
@@ -112,7 +110,6 @@ test('directadmin vacation sync refuses to overwrite untracked native vacation',
$repo = new RuleRepository($dataDir); $repo = new RuleRepository($dataDir);
$repo->create('alice', [ $repo->create('alice', [
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_every_message' => false,
'repeat_minutes' => 1440, 'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => '2026-06-10|morning',
@@ -153,3 +150,98 @@ test('directadmin vacation sync refuses to overwrite untracked native vacation',
assert_true($thrown); assert_true($thrown);
assert_same([], $calls); assert_same([], $calls);
}); });
test('directadmin vacation sync preflights all target mailboxes before saving', function (): void {
$virtualRoot = TEST_TMP . '/da-sync-preflight-virtual';
test_write($virtualRoot . '/domainowners', "example.com: alice\n");
test_write($virtualRoot . '/example.com/passwd', "info:x:1000:12::/home/alice/imap/example.com/info:/bin/false\nsales:x:1000:12::/home/alice/imap/example.com/sales:/bin/false\n");
$dataDir = TEST_TMP . '/da-sync-preflight-data';
$repo = new RuleRepository($dataDir);
$repo->create('alice', [
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'start_value' => '2026-06-10|morning',
'end_value' => '2026-06-24|evening',
'start_ts' => 1,
'end_ts' => 2,
'enabled' => true,
'dynamic_scope' => true,
]);
$calls = [];
$api = new class($calls) extends DirectAdminVacationApi {
public function __construct(private array &$calls) {}
public function vacationExists(string $owner, string $email): bool
{
return $email === 'sales@example.com';
}
public function saveVacation(string $owner, string $email, array $rule, bool $exists): void
{
$this->calls[] = ['save', $owner, $email];
}
};
$sync = new DirectAdminVacationSyncService(
$repo,
new DirectAdminSyncRepository($dataDir),
new MailboxDirectory($virtualRoot),
$api
);
$thrown = false;
try {
$sync->syncUser('alice');
} catch (RuntimeException $e) {
$thrown = true;
assert_contains('sales@example.com', $e->getMessage());
}
assert_true($thrown);
assert_same([], $calls, 'No vacation should be saved before all conflicts are known');
});
test('directadmin vacation sync lists and disables untracked native vacations for user domains', function (): void {
$virtualRoot = TEST_TMP . '/da-native-list-virtual';
test_write($virtualRoot . '/domainowners', "example.com: alice\nother.com: bob\n");
test_write($virtualRoot . '/example.com/passwd', "info:x:1000:12::/home/alice/imap/example.com/info:/bin/false\n");
$dataDir = TEST_TMP . '/da-native-list-data';
$repo = new RuleRepository($dataDir);
$syncRepo = new DirectAdminSyncRepository($dataDir);
$rule = $repo->create('alice', [
'subject_prefix' => 'Urlop',
'body' => 'Body',
'start_ts' => 1,
'end_ts' => 2,
'enabled' => true,
]);
$syncRepo->replaceRuleEntries('alice', (string)$rule['id'], [
['email' => 'tracked@example.com', 'domain' => 'example.com', 'mailbox' => 'tracked', 'api_key' => 'tracked@example.com'],
]);
$calls = [];
$api = new class($calls) extends DirectAdminVacationApi {
public function __construct(private array &$calls) {}
public function listVacations(string $owner, string $domain): array
{
return $domain === 'example.com' ? ['manual', 'tracked'] : ['foreign'];
}
public function deleteVacation(string $owner, string $email): void
{
$this->calls[] = ['delete', $owner, $email];
}
};
$sync = new DirectAdminVacationSyncService($repo, $syncRepo, new MailboxDirectory($virtualRoot), $api);
$native = $sync->untrackedNativeVacations('alice');
assert_same([[
'domain' => 'example.com',
'mailbox' => 'manual',
'email' => 'manual@example.com',
]], $native);
$sync->deleteNativeVacations('alice', $native);
assert_same([['delete', 'alice', 'manual@example.com']], $calls);
});
-151
View File
@@ -1,151 +0,0 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/scripts/global_autoresponder_worker.php';
test('exim worker sends active rule for resolved mailbox only', function (): void {
$settingsPath = TEST_TMP . '/worker-settings.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_BACKEND=exim\n");
$settings = Settings::load($settingsPath);
$virtualRoot = TEST_TMP . '/worker-virtual';
test_write($virtualRoot . '/domainowners', "example.com: alice\n");
test_write($virtualRoot . '/example.com/passwd', "info:x:1000:12::/home/alice/imap/example.com/info:/bin/false\n");
$repo = new RuleRepository(TEST_TMP . '/worker-data');
$created = $repo->create('alice', [
'subject' => 'Urlop',
'subject_prefix' => 'Urlop',
'reply_every_message' => false,
'repeat_minutes' => 60,
'body' => 'Odpowiem później',
'start_ts' => 900,
'end_ts' => 1100,
'enabled' => true,
]);
$sent = [];
$worker = new GlobalAutoresponderWorker(
$settings,
$repo,
new MailboxDirectory($virtualRoot),
new RepeatState(TEST_TMP . '/worker-state', 1000),
static function (string $from, string $to, string $subject, string $body) use (&$sent): bool {
$sent[] = compact('from', 'to', 'subject', 'body');
return true;
},
1000
);
$count = $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'LOCAL_PART' => 'info', 'DOMAIN' => 'example.com'],
"Auto-Submitted: no\nSubject: hello\n\nBody"
);
assert_same(1, $count);
assert_same('info@example.com', $sent[0]['from']);
assert_same('person@example.net', $sent[0]['to']);
assert_same('Urlop: hello', $sent[0]['subject']);
assert_same('Odpowiem później', $sent[0]['body']);
$count = $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'RECIPIENT' => 'info@example.com'],
"Auto-Submitted: no\nSubject: hello\n\nBody"
);
assert_same(0, $count, 'repeat policy should block immediate second response');
assert_true(isset($created['id']));
});
test('exim worker suppresses automated messages and ignores unresolved recipients', function (): void {
$settingsPath = TEST_TMP . '/worker-suppress-settings.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_BACKEND=exim\n");
$settings = Settings::load($settingsPath);
$virtualRoot = TEST_TMP . '/worker-suppress-virtual';
test_write($virtualRoot . '/domainowners', "example.com: alice\n");
test_write($virtualRoot . '/example.com/passwd', "info:x:1000:12::/home/alice/imap/example.com/info:/bin/false\n");
test_write($virtualRoot . '/example.com/aliases', "alias: info\n");
$repo = new RuleRepository(TEST_TMP . '/worker-suppress-data');
$repo->create('alice', [
'subject_prefix' => 'Urlop',
'reply_every_message' => true,
'repeat_minutes' => 0,
'body' => 'Body',
'start_ts' => 1,
'end_ts' => 2000,
'enabled' => true,
]);
$sent = 0;
$worker = new GlobalAutoresponderWorker(
$settings,
$repo,
new MailboxDirectory($virtualRoot),
new RepeatState(TEST_TMP . '/worker-suppress-state', 1000),
static function () use (&$sent): bool {
$sent++;
return true;
},
1000
);
assert_same(0, $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'RECIPIENT' => 'info@example.com'],
"Precedence: bulk\n\nBody"
));
assert_same(0, $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'RECIPIENT' => 'alias@example.com'],
"Auto-Submitted: no\n\nBody"
));
assert_same(0, $sent);
});
test('exim worker respects static mailbox snapshot scope', function (): void {
$settingsPath = TEST_TMP . '/worker-snapshot-settings.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_BACKEND=exim\n");
$settings = Settings::load($settingsPath);
$virtualRoot = TEST_TMP . '/worker-snapshot-virtual';
test_write($virtualRoot . '/domainowners', "example.com: alice\n");
test_write($virtualRoot . '/example.com/passwd', "info:x:1000:12::/home/alice/imap/example.com/info:/bin/false\nsales:x:1000:12::/home/alice/imap/example.com/sales:/bin/false\n");
$repo = new RuleRepository(TEST_TMP . '/worker-snapshot-data');
$repo->create('alice', [
'subject_prefix' => 'Urlop',
'reply_every_message' => true,
'repeat_minutes' => 0,
'body' => 'Body',
'start_ts' => 1,
'end_ts' => 2000,
'enabled' => true,
'dynamic_scope' => false,
'mailbox_snapshot' => [
['domain' => 'example.com', 'mailbox' => 'info', 'email' => 'info@example.com'],
],
]);
$sent = 0;
$worker = new GlobalAutoresponderWorker(
$settings,
$repo,
new MailboxDirectory($virtualRoot),
new RepeatState(TEST_TMP . '/worker-snapshot-state', 1000),
static function () use (&$sent): bool {
$sent++;
return true;
},
1000
);
assert_same(0, $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'RECIPIENT' => 'sales@example.com'],
"Auto-Submitted: no\n\nBody"
));
assert_same(1, $worker->handle(
['SENDER_ADDRESS' => 'person@example.net', 'RECIPIENT' => 'info@example.com'],
"Auto-Submitted: no\n\nBody"
));
assert_same(1, $sent);
});
+374 -23
View File
@@ -1,12 +1,12 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
test('mockup and planned UI do not expose backend terms', function (): void { test('mockup and planned UI do not expose removed internal mail terms', function (): void {
foreach (glob(dirname(__DIR__, 2) . '/docs/mockups/*.html') ?: [] as $file) { foreach (glob(dirname(__DIR__, 2) . '/docs/mockups/*.html') ?: [] as $file) {
$html = file_get_contents($file) ?: ''; $html = file_get_contents($file) ?: '';
assert_false(stripos($html, 'Exim') !== false, basename($file) . ' exposes Exim'); assert_false(stripos($html, 'Ex' . 'im') !== false, basename($file) . ' exposes removed mail integration');
assert_false(stripos($html, 'DirectAdmin API') !== false, basename($file) . ' exposes API'); assert_false(stripos($html, 'DirectAdmin API') !== false, basename($file) . ' exposes API');
assert_false(stripos($html, 'backend.sh') !== false, basename($file) . ' exposes backend script'); assert_false(stripos($html, 'back' . 'end.sh') !== false, basename($file) . ' exposes removed switch script');
} }
}); });
@@ -29,7 +29,24 @@ test('directadmin user hooks are clickable and point to reserved icon path', fun
assert_contains('Globalne autorespondery', $txt); assert_contains('Globalne autorespondery', $txt);
}); });
test('rule form uses minute time input and no summary box in exim mode', function (): void { test('top navigation uses global autoresponder labels', function (): void {
$pl = require PLUGIN_ROOT . '/lang/pl.php';
$en = require PLUGIN_ROOT . '/lang/en.php';
assert_same('Lista globalnych autoresponderów', $pl['AUTORESPONDERS'] ?? '');
assert_same('Dodaj Globalny autoresponder', $pl['ADD AUTORESPONDER'] ?? '');
assert_same('Global autoresponder list', $en['AUTORESPONDERS'] ?? '');
assert_same('Add global autoresponder', $en['ADD AUTORESPONDER'] ?? '');
});
test('autoresponder index keeps add button only in top navigation', function (): void {
$source = file_get_contents(PLUGIN_ROOT . '/exec/handlers/index.php') ?: '';
assert_false(strpos($source, "ctx->url('create.html')") !== false);
assert_false(strpos($source, "ctx->t('Add autoresponder')") !== false);
});
test('rule form uses minute time input and directadmin frequency range', function (): void {
require_once PLUGIN_ROOT . '/exec/lib/Settings.php'; require_once PLUGIN_ROOT . '/exec/lib/Settings.php';
require_once PLUGIN_ROOT . '/exec/lib/Lang.php'; require_once PLUGIN_ROOT . '/exec/lib/Lang.php';
require_once PLUGIN_ROOT . '/exec/lib/DirectAdminUser.php'; require_once PLUGIN_ROOT . '/exec/lib/DirectAdminUser.php';
@@ -40,7 +57,7 @@ test('rule form uses minute time input and no summary box in exim mode', functio
require_once PLUGIN_ROOT . '/exec/handlers/_form_helpers.php'; require_once PLUGIN_ROOT . '/exec/handlers/_form_helpers.php';
$settingsPath = TEST_TMP . '/form.conf'; $settingsPath = TEST_TMP . '/form.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_BACKEND=exim\n"); test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
$ctx = new AppContext( $ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'), new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
@@ -52,20 +69,230 @@ test('rule form uses minute time input and no summary box in exim mode', functio
); );
$html = render_rule_form($ctx, 'create', null); $html = render_rule_form($ctx, 'create', null);
assert_contains('name="name"', $html);
assert_contains('Nazwa autorespondera', $html);
assert_contains('Ta nazwa jest wykorzystywana tylko w celach opisowych', $html);
assert_contains('type="time"', $html); assert_contains('type="time"', $html);
assert_contains('step="60"', $html); assert_contains('step="60"', $html);
assert_false(strpos($html, 'summary-card') !== false, 'Summary box should not be rendered in create/edit form'); assert_false(strpos($html, 'summary-card') !== false, 'Summary box should not be rendered in create/edit form');
assert_contains('Przedrostek tematu', $html); assert_contains('Przedrostek tematu', $html);
assert_contains(': pierwotny temat', $html); assert_contains(': pierwotny temat', $html);
assert_contains('Częstość odpowiedzi', $html); assert_contains('Częstość odpowiedzi', $html);
assert_contains('Wysyłaj automatyczną odpowiedź dla każdej wiadomości', $html); assert_false(strpos($html, 'Wysyłaj automatyczną odpowiedź dla każdej wiadomości') !== false);
assert_contains('14 dni', $html);
assert_contains('1 minuta', $html);
assert_contains('1 dzień', $html); assert_contains('1 dzień', $html);
assert_contains('Treść wiadomości', $html); assert_contains('Treść wiadomości', $html);
}); });
test('rule form uses native period selector in da mode', function (): void { test('autoresponder index shows descriptive name and created timestamp columns', function (): void {
$settingsPath = TEST_TMP . '/index-columns.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$repo = new RuleRepository(TEST_TMP . '/index-data');
$repo->create('alice', [
'name' => 'Urlop zarządu',
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => true,
'start_ts' => 1780495200,
'end_ts' => 1780581540,
]);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
$repo,
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = render_rules_index_body($ctx);
assert_contains('Nazwa autorespondera', $html);
assert_contains('Utworzono', $html);
assert_contains('Urlop zarządu', $html);
assert_false(strpos($html, 'Zaktualizowano') !== false);
});
test('dashboard omits account mailbox helper subtitles', function (): void {
$settingsPath = TEST_TMP . '/index-subtitles.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$repo = new RuleRepository(TEST_TMP . '/index-subtitles-data');
$repo->create('alice', [
'name' => 'Urlop zarządu',
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => true,
'start_ts' => 1780495200,
'end_ts' => 1780581540,
]);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
$repo,
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$index = render_rules_index_body($ctx);
$chrome = file_get_contents(PLUGIN_ROOT . '/exec/lib/AppContext.php') ?: '';
assert_false(strpos($index, 'Wszystkie prawidłowe skrzynki POP/IMAP konta') !== false);
assert_false(strpos($chrome, 'Manage automatic replies for account mailboxes') !== false);
});
test('create conflict modal offers replacing active rule or adding disabled rule', function (): void {
$settingsPath = TEST_TMP . '/create-conflict.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$repo = new RuleRepository(TEST_TMP . '/create-conflict-data');
$existing = $repo->create('alice', [
'name' => 'Stary urlop',
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => true,
'start_ts' => 1780495200,
'end_ts' => 1780581540,
]);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
$repo,
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$modal = render_create_conflict_modal($ctx, [
'name' => 'Nowy urlop',
'subject_prefix' => 'Nowy',
'repeat_minutes' => 1440,
'body' => 'Nowa treść',
'enabled' => true,
'start_value' => '2026-06-10T00:00',
'end_value' => '2026-06-24T23:59',
], $existing);
assert_contains('Dla użytkownika alice istnieje już globalny autoresponder', $modal);
assert_contains('Stary urlop', $modal);
assert_contains('Nowy urlop', $modal);
assert_contains('name="conflict_action" value="replace"', $modal);
assert_contains('name="conflict_action" value="create_disabled"', $modal);
assert_contains('Włącz autoresponder (Nowy urlop) i wyłącz poprzedni (Stary urlop)', $modal);
assert_contains('Dodaj autoresponder (Nowy urlop) jako wyłączony', $modal);
});
test('native directadmin autoresponder modal lists entries before creating global rule', function (): void {
$settingsPath = TEST_TMP . '/native-conflict.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/native-conflict-data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$modal = render_native_vacation_conflict_modal($ctx, [
'name' => 'Nowy urlop',
'subject_prefix' => 'Nowy',
'repeat_minutes' => 1440,
'body' => 'Nowa treść',
'enabled' => true,
'start_value' => '2026-06-10T00:00',
'end_value' => '2026-06-24T23:59',
], [
['domain' => 'example.com', 'mailbox' => 'info', 'email' => 'info@example.com'],
['domain' => 'example.com', 'mailbox' => 'sales', 'email' => 'sales@example.com'],
]);
assert_contains('użytkownik alice ma już utworzone natywne autorespondery', $modal);
assert_contains('info@example.com', $modal);
assert_contains('sales@example.com', $modal);
assert_contains('name="native_conflict_action" value="disable_native"', $modal);
assert_contains('<strong>Istniejące autorespondery / wiadomości urlopowe zostaną usunięte w przypadku kontynuacji.</strong>', $modal);
assert_contains('class="danger-fill" type="submit">USUŃ ISTNIEJĄCE AUTORESPONDERY</button>', $modal);
assert_contains('Anuluj', $modal);
});
test('delete confirmation only asks yes no with rule name and created date', function (): void {
$settingsPath = TEST_TMP . '/delete-confirm.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/delete-confirm-data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$rule = [
'id' => 'rule-delete',
'name' => 'Urlop testowy',
'subject_prefix' => 'Urlop',
'created_at' => 1780495200,
];
$html = render_delete_confirmation_body($ctx, $rule);
assert_contains('Czy napewno chcesz usunąć globalny autoresponder Urlop testowy utworzony 2026-06-03 16:00?', $html);
assert_contains('>Tak</button>', $html);
assert_contains('>Nie</a>', $html);
assert_false(strpos($html, 'Preview autoresponder') !== false);
assert_false(strpos($html, 'Deleting this rule will disable') !== false);
assert_false(strpos($html, 'Treść odpowiedzi') !== false);
});
test('toggle conflict modal asks before replacing currently active rule', function (): void {
$settingsPath = TEST_TMP . '/toggle-conflict.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$repo = new RuleRepository(TEST_TMP . '/toggle-conflict-data');
$existing = $repo->create('alice', [
'name' => 'Aktywny urlop',
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => true,
'start_ts' => 1780495200,
'end_ts' => 1780581540,
]);
$target = $repo->create('alice', [
'name' => 'Nowy aktywny',
'subject_prefix' => 'Nowy',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => false,
'start_ts' => 1780495200,
'end_ts' => 1780581540,
]);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
$repo,
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$modal = render_toggle_conflict_modal($ctx, $target, $existing);
assert_contains('może być aktywny tylko jeden globalny autoresponder', $modal);
assert_contains('Włącz autoresponder', $modal);
assert_contains('name="conflict_action" value="replace"', $modal);
assert_contains('name="id" value="' . $target['id'] . '"', $modal);
});
test('rule form uses exact hour selector and directadmin frequency range', function (): void {
$settingsPath = TEST_TMP . '/form-da.conf'; $settingsPath = TEST_TMP . '/form-da.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_BACKEND=da\n"); test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
$ctx = new AppContext( $ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'), new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
@@ -76,21 +303,77 @@ test('rule form uses native period selector in da mode', function (): void {
new AuditLog(TEST_TMP . '/audit.log') new AuditLog(TEST_TMP . '/audit.log')
); );
$html = render_rule_form($ctx, 'create', null); $html = render_rule_form($ctx, 'create', null);
assert_contains('name="start_value_period"', $html); assert_contains('type="time"', $html);
assert_contains('Rano', $html); assert_contains('step="60"', $html);
assert_false(strpos($html, 'type="time"') !== false); assert_contains('1 minuta', $html);
assert_contains('14 dni', $html);
assert_false(strpos($html, 'Wysyłaj automatyczną odpowiedź dla każdej wiadomości') !== false);
assert_false(strpos($html, 'name="start_value_period"') !== false);
}); });
test('mutating handlers synchronize active backend after storage changes', function (): void { test('rule form groups start and end calendars in one schedule panel', function (): void {
$settingsPath = TEST_TMP . '/form-schedule-layout.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = render_rule_form($ctx, 'create', null);
assert_same(1, substr_count($html, 'schedule-panel'));
assert_contains('schedule-grid', $html);
assert_contains('schedule-column schedule-start', $html);
assert_contains('schedule-column schedule-end', $html);
assert_contains('Data rozpoczęcia', $html);
assert_contains('Godzina rozpoczęcia', $html);
assert_contains('Data zakończenia', $html);
assert_contains('Godzina zakończenia', $html);
});
test('skins define different schedule calendar layouts', function (): void {
$enhanced = file_get_contents(PLUGIN_ROOT . '/user/enhanced.css') ?: '';
$evolution = file_get_contents(PLUGIN_ROOT . '/user/evolution.css') ?: '';
$appContext = file_get_contents(PLUGIN_ROOT . '/exec/lib/AppContext.php') ?: '';
assert_contains('.schedule-grid { grid-template-columns: 1fr;', $enhanced);
assert_contains('.schedule-grid { grid-template-columns: repeat(2, minmax(460px, 1fr));', $evolution);
assert_contains('.schedule-scroll { overflow-x: auto;', $evolution);
assert_contains('width: 100% !important;', $evolution);
assert_contains('margin-left: 0 !important;', $evolution);
assert_contains('max-width: none !important;', $evolution);
assert_false(str_contains($evolution, '#content'), 'Evolution CSS must not override DirectAdmin shell containers globally');
assert_false((bool)preg_match('/^\\.container,$/m', $evolution), 'Evolution CSS must not override every DirectAdmin container globally');
assert_false(str_contains($evolution, '.content-wrapper'), 'Evolution CSS must not override shell wrappers globally');
assert_false(str_contains($evolution, '@import'));
assert_contains("skin === 'evolution'", $appContext);
assert_contains("enhanced.css", $appContext);
assert_contains("evolution.css", $appContext);
assert_contains('expandDirectAdminPluginContainers', $appContext);
assert_contains("pluginSkin !== 'evolution'", $appContext);
assert_contains("wrap.parentElement", $appContext);
});
test('autoresponder table does not expose mailbox scope column', function (): void {
$source = file_get_contents(PLUGIN_ROOT . '/exec/handlers/index.php') ?: '';
assert_false(strpos($source, "ctx->t('Scope')") !== false);
assert_false(strpos($source, "ctx->t(\$rule['dynamic_scope']") !== false);
});
test('mutating handlers synchronize directadmin vacations after storage changes', function (): void {
foreach (['create.php', 'update.php', 'delete.php', 'toggle.php'] as $handler) { foreach (['create.php', 'update.php', 'delete.php', 'toggle.php'] as $handler) {
$source = file_get_contents(PLUGIN_ROOT . '/exec/handlers/' . $handler) ?: ''; $source = file_get_contents(PLUGIN_ROOT . '/exec/handlers/' . $handler) ?: '';
assert_contains('syncActiveBackend', $source, $handler . ' must synchronize backend after mutation'); assert_contains('syncDirectAdminVacations', $source, $handler . ' must synchronize native vacations after mutation');
} }
}); });
test('calendar picker is based on selected rule month and supports month navigation', function (): void { test('calendar picker is based on selected rule month and supports month navigation', function (): void {
$settingsPath = TEST_TMP . '/form-calendar.conf'; $settingsPath = TEST_TMP . '/form-calendar.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_BACKEND=exim\n"); test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
$ctx = new AppContext( $ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'), new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
@@ -104,7 +387,6 @@ test('calendar picker is based on selected rule month and supports month navigat
$html = render_rule_form($ctx, 'update', [ $html = render_rule_form($ctx, 'update', [
'id' => 'abc', 'id' => 'abc',
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_every_message' => false,
'repeat_minutes' => 1440, 'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'enabled' => true, 'enabled' => true,
@@ -119,9 +401,79 @@ test('calendar picker is based on selected rule month and supports month navigat
assert_false(strpos($html, 'Czerwiec 2026') !== false); assert_false(strpos($html, 'Czerwiec 2026') !== false);
}); });
test('calendar picker disables dates before today', function (): void {
$settingsPath = TEST_TMP . '/form-calendar-min.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = render_calendar_picker($ctx, 'start_value', $ctx->t('Start date'), '2000-01-15T09:00');
assert_contains('br-cal-day-disabled', $html);
assert_false(str_contains($html, 'data-date-value="2000-01-15"'), 'Past dates must not be clickable');
});
test('update form calendar allows existing past schedule dates', function (): void {
$settingsPath = TEST_TMP . '/form-calendar-update-past.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$html = render_rule_form($ctx, 'update', [
'id' => 'abc',
'name' => 'Historyczny urlop',
'subject_prefix' => 'Urlop',
'repeat_minutes' => 1440,
'body' => 'Body',
'enabled' => true,
'start_value' => '2000-01-10T09:00',
'end_value' => '2000-01-11T17:00',
]);
assert_contains('data-min-date=""', $html);
assert_contains('data-date-value="2000-01-10"', $html);
assert_contains('data-date-value="2000-01-11"', $html);
assert_false(str_contains($html, 'br-cal-day-disabled'), 'Update form must not disable past dates');
});
test('new rule form selects current date for start and end calendars by default', function (): void {
$settingsPath = TEST_TMP . '/form-calendar-defaults.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
$settings,
new RuleRepository(TEST_TMP . '/data'),
new CsrfGuard('secret', 'alice', 'sid'),
Lang::load('pl', $settings),
new AuditLog(TEST_TMP . '/audit.log')
);
$today = (new DateTimeImmutable('today', new DateTimeZone($settings->timezone())))->format('Y-m-d');
$html = render_rule_form($ctx, 'create', null);
assert_contains('id="start_value_date" name="start_value_date" value="' . $today . '"', $html);
assert_contains('id="end_value_date" name="end_value_date" value="' . $today . '"', $html);
assert_contains('id="start_value" name="start_value" value="' . $today . 'T00:00"', $html);
assert_contains('id="end_value" name="end_value" value="' . $today . 'T23:59"', $html);
});
test('rule form localizes calendar and preview labels without translating user content globally', function (): void { test('rule form localizes calendar and preview labels without translating user content globally', function (): void {
$settingsPath = TEST_TMP . '/form-i18n.conf'; $settingsPath = TEST_TMP . '/form-i18n.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=en\nGLOBAL_AUTORESPONDER_BACKEND=exim\n"); test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=en\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
$ctx = new AppContext( $ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'en', TEST_TMP . '/config'), new DirectAdminUser('alice', 'enhanced', 'en', TEST_TMP . '/config'),
@@ -143,19 +495,18 @@ test('rule form localizes calendar and preview labels without translating user c
assert_contains('Cancel', $preview); assert_contains('Cancel', $preview);
}); });
test('directadmin backend allows only one enabled global rule per account', function (): void { test('plugin allows only one enabled global rule per account', function (): void {
$settingsPath = TEST_TMP . '/form-da-single.conf'; $settingsPath = TEST_TMP . '/form-da-single.conf';
test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\nGLOBAL_AUTORESPONDER_BACKEND=da\n"); test_write($settingsPath, "DEFAULT_PLUGIN_LANGUAGE=pl\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
$repo = new RuleRepository(TEST_TMP . '/single-data'); $repo = new RuleRepository(TEST_TMP . '/single-data');
$repo->create('alice', [ $repo->create('alice', [
'subject_prefix' => 'Pierwsza', 'subject_prefix' => 'Pierwsza',
'reply_every_message' => false,
'repeat_minutes' => 1440, 'repeat_minutes' => 1440,
'body' => 'Body', 'body' => 'Body',
'enabled' => true, 'enabled' => true,
'start_value' => '2026-06-10|morning', 'start_value' => '2026-06-10T00:00',
'end_value' => '2026-06-24|evening', 'end_value' => '2026-06-24T23:59',
]); ]);
$ctx = new AppContext( $ctx = new AppContext(
new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'), new DirectAdminUser('alice', 'enhanced', 'pl', TEST_TMP . '/config'),
@@ -168,10 +519,10 @@ test('directadmin backend allows only one enabled global rule per account', func
$thrown = false; $thrown = false;
try { try {
enforce_rule_backend_constraints($ctx, null, ['enabled' => true]); enforce_rule_directadmin_constraints($ctx, null, ['enabled' => true]);
} catch (RuntimeException $e) { } catch (RuntimeException $e) {
$thrown = true; $thrown = true;
assert_contains('Backend DirectAdmin obsługuje tylko jedną aktywną regułę globalną.', $e->getMessage()); assert_contains('W ramach użytkownika może być aktywny tylko jeden globalny autoresponder.', $e->getMessage());
} }
assert_true($thrown); assert_true($thrown);
}); });
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/Http.php';
test('http redirect fallback renders visible html document for cli plugin runtime', function (): void {
$html = Http::redirectDocument('/CMD_PLUGINS/global-autoresponder/index.html?status=created');
assert_contains('<meta http-equiv="refresh"', $html);
assert_contains('window.location.replace', $html);
assert_contains('/CMD_PLUGINS/global-autoresponder/index.html?status=created', $html);
assert_contains('Przekierowanie', $html);
});
-17
View File
@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/MailSender.php';
test('mail sender rejects subject header injection and builds utf8 message', function (): void {
try {
MailSender::buildMessage('from@example.com', 'to@example.com', "Bad\nSubject", 'Body');
} catch (InvalidArgumentException $e) {
assert_contains('subject', strtolower($e->getMessage()));
}
$message = MailSender::buildMessage('from@example.com', 'to@example.com', 'Temat', "Treść\nDruga linia");
assert_contains('Auto-Submitted: auto-replied', $message);
assert_contains('Content-Type: text/plain; charset=UTF-8', $message);
assert_contains("Subject: =?UTF-8?B?", $message);
});
-13
View File
@@ -1,13 +0,0 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/MessageClassifier.php';
test('message classifier suppresses automated and list messages', function (): void {
assert_true(MessageClassifier::shouldSuppress(['auto-submitted' => 'auto-replied'], 'sender@example.com'));
assert_true(MessageClassifier::shouldSuppress(['precedence' => 'bulk'], 'sender@example.com'));
assert_true(MessageClassifier::shouldSuppress(['list-id' => '<list.example.com>'], 'sender@example.com'));
assert_true(MessageClassifier::shouldSuppress([], ''));
assert_true(MessageClassifier::shouldSuppress([], 'MAILER-DAEMON@example.com'));
assert_false(MessageClassifier::shouldSuppress(['auto-submitted' => 'no'], 'person@example.com'));
});
+19 -11
View File
@@ -29,24 +29,30 @@ test('shipped plugin files do not contain placeholders', function (): void {
continue; continue;
} }
$content = file_get_contents($path) ?: ''; $content = file_get_contents($path) ?: '';
if (preg_match('/placeholder|TODO|FIXME|not implemented|pending_exim_validation|stub/i', $content)) { if (preg_match('/placeholder|TODO|FIXME|not implemented|stub/i', $content)) {
$bad[] = $relative; $bad[] = $relative;
} }
} }
assert_same([], $bad); assert_same([], $bad);
}); });
test('backend script protects custom exim config with rollback and exact section insertion checks', function (): void { test('package source does not ship removed custom mail integration files', function (): void {
$script = file_get_contents(PLUGIN_ROOT . '/scripts/backend.sh') ?: ''; $removedPaths = [
assert_contains('backup_custom_conf()', $script); 'scripts/' . 'back' . 'end.sh',
assert_contains('restore_custom_conf()', $script); 'scripts/' . 'ex' . 'im',
assert_contains("trap 'restore_custom_conf' EXIT", $script); 'scripts/global_auto' . 'responder_worker.php',
assert_contains('ROLLBACK_REBUILD=1', $script); 'exec/lib/Back' . 'endRuntimeConfig.php',
assert_contains('if ! awk -v section="$section" -v snippet="$snippet"', $script); 'exec/lib/Message' . 'Classifier.php',
assert_contains('if (inserted != 1)', $script); 'exec/lib/Mail' . 'Sender.php',
'exec/lib/Repeat' . 'State.php',
];
foreach ($removedPaths as $relative) {
$path = PLUGIN_ROOT . '/' . $relative;
assert_false(is_file($path) || is_dir($path), $relative . ' must not exist');
}
}); });
test('lifecycle scripts install cron sync and remove exim integration on uninstall', function (): void { test('lifecycle scripts install directadmin sync cron only', function (): void {
$install = file_get_contents(PLUGIN_ROOT . '/scripts/install.sh') ?: ''; $install = file_get_contents(PLUGIN_ROOT . '/scripts/install.sh') ?: '';
$update = file_get_contents(PLUGIN_ROOT . '/scripts/update.sh') ?: ''; $update = file_get_contents(PLUGIN_ROOT . '/scripts/update.sh') ?: '';
$uninstall = file_get_contents(PLUGIN_ROOT . '/scripts/uninstall.sh') ?: ''; $uninstall = file_get_contents(PLUGIN_ROOT . '/scripts/uninstall.sh') ?: '';
@@ -55,5 +61,7 @@ test('lifecycle scripts install cron sync and remove exim integration on uninsta
assert_contains('sync_directadmin_vacations.php', $install); assert_contains('sync_directadmin_vacations.php', $install);
assert_contains('/etc/cron.d/global-autoresponder', $update); assert_contains('/etc/cron.d/global-autoresponder', $update);
assert_contains('sync_directadmin_vacations.php', $update); assert_contains('sync_directadmin_vacations.php', $update);
assert_contains('backend.sh" da', $uninstall); assert_false(str_contains($install, 'back' . 'end-state.json'));
assert_false(str_contains($install, 'state/' . 'replies'));
assert_false(str_contains($uninstall, 'back' . 'end.sh'));
}); });
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/PluginLogger.php';
test('plugin logger writes exceptions to plugin log file', function (): void {
$path = TEST_TMP . '/plugin.log';
PluginLogger::init($path);
assert_true(is_file($path), 'Logger should create plugin.log during init');
assert_same('0600', substr(sprintf('%o', fileperms($path)), -4));
PluginLogger::exception(new RuntimeException('DirectAdmin API command failed'), 'CREATE');
$log = file_get_contents($path) ?: '';
assert_contains('CREATE RuntimeException: DirectAdmin API command failed', $log);
assert_contains('plugin_logger_test.php', $log);
assert_same('0600', substr(sprintf('%o', fileperms($path)), -4));
});
-14
View File
@@ -1,14 +0,0 @@
<?php
declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/RepeatState.php';
test('repeat state allows first reply and blocks repeated reply until ttl', function (): void {
$state = new RepeatState(TEST_TMP . '/state', 1000);
assert_true($state->shouldSend('alice', 'rule', 'info@example.com', 'sender@example.com', 60));
$state->record('alice', 'rule', 'info@example.com', 'sender@example.com');
assert_false($state->shouldSend('alice', 'rule', 'info@example.com', 'sender@example.com', 60));
$later = new RepeatState(TEST_TMP . '/state', 5000);
assert_true($later->shouldSend('alice', 'rule', 'info@example.com', 'sender@example.com', 60));
});
+114 -17
View File
@@ -4,43 +4,75 @@ declare(strict_types=1);
require_once PLUGIN_ROOT . '/exec/lib/Settings.php'; require_once PLUGIN_ROOT . '/exec/lib/Settings.php';
require_once PLUGIN_ROOT . '/exec/lib/RuleValidator.php'; require_once PLUGIN_ROOT . '/exec/lib/RuleValidator.php';
/** @return array{0:string,1:string} */
function future_exact_schedule(Settings $settings, string $startTime = '09:37', string $endTime = '17:12'): array
{
$tz = new DateTimeZone($settings->timezone());
[$startHour, $startMinute] = array_map('intval', explode(':', $startTime));
[$endHour, $endMinute] = array_map('intval', explode(':', $endTime));
$start = (new DateTimeImmutable('tomorrow', $tz))->setTime($startHour, $startMinute);
$end = (new DateTimeImmutable('+15 days', $tz))->setTime($endHour, $endMinute);
return [$start->format('Y-m-d\TH:i'), $end->format('Y-m-d\TH:i')];
}
test('rule validator normalizes exact hour schedule', function (): void { test('rule validator normalizes exact hour schedule', function (): void {
$settingsPath = TEST_TMP . '/validator.conf'; $settingsPath = TEST_TMP . '/validator.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\nGLOBAL_AUTORESPONDER_BACKEND=exim\n"); test_write($settingsPath, "GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath); $settings = Settings::load($settingsPath);
[$startValue, $endValue] = future_exact_schedule($settings);
$rule = RuleValidator::validate([ $rule = RuleValidator::validate([
'name' => 'Urlop czerwcowy',
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_frequency' => '120', 'reply_frequency' => '120',
'body' => "Dzień dobry\r\nWracam jutro", 'body' => "Dzień dobry\r\nWracam jutro",
'start_value' => '2026-06-10T09:37', 'start_value' => $startValue,
'end_value' => '2026-06-24T17:12', 'end_value' => $endValue,
'enabled' => '1', 'enabled' => '1',
], $settings); ], $settings);
assert_same('Urlop czerwcowy', $rule['name']);
assert_same('Urlop', $rule['subject_prefix']); assert_same('Urlop', $rule['subject_prefix']);
assert_false($rule['reply_every_message']);
assert_same(120, $rule['repeat_minutes']); assert_same(120, $rule['repeat_minutes']);
assert_same("Dzień dobry\nWracam jutro", $rule['body']); assert_same("Dzień dobry\nWracam jutro", $rule['body']);
assert_same('exact_hour', $rule['schedule_mode']); assert_same('exact_hour', $rule['schedule_mode']);
assert_same('2026-06-10T09:37', $rule['start_value']); assert_same($startValue, $rule['start_value']);
assert_true($rule['start_ts'] < $rule['end_ts']); assert_true($rule['start_ts'] < $rule['end_ts']);
}); });
test('rule validator accepts da period schedule when backend is da', function (): void { test('rule validator accepts exact hour schedule', function (): void {
$settingsPath = TEST_TMP . '/validator-da.conf'; $settings = Settings::load(TEST_TMP . '/validator-da.conf');
test_write($settingsPath, "GLOBAL_AUTORESPONDER_BACKEND=da\n"); [$startValue, $endValue] = future_exact_schedule($settings, '00:00', '23:59');
$settings = Settings::load($settingsPath);
$rule = RuleValidator::validate([ $rule = RuleValidator::validate([
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_frequency' => 'every', 'reply_frequency' => '1',
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => $startValue,
'end_value' => '2026-06-24|evening', 'end_value' => $endValue,
'enabled' => '1', 'enabled' => '1',
], $settings); ], $settings);
assert_same('directadmin_period', $rule['schedule_mode']); assert_same('exact_hour', $rule['schedule_mode']);
assert_true($rule['reply_every_message']); assert_same(1, $rule['repeat_minutes']);
assert_same(0, $rule['repeat_minutes']); assert_same($startValue, $rule['start_value']);
assert_same($endValue, $rule['end_value']);
});
test('rule validator rejects unsupported non-interval frequency', function (): void {
$settings = Settings::load(TEST_TMP . '/validator-da-every.conf');
[$startValue, $endValue] = future_exact_schedule($settings, '00:00', '23:59');
try {
RuleValidator::validate([
'subject_prefix' => 'Urlop',
'reply_frequency' => 'every',
'body' => 'Body',
'start_value' => $startValue,
'end_value' => $endValue,
], $settings);
} catch (InvalidArgumentException $e) {
assert_contains('Częstość odpowiedzi', $e->getMessage());
return;
}
throw new RuntimeException('Expected every-message frequency to fail');
}); });
test('rule validator rejects header injection and reversed dates', function (): void { test('rule validator rejects header injection and reversed dates', function (): void {
@@ -61,13 +93,14 @@ test('rule validator rejects header injection and reversed dates', function ():
test('rule validator rejects unsupported response frequency', function (): void { test('rule validator rejects unsupported response frequency', function (): void {
$settings = Settings::load(TEST_TMP . '/missing-frequency.conf'); $settings = Settings::load(TEST_TMP . '/missing-frequency.conf');
[$startValue, $endValue] = future_exact_schedule($settings, '00:00', '23:59');
try { try {
RuleValidator::validate([ RuleValidator::validate([
'subject_prefix' => 'Urlop', 'subject_prefix' => 'Urlop',
'reply_frequency' => '45', 'reply_frequency' => '45',
'body' => 'Body', 'body' => 'Body',
'start_value' => '2026-06-10|morning', 'start_value' => $startValue,
'end_value' => '2026-06-24|evening', 'end_value' => $endValue,
], $settings); ], $settings);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
assert_contains('Częstość odpowiedzi', $e->getMessage()); assert_contains('Częstość odpowiedzi', $e->getMessage());
@@ -75,3 +108,67 @@ test('rule validator rejects unsupported response frequency', function (): void
} }
throw new RuntimeException('Expected invalid frequency to fail'); throw new RuntimeException('Expected invalid frequency to fail');
}); });
test('rule validator rejects start date before current date', function (): void {
$settingsPath = TEST_TMP . '/validator-past.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$tz = new DateTimeZone($settings->timezone());
$yesterday = (new DateTimeImmutable('yesterday', $tz))->format('Y-m-d');
$tomorrow = (new DateTimeImmutable('tomorrow', $tz))->format('Y-m-d');
try {
RuleValidator::validate([
'subject_prefix' => 'Urlop',
'reply_frequency' => '1440',
'body' => 'Body',
'start_value' => $yesterday . 'T09:00',
'end_value' => $tomorrow . 'T17:00',
], $settings);
} catch (InvalidArgumentException $e) {
assert_contains('wcześniejsza niż aktualna', $e->getMessage());
return;
}
throw new RuntimeException('Expected past start date to fail');
});
test('rule validator rejects end date before current date when creating', function (): void {
$settingsPath = TEST_TMP . '/validator-past-end.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$tz = new DateTimeZone($settings->timezone());
$yesterday = (new DateTimeImmutable('yesterday', $tz))->format('Y-m-d');
$today = (new DateTimeImmutable('today', $tz))->format('Y-m-d');
try {
RuleValidator::validate([
'subject_prefix' => 'Urlop',
'reply_frequency' => '1440',
'body' => 'Body',
'start_value' => $today . 'T09:00',
'end_value' => $yesterday . 'T17:00',
], $settings);
} catch (InvalidArgumentException $e) {
assert_contains('Data zakończenia nie może być wcześniejsza niż aktualna data.', $e->getMessage());
return;
}
throw new RuntimeException('Expected past end date to fail on create');
});
test('rule validator allows past schedule when editing', function (): void {
$settingsPath = TEST_TMP . '/validator-edit-past.conf';
test_write($settingsPath, "GLOBAL_AUTORESPONDER_TIMEZONE=Europe/Warsaw\n");
$settings = Settings::load($settingsPath);
$rule = RuleValidator::validate([
'subject_prefix' => 'Urlop',
'reply_frequency' => '1440',
'body' => 'Body',
'start_value' => '2000-01-10T09:00',
'end_value' => '2000-01-11T17:00',
], $settings, true);
assert_same('2000-01-10T09:00', $rule['start_value']);
assert_same('2000-01-11T17:00', $rule['end_value']);
assert_true($rule['start_ts'] < $rule['end_ts']);
});
+16 -3
View File
@@ -35,6 +35,7 @@ header p { margin: 0; color: var(--amber-strong); font-size: 15px; }
label { display: block; margin-bottom: 6px; font-weight: 600; font-size: 15px; } label { display: block; margin-bottom: 6px; font-weight: 600; font-size: 15px; }
input[type="text"], input[type="time"], select, textarea { width: 100%; border: 1px solid #cdd4e0; border-radius: 6px; padding: 10px 12px; font-size: 15px; background: #fff; } input[type="text"], input[type="time"], select, textarea { width: 100%; border: 1px solid #cdd4e0; border-radius: 6px; padding: 10px 12px; font-size: 15px; background: #fff; }
textarea { min-height: 170px; resize: vertical; line-height: 1.45; } textarea { min-height: 170px; resize: vertical; line-height: 1.45; }
.field-help { color: var(--muted); font-size: 13px; line-height: 1.35; margin-top: 5px; }
.subject-prefix-control { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: stretch; } .subject-prefix-control { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: stretch; }
.subject-prefix-control input { border-top-right-radius: 0; border-bottom-right-radius: 0; } .subject-prefix-control input { border-top-right-radius: 0; border-bottom-right-radius: 0; }
.subject-prefix-control span { display: inline-flex; align-items: center; border: 1px solid #cdd4e0; border-left: 0; border-radius: 0 6px 6px 0; background: #f8fafc; padding: 0 12px; color: var(--muted); white-space: nowrap; font-size: 15px; } .subject-prefix-control span { display: inline-flex; align-items: center; border: 1px solid #cdd4e0; border-left: 0; border-radius: 0 6px 6px 0; background: #f8fafc; padding: 0 12px; color: var(--muted); white-space: nowrap; font-size: 15px; }
@@ -42,8 +43,8 @@ button, .btn { border: 1px solid #b7c6da; background: #fff; color: #1f2d3d; bord
.btn.amber, button.primary { background: var(--amber); border-color: var(--amber); color: #fff; } .btn.amber, button.primary { background: var(--amber); border-color: var(--amber); color: #fff; }
.btn.amber.active { background: var(--amber-strong); border-color: var(--amber-strong); } .btn.amber.active { background: var(--amber-strong); border-color: var(--amber-strong); }
.btn.danger, button.danger { border-color: var(--danger); color: var(--danger); background: #fff; } .btn.danger, button.danger { border-color: var(--danger); color: var(--danger); background: #fff; }
button.danger-fill { background: var(--danger); border-color: var(--danger); color: #fff; } button.danger-fill, .btn.danger-fill { background: var(--danger); border-color: var(--danger); color: #fff; }
button.success { background: var(--ok); border-color: var(--ok); color: #fff; } button.success, .btn.success { background: var(--ok); border-color: var(--ok); color: #fff; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; align-items: center; } .actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; align-items: center; }
.table-actions { display: inline-flex; flex-wrap: wrap; gap: 6px; } .table-actions { display: inline-flex; flex-wrap: wrap; gap: 6px; }
table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 15px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: #fff; } table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 15px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: #fff; }
@@ -53,6 +54,11 @@ th { background: #f6f8fb; color: #4a5566; font-weight: 600; }
.badge { display: inline-block; background: #fce2b7; color: #7b4b00; border: 1px solid #efc57f; border-radius: 5px; padding: 2px 8px; font-size: 13px; white-space: nowrap; } .badge { display: inline-block; background: #fce2b7; color: #7b4b00; border: 1px solid #efc57f; border-radius: 5px; padding: 2px 8px; font-size: 13px; white-space: nowrap; }
.badge.ok { background: #def5e5; color: #12562b; border-color: #a8ddb8; } .badge.ok { background: #def5e5; color: #12562b; border-color: #a8ddb8; }
.badge.off { background: #eef1f5; color: #5f6a7b; border-color: #d7dde8; } .badge.off { background: #eef1f5; color: #5f6a7b; border-color: #d7dde8; }
.schedule-scroll { overflow: visible; }
.schedule-grid { grid-template-columns: 1fr; display: grid; gap: 14px; align-items: start; }
.schedule-column { border: 1px solid var(--border); border-radius: 12px; padding: 12px; background: #f8fafc; }
.schedule-column .br-restore-calendar { border: 0; border-radius: 0; padding: 0; background: transparent; }
.schedule-column .br-time-picker { margin: 12px 0 0; padding-top: 10px; border-top: 1px solid var(--border); }
.br-restore-layout { display: grid; grid-template-columns: 280px 1fr; gap: 16px; align-items: start; } .br-restore-layout { display: grid; grid-template-columns: 280px 1fr; gap: 16px; align-items: start; }
.br-restore-calendar { border: 1px solid var(--border); border-radius: 12px; padding: 12px; background: #f8fafc; } .br-restore-calendar { border: 1px solid var(--border); border-radius: 12px; padding: 12px; background: #f8fafc; }
.br-restore-calendar h4 { margin: 0 0 10px; font-size: 16px; font-weight: 700; } .br-restore-calendar h4 { margin: 0 0 10px; font-size: 16px; font-weight: 700; }
@@ -64,7 +70,7 @@ th { background: #f6f8fb; color: #4a5566; font-weight: 600; }
.br-calendar-grid td { padding: 4px; text-align: center; border-bottom: 0; } .br-calendar-grid td { padding: 4px; text-align: center; border-bottom: 0; }
.br-cal-day, .br-cal-day-disabled { width: 30px; height: 30px; border-radius: 8px; border: 1px solid var(--border); background: #fff; padding: 0; display: inline-flex; align-items: center; justify-content: center; } .br-cal-day, .br-cal-day-disabled { width: 30px; height: 30px; border-radius: 8px; border: 1px solid var(--border); background: #fff; padding: 0; display: inline-flex; align-items: center; justify-content: center; }
.br-cal-day.is-selected { background: var(--amber); color: #fff; border-color: var(--amber); } .br-cal-day.is-selected { background: var(--amber); color: #fff; border-color: var(--amber); }
.br-cal-day-disabled { color: #a0a7b4; border-color: transparent; background: transparent; } .br-cal-day-disabled { color: #a0a7b4; border-color: transparent; background: transparent; cursor: not-allowed; }
.br-date-label { font-weight: 600; color: #1f2a37; margin: 6px 0 10px; } .br-date-label { font-weight: 600; color: #1f2a37; margin: 6px 0 10px; }
.br-time-picker { margin: 8px 0 14px; } .br-time-picker { margin: 8px 0 14px; }
.br-time-title { font-weight: 600; margin-bottom: 6px; color: var(--muted); } .br-time-title { font-weight: 600; margin-bottom: 6px; color: var(--muted); }
@@ -74,4 +80,11 @@ th { background: #f6f8fb; color: #4a5566; font-weight: 600; }
.summary-card, .preview-box { border: 1px solid var(--border); background: #f8fafc; border-radius: 10px; padding: 12px; display: grid; gap: 8px; } .summary-card, .preview-box { border: 1px solid var(--border); background: #f8fafc; border-radius: 10px; padding: 12px; display: grid; gap: 8px; }
.kv { display: grid; grid-template-columns: 180px 1fr; gap: 6px 10px; font-size: 15px; } .kv { display: grid; grid-template-columns: 180px 1fr; gap: 6px 10px; font-size: 15px; }
.empty-state { min-height: 240px; display: grid; place-items: center; text-align: center; border: 1px dashed #cfd6e3; border-radius: 12px; background: #f8fafc; padding: 24px; } .empty-state { min-height: 240px; display: grid; place-items: center; text-align: center; border: 1px dashed #cfd6e3; border-radius: 12px; background: #f8fafc; padding: 24px; }
body.modal-open { overflow: hidden; }
.br-overlay { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); display: flex; align-items: center; justify-content: center; z-index: 9999; padding: 16px; }
.br-modal { width: min(640px, 94vw); background: #fff; border-radius: 12px; padding: 18px; border: 2px solid var(--border); box-shadow: 0 20px 40px rgba(15, 23, 42, 0.25); max-height: 90vh; overflow: auto; }
.br-modal h3 { margin: 0 0 10px; font-size: 22px; }
.br-modal p { margin: 0 0 10px; line-height: 1.45; }
.br-modal-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 14px; }
.br-modal-actions form { display: inline-flex; margin: 0; }
@media (max-width: 760px) { header { display: block; } header h1 { font-size: 30px; margin-bottom: 4px; } .br-restore-layout { grid-template-columns: 1fr; } .top-actions { justify-content: flex-start; } .kv { grid-template-columns: 1fr; } .subject-prefix-control { grid-template-columns: 1fr; } .subject-prefix-control input { border-radius: 6px 6px 0 0; } .subject-prefix-control span { border-left: 1px solid #cdd4e0; border-top: 0; border-radius: 0 0 6px 6px; min-height: 38px; } } @media (max-width: 760px) { header { display: block; } header h1 { font-size: 30px; margin-bottom: 4px; } .br-restore-layout { grid-template-columns: 1fr; } .top-actions { justify-content: flex-start; } .kv { grid-template-columns: 1fr; } .subject-prefix-control { grid-template-columns: 1fr; } .subject-prefix-control input { border-radius: 6px 6px 0 0; } .subject-prefix-control span { border-left: 1px solid #cdd4e0; border-top: 0; border-radius: 0 0 6px 6px; min-height: 38px; } }
+17 -1
View File
@@ -1 +1,17 @@
@import url("enhanced.css"); .wrap {
width: 100% !important;
max-width: none !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
.main-section,
.schedule-panel {
width: 100%;
max-width: none;
}
.schedule-scroll { overflow-x: auto; padding-bottom: 2px; }
.schedule-grid { grid-template-columns: repeat(2, minmax(460px, 1fr)); min-width: 960px; }
@media (min-width: 1240px) {
.schedule-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); min-width: 0; }
}