rinkplanner/hub/app/util.php

334 lines
8.8 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
/**
* Kleine Helfer: Konfiguration, Session, CSRF, Ausgabe, Zeit und Dateien.
*/
function config(string $key, mixed $default = null): mixed
{
$value = $GLOBALS['hub_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:; "
. "style-src 'self'; script-src 'none'; 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', 2592000);
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('RHUB_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 url(string $path = '/'): string
{
$base = rtrim((string) config('app.base_path', ''), '/');
if ($path === '' || $path[0] !== '/') {
$path = '/' . $path;
}
return $base . $path;
}
/** Cache-Buster für /assets/: bei Änderungen an hub.css erhöhen. */
const HUB_ASSET_VERSION = '3';
function redirect(string $path, int $status = 303): never
{
header('Location: ' . url($path), true, $status);
exit;
}
function client_ip(): string
{
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
}
function user_agent(): string
{
return substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
}
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 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 e_attr(mixed $value): string
{
return e($value);
}
function fmt_dt(?string $utc): string
{
if ($utc === null || $utc === '') {
return '–';
}
try {
$date = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
$format = hub_locale() === 'en' ? 'Y-m-d H:i' : 'd.m.Y H:i';
return $date->setTimezone(new DateTimeZone('Europe/Berlin'))->format($format);
} catch (Throwable) {
return '–';
}
}
/** Zahl mit den Trennzeichen der aktuellen Sprache. */
function fmt_number(float $value, int $decimals = 1): string
{
if (hub_locale() === 'en') {
return number_format($value, $decimals, '.', ',');
}
return number_format($value, $decimals, ',', '.');
}
function human_bytes(int|float|null $bytes): string
{
$bytes = (float) ($bytes ?? 0);
if ($bytes < 1024) {
return fmt_number($bytes, 0) . ' B';
}
$units = ['KB', 'MB', 'GB'];
$index = -1;
do {
$bytes /= 1024;
$index++;
} while ($bytes >= 1024 && $index < count($units) - 1);
return fmt_number($bytes, 1) . ' ' . $units[$index];
}
function truncate_text(string $value, int $length): string
{
if (mb_strlen($value, 'UTF-8') <= $length) {
return $value;
}
return mb_substr($value, 0, max(0, $length - 1), 'UTF-8') . '…';
}
function clean_filename(string $name): string
{
$name = basename(str_replace('\\', '/', $name));
$name = preg_replace('/[\x00-\x1F\x7F]/u', '', $name) ?? '';
$name = trim($name);
if ($name === '' || $name === '.' || $name === '..') {
return 'datei';
}
return mb_substr($name, 0, 190, 'UTF-8');
}
/** Dateiname für Content-Disposition: ASCII-Fallback plus UTF-8-Variante. */
function content_disposition(string $filename): string
{
$filename = clean_filename($filename);
$ascii = preg_replace('/[^\x20-\x7E]/', '_', $filename) ?? 'datei';
$ascii = str_replace(['"', '\\', ';'], '_', $ascii);
return 'attachment; filename="' . $ascii . '"; filename*=UTF-8\'\'' . rawurlencode($filename);
}
function flash(string $type, string $message): void
{
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
}
function flash_secret(string $label, string $value): void
{
$_SESSION['flash'][] = ['type' => 'secret', 'label' => $label, 'value' => $value];
}
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 csrf_require(): void
{
if (!csrf_valid()) {
abort_page(419, t('auth.session_expired'));
}
}
function wants_json(): bool
{
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
return str_starts_with($path, '/api/')
|| str_contains(strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), 'application/json');
}
function json_response(mixed $data, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function json_input(): array
{
$raw = file_get_contents('php://input');
if (is_string($raw) && $raw !== '') {
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
return $decoded;
}
}
return $_POST;
}
function render(string $view, array $data = []): string
{
$file = HUB_ROOT . '/views/' . $view . '.php';
if (!is_file($file)) {
throw new RuntimeException('View fehlt: ' . $view);
}
extract($data, EXTR_SKIP);
ob_start();
require $file;
return (string) ob_get_clean();
}
function render_page(string $view, array $data = [], ?string $title = null): void
{
$content = render($view, $data);
echo render('layout', [
'title' => $title ?? t('page.title_default'),
'content' => $content,
'user' => auth_user(),
]);
}
function abort_page(int $status, string $message): never
{
http_response_code($status);
$content = render('error', ['status' => $status, 'message' => $message]);
echo render('layout', [
'title' => t('page.title_error', ['status' => $status]),
'content' => $content,
'user' => auth_user(),
]);
exit;
}
function abort_api(int $status, string $code, string $message): never
{
json_response(['error' => ['code' => $code, 'message' => $message]], $status);
}
function password_policy_error(string $password, string $username = ''): ?string
{
$length = mb_strlen($password, 'UTF-8');
if ($length < 10) {
return t('password.min');
}
if ($length > 200) {
return t('password.max');
}
if ($username !== '' && mb_strtolower($password) === mb_strtolower($username)) {
return t('password.same_as_username');
}
return null;
}
function hub_log(string $message): void
{
error_log('Hub: ' . $message);
}