LuminaWebsite/includes/gear.php
Maaxxs 525bd0d4b5 Gear planner: sets can be shared by link or build code and imported as your own
Asked for: share a build with a link or build code, and an import tool that takes such a code.

- "Teilen" on an own set creates a link (gear.php?build=CODE) and the same code as build code: 10
  characters without 0/O and 1/I/L, shown as K7QX2-M9FRT, stored in gear_sets.share_code (schema
  version 59, unique; also in sql/schema.sql). Whoever opens it sees the set even if it is not on the
  profile, always in its current state; the session remembers the code so tabs, slots and compare
  work, and a renewed or withdrawn code ends that access. "Neuen Code erzeugen" and "Nicht mehr
  teilen" invalidate the old one. The dialog reopens after creating (#teilen) with copy buttons.
- "Build importieren" on "Meine Sets" takes the code (with or without dash, any case) or the whole
  link; viewing someone else's set (shared or on the profile) offers "In meine Sets übernehmen".
  Both copy the set with gear, skills, macros and all planner pages via gear_set_copy() (also used
  by "Kopieren" now); the copy is neither shared nor on the profile. Errors reopen the dialog (#import).
- Members only (gear.view). Opening any page without being logged in now brings you back to it after
  the login (auth_login_return_target) - only for page views in the browser, not for background
  requests like live updates or autosave.
- Privacy policy (shared sets), patch notes and README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 01:44:52 +02:00

740 lines
31 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, Skillstufen) und der Katalog der Gegenstaende mit ihren Werten.
* Die Skills stehen in includes/gear_skills.php.
*
* 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';
require_once __DIR__ . '/gear_skills.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']],
'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']],
];
// Anordnung der Slots im Ausruestungsraster (zwei pro Reihe, wie im Spiel)
const GEAR_DOLL_ORDER = [
'main_hand', 'off_hand',
'head', 'shoulder',
'torso', 'belt',
'pants', 'gloves',
'cape', 'boots',
'earring_1', 'earring_2',
'necklace', 'amulet',
'ring_1', 'ring_2',
'bracelet_1', 'bracelet_2',
];
// Umriss-Silhouetten fuer leere Slots (SVG-Pfade, 24er Raster, nur Linien)
const GEAR_SLOT_SILHOUETTES = [
'main_hand' => '<path d="M14.5 17.5 3 6V3h3l11.5 11.5"/><path d="m13 19 6-6"/><path d="m16 16 4 4"/><path d="m19 21 2-2"/>',
'off_hand' => '<path d="M12 21c4.5-1.8 7-5.2 7-9.5V6l-7-3-7 3v5.5c0 4.3 2.5 7.7 7 9.5z"/><path d="M12 3v18"/>',
'head' => '<path d="M4 15a8 8 0 0 1 16 0v3h-5v3H9v-3H4z"/><path d="M8 15h8"/><path d="M12 7v4"/>',
'shoulder' => '<path d="M3 15c0-4.4 3.6-8 8-8h2c4.4 0 8 3.6 8 8l-3 2-2-3H8l-2 3z"/><path d="M8 7l2-3h4l2 3"/>',
'torso' => '<path d="M8 3 4 6v5h3v10h10V11h3V6l-4-3-2 2h-4z"/><path d="M12 5v16"/>',
'belt' => '<path d="M2 10h20v4H2z"/><path d="M10 8.5h4v7h-4z"/>',
'pants' => '<path d="M6 3h12l1 18h-5l-2-10-2 10H5z"/><path d="M6 6h12"/>',
'gloves' => '<path d="M8 21v-7L6 10V6.5a1 1 0 0 1 2 0V10"/><path d="M8 10V4.5a1 1 0 0 1 2 0V10"/><path d="M10 9V4a1 1 0 0 1 2 0v5"/><path d="M12 9.5V5a1 1 0 0 1 2 0v6l1.8-1.6a1 1 0 0 1 1.4 1.4L15 14.5V21"/>',
'cape' => '<path d="M8 3h8l4 18-4-2-4 2-4-2-4 2z"/><path d="M9 3c0 2 1.3 3 3 3s3-1 3-3"/>',
'boots' => '<path d="M7 3h6v10l6 3v5H6z"/><path d="M6 18h13"/>',
'earring_1' => '<circle cx="12" cy="4.5" r="1.5"/><path d="M12 6v4"/><path d="M12 10l-3.5 5.5a3.5 3.5 0 0 0 7 0z"/>',
'earring_2' => '<circle cx="12" cy="4.5" r="1.5"/><path d="M12 6v4"/><path d="M12 10l-3.5 5.5a3.5 3.5 0 0 0 7 0z"/>',
'necklace' => '<path d="M5 3c0 6.5 3 11 7 11s7-4.5 7-11"/><path d="M12 14l-2.5 3.5L12 21l2.5-3.5z"/>',
'amulet' => '<circle cx="12" cy="14" r="6"/><circle cx="12" cy="14" r="2.5"/><path d="M12 3v5"/>',
'ring_1' => '<circle cx="12" cy="15" r="6"/><path d="m9 6.5 3-3.5 3 3.5-3 2.5z"/>',
'ring_2' => '<circle cx="12" cy="15" r="6"/><path d="m9 6.5 3-3.5 3 3.5-3 2.5z"/>',
'bracelet_1' => '<ellipse cx="12" cy="12" rx="9" ry="5"/><ellipse cx="12" cy="12" rx="5.5" ry="2.5"/>',
'bracelet_2' => '<ellipse cx="12" cy="12" rx="9" ry="5"/><ellipse cx="12" cy="12" rx="5.5" ry="2.5"/>',
];
/** Umriss-Symbol eines leeren Slots. */
function gear_slot_silhouette(string $slotKey): string
{
return '<svg class="gear-doll-silhouette" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
. (GEAR_SLOT_SILHOUETTES[$slotKey] ?? '') . '</svg>';
}
/**
* Kleines Ausruestungsraster fuer Set-Karten: alle Slots in der Reihenfolge des grossen Rasters,
* mit Seltenheitsfarbe, Aufwertung und Silhouetten fuer leere Slots. Standard sind sechs pro
* Reihe ("Meine Sets"); $column = zwei pro Reihe als Saeule wie im Spiel (Profilseite).
*
* @param array<string, array> $slots Slots eines Sets (gear_slots_for_sets)
*/
function gear_doll_mini_html(array $slots, bool $column = false): string
{
$html = '<span class="gear-doll gear-doll-mini' . ($column ? ' gear-doll-column' : '') . '">';
foreach (GEAR_DOLL_ORDER as $slotKey) {
$row = $slots[$slotKey] ?? null;
$item = $row['item'] ?? null;
$label = GEAR_SLOTS[$slotKey][0];
$tip = $label . ': ' . ($item ? $item['name'] . ((int) $row['enchant'] > 0 ? ' +' . (int) $row['enchant'] : '') : 'leer');
$html .= '<span class="gear-doll-slot' . ($item ? ' is-filled ' . e(gear_grade_class($item['grade'])) : '') . '" title="' . e($tip) . '">';
$iconUrl = gear_icon_url($item);
if ($item && $iconUrl) {
$html .= '<img src="' . e($iconUrl) . '" alt="" loading="lazy">';
} elseif ($item) {
$html .= '<span class="gear-doll-initial">' . e(mb_substr((string) $item['name'], 0, 1)) . '</span>';
} else {
$html .= gear_slot_silhouette($slotKey);
}
if ($item && (int) $row['enchant'] > 0) {
$html .= '<span class="gear-doll-enchant">+' . (int) $row['enchant'] . '</span>';
}
$html .= '</span>';
}
return $html . '</span>';
}
// In der Nebenhand traegt in Aion 2 jede Klasse einen Schutz (Guard, Spiel-Slot SubHand) - zwei
// Waffen gibt es nicht. Aeltere Sets mit einer Waffe dort behalten sie, sie wird nur markiert.
// Hauptwaffe je Klasse (Aion 2: genau eine Waffenart pro Klasse, laut aion2hub). An die Klasse
// gebunden sind nur Waffen mit dem Spiel-Slot MainHand - Schutz, Ruestung und Schmuck nicht.
const GEAR_CLASS_WEAPONS = [
'Templer' => 'Sword',
'Gladiator' => 'Greatsword',
'Assassine' => 'Dagger',
'Jäger' => 'Bow',
'Magier' => 'Magicbook',
'Beschwörer' => 'Orb',
'Kleriker' => 'Mace',
'Kantor' => 'Staff',
];
// Waffenarten auf Deutsch (aion2hub liefert sie englisch)
const GEAR_TYPE_LABELS = [
'Sword' => 'Schwert', 'Greatsword' => 'Zweihänder', 'Dagger' => 'Dolch', 'Bow' => 'Bogen', 'Magicbook' => 'Zauberbuch',
'Orb' => 'Orb', 'Staff' => 'Stab', 'Mace' => 'Streitkolben', 'Guarder' => 'Schutz',
];
// 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');
}
/** Art eines Gegenstands zum Anzeigen: Waffenarten auf Deutsch, alles andere wie bei aion2hub. */
function gear_type_label(string $type): string
{
return GEAR_TYPE_LABELS[$type] ?? $type;
}
/** Passt ein Katalog-Gegenstand in diesen Slot eines Sets? */
function gear_item_fits_slot(array $item, string $slotKey): bool
{
return isset(GEAR_SLOTS[$slotKey]) && in_array($item['slot'], GEAR_SLOTS[$slotKey][2], true);
}
/**
* Kann die Klasse des Sets diesen Gegenstand tragen? Gebunden sind nur Waffen mit dem Spiel-Slot
* MainHand (GEAR_CLASS_WEAPONS), auch in der Nebenhand. Sets ohne Klasse duerfen alles.
*/
function gear_item_fits_class(array $item, ?string $className): bool
{
$weapon = GEAR_CLASS_WEAPONS[$className ?? ''] ?? null;
return $weapon === null || $item['slot'] !== 'MainHand' || $item['item_type'] === $weapon;
}
/**
* Warum passt ein Gegenstand nicht (mehr) in diesen Slot des Sets, z.B. nach einem Klassenwechsel?
* null = passt. Geloescht wird so ein Gegenstand nie - er wird nur markiert und laesst sich weiter
* bearbeiten (gear_action.php, save_slot), neu einsetzen laesst sich nur, was passt.
*/
function gear_item_mismatch(array $item, string $slotKey, ?string $className): ?string
{
if (!gear_item_fits_slot($item, $slotKey)) {
return 'passt nicht in diesen Slot';
}
return gear_item_fits_class($item, $className) ? null : 'passt nicht zu ' . $className;
}
/**
* Eintraege fuer die Suchliste (assets/js/item-picker.js) eines Slots, mit Klasse nur deren Waffen.
* Der eingesetzte Gegenstand ($keepId) bleibt immer drin, auch wenn er nicht mehr passt - fehlt er,
* leert die Suchliste beim Laden das Feld und der Slot laesst sich nicht mehr speichern.
*/
function gear_picker_items(string $slotKey, ?string $className = null, int $keepId = 0): 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), '?')) . ') OR id = ? ORDER BY item_level DESC, name'
);
$stmt->execute([...$slots, $keepId]);
$rows = [];
foreach ($stmt->fetchAll() as $row) {
$row['mismatch'] = gear_item_mismatch($row, $slotKey, $className);
if ($row['mismatch'] === null || (int) $row['id'] === $keepId) {
$rows[] = $row;
}
}
// 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'] ? ' · ' . gear_type_label($row['item_type']) : '')
. ($row['mismatch'] !== null ? ' · ' . $row['mismatch'] : ''),
], $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
{
return gear_image_download(GEAR_SOURCE_ICON_URL . $id, GEAR_ICON_DIR, (string) $id);
}
/** Bild von aion2hub als <Name>.<Endung> in $dir speichern - nur echte Bilder bis 512 KB. */
function gear_image_download(string $url, string $dir, string $baseName): ?string
{
try {
$body = gear_source_fetch($url);
} 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($dir)) {
@mkdir($dir, 0755, true);
}
$name = $baseName . '.' . $types[$info[2]];
return @file_put_contents($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 ----
// Planer-Seiten, auf die ein Set als Skill-/Daevanion-Plan verlinken darf (auch deren Subdomains).
// Die Daevanion-Bretter kennt die Website (noch) nicht - dafuer der Link zum Build.
const GEAR_BUILD_HOSTS = ['aion2hub.com', 'talentbuilds.com', 'aion2t.com', 'aion2.online', 'gamers4.life', 'aion2.app'];
const GEAR_BUILD_URL_MAX = 300;
/** Die Planer-Seite eines Build-Links ("aion2hub.com") oder null, wenn sie nicht erlaubt ist. */
function gear_build_host(string $url): ?string
{
$parts = parse_url($url);
$host = strtolower((string) ($parts['host'] ?? ''));
if (($parts['scheme'] ?? '') !== 'https' || $host === '' || isset($parts['user']) || isset($parts['pass'])) {
return null;
}
foreach (GEAR_BUILD_HOSTS as $allowed) {
if ($host === $allowed || str_ends_with($host, '.' . $allowed)) {
return $allowed;
}
}
return null;
}
/**
* Build-Link aus dem Formular pruefen: leer oder ein https-Link auf eine der Planer-Seiten.
*
* @return array{0: ?string, 1: ?string} [Link oder null, Fehlermeldung oder null]
*/
function gear_build_url_input(string $raw): array
{
$url = trim($raw);
if ($url === '') {
return [null, null];
}
if (mb_strlen($url) > GEAR_BUILD_URL_MAX || preg_match('/\s/u', $url) || gear_build_host($url) === null) {
return [null, 'Der Build-Link muss eine https-Adresse von ' . implode(', ', GEAR_BUILD_HOSTS) . ' sein (höchstens ' . GEAR_BUILD_URL_MAX . ' Zeichen).'];
}
return [$url, null];
}
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, wenn aufs Profil freigegeben oder per Link/Buildcode
* geteilt und der Code in dieser Sitzung geoeffnet wurde - solange der Besitzer ihn nicht zurueckgezogen oder erneuert hat.
*/
function gear_can_view_set(array $set): bool
{
$me = current_user();
if (!$me) {
return false;
}
if ((int) $me['id'] === (int) $set['user_id'] || !empty($set['show_on_profile'])) {
return true;
}
$opened = $_SESSION['gear_shared'][(int) $set['id']] ?? null;
return is_string($opened) && !empty($set['share_code']) && hash_equals((string) $set['share_code'], $opened);
}
// ---- Teilen per Link und Buildcode ----
// Der Code ist zugleich der Link (/gear.php?build=CODE): wer ihn hat, sieht das Set - auch wenn es nicht auf dem Profil
// steht - und kann es in seine eigenen Sets uebernehmen. Er zeigt immer den aktuellen Stand des Sets. Zeichen ohne die
// leicht verwechselbaren 0/O, 1/I/L; angezeigt in zwei Fuenfergruppen (K7QX2-M9FRT), gespeichert ohne Strich.
const GEAR_SHARE_ALPHABET = '23456789ABCDEFGHJKMNPQRSTUVWXYZ';
const GEAR_SHARE_LENGTH = 10;
function gear_share_code_new(): string
{
$code = '';
for ($i = 0; $i < GEAR_SHARE_LENGTH; $i++) {
$code .= GEAR_SHARE_ALPHABET[random_int(0, strlen(GEAR_SHARE_ALPHABET) - 1)];
}
return $code;
}
/** Code zum Anzeigen: "K7QX2-M9FRT" */
function gear_share_code_label(string $code): string
{
return substr($code, 0, 5) . '-' . substr($code, 5);
}
/** Link zum geteilten Set */
function gear_share_url(string $code): string
{
return site_url('/gear.php?build=' . rawurlencode($code));
}
/**
* Eingabe beim Importieren: der Buildcode (mit oder ohne Strich und Leerzeichen, egal ob gross oder klein) oder der
* ganze Link. Gibt den Code zurueck oder null, wenn es keiner sein kann.
*/
function gear_share_code_input(string $raw): ?string
{
$raw = trim($raw);
if (preg_match('~[?&]build=([^&#\s]+)~i', $raw, $match)) {
$raw = rawurldecode($match[1]);
}
$code = strtoupper((string) preg_replace('/[\s\-]+/u', '', $raw));
return preg_match('/^[' . GEAR_SHARE_ALPHABET . ']{' . GEAR_SHARE_LENGTH . '}$/', $code) ? $code : null;
}
function gear_set_by_share_code(string $code): ?array
{
$stmt = db()->prepare('SELECT id FROM gear_sets WHERE share_code = ?');
$stmt->execute([$code]);
$id = $stmt->fetchColumn();
return $id !== false ? gear_set((int) $id) : null;
}
/**
* Kopie eines Sets anlegen - beim Kopieren eines eigenen Sets und beim Uebernehmen eines geteilten oder aufs Profil
* gestellten: Ausruestung, Skills und alle Planer-Seiten samt Makro. Die Kopie ist weder geteilt noch auf dem Profil.
* Ohne $sortOrder kommt sie ans Ende der Sets. Gibt die ID der Kopie zurueck.
*/
function gear_set_copy(array $source, int $userId, string $name, ?int $sortOrder = null): int
{
$pdo = db();
if ($sortOrder === null) {
$last = $pdo->prepare('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM gear_sets WHERE user_id = ?');
$last->execute([$userId]);
$sortOrder = (int) $last->fetchColumn();
}
$pdo->beginTransaction();
try {
$pdo->prepare(
'INSERT INTO gear_sets (user_id, name, class_name, note, build_url, show_on_profile, sort_order, updated_at)
SELECT ?, ?, class_name, note, build_url, 0, ?, NOW() FROM gear_sets WHERE id = ?'
)->execute([$userId, $name, $sortOrder, (int) $source['id']]);
$newId = (int) $pdo->lastInsertId();
$pdo->prepare(
'INSERT INTO gear_set_slots (set_id, slot, item_id, enchant, exceed, soul_imprint, manastones, godstone)
SELECT ?, slot, item_id, enchant, exceed, soul_imprint, manastones, godstone FROM gear_set_slots WHERE set_id = ?'
)->execute([$newId, (int) $source['id']]);
$pdo->prepare('INSERT INTO gear_set_skills (set_id, skill_id, level, specs) SELECT ?, skill_id, level, specs FROM gear_set_skills WHERE set_id = ?')
->execute([$newId, (int) $source['id']]);
$pdo->prepare('INSERT INTO gear_set_plans (set_id, section, data, updated_at) SELECT ?, section, data, NOW() FROM gear_set_plans WHERE set_id = ?')
->execute([$newId, (int) $source['id']]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
return $newId;
}
/** Geoeffneten Buildcode fuer diese Sitzung merken - dann gehen auch die Reiter, Slots und der Vergleich des Sets. */
function gear_share_remember(array $set): void
{
$opened = is_array($_SESSION['gear_shared'] ?? null) ? $_SESSION['gear_shared'] : [];
unset($opened[(int) $set['id']]);
$opened[(int) $set['id']] = (string) $set['share_code'];
$_SESSION['gear_shared'] = array_slice($opened, -50, null, true);
}
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, skills], …] */
function gear_profile_sets(int $userId): array
{
$sets = gear_sets_for_user($userId, true);
$slots = gear_slots_for_sets(array_column($sets, 'id'));
$skills = gear_set_skills_for_sets($sets);
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']] ?? []),
'skills' => $skills[(int) $set['id']] ?? [],
], $sets);
}