LuminaWebsite/includes/gear.php
Maaxxs 5dabbccbd7 Gear planner, dashboard polish, images on bug reports
Gear planner:
- Personal gear sets (18 slots) with enchant, exceed, soul imprint and manastones,
  stat totals by source and side-by-side comparison of 2-4 sets
- Sets can be shown on the own profile page (read-only for other members)
- Admin catalog: import items from aion2hub.com (Global client), compare stored
  values with the source one by one or all at once, at most one request per second
- New permissions gear.view (all with dashboard access) and gear.manage

Dashboard:
- Role badges ordered like the member list (roster_order)
- Stronger hover effect on "Rangliste & Verlauf" / "Zum Lumishop", no more blue
  hover on secondary buttons
- "Anstehende Raids" box links to the raids page, next raids link to the raid
  and to the calendar day
- Raid attendance only knows present/absent (old "excused" entries count as unset)

Bug reports:
- Up to 5 images per report, pasting copied images with Ctrl+V (also for the gallery)
- Images are only served to the reporter and bugs.manage via bug_image.php

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 09:27:09 +02:00

459 lines
18 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);
/**
* Gear-Planer: persoenliche Ausruestungssets (Gegenstand je Slot, Aufwertung, Durchbruch,
* Seelenpraegung, Manasteine) und der Katalog der Gegenstaende mit ihren Werten.
*
* Der Katalog kommt von aion2hub.com (Global-Client, siehe includes/gear_source.php) und wird
* von Admins unter /admin/gear_items.php uebernommen und abgeglichen. Verlaesslich sind die
* Grundwerte, die Sockel und die Werte bei maximaler Aufwertung/Durchbruch - Zwischenstufen
* rechnen wir gleichmaessig hoch und kennzeichnen sie als geschaetzt (≈). Seelenpraegung und
* Manasteine sind im Spiel zufaellig, die traegt jedes Mitglied so ein, wie sie gewuerfelt wurden.
*/
require_once __DIR__ . '/gear_source.php';
const GEAR_ICON_DIR = __DIR__ . '/../assets/uploads/gear/';
const GEAR_ICON_URL = '/assets/uploads/gear/';
const GEAR_MAX_SETS = 20;
/**
* Slots eines Sets: Schluessel => [Beschriftung, Gruppe, erlaubte Slots laut aion2hub].
* Ohrringe, Ringe und Armbaender gibt es doppelt.
*/
const GEAR_SLOTS = [
'main_hand' => ['Haupthand', 'Waffen', ['MainHand']],
'off_hand' => ['Nebenhand', 'Waffen', ['SubHand', 'MainHand']],
'head' => ['Kopf', 'Rüstung', ['Helmet']],
'shoulder' => ['Schultern', 'Rüstung', ['Shoulder']],
'torso' => ['Brust', 'Rüstung', ['Torso']],
'gloves' => ['Hände', 'Rüstung', ['Gloves']],
'pants' => ['Beine', 'Rüstung', ['Pants']],
'boots' => ['Füße', 'Rüstung', ['Boots']],
'cape' => ['Umhang', 'Rüstung', ['Cape']],
'necklace' => ['Halskette', 'Schmuck', ['Necklace']],
'earring_1' => ['Ohrring 1', 'Schmuck', ['Earring']],
'earring_2' => ['Ohrring 2', 'Schmuck', ['Earring']],
'ring_1' => ['Ring 1', 'Schmuck', ['Ring']],
'ring_2' => ['Ring 2', 'Schmuck', ['Ring']],
'bracelet_1' => ['Armband 1', 'Schmuck', ['Bracelet']],
'bracelet_2' => ['Armband 2', 'Schmuck', ['Bracelet']],
'belt' => ['Gürtel', 'Schmuck', ['Belt']],
'amulet' => ['Amulett', 'Schmuck', ['Amulet']],
];
// In der Nebenhand: Schilde & Co. (SubHand) und Einhandwaffen fuer zwei Waffen
const GEAR_OFFHAND_WEAPON_TYPES = ['Sword', 'Dagger', 'Mace'];
// Seltenheit: Reihenfolge und CSS-Klasse (Farbe)
const GEAR_GRADES = ['Common' => 'common', 'Rare' => 'rare', 'Epic' => 'epic', 'Unique' => 'unique', 'Heroic' => 'heroic', 'Special' => 'special'];
// Herkunft eines Wertes in der Summe
const GEAR_SOURCES = [
'base' => 'Grundwerte',
'enchant' => 'Aufwertung',
'exceed' => 'Durchbruch',
'soul' => 'Seelenprägung',
'manastone' => 'Manasteine',
];
// Diese Werte stehen in der Summe oben, der Rest folgt in der Reihenfolge des Auftretens
const GEAR_STAT_ORDER = ['Min Attack', 'Max Attack', 'Attack', 'Defense', 'HP', 'MP', 'Accuracy', 'Critical Hit', 'Critical Attack', 'Evasion', 'Block', 'Critical Hit Resist'];
// Beschriftungen der Felder beim Abgleich
const GEAR_FIELD_LABELS = [
'name' => 'Name', 'grade' => 'Seltenheit', 'item_level' => 'Gegenstandsstufe', 'required_level' => 'Benötigte Stufe',
'slot' => 'Slot', 'item_type' => 'Art', 'stats' => 'Grundwerte', 'soul_imprint' => 'Seelenprägung (Spannen)',
'soul_imprint_count' => 'Seelenprägung (Anzahl)', 'manastone_slots' => 'Manastein-Sockel', 'godstone_slots' => 'Götterstein-Sockel',
'enchant_max' => 'Aufwertung bis', 'enchant_stats' => 'Aufwertung (Maximum)', 'exceed_max' => 'Durchbruch bis', 'exceed_stats' => 'Durchbruch (Maximum)',
];
// Felder, die als JSON in gear_items.data liegen
const GEAR_DATA_FIELDS = ['stats', 'soul_imprint', 'soul_imprint_count', 'manastone_slots', 'godstone_slots', 'enchant_max', 'enchant_stats', 'exceed_max', 'exceed_stats'];
// ---- Katalog ----
/** Zeile aus gear_items mit ausgepackten Werten. */
function gear_item_decode(array $row): array
{
$data = json_decode((string) ($row['data'] ?? ''), true) ?: [];
foreach (GEAR_DATA_FIELDS as $field) {
$row[$field] = $data[$field] ?? (in_array($field, ['stats', 'soul_imprint', 'enchant_stats', 'exceed_stats'], true) ? [] : 0);
}
unset($row['data']);
return $row;
}
/** @return array<int, array> Gegenstaende nach ID */
function gear_items_by_ids(array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
if (!$ids) {
return [];
}
$stmt = db()->prepare('SELECT * FROM gear_items WHERE id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')');
$stmt->execute($ids);
$items = [];
foreach ($stmt->fetchAll() as $row) {
$items[(int) $row['id']] = gear_item_decode($row);
}
return $items;
}
function gear_item(int $id): ?array
{
return gear_items_by_ids([$id])[$id] ?? null;
}
function gear_icon_url(?array $item): ?string
{
return !empty($item['icon']) ? GEAR_ICON_URL . rawurlencode((string) $item['icon']) : null;
}
function gear_grade_class(?string $grade): string
{
return 'grade-' . (GEAR_GRADES[$grade ?? ''] ?? 'common');
}
/** Passt ein Katalog-Gegenstand in diesen Slot eines Sets? */
function gear_item_fits_slot(array $item, string $slotKey): bool
{
if (!isset(GEAR_SLOTS[$slotKey]) || !in_array($item['slot'], GEAR_SLOTS[$slotKey][2], true)) {
return false;
}
if ($slotKey === 'off_hand' && $item['slot'] === 'MainHand') {
return in_array($item['item_type'], GEAR_OFFHAND_WEAPON_TYPES, true);
}
return true;
}
/** Eintraege fuer die Suchliste (assets/js/item-picker.js) eines Slots. */
function gear_picker_items(string $slotKey): array
{
$slots = GEAR_SLOTS[$slotKey][2] ?? [];
if (!$slots) {
return [];
}
$stmt = db()->prepare(
'SELECT id, name, slot, item_type, grade, item_level, icon FROM gear_items
WHERE slot IN (' . implode(',', array_fill(0, count($slots), '?')) . ') ORDER BY item_level DESC, name'
);
$stmt->execute($slots);
$rows = array_values(array_filter($stmt->fetchAll(), static fn (array $row): bool => gear_item_fits_slot($row, $slotKey)));
// Gleiche Namen (z.B. zwei Varianten) auseinanderhalten - die Suchliste waehlt ueber den Namen
$names = array_count_values(array_column($rows, 'name'));
return array_map(static fn (array $row): array => [
'id' => (int) $row['id'],
'name' => $names[$row['name']] > 1 ? $row['name'] . ' (Stufe ' . (int) $row['item_level'] . ', #' . (int) $row['id'] . ')' : $row['name'],
'icon' => gear_icon_url($row),
'category' => $row['grade'] . ' · Stufe ' . (int) $row['item_level'] . ($row['item_type'] !== $row['slot'] ? ' · ' . $row['item_type'] : ''),
], $rows);
}
/**
* Werte, die fuer Manasteine zur Wahl stehen: alle festen (nicht prozentualen) Werte, die im
* Katalog als Seelenpraegung vorkommen - die Manasteine wuerfeln aus denselben Grundwerten.
*/
function gear_manastone_stats(): array
{
static $stats = null;
if ($stats !== null) {
return $stats;
}
$stats = [];
foreach (db()->query('SELECT data FROM gear_items')->fetchAll(PDO::FETCH_COLUMN) as $json) {
foreach ((json_decode((string) $json, true)['soul_imprint'] ?? []) as $entry) {
if (($entry[3] ?? '') === '' && !str_contains((string) $entry[0], '[')) {
$stats[$entry[0]] = true;
}
}
}
$stats = array_keys($stats);
usort($stats, static function (string $a, string $b): int {
$ia = array_search($a, GEAR_STAT_ORDER, true);
$ib = array_search($b, GEAR_STAT_ORDER, true);
return [$ia === false ? 99 : $ia, $a] <=> [$ib === false ? 99 : $ib, $b];
});
return $stats;
}
/** Wert lesbar: 1.100 / 5,95 % */
function gear_format_value(float $value, string $unit = ''): string
{
$text = floor($value) == $value
? number_format($value, 0, ',', '.')
: rtrim(rtrim(number_format($value, 2, ',', '.'), '0'), ',');
return $text . ($unit === '%' ? ' %' : '');
}
/** Liste [[Name, Wert, Einheit], …] als Text, z.B. fuer den Abgleich. */
function gear_stats_text(array $stats): string
{
return implode(', ', array_map(static fn (array $s): string => $s[0] . ' ' . gear_format_value((float) $s[1], (string) ($s[2] ?? '')), $stats)) ?: '–';
}
/** Spannen der Seelenpraegung als Text. */
function gear_soul_text(array $entries): string
{
return implode(', ', array_map(
static fn (array $s): string => $s[0] . ' ' . gear_format_value((float) $s[1], $s[3]) . '–' . gear_format_value((float) $s[2], $s[3]),
$entries
)) ?: '–';
}
/** Unterschiede zwischen gespeichertem und neu ausgelesenem Gegenstand: [[Feld, alt, neu], …] */
function gear_item_diff(?array $old, array $new): array
{
$diffs = [];
foreach (GEAR_FIELD_LABELS as $field => $label) {
$format = static function ($value) use ($field): string {
if (in_array($field, ['stats', 'enchant_stats', 'exceed_stats'], true)) {
return gear_stats_text((array) $value);
}
if ($field === 'soul_imprint') {
return gear_soul_text((array) $value);
}
return $value === null || $value === '' ? '–' : (string) $value;
};
$before = $old === null ? '–' : $format($old[$field] ?? null);
$after = $format($new[$field] ?? null);
if ($before !== $after) {
$diffs[] = [$label, $before, $after];
}
}
return $diffs;
}
/** Icon von aion2hub laden (einmalig beim Uebernehmen). Gibt den Dateinamen zurueck oder null. */
function gear_icon_download(int $id): ?string
{
try {
$body = gear_source_fetch(GEAR_SOURCE_ICON_URL . $id);
} catch (RuntimeException $e) {
return null;
}
$info = @getimagesizefromstring($body);
$types = [IMAGETYPE_PNG => 'png', IMAGETYPE_WEBP => 'webp', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif'];
if ($info === false || !isset($types[$info[2]]) || strlen($body) > 512 * 1024) {
return null;
}
if (!is_dir(GEAR_ICON_DIR)) {
@mkdir(GEAR_ICON_DIR, 0755, true);
}
$name = $id . '.' . $types[$info[2]];
return @file_put_contents(GEAR_ICON_DIR . $name, $body) !== false ? $name : null;
}
/**
* Ausgelesenen Gegenstand speichern (neu oder aktualisiert).
*
* @return array{new: bool, diffs: array} diffs = was sich gegenueber vorher geaendert hat
*/
function gear_item_store(array $parsed, int $userId): array
{
$id = (int) $parsed['source_id'];
$old = gear_item($id);
$diffs = gear_item_diff($old, $parsed);
$data = json_encode(array_intersect_key($parsed, array_flip(GEAR_DATA_FIELDS)), JSON_UNESCAPED_UNICODE);
$icon = $old['icon'] ?? null;
if (!$icon || !is_file(GEAR_ICON_DIR . $icon)) {
$icon = gear_icon_download($id);
}
db()->prepare(
'INSERT INTO gear_items (id, name, category, slot, item_type, grade, item_level, required_level, data, icon, source_version, checked_at, checked_by, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW())
ON DUPLICATE KEY UPDATE name = VALUES(name), category = VALUES(category), slot = VALUES(slot), item_type = VALUES(item_type),
grade = VALUES(grade), item_level = VALUES(item_level), required_level = VALUES(required_level), data = VALUES(data),
icon = VALUES(icon), source_version = VALUES(source_version), checked_at = NOW(), checked_by = VALUES(checked_by),
updated_at = IF(data <=> VALUES(data) AND name <=> VALUES(name) AND item_level <=> VALUES(item_level), updated_at, NOW())'
)->execute([
$id, $parsed['name'], $parsed['category'], $parsed['slot'], $parsed['item_type'], $parsed['grade'],
$parsed['item_level'], $parsed['required_level'], $data, $icon, mb_substr($parsed['source_version'], 0, 120), $userId,
]);
return ['new' => $old === null, 'diffs' => $old === null ? [] : $diffs];
}
/** Gegenstand bei aion2hub abrufen und auslesen (ohne zu speichern). */
function gear_item_fetch(int $id): array
{
$parsed = gear_source_parse_item(gear_source_fetch(GEAR_SOURCE_ITEM_URL . $id));
if ((int) $parsed['source_id'] !== $id) {
throw new RuntimeException('Die Seite gehört zu einem anderen Gegenstand (#' . (int) $parsed['source_id'] . ').');
}
return $parsed;
}
// ---- Werte berechnen ----
/**
* Werte bei Stufe $level, wenn $atMax die Werte bei der Hoechststufe $max sind. Zwischenstufen
* werden gleichmaessig hochgerechnet (geschaetzt).
*
* @return array<int, array{0: string, 1: float, 2: string, 3: bool}> [Name, Wert, Einheit, geschaetzt]
*/
function gear_scaled_stats(array $atMax, int $level, int $max): array
{
if ($level <= 0 || $max <= 0) {
return [];
}
$level = min($level, $max);
$estimated = $level < $max;
return array_map(static function (array $stat) use ($level, $max, $estimated): array {
$value = (float) $stat[1] * $level / $max;
$value = ($stat[2] ?? '') === '%' ? round($value, 2) : round($value);
return [$stat[0], $value, (string) ($stat[2] ?? ''), $estimated];
}, $atMax);
}
/**
* Alle Werte, die ein belegter Slot beitraegt.
*
* @return array<int, array{source: string, name: string, value: float, unit: string, estimated: bool}>
*/
function gear_slot_contributions(array $slot, array $item): array
{
$out = [];
$add = static function (string $source, string $name, float $value, string $unit, bool $estimated = false) use (&$out): void {
$out[] = ['source' => $source, 'name' => $name, 'value' => $value, 'unit' => $unit, 'estimated' => $estimated];
};
foreach ($item['stats'] as $stat) {
$add('base', $stat[0], (float) $stat[1], (string) $stat[2]);
}
foreach (gear_scaled_stats($item['enchant_stats'], (int) $slot['enchant'], (int) $item['enchant_max']) as $stat) {
$add('enchant', $stat[0], $stat[1], $stat[2], $stat[3]);
}
foreach (gear_scaled_stats($item['exceed_stats'], (int) $slot['exceed'], (int) $item['exceed_max']) as $stat) {
$add('exceed', $stat[0], $stat[1], $stat[2], $stat[3]);
}
$ranges = [];
foreach ($item['soul_imprint'] as $entry) {
$ranges[$entry[0]] = $entry;
}
foreach ($slot['soul_imprint'] as $entry) {
if (isset($ranges[$entry[0]])) {
$add('soul', $entry[0], (float) $entry[1], (string) $ranges[$entry[0]][3]);
}
}
foreach ($slot['manastones'] as $entry) {
$add('manastone', $entry[0], (float) $entry[1], '');
}
return $out;
}
/**
* Summe aller Werte eines Sets.
*
* @return array<string, array{name: string, unit: string, total: float, by: array<string, float>, estimated: bool}>
*/
function gear_set_totals(array $slots): array
{
$totals = [];
foreach ($slots as $slot) {
if (empty($slot['item'])) {
continue;
}
foreach (gear_slot_contributions($slot, $slot['item']) as $c) {
$key = $c['name'] . '|' . $c['unit'];
$totals[$key] ??= ['name' => $c['name'], 'unit' => $c['unit'], 'total' => 0.0, 'by' => [], 'estimated' => false];
$totals[$key]['total'] += $c['value'];
$totals[$key]['by'][$c['source']] = ($totals[$key]['by'][$c['source']] ?? 0) + $c['value'];
$totals[$key]['estimated'] = $totals[$key]['estimated'] || $c['estimated'];
}
}
uksort($totals, static function (string $a, string $b) use ($totals): int {
$ia = array_search($totals[$a]['name'], GEAR_STAT_ORDER, true);
$ib = array_search($totals[$b]['name'], GEAR_STAT_ORDER, true);
return [$ia === false ? 99 : $ia, $totals[$a]['unit'], $a] <=> [$ib === false ? 99 : $ib, $totals[$b]['unit'], $b];
});
return $totals;
}
/** Durchschnittliche Gegenstandsstufe der belegten Slots (grobe Einordnung eines Sets). */
function gear_set_item_level(array $slots): ?float
{
$levels = [];
foreach ($slots as $slot) {
if (!empty($slot['item'])) {
$levels[] = (int) $slot['item']['item_level'];
}
}
return $levels ? array_sum($levels) / count($levels) : null;
}
// ---- Sets ----
function gear_set(int $id): ?array
{
$stmt = db()->prepare(
"SELECT s.*, COALESCE(NULLIF(u.display_name, ''), u.username) AS owner_name
FROM gear_sets s JOIN users u ON u.id = s.user_id WHERE s.id = ?"
);
$stmt->execute([$id]);
return $stmt->fetch() ?: null;
}
/** @return array<int, array> Sets eines Mitglieds (nur die fuers Profil freigegebenen, wenn $profileOnly) */
function gear_sets_for_user(int $userId, bool $profileOnly = false): array
{
$stmt = db()->prepare(
'SELECT * FROM gear_sets WHERE user_id = ?' . ($profileOnly ? ' AND show_on_profile = 1' : '') . ' ORDER BY sort_order, id'
);
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
/** Darf der aktuelle Nutzer das Set ansehen? Eigene immer, fremde nur, wenn aufs Profil freigegeben. */
function gear_can_view_set(array $set): bool
{
$me = current_user();
return $me && ((int) $me['id'] === (int) $set['user_id'] || !empty($set['show_on_profile']));
}
function gear_is_own_set(array $set): bool
{
$me = current_user();
return $me && (int) $me['id'] === (int) $set['user_id'];
}
/**
* Slots mehrerer Sets mit ihren Gegenstaenden.
*
* @return array<int, array<string, array>> [Set-ID => [Slot => Zeile mit 'item']]
*/
function gear_slots_for_sets(array $setIds): array
{
$setIds = array_values(array_unique(array_map('intval', $setIds)));
$result = array_fill_keys($setIds, []);
if (!$setIds) {
return $result;
}
$stmt = db()->prepare('SELECT * FROM gear_set_slots WHERE set_id IN (' . implode(',', array_fill(0, count($setIds), '?')) . ')');
$stmt->execute($setIds);
$rows = $stmt->fetchAll();
$items = gear_items_by_ids(array_column($rows, 'item_id'));
foreach ($rows as $row) {
if (!isset(GEAR_SLOTS[$row['slot']])) {
continue;
}
$row['soul_imprint'] = json_decode((string) $row['soul_imprint'], true) ?: [];
$row['manastones'] = json_decode((string) $row['manastones'], true) ?: [];
$row['item'] = $items[(int) $row['item_id']] ?? null;
$result[(int) $row['set_id']][$row['slot']] = $row;
}
return $result;
}
/** Sets fuer die Profilseite: [[set, slots, item_level], …] */
function gear_profile_sets(int $userId): array
{
$sets = gear_sets_for_user($userId, true);
$slots = gear_slots_for_sets(array_column($sets, 'id'));
return array_map(static fn (array $set): array => [
'set' => $set,
'slots' => $slots[(int) $set['id']] ?? [],
'item_level' => gear_set_item_level($slots[(int) $set['id']] ?? []),
], $sets);
}