rpg-westreiche/westreiche_website/app/util.php

218 lines
5.8 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/** Westreiche – Basis: Konfiguration, Session, CSRF, Ausgabe, Zeit. */
function config(string $key, mixed $default = null): mixed
{
$value = $GLOBALS['ws_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(): void
{
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
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('WESTREICHE_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 now_local(): string
{
return (new DateTimeImmutable('now', new DateTimeZone('Europe/Berlin')))->format('d.m.Y H:i');
}
function e(mixed $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
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 WS_ASSET_VERSION = '5';
function asset(string $path): string
{
return url('/assets/' . ltrim($path, '/')) . '?v=' . WS_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_int(string $key, int $default = 0): int
{
$value = $_POST[$key] ?? null;
if (is_int($value)) {
return $value;
}
return is_string($value) && preg_match('/^-?\d+$/', trim($value)) === 1 ? (int) $value : $default;
}
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 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'] ?? '';
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
}
function require_post(): void
{
if (!is_post()) {
abort_page(405, 'Diese Aktion erfordert ein Formular.');
}
if (!csrf_valid()) {
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.');
}
}
function abort_page(int $status, string $message): never
{
http_response_code($status);
$user = auth_user();
$title = 'Fehler ' . $status;
$content = '<section class="panel"><h1>' . e($title) . '</h1><p>' . e($message) . '</p>'
. '<p><a class="btn" href="' . e(url('/')) . '">Zurück zur Übersicht</a></p></section>';
require WS_ROOT . '/views/layout.php';
exit;
}
/** Kürzt Text auf eine Zeichenzahl (mb-safe) und ergänzt eine Ellipse. */
function shorten(string $text, int $max): string
{
if (mb_strlen($text, 'UTF-8') <= $max) {
return $text;
}
return rtrim(mb_substr($text, 0, $max - 1, 'UTF-8')) . '…';
}