LuminaWebsite/includes/gear.php
Maaxxs 8488daabf8 Gear-Planer Guide: Formatierung in der Beschreibung (fett, kursiv, unterstrichen, Listen, ...)
Knopfleiste ueber dem Textfeld (assets/js/format-toolbar.js, Strg+B/I/U), Schreibweise wie im Wiki:
**fett**, *kursiv*, __unterstrichen__, ~~durchgestrichen~~, ## Ueberschrift, - / 1. Listen,
> Hinweis, [Text](Adresse). Wirkt in allen Guide-Texten mit Absaetzen; Kartenvorschau ohne Zeichen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 18:33:52 +02:00

1058 lines
46 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, bool $tips = 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');
// Mit $tips (Guide): Info-Blase wie bei den Skills (assets/js/gear.js, data-skill-tip) statt des einfachen Titels
$tipAttrs = $tips && $item ? ' data-skill data-skill-tip tabindex="0" aria-label="' . e($tip) . '"' : ' title="' . e($tip) . '"';
$html .= '<span class="gear-doll-slot' . ($item ? ' is-filled ' . e(gear_grade_class($item['grade'])) : '') . '"' . $tipAttrs . '>'
. ($tips && $item ? gear_item_tip_src_html($slotKey, $row) : '');
$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>';
}
/**
* Inhalt der Info-Blase zu einem belegten Slot (assets/js/gear.js): Name in der Farbe der Seltenheit mit Aufwertung,
* Slot, Art und Gegenstandsstufe, die Werte bei Aufwertung/Durchbruch (Grundwert + Aufwertung zusammengezaehlt),
* Seelenpraegung, Manasteine und Goetterstein so, wie sie im Set eingetragen sind.
*/
function gear_item_tip_src_html(string $slotKey, array $row): string
{
$item = $row['item'];
$enchant = (int) $row['enchant'];
$exceed = (int) ($row['exceed'] ?? 0);
$stats = [];
foreach (gear_slot_contributions($row, $item) as $c) {
if (in_array($c['source'], ['base', 'enchant', 'exceed'], true)) {
$key = $c['name'] . '|' . $c['unit'];
$stats[$key] = ($stats[$key] ?? ['name' => $c['name'], 'unit' => $c['unit'], 'value' => 0.0, 'estimated' => false]);
$stats[$key]['value'] += $c['value'];
$stats[$key]['estimated'] = $stats[$key]['estimated'] || $c['estimated'];
}
}
$meta = array_filter([
GEAR_SLOTS[$slotKey][0],
gear_type_label((string) $item['item_type']),
(int) $item['item_level'] > 0 ? 'Stufe ' . (int) $item['item_level'] : '',
$exceed > 0 ? 'Durchbruch ' . $exceed : '',
], static fn (string $part): bool => $part !== '');
$html = '<span class="gear-tip-src" hidden>'
. '<span class="gear-tip-head"><strong class="' . e(gear_grade_class($item['grade'])) . '">' . e($item['name']) . '</strong>'
. ($enchant > 0 ? '<span class="gear-tip-enchant">+' . $enchant . '</span>' : '') . '</span>'
. '<span class="gear-tip-meta">' . e(implode(' · ', $meta)) . '</span>';
if ($stats) {
$html .= '<span class="gear-tip-stats">';
foreach ($stats as $stat) {
$html .= '<span><span>' . e($stat['name']) . '</span><b>' . ($stat['estimated'] ? '≈ ' : '') . e(gear_format_value($stat['value'], $stat['unit'])) . '</b></span>';
}
$html .= '</span>';
}
if ($row['soul_imprint']) {
$html .= '<span class="gear-tip-group">Seelenprägung</span><span class="gear-tip-chips">';
foreach ($row['soul_imprint'] as $entry) {
$html .= '<i>' . e(gear_soul_entry_label($entry)) . '</i>';
}
$html .= '</span>';
}
if ($row['manastones']) {
$html .= '<span class="gear-tip-group">Manasteine</span><span class="gear-tip-chips is-stones">';
foreach ($row['manastones'] as [$stat, $value]) {
$html .= '<i>' . e($stat) . ' +' . (int) $value . '</i>';
}
$html .= '</span>';
}
if (!empty($row['godstone'])) {
$html .= '<span class="gear-tip-group">Götterstein</span><span class="gear-tip-chips is-god"><i>' . e((string) $row['godstone']) . '</i></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)',
'soul_skills' => 'Seelenprägung (Skills)',
];
// Felder, die als JSON in gear_items.data liegen
const GEAR_DATA_FIELDS = ['stats', 'soul_imprint', 'soul_imprint_count', 'soul_skills', 'manastone_slots', 'godstone_slots', 'enchant_max', 'enchant_stats', 'exceed_max', 'exceed_stats'];
// Seelenpraegung auf einen Skill (+Stufe): im Slot gespeichert als ['skill:<Skill-ID>', Stufe]
const GEAR_SOUL_SKILL_PREFIX = 'skill:';
// ---- 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', 'soul_skills', '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
)) ?: '–';
}
/** Skills der Seelenpraegung als Text fuer den Abgleich: "Stufe 1 · Kleriker: Bolt, Divine Aura, …; Gladiator: …" */
function gear_soul_skills_text(array $soulSkills): string
{
$classes = (array) ($soulSkills['classes'] ?? []);
if (!$classes) {
return '–';
}
$parts = [];
foreach ($classes as $class => $names) {
$parts[] = $class . ': ' . implode(', ', (array) $names);
}
return 'Stufe ' . (int) ($soulSkills['level'] ?? 1) . ' · ' . implode('; ', $parts);
}
/**
* Skills, die bei einem Gegenstand fuer die Klasse des Sets als Seelenpraegung kommen koennen - zugeordnet ueber den
* englischen Namen (gear_skills.name). [Skill-ID => Skill]; leer ohne Klasse oder wenn der Gegenstand keine hat.
*
* @return array<int, array>
*/
function gear_item_soul_skills(array $item, ?string $className): array
{
$names = (array) ($item['soul_skills']['classes'][$className ?? ''] ?? []);
if (!$names || $className === null || $className === '') {
return [];
}
$byName = [];
foreach (gear_skills_for_class($className, false) as $skill) {
$byName[mb_strtolower((string) $skill['name'], 'UTF-8')] = $skill;
}
$out = [];
foreach ($names as $name) {
$skill = $byName[mb_strtolower((string) $name, 'UTF-8')] ?? null;
if ($skill) {
$out[(int) $skill['id']] = $skill;
}
}
return $out;
}
/** Skill-ID einer Seelenpraegung "skill:<ID>" oder null, wenn es ein normaler Wert ist. */
function gear_soul_skill_id(string $stat): ?int
{
return str_starts_with($stat, GEAR_SOUL_SKILL_PREFIX) && ctype_digit(substr($stat, strlen(GEAR_SOUL_SKILL_PREFIX)))
? (int) substr($stat, strlen(GEAR_SOUL_SKILL_PREFIX)) : null;
}
/** Eine Seelenpraegung lesbar: "Critical Hit 41" bzw. "Heilkreis +1" */
function gear_soul_entry_label(array $entry): string
{
$skillId = gear_soul_skill_id((string) $entry[0]);
if ($skillId !== null) {
$skill = gear_skill($skillId);
return ($skill ? gear_skill_display_name($skill) : 'Skill #' . $skillId) . ' +' . (int) $entry[1];
}
return $entry[0] . ' ' . str_replace('.', ',', (string) $entry[1]);
}
/**
* Skillstufen aus der Seelenpraegung der Ausruestung: [Skill-ID => Stufen] (mehrere Teile mit demselben Skill zaehlen
* zusammen - die Obergrenze setzt gear_skill_effective_level).
*
* @param array<string, array> $slots Slots eines Sets (gear_slots_for_sets)
* @return array<int, int>
*/
function gear_slots_skill_bonus(array $slots): array
{
$bonus = [];
foreach ($slots as $row) {
if (empty($row['item'])) {
continue;
}
foreach ($row['soul_imprint'] as $entry) {
$skillId = gear_soul_skill_id((string) $entry[0]);
if ($skillId !== null) {
$bonus[$skillId] = ($bonus[$skillId] ?? 0) + max(0, (int) $entry[1]);
}
}
}
return $bonus;
}
/** 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);
}
if ($field === 'soul_skills') {
return gear_soul_skills_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, (" . gear_public_sql() . ") AS is_listed
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();
}
// ---- Oeffentliche Builds ----
// Rolle je Klasse fuer die Klassen-Kacheln der Build-Liste
const GEAR_CLASS_ROLES = [
'Templer' => 'Tank',
'Gladiator' => 'Bruiser',
'Assassine' => 'Nahkampf-DD',
'Jäger' => 'Fernkampf-DD',
'Magier' => 'Magie-DD',
'Beschwörer' => 'Pet-DD',
'Kleriker' => 'Heiler',
'Kantor' => 'Support',
];
// Sortierungen der Build-Liste
const GEAR_PUBLIC_SORTS = ['new' => 'Zuletzt geändert', 'level' => 'Ø Gegenstandsstufe', 'name' => 'Name'];
/**
* SQL-Bedingung: das Set (s) ist ein oeffentlicher Build - oeffentlich gestellt von einem aktiven Konto (u), das noch
* oeffentliche Builds stellen darf (gear.publish). Verliert jemand das Recht, verschwinden seine Builds aus der Liste.
*/
function gear_public_sql(): string
{
return "s.is_public = 1 AND u.status = 'active' AND " . sql_user_has_permission('u', 'gear.publish');
}
/**
* Oeffentliche Builds der Klassenmeister, optional nur einer Klasse. Sortiert nach letzter Aenderung - die Sortierung
* nach Gegenstandsstufe braucht die Slots und passiert in gear.php.
*
* @return array<int, array>
*/
function gear_public_sets(?string $className = null): 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 " . gear_public_sql() . ($className !== null ? ' AND s.class_name = ?' : '') . '
ORDER BY COALESCE(s.updated_at, s.created_at) DESC, s.id DESC'
);
$stmt->execute($className !== null ? [$className] : []);
return $stmt->fetchAll();
}
/**
* Klassenmeister je Klasse: aktive Mitglieder, denen gear.publish ueber eine Gruppe oder einzeln gegeben wurde, bei ihrer
* Main-Klasse. Nicht ueber die Gruppe "Administrator" (die bekommt jedes neue Recht automatisch, schema_sync_core_permissions)
* und nicht nur ueber is_admin - Administratoren zaehlen nur, wenn sie das Recht ausdruecklich haben.
*
* @return array<string, array<int, array{id: int, name: string}>>
*/
function gear_class_masters(): array
{
$masters = [];
$rows = db()->query(
"SELECT u.id, u.class_name, COALESCE(NULLIF(u.display_name, ''), u.username) AS name
FROM users u
WHERE u.status = 'active' AND u.class_name IS NOT NULL
AND (EXISTS (SELECT 1 FROM user_roles ur JOIN roles r ON r.id = ur.role_id JOIN role_permissions rp ON rp.role_id = ur.role_id
JOIN permissions p ON p.id = rp.permission_id
WHERE ur.user_id = u.id AND p.`key` = 'gear.publish' AND r.name <> 'Administrator')
OR EXISTS (SELECT 1 FROM user_permissions up JOIN permissions p2 ON p2.id = up.permission_id
WHERE up.user_id = u.id AND p2.`key` = 'gear.publish'))
ORDER BY name"
);
foreach ($rows as $row) {
$masters[(string) $row['class_name']][] = ['id' => (int) $row['id'], 'name' => (string) $row['name']];
}
return $masters;
}
/** @return array<string, int> Anzahl oeffentlicher Builds je Klasse ('' = ohne Klasse) */
function gear_public_class_counts(): array
{
$counts = [];
foreach (db()->query('SELECT COALESCE(s.class_name, \'\') AS class_name, COUNT(*) AS n FROM gear_sets s JOIN users u ON u.id = s.user_id WHERE ' . gear_public_sql() . ' GROUP BY s.class_name') as $row) {
$counts[(string) $row['class_name']] = (int) $row['n'];
}
return $counts;
}
// Beschreibung eines Builds (gear_sets.description): erklaert den Build fuer alle, die das Set sehen
const GEAR_DESCRIPTION_MAX = 10000;
/** Beschreibung als HTML: Absaetze bei Leerzeilen, sonst Zeilenumbrueche - nur Text, keine Links oder Formatierung. */
/**
* Text mit Formatierung (Schreibweise wie im Wiki, Knoepfe: assets/js/format-toolbar.js) als HTML:
* **fett**, *kursiv*, __unterstrichen__, ~~durchgestrichen~~, [Linktext](https://...), Zeilen mit "## " (Ueberschrift),
* "- " (Liste), "1. " (nummerierte Liste) und "> " (Hinweis-Kasten). Absaetze mit einer Leerzeile.
*/
function gear_description_html(string $text): string
{
$html = '';
$paragraph = [];
$list = null; // ['ul'|'ol', [Eintraege]]
$quote = [];
$flush = static function () use (&$html, &$paragraph, &$list, &$quote): void {
if ($paragraph) {
$html .= '<p>' . implode('<br>', array_map('gear_format_inline', $paragraph)) . '</p>';
}
if ($list) {
$html .= '<' . $list[0] . '>' . implode('', array_map(static fn (string $item): string => '<li>' . gear_format_inline($item) . '</li>', $list[1])) . '</' . $list[0] . '>';
}
if ($quote) {
$html .= '<blockquote>' . implode('<br>', array_map('gear_format_inline', $quote)) . '</blockquote>';
}
$paragraph = $quote = [];
$list = null;
};
foreach (explode("\n", str_replace(["\r\n", "\r"], "\n", trim($text))) as $line) {
$line = rtrim($line);
if (trim($line) === '') {
$flush();
} elseif (preg_match('/^(#{1,3})\s+(.+)$/u', $line, $m)) {
$flush();
$level = strlen($m[1]) + 2; // ## -> h4, damit es unter den Ueberschriften der Seite bleibt
$html .= '<h' . $level . ' class="gear-format-heading">' . gear_format_inline($m[2]) . '</h' . $level . '>';
} elseif (preg_match('/^\s*(?:([-•]|\*(?=\s))|\d{1,3}[.)])\s+(.+)$/u', $line, $m)) {
// "- " / "• " / "* " = Liste, "1. " / "1) " = nummerierte Liste
$type = $m[1] !== '' ? 'ul' : 'ol';
if ($paragraph || $quote || ($list && $list[0] !== $type)) {
$flush();
}
$list ??= [$type, []];
$list[1][] = $m[2];
} elseif (preg_match('/^>\s?(.*)$/u', $line, $m)) {
if ($paragraph || $list) {
$flush();
}
$quote[] = $m[1];
} else {
if ($list || $quote) {
$flush();
}
$paragraph[] = $line;
}
}
$flush();
return $html;
}
/** Eine Zeile formatieren (fett, kursiv, ... siehe gear_description_html) - maskiert selbst. */
function gear_format_inline(string $text): string
{
$html = e($text);
// Links zuerst herausnehmen, damit die Formatierung unten nichts in der Adresse veraendert
$links = [];
$html = (string) preg_replace_callback('/\[([^\[\]]+)\]\(([^)\s]+)\)/u', static function (array $m) use (&$links): string {
$url = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8');
$external = (bool) preg_match('#^https?://#i', $url);
if (!$external && !($url !== '' && $url[0] === '/' && !str_starts_with($url, '//'))) {
return $m[0];
}
$links[] = '<a href="' . e($url) . '"' . ($external ? ' target="_blank" rel="noopener noreferrer"' : '') . '>' . $m[1] . '</a>';
return "\x01" . (count($links) - 1) . "\x01";
}, $html);
$html = (string) preg_replace('/__(?!\s)(.+?)(?<!\s)__/su', '<u>$1</u>', $html);
$html = (string) preg_replace('/\*\*\*(?!\s)(.+?)(?<!\s)\*\*\*/su', '<strong><em>$1</em></strong>', $html);
$html = (string) preg_replace('/\*\*(?!\s)(.+?)(?<!\s)\*\*/su', '<strong>$1</strong>', $html);
$html = (string) preg_replace('/(?<![\w*])\*(?![\s*])(.+?)(?<![\s*])\*(?![\w*])/su', '<em>$1</em>', $html);
$html = (string) preg_replace('/~~(?!\s)(.+?)(?<!\s)~~/su', '<del>$1</del>', $html);
return (string) preg_replace_callback("/\x01(\d+)\x01/", static fn (array $m): string => $links[(int) $m[1]], $html);
}
/** Text ohne die Formatierungszeichen - fuer kurze Vorschauen (z.B. Karten der Build-Liste). */
function gear_format_plain(string $text): string
{
$text = (string) preg_replace('/\[([^\[\]]+)\]\([^)\s]+\)/u', '$1', $text);
$text = (string) preg_replace('/^\s*(?:#{1,3}|>|[-•]|\*(?=\s)|\d{1,3}[.)])\s*/mu', '', $text);
$text = (string) preg_replace('/(?<![\w*])\*(?![\s*])(.+?)(?<![\s*])\*(?![\w*])/su', '$1', $text);
return str_replace(['***', '**', '__', '~~'], '', $text);
}
/**
* Darf der aktuelle Nutzer das Set ansehen? Eigene immer, fremde, wenn oeffentlich, 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']) || !empty($set['is_listed'])) {
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 oeffentlich 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, description, guide, build_url, show_on_profile, sort_order, updated_at)
SELECT ?, ?, class_name, note, description, guide, 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);
}