Merge origin/main: Remote-Stand übernehmen

Konflikte in app/bootstrap.php, app/pages.php, app/privacy.php,
app/util.php, tools/send_reminders.php, views/booking_form.php und
views/legal_datenschutz.php zugunsten von origin/main aufgelöst
(Enthalten u. a. Einladungen, Buchungsformular-Neustrukturierung und
die überarbeiteten Rechtsseiten).

Eigene Ergänzungen bleiben erhalten, soweit sie nicht ersetzt wurden:
README-Abschnitt "Rechtliches / DSGVO", docs/dsgvo.md,
docs/architecture.md, app/config.example.php, install.php und
web/offline.html.
This commit is contained in:
torsten 2026-11-18 23:52:30 +01:00
commit dd1fba062e
34 changed files with 1784 additions and 256 deletions

View file

@ -22,6 +22,10 @@ function admin_handle(string $path, array $user): void
admin_user_form((int) $m[1]);
return;
}
if (preg_match('#^/admin/users/(\d+)/invite$#', $path, $m) === 1) {
admin_user_invite((int) $m[1], $user);
return;
}
if (preg_match('#^/admin/users/(\d+)/delete$#', $path, $m) === 1) {
admin_user_delete((int) $m[1], $user);
return;
@ -48,11 +52,21 @@ function admin_users_list(): void
FROM users u LEFT JOIN employees e ON e.id = u.employee_id
ORDER BY u.last_name, u.first_name';
$users = db()->query($sql)->fetchAll();
// Offene Einladungen, damit der Admin sieht, wer noch keinen Zugang hat.
$stmt = db()->prepare('SELECT user_id, expires_at FROM user_invites WHERE used_at IS NULL AND expires_at >= ?');
$stmt->execute([utc_now()]);
$openInvites = [];
foreach ($stmt->fetchAll() as $row) {
$openInvites[(int) $row['user_id']] = (string) $row['expires_at'];
}
render_page('admin_users', [
'users' => $users,
'pushCounts' => push_counts_by_user(),
'pushLastUpdate' => push_last_update_by_user(),
'pushConfigured' => push_is_configured(),
'openInvites' => $openInvites,
], 'Benutzer');
}
@ -95,6 +109,8 @@ function admin_user_form(?int $id): void
'must_change_password' => post_string('must_change_password') === '1' ? 1 : 0,
];
$password = (string) ($_POST['password'] ?? '');
// Einladung: Passwort setzt der Benutzer selbst über einen Link.
$sendInvite = $id === null && post_string('send_invite') === '1';
if ($values['first_name'] === '' || mb_strlen($values['first_name']) > 80) {
$errors['first_name'] = 'Bitte einen Vornamen angeben (max. 80 Zeichen).';
@ -129,7 +145,14 @@ function admin_user_form(?int $id): void
}
}
if ($id === null && mb_strlen($password) < 8) {
if ($sendInvite && $values['email'] === '') {
$errors['email'] = 'Für die Einladung wird eine E-Mail-Adresse benötigt – oder das Startpasswort selbst vergeben.';
}
if ($sendInvite && $values['status'] !== 'active') {
$errors['status'] = 'Einladungen sind nur für aktive Konten möglich.';
}
if ($id === null && !$sendInvite && mb_strlen($password) < 8) {
$errors['password'] = 'Das Startpasswort muss mindestens 8 Zeichen haben.';
}
if ($id !== null && $password !== '' && mb_strlen($password) < 8) {
@ -163,13 +186,24 @@ function admin_user_form(?int $id): void
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)'
);
$stmt->execute([
$values['first_name'], $values['last_name'], $email, hash_password($password),
$values['first_name'], $values['last_name'], $email,
hash_password($sendInvite ? bin2hex(random_bytes(24)) : $password),
$values['role'], $values['status'], $values['employee_id'] ?: null,
$values['must_change_password'], utc_now(), utc_now(), utc_now(),
]);
$newId = (int) $pdo->lastInsertId();
$pdo->commit();
flash('success', 'Benutzer ' . $values['first_name'] . ' ' . $values['last_name'] . ' wurde angelegt.');
$message = 'Benutzer ' . $values['first_name'] . ' ' . $values['last_name'] . ' wurde angelegt.';
if ($sendInvite) {
// Link erzeugen (und mailen, wenn der Versand aktiv ist).
$inviteResult = invite_provision($newId, (int) auth_user()['id']);
invite_notice_set($newId, $inviteResult);
$message .= $inviteResult['sent']
? ' Die Einladung ist an ' . $email . ' unterwegs.'
: ' Die Einladung ist erzeugt – der Link steht im Formular.';
}
flash('success', $message);
redirect('/admin/users/' . $newId);
}
@ -216,9 +250,41 @@ function admin_user_form(?int $id): void
'employees' => $employees,
'pushCount' => $editing ? push_subscription_count((int) $editing['id']) : 0,
'pushAvailable' => push_is_configured(),
'mailEnabled' => mail_is_enabled(),
'sendInvite' => $id === null && (!is_post() || post_string('send_invite') === '1'),
'inviteNotice' => invite_notice_take($id),
'openInvite' => $editing ? invite_active_for_user((int) $editing['id']) : null,
], $editing ? 'Benutzer bearbeiten' : 'Benutzer anlegen');
}
/**
* Erzeugt einen neuen Einladungslink und mailt ihn. Ein bisheriges Passwort
* wird dabei ungültig, angemeldete Geräte werden abgemeldet.
*/
function admin_user_invite(int $id, array $actor): void
{
require_post();
$target = auth_user_by_id($id);
if (!$target) {
abort_page(404, 'Benutzer nicht gefunden.');
}
if ($id === (int) $actor['id']) {
abort_page(422, 'Für das eigene Konto lässt sich keine Einladung versenden. Bitte das Passwort unter „Mein Konto" ändern.');
}
if ($target['status'] !== 'active') {
flash('error', 'Für ein deaktiviertes Konto kann keine Einladung versendet werden. Bitte das Konto zuerst aktivieren.');
redirect('/admin/users/' . $id);
}
$result = invite_provision($id, (int) $actor['id']);
invite_notice_set($id, $result);
$email = trim((string) ($target['email'] ?? ''));
flash('success', $result['sent']
? 'Einladung an ' . $email . ' gesendet. Das bisherige Passwort ist jetzt ungültig.'
: 'Einladung erzeugt. Das bisherige Passwort ist jetzt ungültig.');
redirect('/admin/users/' . $id);
}
function admin_user_delete(int $id, array $actor): void
{
require_post();

View file

@ -33,6 +33,7 @@ require DIC_APP . '/auth.php';
require DIC_APP . '/data.php';
require DIC_APP . '/push.php';
require DIC_APP . '/mail.php';
require DIC_APP . '/invite.php';
require DIC_APP . '/privacy.php';
require DIC_APP . '/pages.php';
require DIC_APP . '/admin.php';

View file

@ -29,7 +29,8 @@ return [
'login_window_seconds' => 900,
'login_max_per_user' => 5,
'login_max_per_ip' => 15,
// Optionaler täglicher E-Mail-Digest (tools/send_reminders.php).
// Optionaler E-Mail-Versand: täglicher Erinnerungs-Digest
// (tools/send_reminders.php) und Einladungen für neue Benutzer.
'mail_enabled' => false,
'mail_from' => 'Drink it cold <noreply@drink-it-cold.programmschmiede.de>',
// Token für /cron/reminders?token=…, falls kein CLI-Cron möglich ist.

View file

@ -20,6 +20,12 @@ function trailers_map(bool $activeOnly = false): array
return $out;
}
/** Truhen erkennt die App an der Bezeichnung ("Truhe", "Truhe 1", "Truhe 2 (verschrottet)"). */
function trailer_is_chest(array $trailer): bool
{
return mb_stripos(trim((string) $trailer['label']), 'truhe') === 0;
}
function trailer_find(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM trailers WHERE id = ?');
@ -118,14 +124,34 @@ function booking_conflicts(int $trailerId, string $start, string $end, int $excl
function booking_input(array $source): array
{
$kind = (string) ($source['kind'] ?? 'pickup');
if (array_key_exists('rent_cents', $source) || array_key_exists('delivery_cents', $source)) {
$rent = max(0, (int) ($source['rent_cents'] ?? 0));
$delivery = max(0, (int) ($source['delivery_cents'] ?? 0));
} elseif (array_key_exists('rent', $source) || array_key_exists('delivery', $source)) {
$rent = parse_money((string) ($source['rent'] ?? '0'));
$delivery = parse_money((string) ($source['delivery'] ?? '0'));
} else {
// Aufrufer ohne getrennte Beträge: Gesamtbetrag gilt als Miete.
$rent = parse_money((string) ($source['total'] ?? '0'));
$delivery = 0;
}
$invoiceNo = trim((string) ($source['invoice_no'] ?? ''));
$invoice = $invoiceNo !== '' || ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0;
return [
'trailer_id' => (int) ($source['trailer_id'] ?? 0),
'employee_id' => (int) ($source['employee_id'] ?? 0),
'start_date' => trim((string) ($source['start_date'] ?? '')),
'end_date' => trim((string) ($source['end_date'] ?? '')),
'start_time' => normalize_time($source['start_time'] ?? ''),
'end_time' => normalize_time($source['end_time'] ?? ''),
'deposit_cents' => parse_money((string) ($source['deposit'] ?? '0')),
'total_cents' => parse_money((string) ($source['total'] ?? '0')),
'invoice' => ((string) ($source['invoice'] ?? '0')) === '1' ? 1 : 0,
'rent_cents' => $rent,
'delivery_cents' => $delivery,
'total_cents' => $rent + $delivery,
'invoice' => $invoice,
'invoice_no' => $invoiceNo,
'kind' => in_array($kind, ['pickup', 'delivery'], true) ? $kind : 'pickup',
'customer_name' => trim((string) ($source['customer_name'] ?? '')),
'street' => trim((string) ($source['street'] ?? '')),
@ -135,6 +161,31 @@ function booking_input(array $source): array
];
}
/** Bestehende Buchung als Eingabedaten (Validierung, Verschieben, Wiederherstellen). */
function booking_to_input(array $booking): array
{
return [
'trailer_id' => (int) $booking['trailer_id'],
'employee_id' => (int) $booking['employee_id'],
'start_date' => (string) $booking['start_date'],
'end_date' => (string) $booking['end_date'],
'start_time' => normalize_time($booking['start_time'] ?? ''),
'end_time' => normalize_time($booking['end_time'] ?? ''),
'deposit_cents' => (int) $booking['deposit_cents'],
'rent_cents' => (int) ($booking['rent_cents'] ?? $booking['total_cents']),
'delivery_cents' => (int) ($booking['delivery_cents'] ?? 0),
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'invoice_no' => (string) ($booking['invoice_no'] ?? ''),
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],
'city' => (string) $booking['city'],
'mobile' => (string) $booking['mobile'],
'email' => (string) $booking['email'],
];
}
function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId = 0, int $allowEmployeeId = 0): array
{
$errors = [];
@ -163,6 +214,20 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
}
}
foreach (['start_time' => 'Mietbeginn', 'end_time' => 'Mietende'] as $field => $label) {
if (!valid_time((string) $data[$field])) {
$errors[$field] = 'Bitte für ' . $label . ' eine gültige Uhrzeit angeben (HH:MM).';
}
}
if (!isset($errors['start_time']) && !isset($errors['end_time'])
&& !isset($errors['start_date']) && !isset($errors['end_date'])
&& $data['start_date'] === $data['end_date']
&& $data['start_time'] !== '' && $data['end_time'] !== ''
&& $data['end_time'] <= $data['start_time']
) {
$errors['end_time'] = 'Am selben Tag muss das Mietende nach dem Mietbeginn liegen.';
}
if ($data['customer_name'] === '') {
$errors['customer_name'] = 'Bitte den Kundennamen angeben.';
} elseif (mb_strlen($data['customer_name']) > 190) {
@ -182,11 +247,19 @@ function booking_validate(array $data, int $excludeId = 0, int $allowTrailerId =
}
}
if ($data['invoice_no'] !== '') {
if (mb_strlen($data['invoice_no']) > 40) {
$errors['invoice_no'] = 'Die Rechnungsnummer ist zu lang (max. 40 Zeichen).';
} elseif (preg_match('/^[A-Za-z0-9._\/\- ]+$/', $data['invoice_no']) !== 1) {
$errors['invoice_no'] = 'Die Rechnungsnummer darf nur Buchstaben, Ziffern, Punkt, Schrägstrich, Bindestrich und Leerzeichen enthalten.';
}
}
$maxAmount = 10000000; // 100.000,00 €
if ($data['total_cents'] < 0 || $data['deposit_cents'] < 0) {
$errors['total'] = 'Beträge dürfen nicht negativ sein.';
} elseif ($data['total_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
$errors['total'] = 'Der Betrag ist unrealistisch hoch.';
if ($data['rent_cents'] < 0 || $data['delivery_cents'] < 0 || $data['deposit_cents'] < 0) {
$errors['rent'] = 'Beträge dürfen nicht negativ sein.';
} elseif ($data['rent_cents'] > $maxAmount || $data['delivery_cents'] > $maxAmount || $data['deposit_cents'] > $maxAmount) {
$errors['rent'] = 'Der Betrag ist unrealistisch hoch.';
} elseif ($data['deposit_cents'] > $data['total_cents']) {
$errors['deposit'] = 'Die Anzahlung darf den Gesamtbetrag nicht übersteigen.';
}
@ -234,13 +307,16 @@ function booking_create(array $data, int $userId): int
}
$stmt = $pdo->prepare(
'INSERT INTO bookings
(trailer_id, employee_id, start_date, end_date, deposit_cents, total_cents, invoice, kind,
(trailer_id, employee_id, start_date, end_date, start_time, end_time, deposit_cents,
rent_cents, delivery_cents, total_cents, invoice, invoice_no, kind,
customer_name, street, city, mobile, email, status, created_at, updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active", ?, ?, ?, ?)'
);
$stmt->execute([
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
utc_now(), utc_now(), $userId, $userId,
]);
@ -270,12 +346,15 @@ function booking_update(int $id, array $data, int $userId): void
}
$stmt = $pdo->prepare(
'UPDATE bookings SET trailer_id = ?, employee_id = ?, start_date = ?, end_date = ?,
deposit_cents = ?, total_cents = ?, invoice = ?, kind = ?, customer_name = ?, street = ?,
start_time = ?, end_time = ?, deposit_cents = ?, rent_cents = ?, delivery_cents = ?,
total_cents = ?, invoice = ?, invoice_no = ?, kind = ?, customer_name = ?, street = ?,
city = ?, mobile = ?, email = ?, updated_at = ?, updated_by = ? WHERE id = ?'
);
$stmt->execute([
$data['trailer_id'], $data['employee_id'], $data['start_date'], $data['end_date'],
$data['deposit_cents'], $data['total_cents'], $data['invoice'], $data['kind'],
null_if_empty($data['start_time']), null_if_empty($data['end_time']),
$data['deposit_cents'], $data['rent_cents'], $data['delivery_cents'], $data['total_cents'],
$data['invoice'], null_if_empty($data['invoice_no']), $data['kind'],
$data['customer_name'], $data['street'], $data['city'], $data['mobile'], $data['email'],
utc_now(), $userId, $id,
]);
@ -320,21 +399,12 @@ function booking_restore(int $id, int $userId): array
if (!$booking) {
throw new RuntimeException('not_found');
}
$errors = booking_validate([
'trailer_id' => (int) $booking['trailer_id'],
'employee_id' => (int) $booking['employee_id'],
'start_date' => $booking['start_date'],
'end_date' => $booking['end_date'],
'deposit_cents' => (int) $booking['deposit_cents'],
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'kind' => $booking['kind'],
'customer_name' => $booking['customer_name'],
'street' => $booking['street'],
'city' => $booking['city'],
'mobile' => $booking['mobile'],
'email' => $booking['email'],
], $id, (int) $booking['trailer_id'], (int) $booking['employee_id']);
$errors = booking_validate(
booking_to_input($booking),
$id,
(int) $booking['trailer_id'],
(int) $booking['employee_id']
);
if ($errors) {
return $errors;
}
@ -368,21 +438,10 @@ function booking_move(int $id, string $newStart, int $newTrailerId, int $userId)
return ['error' => 'Bitte einen gültigen Kühlanhänger wählen.'];
}
$data = [
'trailer_id' => $newTrailerId,
'employee_id' => (int) $booking['employee_id'],
'start_date' => $newStart,
'end_date' => $newEnd,
'deposit_cents' => (int) $booking['deposit_cents'],
'total_cents' => (int) $booking['total_cents'],
'invoice' => (int) $booking['invoice'],
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],
'city' => (string) $booking['city'],
'mobile' => (string) $booking['mobile'],
'email' => (string) $booking['email'],
];
$data = booking_to_input($booking);
$data['trailer_id'] = $newTrailerId;
$data['start_date'] = $newStart;
$data['end_date'] = $newEnd;
$pdo = db();
$pdo->beginTransaction();
@ -432,6 +491,14 @@ function booking_invoice_label(int|string $invoice): string
return (int) $invoice === 1 ? 'JA' : 'NEIN';
}
/** Rechnung inklusive Nummer, z. B. "JA (RE2026054)". */
function booking_invoice_display(array $booking): string
{
$label = booking_invoice_label($booking['invoice']);
$number = trim((string) ($booking['invoice_no'] ?? ''));
return $number === '' ? $label : $label . ' (' . $number . ')';
}
/** Exakt der Text aus der Anforderung, Zeile für Zeile. */
function booking_copy_text(array $booking): string
{
@ -439,9 +506,9 @@ function booking_copy_text(array $booking): string
'Anzahlung: ' . fmt_money((int) $booking['deposit_cents']),
'Gesamtbetrag: ' . fmt_money((int) $booking['total_cents']),
'Noch zu zahlen: ' . fmt_money(due_cents((int) $booking['total_cents'], (int) $booking['deposit_cents'])),
'Rechnung: ' . booking_invoice_label($booking['invoice']),
'Von: ' . fmt_date_short((string) $booking['start_date']),
'Bis: ' . fmt_date_short((string) $booking['end_date']),
'Rechnung: ' . booking_invoice_display($booking),
'Von: ' . fmt_date_short_with_time((string) $booking['start_date'], $booking['start_time'] ?? null),
'Bis: ' . fmt_date_short_with_time((string) $booking['end_date'], $booking['end_time'] ?? null),
'Art: ' . booking_kind_label((string) $booking['kind']),
'Name: ' . $booking['customer_name'],
'Straße: ' . $booking['street'],

213
app/invite.php Normal file
View file

@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
/**
* Einladungen für neue Benutzerkonten.
*
* Der Admin legt das Konto an und erzeugt dabei einen einmaligen Link. Über
* diesen Link vergibt der Benutzer sein Passwort selbst – es muss also kein
* Startpasswort weitergegeben werden. Gespeichert wird nur der SHA-256-Hash
* des Tokens; der Link ist sieben Tage gültig.
*
* Der Versand per E-Mail ist optional (app.mail_enabled). Ist er aus oder
* fehlt die Adresse, zeigt die App den Link im Benutzerformular an, damit der
* Admin ihn über einen anderen Weg weitergeben kann.
*/
const DIC_INVITE_SECONDS = 7 * 86400;
function invite_url(string $token): string
{
$base = rtrim((string) config('app.public_url', ''), '/');
return $base . url('/invite/' . $token);
}
/** Legt einen neuen Einladungslink an; ein älterer Link wird ungültig. */
function invite_create(int $userId, ?int $createdBy): array
{
$token = bin2hex(random_bytes(32));
$expiresAt = utc_after(DIC_INVITE_SECONDS);
db()->prepare('DELETE FROM user_invites WHERE user_id = ?')->execute([$userId]);
db()->prepare(
'INSERT INTO user_invites (user_id, token_hash, created_by, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)'
)->execute([$userId, hash('sha256', $token), $createdBy, utc_now(), $expiresAt]);
return ['token' => $token, 'url' => invite_url($token), 'expires_at' => $expiresAt];
}
/** Sucht eine offene, noch gültige Einladung zum Token. */
function invite_find(string $token): ?array
{
if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
return null;
}
$stmt = db()->prepare(
'SELECT i.*, u.first_name, u.last_name, u.email, u.status
FROM user_invites i JOIN users u ON u.id = i.user_id
WHERE i.token_hash = ? AND i.used_at IS NULL AND i.expires_at >= ? LIMIT 1'
);
$stmt->execute([hash('sha256', $token), utc_now()]);
$row = $stmt->fetch();
if (!$row) {
return null;
}
$row['id'] = (int) $row['id'];
$row['user_id'] = (int) $row['user_id'];
return $row;
}
function invite_active_for_user(int $userId): ?array
{
$stmt = db()->prepare(
'SELECT * FROM user_invites WHERE user_id = ? AND used_at IS NULL AND expires_at >= ?
ORDER BY id DESC LIMIT 1'
);
$stmt->execute([$userId, utc_now()]);
$row = $stmt->fetch();
return $row ?: null;
}
/**
* Setzt Passwort und Session-Sperre für ein Konto zurück, erzeugt einen neuen
* Einladungslink und verschickt ihn, wenn E-Mail-Versand aktiv ist.
*
* @return array{url: string, sent: bool, error: string, expires_at: string}
*/
function invite_provision(int $userId, ?int $createdBy): array
{
$user = auth_user_by_id($userId);
if (!$user) {
throw new RuntimeException('Benutzer nicht gefunden.');
}
$pdo = db();
$pdo->beginTransaction();
try {
// Zufälliges Ersatzpasswort: das bisherige Passwort ist sofort ungültig,
// angemeldete Geräte werden abgemeldet.
$pdo->prepare(
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 1,
auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?'
)->execute([hash_password(bin2hex(random_bytes(24))), utc_now(), utc_now(), $userId]);
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
$pdo->commit();
} catch (Throwable $error) {
$pdo->rollBack();
throw $error;
}
$invite = invite_create($userId, $createdBy);
$result = ['url' => $invite['url'], 'sent' => false, 'error' => '', 'expires_at' => $invite['expires_at']];
$email = trim((string) ($user['email'] ?? ''));
if (!mail_is_enabled()) {
$result['error'] = 'E-Mail-Versand ist deaktiviert. Bitte den Link selbst weitergeben.';
return $result;
}
if ($email === '') {
$result['error'] = 'Für dieses Konto ist keine E-Mail-Adresse hinterlegt. Bitte den Link selbst weitergeben.';
return $result;
}
[$subject, $body] = invite_mail_text($user, $invite['url'], $invite['expires_at']);
if (!mail_send($email, $subject, $body)) {
$result['error'] = 'Versand an ' . $email . ' fehlgeschlagen. Bitte den Link selbst weitergeben.';
return $result;
}
$result['sent'] = true;
return $result;
}
/** @return array{0: string, 1: string} Betreff und Text der Einladungs-E-Mail */
function invite_mail_text(array $user, string $url, string $expiresAt): array
{
$firstName = (string) $user['first_name'];
$loginUrl = rtrim((string) config('app.public_url', ''), '/') . url('/login');
$lines = [
'Guten Tag ' . $firstName . ',',
'',
'für Sie wurde ein Zugang zur Terminplanung von Drink it cold angelegt.',
'',
'Zugang einrichten (Link sieben Tage gültig, einmal nutzbar):',
$url,
'',
'Danach melden Sie sich mit Vorname, Nachname und Ihrem selbst gewählten',
'Passwort an: ' . $loginUrl,
'',
'Der Link verfällt am ' . fmt_datetime($expiresAt) . '. Ist er nicht mehr gültig,',
'wenden Sie sich bitte an den Administrator.',
'',
'Diese Nachricht wurde automatisch von der Terminplanung erzeugt.',
];
return ['Drink it cold – Zugang zur Terminplanung', implode("\n", $lines)];
}
/**
* Vergibt das Passwort über die Einladung: Passwort speichern, Einladung
* verbrauchen, neue Anmeldung mit diesem Konto vorbereiten.
*/
function invite_accept(array $invite, string $password): array
{
$userId = (int) $invite['user_id'];
$pdo = db();
$pdo->beginTransaction();
try {
// Einmal-Verwendung: nur wer den Eintrag als erster auf „benutzt“ setzt,
// darf das Passwort vergeben.
$claim = $pdo->prepare('UPDATE user_invites SET used_at = ? WHERE id = ? AND used_at IS NULL');
$claim->execute([utc_now(), (int) $invite['id']]);
if ($claim->rowCount() === 0) {
$pdo->rollBack();
throw new RuntimeException('invite_used');
}
$pdo->prepare(
'UPDATE users SET password_hash = ?, password_changed_at = ?, updated_at = ?,
must_change_password = 0, auth_epoch = auth_epoch + 1 WHERE id = ?'
)->execute([hash_password($password), utc_now(), utc_now(), $userId]);
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
// Weitere offene Einladungen desselben Kontos werden ungültig.
$pdo->prepare('DELETE FROM user_invites WHERE user_id = ? AND id <> ?')->execute([$userId, (int) $invite['id']]);
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $error;
}
$user = auth_user_by_id($userId);
if (!$user) {
throw new RuntimeException('Benutzer nicht gefunden.');
}
return $user;
}
/* ------------------------------------------------- Einladung nach dem Anlegen */
/** Merkt den Link für genau einen Seitenaufruf im Benutzerformular. */
function invite_notice_set(int $userId, array $result): void
{
$_SESSION['invite_notice'] = [
'user_id' => $userId,
'url' => (string) $result['url'],
'sent' => (bool) $result['sent'],
'error' => (string) ($result['error'] ?? ''),
'expires_at' => (string) $result['expires_at'],
];
}
function invite_notice_take(?int $userId): ?array
{
$notice = $_SESSION['invite_notice'] ?? null;
unset($_SESSION['invite_notice']);
if (!is_array($notice) || $userId === null || (int) ($notice['user_id'] ?? 0) !== $userId) {
return null;
}
return $notice;
}

View file

@ -2,14 +2,46 @@
declare(strict_types=1);
/**
* Optionaler täglicher E-Mail-Digest für fällige Erinnerungen.
* E-Mail-Versand: optionaler täglicher Digest für fällige Erinnerungen und
* Einladungen für neue Benutzer.
*
* Die In-App-Erinnerungen sind immer vorhanden. Dieser Versand ist zusätzlich
* Die In-App-Erinnerungen sind immer vorhanden. Der Digest ist zusätzlich
* und wird über tools/send_reminders.php (Cron) oder /cron/reminders?token=…
* ausgelöst. Jede Erinnerung wird genau einmal verschickt; das Protokoll steht
* in reminder_mail_log.
*
* Eingeschaltet wird der Versand über app.mail_enabled. Ist er aus, bleibt die
* App vollständig nutzbar; Einladungslinks zeigt der Admin dann selbst an.
*/
function mail_is_enabled(): bool
{
return (bool) config('app.mail_enabled', false);
}
/**
* Verschickt eine reine Textnachricht. Absender kommt aus app.mail_from.
* Der Aufrufer prüft mail_is_enabled() und die Empfängeradresse.
*/
function mail_send(string $to, string $subject, string $body): bool
{
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
return false;
}
$headers = [
'From: ' . (string) config('app.mail_from', 'Drink it cold <noreply@localhost>'),
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
];
return @mail(
$to,
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
$body,
implode("\r\n", $headers)
);
}
function reminder_mail_recipients(): array
{
$sql = "SELECT u.employee_id, u.email, u.first_name, u.last_name, e.name AS employee_name
@ -31,7 +63,7 @@ function reminder_mail_recipients(): array
*/
function reminder_send_due(int $lookbackDays = 7): array
{
$result = ['enabled' => (bool) config('app.mail_enabled', false), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
$result = ['enabled' => mail_is_enabled(), 'sent' => 0, 'skipped' => 0, 'errors' => [], 'details' => []];
if (!$result['enabled']) {
return $result;
}
@ -61,7 +93,6 @@ function reminder_send_due(int $lookbackDays = 7): array
$byEmployee[$employeeId][] = $row;
}
$fromHeader = (string) config('app.mail_from', 'Drink it cold <noreply@localhost>');
$appUrl = rtrim((string) config('app.public_url', ''), '/');
foreach ($byEmployee as $employeeId => $items) {
@ -87,18 +118,7 @@ function reminder_send_due(int $lookbackDays = 7): array
$body = implode("\n", $lines);
$subject = 'Drink it cold – ' . count($items) . ' fällige Erinnerung' . (count($items) === 1 ? '' : 'en');
$headers = [
'From: ' . $fromHeader,
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
];
$ok = @mail(
(string) $recipient['email'],
mb_encode_mimeheader($subject, 'UTF-8', 'B'),
$body,
implode("\r\n", $headers)
);
$ok = mail_send((string) $recipient['email'], $subject, $body);
if (!$ok) {
$result['errors'][] = 'Versand an ' . $recipient['email'] . ' fehlgeschlagen.';
continue;

View file

@ -54,6 +54,10 @@ function page_handle(string $method, string $path): void
page_login($method);
return;
}
if (preg_match('#^/invite/([a-f0-9]{64})$#', $path, $m) === 1) {
page_invite($method, $m[1]);
return;
}
if ($path === '/impressum' || $path === '/datenschutz') {
legal_page(substr($path, 1));
return;
@ -83,6 +87,10 @@ function page_handle(string $method, string $path): void
page_calendar($user);
return;
}
if ($path === '/availability') {
page_availability($user);
return;
}
if ($path === '/bookings/new') {
page_booking_new($user, $method);
return;
@ -186,8 +194,9 @@ function cron_reminders(): void
$mail = reminder_send_due();
echo 'Drink it cold – Erinnerungslauf ' . fmt_datetime(utc_now()) . "\n";
echo sprintf(
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['reminder_mail_log'],
"Aufräumen: %d Login-Fehlversuche, %d Tokens, %d Einladungen, %d E-Mail-Protokolle, %d Push-Protokolle entfernt%s.\n",
$cleanup['login_attempts'], $cleanup['auth_tokens'], $cleanup['user_invites'],
$cleanup['reminder_mail_log'],
$cleanup['reminder_push_log'], $cleanup['log_rotated'] ? ', Fehlerprotokoll rotiert' : ''
);
if (!push_is_configured()) {
@ -264,6 +273,67 @@ function page_login(string $method): void
], 'Anmelden');
}
/* --------------------------------------------------------------- Einladung */
/**
* Einmaliger Link aus der Einladungs-E-Mail: Der Benutzer vergibt hier sein
* Passwort selbst. Danach wird er bewusst zur Anmeldung geschickt, damit er
* das neue Passwort direkt ausprobiert.
*/
function page_invite(string $method, string $token): void
{
$invite = invite_find($token);
$state = 'form';
$error = '';
if ($invite === null) {
$state = 'invalid';
http_response_code(410);
} elseif ($invite['status'] !== 'active') {
$state = 'invalid';
http_response_code(403);
} elseif ($method === 'POST') {
require_post();
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['repeat_password'] ?? '');
if (mb_strlen($password) < 8) {
$error = 'Das Passwort muss mindestens 8 Zeichen haben.';
} elseif ($password !== $repeat) {
$error = 'Die beiden Passwörter stimmen nicht überein.';
} else {
try {
invite_accept($invite, $password);
// Eine bestehende Sitzung dieses Kontos ist durch den neuen
// auth_epoch ohnehin ungültig; hier wird sie auch formal beendet.
$current = auth_user();
if ($current !== null && (int) $current['id'] === (int) $invite['user_id']) {
auth_clear_session();
}
flash('success', 'Ihr Zugang ist eingerichtet. Bitte jetzt mit Vorname, Nachname und dem neuen Passwort anmelden.');
redirect('/login');
} catch (RuntimeException $e) {
if ($e->getMessage() !== 'invite_used') {
throw $e;
}
// Zwei Geräte haben den Link gleichzeitig geöffnet.
$state = 'invalid';
http_response_code(410);
}
}
if ($state === 'form') {
http_response_code(422);
}
}
render_standalone('invite', [
'state' => $state,
'error' => $error,
'firstName' => $invite !== null ? (string) $invite['first_name'] : '',
'lastName' => $invite !== null ? (string) $invite['last_name'] : '',
'email' => $invite !== null ? (string) ($invite['email'] ?? '') : '',
], 'Zugang einrichten');
}
/* --------------------------------------------------------------- Übersicht */
function page_dashboard(array $user): void
@ -327,9 +397,9 @@ function calendar_url(string $date, string $view, int $employeeId, bool $showCan
function page_calendar(array $user): void
{
$view = query_string('view', 'week');
$view = query_string('view', 'month');
if (!in_array($view, ['day', 'week', 'month'], true)) {
$view = 'week';
$view = 'month';
}
$date = query_string('date');
if (!valid_date($date)) {
@ -374,8 +444,8 @@ function page_calendar(array $user): void
$cursor = add_days($cursor, 1);
}
$barBase = ['day' => 76, 'week' => 48, 'month' => 28][$view];
$rowMin = ['day' => 104, 'week' => 64, 'month' => 40][$view];
$barBase = ['day' => 76, 'week' => 48, 'month' => 34][$view];
$rowMin = ['day' => 104, 'week' => 64, 'month' => 44][$view];
$rows = [];
foreach ($trailers as $trailer) {
@ -438,6 +508,66 @@ function page_calendar(array $user): void
], 'Kalender');
}
/* ----------------------------------------------------------- Verfügbarkeit */
function page_availability(array $user): void
{
$from = query_string('from');
$to = query_string('to');
$checked = $from !== '' || $to !== '';
$errors = [];
if (!$checked) {
$from = today_iso();
$to = add_days($from, 3);
} else {
if (!valid_date($from)) {
$errors['from'] = 'Bitte ein gültiges Startdatum angeben.';
}
if ($to === '') {
$to = $from;
}
if (!valid_date($to)) {
$errors['to'] = 'Bitte ein gültiges Enddatum angeben.';
}
if (!$errors) {
if ($to < $from) {
$errors['to'] = 'Das Ende darf nicht vor dem Beginn liegen.';
} elseif (days_between($from, $to) > 365) {
$errors['to'] = 'Der Zeitraum darf höchstens 365 Tage betragen.';
}
}
}
$groups = ['trailer' => [], 'chest' => []];
$totals = ['trailer' => 0, 'chest' => 0];
$freeCount = 0;
if ($checked && !$errors) {
foreach (trailers_all() as $trailer) {
$key = trailer_is_chest($trailer) ? 'chest' : 'trailer';
$totals[$key]++;
// Nur tatsächlich freie Fahrzeuge ausweisen; belegte entfallen.
if (booking_conflicts((int) $trailer['id'], $from, $to)) {
continue;
}
$freeCount++;
$groups[$key][] = ['trailer' => $trailer];
}
}
render_page('availability', [
'from' => $from,
'to' => $to,
'checked' => $checked,
'errors' => $errors,
'groups' => $groups,
'totals' => $totals,
'freeCount' => $freeCount,
'total' => $totals['trailer'] + $totals['chest'],
'user' => $user,
], 'Verfügbarkeit');
}
/* --------------------------------------------------------------- Buchungen */
function booking_form_context(array $user, ?array $booking = null, array $values = [], array $errors = []): array
@ -473,9 +603,13 @@ function form_values_from_input(array $data): array
'employee_id' => (int) $data['employee_id'],
'start_date' => (string) $data['start_date'],
'end_date' => (string) $data['end_date'],
'start_time' => (string) ($data['start_time'] ?? ''),
'end_time' => (string) ($data['end_time'] ?? ''),
'deposit' => number_format($data['deposit_cents'] / 100, 2, ',', ''),
'total' => number_format($data['total_cents'] / 100, 2, ',', ''),
'rent' => number_format($data['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format($data['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $data['invoice'],
'invoice_no' => (string) ($data['invoice_no'] ?? ''),
'kind' => (string) $data['kind'],
'customer_name' => (string) $data['customer_name'],
'street' => (string) $data['street'],
@ -515,9 +649,13 @@ function page_booking_new(array $user, string $method): void
'employee_id' => $employeeId,
'start_date' => $start,
'end_date' => $end,
'start_time' => '',
'end_time' => '',
'deposit' => '',
'total' => '',
'rent' => '',
'delivery' => '',
'invoice' => 0,
'invoice_no' => '',
'kind' => 'pickup',
'customer_name' => '',
'street' => '',
@ -559,9 +697,13 @@ function page_booking_edit(array $user, int $id, string $method): void
'employee_id' => (int) $booking['employee_id'],
'start_date' => (string) $booking['start_date'],
'end_date' => (string) $booking['end_date'],
'start_time' => (string) ($booking['start_time'] ?? ''),
'end_time' => (string) ($booking['end_time'] ?? ''),
'deposit' => number_format((int) $booking['deposit_cents'] / 100, 2, ',', ''),
'total' => number_format((int) $booking['total_cents'] / 100, 2, ',', ''),
'rent' => number_format((int) $booking['rent_cents'] / 100, 2, ',', ''),
'delivery' => number_format((int) $booking['delivery_cents'] / 100, 2, ',', ''),
'invoice' => (int) $booking['invoice'],
'invoice_no' => (string) ($booking['invoice_no'] ?? ''),
'kind' => (string) $booking['kind'],
'customer_name' => (string) $booking['customer_name'],
'street' => (string) $booking['street'],

View file

@ -6,13 +6,15 @@ declare(strict_types=1);
*
* Wird beim täglichen Erinnerungslauf (Cron) ausgeführt und hält die
* Speicherdauer kurz, die in der Datenschutzerklärung zugesagt wird:
* Login-Fehlversuche, abgelaufene Remember-Tokens und alte Versandprotokolle.
* Login-Fehlversuche, abgelaufene Remember-Tokens, verbrauchte Einladungen
* und alte Versandprotokolle.
*/
function privacy_cleanup(): array
{
$result = [
'login_attempts' => 0,
'auth_tokens' => 0,
'user_invites' => 0,
'reminder_mail_log' => 0,
'reminder_push_log' => 0,
'log_rotated' => false,
@ -27,6 +29,11 @@ function privacy_cleanup(): array
'DELETE FROM auth_tokens WHERE expires_at < ?',
[utc_now()]
);
// Einladungen nur bis zum Verfall bzw. nach dem Einlösen aufbewahren.
$result['user_invites'] = privacy_delete(
'DELETE FROM user_invites WHERE expires_at < ? OR used_at IS NOT NULL',
[utc_now()]
);
$result['reminder_mail_log'] = privacy_delete(
'DELETE FROM reminder_mail_log WHERE sent_at < ?',
[utc_after(-365 * 86400)]

View file

@ -89,7 +89,7 @@ function url(string $path = '/'): string
}
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
const DIC_ASSET_VERSION = '9';
const DIC_ASSET_VERSION = '16';
function asset(string $path): string
{
@ -260,6 +260,55 @@ function date_obj(string $iso): DateTimeImmutable
return new DateTimeImmutable($iso . ' 12:00:00', new DateTimeZone('Europe/Berlin'));
}
/** Uhrzeit als "HH:MM" normalisieren; leer bleibt leer (optional). */
function normalize_time(mixed $value): string
{
$text = trim((string) $value);
if ($text === '') {
return '';
}
if (preg_match('/^(\d{1,2}):(\d{2})(?::\d{2})?$/', $text, $match) === 1) {
return sprintf('%02d:%02d', (int) $match[1], (int) $match[2]);
}
return $text;
}
/** Leere Uhrzeit wird in der Datenbank als NULL gespeichert. */
function null_if_empty(string $value): ?string
{
return $value === '' ? null : $value;
}
/** Leere Uhrzeit ist erlaubt – sie ist ein optionales Zusatzfeld. */
function valid_time(?string $time): bool
{
if ($time === null || $time === '') {
return true;
}
return preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) === 1;
}
function fmt_time(?string $time): string
{
$value = normalize_time($time);
return $value !== '' && valid_time($value) ? $value : '';
}
/** Datum mit optionaler Uhrzeit, z. B. "30.11.2026 14:00". */
function fmt_date_with_time(string $iso, ?string $time): string
{
$clock = fmt_time($time);
return $clock === '' ? fmt_date($iso) : fmt_date($iso) . ' ' . $clock;
}
/** Kurzform für Listen/Kopiertext: "30.11.26 14:00". */
function fmt_date_short_with_time(string $iso, ?string $time): string
{
$clock = fmt_time($time);
return $clock === '' ? fmt_date_short($iso) : fmt_date_short($iso) . ' ' . $clock;
}
function add_days(string $iso, int $days): string
{
return date_obj($iso)->modify(($days >= 0 ? '+' : '') . $days . ' days')->format('Y-m-d');