drink-it-cold/app/util.php

494 lines
14 KiB
PHP
Raw Normal View History

<?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');
}
}
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 = '17';
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('/')) . '">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');
}
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');
}
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)) . '…';
}