drink-it-cold/app/util.php
torsten 11bb83c66c feat(legal): AGB als öffentliche Seite und Stilllegung des alten Deploys
- /agb ist ohne Anmeldung erreichbar (legal.php, views/legal.php,
  views/legal_agb.php), Verlinkung auf der Startseite und in der Sitemap.
- Stilllegung: app.retired_url zeigt nur noch einen Umzugsvermerk
  (retired_notice() in util.php, Prüfung in bootstrap.php); Bausteine in
  tools/retire/ und Anleitung in docs/stilllegung-programmschmiede.md.
2026-11-30 15:40:34 +01:00

617 lines
19 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/** Kleine Helfer: Konfiguration, Session, CSRF, Ausgabe, Zeit und Geld. */
function config(string $key, mixed $default = null): mixed
{
$value = $GLOBALS['dic_config'] ?? [];
foreach (explode('.', $key) as $part) {
if (!is_array($value) || !array_key_exists($part, $value)) {
return $default;
}
$value = $value[$part];
}
return $value;
}
function is_https(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
return strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
}
function security_headers(bool $indexable = false): void
{
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
// Impressum/Datenschutz bleiben abrufbar; alles andere ist eine private App.
if (!$indexable) {
header('X-Robots-Tag: noindex, nofollow, noarchive');
}
header('Referrer-Policy: same-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header(
"Content-Security-Policy: default-src 'self'; img-src 'self' data:; "
. "font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; "
. "connect-src 'self'; media-src 'self'; form-action 'self'; "
. "frame-ancestors 'none'; base-uri 'none'"
);
header('Cache-Control: no-store');
if (is_https()) {
header('Strict-Transport-Security: max-age=15552000');
}
}
/**
* Stilllegung: Zeigt nur einen Umzugsvermerk und beendet die Anfrage.
*
* Wird über `app.retired_url` in config.local.php aktiviert – gedacht für ein
* abgelöstes Deployment (z. B. den alten Test-Deploy), das noch erreichbar ist,
* aber keine Anmeldung mehr zulassen soll.
*/
function retired_notice(string $url): void
{
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
header('X-Robots-Tag: noindex, nofollow, noarchive');
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
if (is_https()) {
header('Strict-Transport-Security: max-age=15552000');
}
$target = e($url);
echo '<!doctype html><html lang="de"><head><meta charset="utf-8">'
. '<meta name="viewport" content="width=device-width, initial-scale=1">'
. '<meta name="robots" content="noindex, nofollow">'
. '<title>Umgezogen · ' . e((string) config('legal.business_name', 'Drink it cold')) . '</title>'
. '<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#eef6fd;color:#0e1b26;'
. 'padding:1.5rem;font-family:Manrope,"Segoe UI",system-ui,-apple-system,sans-serif}'
. 'main{max-width:34rem;background:#fff;border-radius:1.25rem;padding:2.5rem 2rem;text-align:center;'
. 'box-shadow:0 1.5rem 3rem rgba(14,27,38,.12)}h1{margin:0 0 1rem;font-size:1.6rem;line-height:1.25}'
. 'p{margin:0 0 1rem;line-height:1.6;color:#38505f}a.btn{display:inline-block;margin-top:.5rem;'
. 'padding:.85rem 1.6rem;border-radius:.7rem;background:#196abc;color:#fff;font-weight:700;'
. 'text-decoration:none}a.btn:hover{background:#12518f}</style></head><body><main>'
. '<h1>Diese Adresse ist umgezogen</h1>'
. '<p>Die Terminplanung finden Sie ab sofort unter <strong>' . $target . '</strong>. '
. 'Diese Adresse wird nicht mehr genutzt.</p>'
. '<p><a class="btn" href="' . $target . '">Weiter zur aktuellen Seite</a></p>'
. '</main></body></html>';
}
function start_session(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
$absolute = (int) config('app.session_absolute_seconds', 7776000);
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.cookie_secure', is_https() ? '1' : '0');
ini_set('session.cookie_path', '/');
ini_set('session.gc_maxlifetime', (string) $absolute);
session_name('DIC_SESSION');
session_start();
}
function utc_now(): string
{
return gmdate('Y-m-d H:i:s');
}
function utc_after(int $seconds): string
{
return gmdate('Y-m-d H:i:s', time() + $seconds);
}
function e(mixed $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function e_attr(mixed $value): string
{
return e($value);
}
function url(string $path = '/'): string
{
$base = rtrim((string) config('app.base_path', ''), '/');
if ($path === '' || $path[0] !== '/') {
$path = '/' . $path;
}
return $base . $path;
}
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
const DIC_ASSET_VERSION = '29';
function asset(string $path): string
{
return url('/assets/' . ltrim($path, '/')) . '?v=' . DIC_ASSET_VERSION;
}
function redirect(string $path, int $status = 303): never
{
header('Location: ' . url($path), true, $status);
exit;
}
function current_path(): string
{
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
$base = rtrim((string) config('app.base_path', ''), '/');
if ($base !== '' && str_starts_with($path, $base)) {
$path = substr($path, strlen($base));
}
return '/' . trim($path, '/');
}
function client_ip(): string
{
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
}
function request_method(): string
{
return strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
}
function is_post(): bool
{
return request_method() === 'POST';
}
function post_string(string $key, string $default = ''): string
{
$value = $_POST[$key] ?? $default;
return is_string($value) ? trim($value) : $default;
}
function post_array(string $key): array
{
$value = $_POST[$key] ?? [];
return is_array($value) ? $value : [];
}
function query_string(string $key, string $default = ''): string
{
$value = $_GET[$key] ?? $default;
return is_string($value) ? trim($value) : $default;
}
function query_int(string $key, int $default = 0): int
{
$value = $_GET[$key] ?? null;
return is_numeric($value) ? (int) $value : $default;
}
function wants_json(): bool
{
$accept = strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? ''));
return str_contains($accept, 'application/json')
|| strtolower((string) ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === 'fetch';
}
function json_response(array $payload, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function flash(string $type, string $message): void
{
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
}
function flash_pull(): array
{
$items = $_SESSION['flash'] ?? [];
unset($_SESSION['flash']);
return is_array($items) ? $items : [];
}
function csrf_token(): string
{
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return (string) $_SESSION['csrf'];
}
function csrf_field(): string
{
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
}
function csrf_valid(): bool
{
$sent = $_POST['_csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
}
function require_post(): void
{
if (!is_post()) {
abort_page(405, 'Diese Aktion ist nur per POST möglich.');
}
if (!csrf_valid()) {
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte die Seite neu laden und erneut versuchen.');
}
}
/** Nur lokale Pfade als Rücksprungziel zulassen. */
function safe_next(string $next, string $fallback = '/'): string
{
$next = trim($next);
if ($next === '' || $next[0] !== '/' || str_starts_with($next, '//') || str_contains($next, '\\')) {
return $fallback;
}
return $next;
}
function abort_page(int $code, string $message): never
{
http_response_code($code);
$titles = [403 => 'Kein Zugriff', 404 => 'Nicht gefunden', 405 => 'Nicht erlaubt', 419 => 'Sitzung abgelaufen'];
$title = $titles[$code] ?? 'Fehler';
header('Content-Type: text/html; charset=utf-8');
echo '<!doctype html><html lang="de"><head><meta charset="utf-8">'
. '<meta name="viewport" content="width=device-width, initial-scale=1">'
. '<title>' . e($title) . ' · Drink it cold</title>'
. '<link rel="stylesheet" href="' . e(asset('app.css')) . '"></head>'
. '<body class="error-page"><div class="error-card">'
. '<img src="' . e(asset('logo-mark.svg')) . '" alt="" width="64" height="46">'
. '<p class="eyebrow">Drink it cold · Terminplanung</p>'
. '<h1>' . e($title) . '</h1><p>' . e($message) . '</p>'
. '<p><a class="btn primary" href="' . e(url('/dashboard')) . '">Zur Übersicht</a></p>'
. '<p class="muted small"><a href="' . e(url('/impressum')) . '">Impressum</a>'
. ' · <a href="' . e(url('/datenschutz')) . '">Datenschutz</a></p>'
. '</div></body></html>';
exit;
}
/* ---------------------------------------------------------------- Datum */
function today_iso(): string
{
return date('Y-m-d');
}
function valid_date(?string $iso): bool
{
if ($iso === null || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $iso)) {
return false;
}
[$y, $m, $d] = array_map('intval', explode('-', $iso));
return checkdate($m, $d, $y);
}
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');
}
function days_between(string $from, string $to): int
{
return (int) date_obj($from)->diff(date_obj($to))->format('%r%a');
}
function week_start(string $iso): string
{
$date = date_obj($iso);
$weekday = (int) $date->format('N');
return $date->modify('-' . ($weekday - 1) . ' days')->format('Y-m-d');
}
/** Anzahl der Kalenderwochen, die die Kalenderansicht standardmäßig zeigt. */
const CALENDAR_WEEKS = 4;
/**
* Auf Smartphones wird zusätzlich Zeitraum vor/nach der Startwoche gerendert,
* damit sich der Kalender seitlich durchwischen lässt (in Monaten).
*/
const CALENDAR_MOBILE_MONTHS = 2;
/** Grobe Geräteerkennung: schmale Touch-Geräte bekommen den erweiterten Kalender. */
function client_is_mobile(): bool
{
$agent = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
return $agent !== '' && preg_match('/Android|iPhone|iPod|Windows Phone|IEMobile|Opera Mini|Mobile Safari|Mobile\//i', $agent) === 1;
}
function month_start(string $iso): string
{
return date_obj($iso)->modify('first day of this month')->format('Y-m-d');
}
function month_end(string $iso): string
{
return date_obj($iso)->modify('last day of this month')->format('Y-m-d');
}
/* ------------------------------------------------------------------ Feiertage */
/**
* Ostersonntag nach der anonymen gregorianischen Osterformel. Bewusst ohne
* `easter_date()`, damit keine zusätzliche PHP-Extension nötig ist.
*/
function easter_sunday(int $year): string
{
$a = $year % 19;
$b = intdiv($year, 100);
$c = $year % 100;
$d = intdiv($b, 4);
$e = $b % 4;
$f = intdiv($b + 8, 25);
$g = intdiv($b - $f + 1, 3);
$h = (19 * $a + $b - $d - $g + 15) % 30;
$i = intdiv($c, 4);
$k = $c % 4;
$l = (32 + 2 * $e + 2 * $i - $h - $k) % 7;
$m = intdiv($a + 11 * $h + 22 * $l, 451);
$month = intdiv($h + $l - 7 * $m + 114, 31);
$day = (($h + $l - 7 * $m + 114) % 31) + 1;
return sprintf('%04d-%02d-%02d', $year, $month, $day);
}
/**
* Gesetzliche Feiertage in Nordrhein-Westfalen als `['Y-m-d' => Name]`.
* Grundlage für die farbliche Markierung im Kalender (Wochenenden und
* Feiertage werden preislich anders berechnet).
*/
function holidays_nrw(int $year): array
{
static $cache = [];
if (isset($cache[$year])) {
return $cache[$year];
}
$easter = easter_sunday($year);
$map = [
sprintf('%04d-01-01', $year) => 'Neujahr',
add_days($easter, -2) => 'Karfreitag',
add_days($easter, 1) => 'Ostermontag',
sprintf('%04d-05-01', $year) => 'Tag der Arbeit',
add_days($easter, 39) => 'Christi Himmelfahrt',
add_days($easter, 50) => 'Pfingstmontag',
add_days($easter, 60) => 'Fronleichnam',
sprintf('%04d-10-03', $year) => 'Tag der Deutschen Einheit',
sprintf('%04d-11-01', $year) => 'Allerheiligen',
sprintf('%04d-12-25', $year) => '1. Weihnachtstag',
sprintf('%04d-12-26', $year) => '2. Weihnachtstag',
];
ksort($map);
$cache[$year] = $map;
return $map;
}
/** Name des Feiertags am Datum oder `null`, wenn kein gesetzlicher Feiertag (NRW). */
function holiday_name(string $iso): ?string
{
if (!valid_date($iso)) {
return null;
}
return holidays_nrw((int) substr($iso, 0, 4))[$iso] ?? null;
}
function is_holiday(string $iso): bool
{
return holiday_name($iso) !== null;
}
function fmt_date(string $iso): string
{
return valid_date($iso) ? date_obj($iso)->format('d.m.Y') : '–';
}
function fmt_date_short(string $iso): string
{
return valid_date($iso) ? date_obj($iso)->format('d.m.y') : '–';
}
function fmt_date_long(string $iso): string
{
if (!valid_date($iso)) {
return '–';
}
$days = ['', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
$months = ['', 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
$date = date_obj($iso);
return $days[(int) $date->format('N')] . ', ' . (int) $date->format('j') . '. ' . $months[(int) $date->format('n')] . ' ' . $date->format('Y');
}
function fmt_month(string $iso): string
{
$months = ['', 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
return $months[(int) date_obj($iso)->format('n')] . ' ' . date_obj($iso)->format('Y');
}
function fmt_month_short(string $iso): string
{
$months = ['', 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
return $months[(int) date_obj($iso)->format('n')];
}
function fmt_weekday_short(string $iso): string
{
$days = ['', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
return $days[(int) date_obj($iso)->format('N')];
}
function fmt_date_range(string $from, string $to): string
{
if ($from === $to) {
return fmt_date($from);
}
if (date_obj($from)->format('Y-m') === date_obj($to)->format('Y-m')) {
return (int) date_obj($from)->format('j') . '.–' . fmt_date($to);
}
return fmt_date($from) . ' – ' . fmt_date($to);
}
function fmt_datetime(?string $utc): string
{
if ($utc === null || $utc === '') {
return '–';
}
try {
$date = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
return $date->setTimezone(new DateTimeZone('Europe/Berlin'))->format('d.m.Y H:i');
} catch (Throwable) {
return '–';
}
}
function relative_day(string $iso): string
{
$diff = days_between(today_iso(), $iso);
return match (true) {
$diff === 0 => 'Heute',
$diff === 1 => 'Morgen',
$diff === -1 => 'Gestern',
$diff < 0 => abs($diff) . ' Tage überfällig',
default => 'in ' . $diff . ' Tagen',
};
}
function greeting(): string
{
$hour = (int) date('G');
if ($hour < 11) {
return 'Guten Morgen';
}
if ($hour < 18) {
return 'Guten Tag';
}
return 'Guten Abend';
}
/* ---------------------------------------------------------------- Geld */
function fmt_money(int $cents): string
{
return number_format($cents / 100, 2, ',', '.') . ' €';
}
function parse_money(string $value): int
{
$value = trim($value);
$value = str_replace(["\u{00A0}", ' ', '€', 'EUR'], '', $value);
$value = preg_replace('/[^0-9,.\-]/u', '', $value) ?? '';
if ($value === '' || $value === '-') {
return 0;
}
if (str_contains($value, ',')) {
$value = str_replace('.', '', $value);
$value = str_replace(',', '.', $value);
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $value) === 1) {
$value = str_replace('.', '', $value);
}
return (int) round((float) $value * 100);
}
function due_cents(int $total, int $deposit): int
{
return $total - $deposit;
}
/** Lesbare Textfarbe für eine Anhängerfarbe. */
function contrast_color(string $hex): string
{
$hex = ltrim($hex, '#');
if (strlen($hex) !== 6) {
return '#ffffff';
}
$r = hexdec(substr($hex, 0, 2)) / 255;
$g = hexdec(substr($hex, 2, 2)) / 255;
$b = hexdec(substr($hex, 4, 2)) / 255;
$channel = static function (float $c): float {
return $c <= 0.03928 ? $c / 12.92 : (($c + 0.055) / 1.055) ** 2.4;
};
$luminance = 0.2126 * $channel($r) + 0.7152 * $channel($g) + 0.0722 * $channel($b);
return $luminance > 0.46 ? '#10202c' : '#ffffff';
}
function initials(string $name): string
{
$parts = preg_split('/\s+/', trim($name)) ?: [];
$out = '';
foreach (array_slice($parts, 0, 2) as $part) {
if ($part !== '') {
$out .= mb_strtoupper(mb_substr($part, 0, 1));
}
}
return $out !== '' ? $out : '?';
}
function truncate(string $value, int $length): string
{
if (mb_strlen($value) <= $length) {
return $value;
}
return mb_substr($value, 0, max(0, $length - 1)) . '…';
}