rpg-westreiche/westreiche_website/app/portrait.php

177 lines
6.3 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);
/**
* Westreiche – Charakterporträts.
*
* Hochgeladene Bilder werden serverseitig über GD neu kodiert (JPEG, max.
* 900 px Kantenlänge). Das entfernt Metadaten, verhindert eingeschleuste
* Dateiinhalte und hält die Dateien klein. Ohne Upload greift ein gemaltes
* Platzhalterporträt der jeweiligen Klasse aus assets/portraits/.
*/
const WS_PORTRAIT_REL_DIR = 'uploads/portraits';
const WS_PORTRAIT_MAX_BYTES = 5 * 1024 * 1024;
const WS_PORTRAIT_MAX_EDGE = 900;
/** Dateiname-Stamm einer Klasse (Kämpfer → kaempfer). */
function portrait_class_slug(string $className): string
{
$slug = mb_strtolower($className, 'UTF-8');
$slug = str_replace(['ä', 'ö', 'ü', 'ß'], ['ae', 'oe', 'ue', 'ss'], $slug);
$slug = preg_replace('/[^a-z0-9]+/', '-', $slug) ?? '';
return trim($slug, '-');
}
function portrait_dir(): string
{
return WS_ROOT . '/' . WS_PORTRAIT_REL_DIR;
}
function portrait_placeholder_rel(string $className): string
{
$slug = portrait_class_slug($className);
$rel = 'assets/portraits/' . $slug . '.webp';
return is_file(WS_ROOT . '/' . $rel) ? $rel : '';
}
/** Anzeige-URL: eigenes Bild, sonst Platzhalter der Klasse, sonst leer. */
function portrait_url(array $character): string
{
$stored = (string) ($character['portrait'] ?? '');
if ($stored !== '' && is_file(WS_ROOT . '/' . ltrim($stored, '/'))) {
return url('/' . ltrim($stored, '/'));
}
$placeholder = portrait_placeholder_rel((string) ($character['class_name'] ?? ''));
return $placeholder === '' ? '' : url('/' . $placeholder);
}
/**
* Nimmt ein hochgeladenes Bild an, kodiert es neu und speichert den Pfad.
*
* @param array{name?:string,type?:string,tmp_name?:string,error?:int,size?:int} $file
* @return array{ok: bool, error: string}
*/
function portrait_upload(int $characterId, array $file): array
{
$error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE);
if ($error === UPLOAD_ERR_NO_FILE) {
return ['ok' => false, 'error' => 'Bitte eine Bilddatei auswählen.'];
}
if ($error === UPLOAD_ERR_INI_SIZE || $error === UPLOAD_ERR_FORM_SIZE) {
return ['ok' => false, 'error' => 'Das Bild ist zu groß (höchstens 5 MB).'];
}
if ($error !== UPLOAD_ERR_OK) {
return ['ok' => false, 'error' => 'Der Upload ist fehlgeschlagen (Code ' . $error . ').'];
}
$tmp = (string) ($file['tmp_name'] ?? '');
if ($tmp === '' || !is_uploaded_file($tmp)) {
return ['ok' => false, 'error' => 'Der Upload konnte nicht geprüft werden.'];
}
if ((int) ($file['size'] ?? 0) > WS_PORTRAIT_MAX_BYTES) {
return ['ok' => false, 'error' => 'Das Bild ist zu groß (höchstens 5 MB).'];
}
if (!function_exists('imagecreatefromstring')) {
return ['ok' => false, 'error' => 'Auf dem Server fehlt die GD-Erweiterung.'];
}
$info = @getimagesize($tmp);
if ($info === false || !in_array($info[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP], true)) {
return ['ok' => false, 'error' => 'Nur JPEG, PNG oder WebP werden angenommen.'];
}
$image = @imagecreatefromstring((string) file_get_contents($tmp));
if ($image === false) {
return ['ok' => false, 'error' => 'Das Bild konnte nicht gelesen werden.'];
}
$width = imagesx($image);
$height = imagesy($image);
$scale = min(1.0, WS_PORTRAIT_MAX_EDGE / max($width, $height));
$newWidth = max(1, (int) round($width * $scale));
$newHeight = max(1, (int) round($height * $scale));
$canvas = imagecreatetruecolor($newWidth, $newHeight);
// JPEG kennt keine Transparenz – weißer Grund statt schwarzer Flächen.
$white = imagecolorallocate($canvas, 250, 245, 230);
imagefilledrectangle($canvas, 0, 0, $newWidth, $newHeight, $white);
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagedestroy($image);
$dir = portrait_dir();
if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
imagedestroy($canvas);
return ['ok' => false, 'error' => 'Der Bildordner konnte nicht angelegt werden.'];
}
$fileName = sprintf('c%d-%s.jpg', $characterId, bin2hex(random_bytes(6)));
$absolute = $dir . '/' . $fileName;
$saved = imagejpeg($canvas, $absolute, 86);
imagedestroy($canvas);
if (!$saved) {
return ['ok' => false, 'error' => 'Das Bild konnte nicht gespeichert werden.'];
}
portrait_delete_file((string) current_portrait((int) $characterId));
db()->prepare('UPDATE characters SET portrait = ?, updated_at = ? WHERE id = ?')
->execute([WS_PORTRAIT_REL_DIR . '/' . $fileName, utc_now(), $characterId]);
return ['ok' => true, 'error' => ''];
}
function current_portrait(int $characterId): string
{
$stmt = db()->prepare('SELECT portrait FROM characters WHERE id = ? LIMIT 1');
$stmt->execute([$characterId]);
return (string) ($stmt->fetchColumn() ?: '');
}
function portrait_remove(int $characterId): void
{
portrait_delete_file(current_portrait($characterId));
db()->prepare('UPDATE characters SET portrait = \'\', updated_at = ? WHERE id = ?')
->execute([utc_now(), $characterId]);
}
function portrait_delete_file(string $relPath): void
{
$relPath = ltrim($relPath, '/');
if ($relPath === '' || !str_starts_with($relPath, WS_PORTRAIT_REL_DIR . '/')) {
return;
}
$absolute = WS_ROOT . '/' . $relPath;
if (is_file($absolute)) {
@unlink($absolute);
}
}
/**
* JPEG-Bytes für den PDF-Export: eigenes Bild direkt, Platzhalter (WebP)
* wird über GD in JPEG umgewandelt.
*/
function portrait_jpeg_bytes(array $character): string
{
$stored = (string) ($character['portrait'] ?? '');
if ($stored !== '' && is_file(WS_ROOT . '/' . ltrim($stored, '/'))) {
$bytes = (string) file_get_contents(WS_ROOT . '/' . ltrim($stored, '/'));
if (strncmp($bytes, "\xFF\xD8", 2) === 0) {
return $bytes;
}
}
$placeholder = portrait_placeholder_rel((string) ($character['class_name'] ?? ''));
if ($placeholder === '' || !function_exists('imagecreatefromwebp')) {
return '';
}
$image = @imagecreatefromwebp(WS_ROOT . '/' . $placeholder);
if ($image === false) {
return '';
}
ob_start();
imagejpeg($image, null, 88);
$bytes = (string) ob_get_clean();
imagedestroy($image);
return $bytes;
}