LuminaWebsite/includes/armory.php

716 lines
34 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);
/**
* Live-Daten der Charaktere aus Aion 2 (Arsenal): Die Charaktere der Profilseiten lassen sich mit
* ihrem Charakter im Spiel verknuepfen (member_characters.aion_char_id + aion_server_id). Die Daten
* kommen von denselben Schnittstellen, die NCSoft fuer die Charaktersuche auf aion2.plaync.com nutzt
* (nicht offiziell dokumentiert - aendert NCSoft etwas, faellt nur die Anzeige aus).
*
* Abgerufen wird nur von unserem Server aus: Besucher sprechen nie mit NCSoft, auch Bilder und Icons
* kommen ueber uns (armory_icon.php bzw. assets/uploads/armory/). Die Antworten liegen aufbereitet in
* member_characters.aion_data und werden nach ARMORY_TTL im Hintergrund erneuert (armory_api.php).
*/
const ARMORY_API_HOST = 'aion2.plaync.com';
const ARMORY_SEARCH_URL = 'https://api-search.plaync.com/aion2global/search/v2/character';
const ARMORY_REGION = 'eu';
const ARMORY_LANG = 'de-DE';
const ARMORY_AGENT = 'LuminaAscendens/1.0 (+https://lumina-ascendens.de; Charakteranzeige der Legion)';
// Icons der Gegenstaende, Boards und Begleiter (nur diese Adresse wird zwischengespeichert)
const ARMORY_ICON_BASE = 'https://assets.playnccdn.com/static-aion2-gamedata/resources/';
const ARMORY_ICON_DIR = __DIR__ . '/../assets/uploads/armory/';
const ARMORY_ICON_URL = '/assets/uploads/armory/';
// Nach so vielen Sekunden gelten die gespeicherten Daten als alt und werden beim Ansehen erneuert
const ARMORY_TTL = 3600;
// "Aktualisieren" von Hand hoechstens so oft pro Charakter
const ARMORY_MANUAL_COOLDOWN = 300;
// Item-Infos (Werte, Manasteine) so lange zwischenspeichern
const ARMORY_ITEM_TTL = 6 * 3600;
// Elyos-Server von Aion 2 (EU) laut aion2.plaync.com/api/gameinfo/servers - die Legion spielt auf Kaisinel
const ARMORY_SERVERS = [
1301 => 'Siel', 1302 => 'Nezekan', 1303 => 'Vaizel', 1304 => 'Kaisinel', 1305 => 'Yustiel', 1306 => 'Ariel',
1307 => 'Fregion', 1308 => 'Meslamtaeda', 1309 => 'Hithanya', 1310 => 'Nania', 1311 => 'Tahavatha',
1312 => 'Luteros', 1313 => 'Phernos', 1314 => 'Daminu', 1315 => 'Kasaka', 1316 => 'Bakarma', 1317 => 'Tsenka',
1318 => 'Kochi', 1319 => 'Ishtar', 1320 => 'Tiamat', 1321 => 'Gauss', 1322 => 'Lamuatan',
];
const ARMORY_DEFAULT_SERVER = 1304;
// Klasse laut Suche (pcId: je vier IDs pro Klasse, ab 5) und laut Charakterinfo (deutscher Name) -> AION_CLASSES
const ARMORY_PC_CLASSES = ['Gladiator', 'Templer', 'Jäger', 'Assassine', 'Beschwörer', 'Magier', 'Kleriker', 'Kantor'];
const ARMORY_CLASS_NAMES = ['Waldläufer' => 'Jäger', 'Ranger' => 'Jäger', 'Templar' => 'Templer', 'Assassin' => 'Assassine',
'Spiritmaster' => 'Beschwörer', 'Elementalist' => 'Beschwörer', 'Sorcerer' => 'Magier', 'Cleric' => 'Kleriker', 'Chanter' => 'Kantor'];
// Seltenheit bei NCSoft -> Farbe wie im Gear-Planer (NCSoft "Legend" heisst auf Deutsch "Episch" und ist blau)
const ARMORY_GRADES = ['Common' => 'common', 'Rare' => 'rare', 'Legend' => 'epic', 'Unique' => 'unique', 'Epic' => 'heroic',
'Mythic' => 'heroic', 'Special' => 'special'];
// Slots der Ausruestung (slotPosName) -> Slots des Gear-Planers (GEAR_SLOTS, includes/gear.php)
const ARMORY_SLOTS = [
'MainHand' => 'main_hand', 'SubHand' => 'off_hand', 'Helmet' => 'head', 'Shoulder' => 'shoulder', 'Torso' => 'torso',
'Gloves' => 'gloves', 'Pants' => 'pants', 'Boots' => 'boots', 'Cape' => 'cape', 'Necklace' => 'necklace',
'Earring1' => 'earring_1', 'Earring2' => 'earring_2', 'Ring1' => 'ring_1', 'Ring2' => 'ring_2',
'Bracelet1' => 'bracelet_1', 'Bracelet2' => 'bracelet_2', 'Belt' => 'belt', 'Amulet' => 'amulet',
];
// Weitere Slots (Runen), die es im Gear-Planer nicht gibt
const ARMORY_EXTRA_SLOTS = ['Rune1' => 'Rune 1', 'Rune2' => 'Rune 2'];
// Grundwerte und Werte der Gottheiten (statList.type), in dieser Reihenfolge
const ARMORY_BASE_STATS = ['STR', 'DEX', 'INT', 'CON', 'AGI', 'WIS'];
const ARMORY_GOD_STATS = ['Justice', 'Freedom', 'Illusion', 'Life', 'Time', 'Destruction', 'Death', 'Wisdom', 'Destiny', 'Space'];
/**
* Fragt eine Schnittstelle von NCSoft ab (nur aion2.plaync.com und die Charaktersuche, kein Weiterleiten).
*
* @return array<string, mixed>
* @throws RuntimeException mit verstaendlicher Meldung (Code 404 = Charakter/Gegenstand nicht gefunden)
*/
function armory_request(string $url): array
{
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
if (parse_url($url, PHP_URL_SCHEME) !== 'https' || !in_array($host, [ARMORY_API_HOST, 'api-search.plaync.com'], true)) {
throw new RuntimeException('Unerlaubte Adresse.');
}
if (!function_exists('curl_init')) {
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_USERAGENT => ARMORY_AGENT,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$body = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($body === false) {
throw new RuntimeException('Die Aion-2-Seite von NCSoft ist gerade nicht erreichbar (' . $error . ').');
}
if ($status === 404) {
throw new RuntimeException('Diesen Charakter gibt es im Spiel nicht (mehr).', 404);
}
if ($status !== 200) {
throw new RuntimeException('Die Aion-2-Seite von NCSoft antwortet mit Status ' . $status . '.');
}
$data = json_decode((string) $body, true);
if (!is_array($data)) {
throw new RuntimeException('Die Aion-2-Seite von NCSoft hat unerwartet geantwortet.');
}
return $data;
}
/** Abfrage-Teil fuer einen Charakter (Sprache, Charakter, Server, Region). */
function armory_query(string $charId, int $serverId, array $extra = []): string
{
return http_build_query(array_merge(['lang' => ARMORY_LANG, 'characterId' => $charId, 'serverId' => $serverId], $extra, ['region' => ARMORY_REGION]));
}
function armory_server_name(?int $serverId): string
{
return ARMORY_SERVERS[$serverId ?? 0] ?? ('Server ' . (int) $serverId);
}
function armory_class_from_pc(int $pcId): ?string
{
return $pcId >= 5 ? (ARMORY_PC_CLASSES[intdiv($pcId - 5, 4)] ?? null) : null;
}
function armory_class_name(string $name): ?string
{
$name = ARMORY_CLASS_NAMES[$name] ?? $name;
return in_array($name, AION_CLASSES, true) ? $name : null;
}
function armory_grade_class(?string $grade): string
{
return 'grade-' . (ARMORY_GRADES[$grade ?? ''] ?? 'common');
}
/**
* Sucht Elyos-Charaktere auf einem Server (Namensteil, wie die Suche auf aion2.plaync.com).
*
* @return array<int, array{id: string, name: string, level: int, class: ?string, server_id: int, server: string}>
*/
function armory_search(string $name, int $serverId): array
{
$data = armory_request(ARMORY_SEARCH_URL . '?' . http_build_query([
'keyword' => $name, 'page' => 1, 'size' => 20, 'localeInfo' => ARMORY_LANG, 'region' => ARMORY_REGION, 'serverId' => $serverId,
]));
$results = [];
foreach ((array) ($data['list'] ?? []) as $row) {
if (!is_array($row) || (int) ($row['race'] ?? 1) !== 1 || (int) ($row['serverId'] ?? 0) !== $serverId) {
continue;
}
// Die Suche hebt den Treffer mit <strong> hervor und liefert die ID URL-kodiert
$results[] = [
'id' => rawurldecode((string) ($row['characterId'] ?? '')),
'name' => html_entity_decode(strip_tags((string) ($row['name'] ?? '')), ENT_QUOTES, 'UTF-8'),
'level' => (int) ($row['level'] ?? 0),
'class' => armory_class_from_pc((int) ($row['pcId'] ?? 0)),
'server_id' => $serverId,
'server' => armory_server_name($serverId),
];
}
// Genauer Name zuerst, dann hoechste Stufe
$lower = mb_strtolower($name);
usort($results, static fn (array $a, array $b): int => [mb_strtolower($a['name']) !== $lower, -$a['level'], $a['name']]
<=> [mb_strtolower($b['name']) !== $lower, -$b['level'], $b['name']]);
return array_values(array_filter($results, static fn (array $r): bool => $r['id'] !== '' && $r['name'] !== ''));
}
/** Gueltige Charakter-ID von NCSoft (Base64-URL mit "="). */
function armory_valid_char_id(string $charId): bool
{
return (bool) preg_match('/^[A-Za-z0-9_\-]{20,120}={0,2}$/', $charId);
}
/**
* Holt Charakterinfo und Ausruestung und bereitet sie fuer die Anzeige auf (nur was wir zeigen).
*
* @return array<string, mixed>
*/
function armory_fetch(string $charId, int $serverId): array
{
$info = armory_request('https://' . ARMORY_API_HOST . '/api/character/info?' . armory_query($charId, $serverId));
$equip = armory_request('https://' . ARMORY_API_HOST . '/api/character/equipment?' . armory_query($charId, $serverId));
$profile = (array) ($info['profile'] ?? []);
if (empty($profile['characterName'])) {
throw new RuntimeException('Diesen Charakter gibt es im Spiel nicht (mehr).', 404);
}
$stats = [];
$itemLevel = null;
foreach ((array) ($info['stat']['statList'] ?? []) as $stat) {
$type = (string) ($stat['type'] ?? '');
if ($type === 'ItemLevel') {
$itemLevel = (int) ($stat['value'] ?? 0);
} elseif (in_array($type, ARMORY_BASE_STATS, true) || in_array($type, ARMORY_GOD_STATS, true)) {
$stats[$type] = [
'name' => (string) ($stat['name'] ?? $type),
'value' => (int) ($stat['value'] ?? 0),
'effects' => array_values(array_map('strval', (array) ($stat['statSecondList'] ?? []))),
];
}
}
$boards = [];
foreach ((array) ($info['daevanion']['boardList'] ?? []) as $board) {
$boards[] = [
'name' => (string) ($board['name'] ?? ''),
'icon' => (string) ($board['icon'] ?? ''),
'open' => (int) ($board['openNodeCount'] ?? 0),
'total' => (int) ($board['totalNodeCount'] ?? 0),
];
}
$equipment = [];
$extra = [];
foreach ((array) ($equip['equipment']['equipmentList'] ?? []) as $item) {
$slotName = (string) ($item['slotPosName'] ?? '');
$entry = [
'id' => (int) ($item['id'] ?? 0),
'name' => (string) ($item['name'] ?? ''),
'grade' => (string) ($item['grade'] ?? ''),
'icon' => (string) ($item['icon'] ?? ''),
'enchant' => (int) ($item['enchantLevel'] ?? 0),
'exceed' => (int) ($item['exceedLevel'] ?? 0),
'slot_pos' => (int) ($item['slotPos'] ?? 0),
];
if (isset(ARMORY_SLOTS[$slotName])) {
$equipment[ARMORY_SLOTS[$slotName]] = $entry;
} elseif (isset(ARMORY_EXTRA_SLOTS[$slotName])) {
$extra[$slotName] = $entry + ['label' => ARMORY_EXTRA_SLOTS[$slotName]];
}
}
$pet = (array) ($equip['petwing']['pet'] ?? []);
$wing = (array) ($equip['petwing']['wing'] ?? []);
return [
'name' => (string) $profile['characterName'],
'level' => (int) ($profile['characterLevel'] ?? 0),
'class' => armory_class_name((string) ($profile['className'] ?? '')),
'class_label' => (string) ($profile['className'] ?? ''),
'combat_power' => (int) ($profile['combatPower'] ?? 0),
'item_level' => $itemLevel,
'title' => !empty($profile['titleName']) ? ['name' => (string) $profile['titleName'], 'grade' => (string) ($profile['titleGrade'] ?? '')] : null,
'portrait' => (string) ($profile['profileImage'] ?? ''),
'server_id' => $serverId,
'stats' => $stats,
'boards' => $boards,
'equipment' => $equipment,
'extra' => $extra,
'pet' => !empty($pet['name']) ? ['name' => (string) $pet['name'], 'icon' => (string) ($pet['icon'] ?? ''), 'level' => (int) ($pet['level'] ?? 0)] : null,
'wing' => !empty($wing['name']) ? ['name' => (string) $wing['name'], 'icon' => (string) ($wing['icon'] ?? ''), 'grade' => (string) ($wing['grade'] ?? ''), 'enchant' => (int) ($wing['enchantLevel'] ?? 0)] : null,
];
}
/**
* Erneuert die Live-Daten eines verknuepften Charakters: speichert sie, holt das Portrait und
* gleicht Name, Klasse und Stufe des Profil-Charakters an. Gibt es den Charakter nicht mehr, bleibt
* die Verknuepfung bestehen, nur mit Fehlermeldung (aion_error).
*
* @param array<string, mixed> $character Zeile aus member_characters
* @return array<string, mixed> die aktualisierte Zeile
* @throws RuntimeException wenn NCSoft nicht erreichbar ist (die alten Daten bleiben dann stehen)
*/
function armory_refresh(array $character): array
{
$charId = (string) $character['aion_char_id'];
$serverId = (int) $character['aion_server_id'];
$pdo = db();
try {
$data = armory_fetch($charId, $serverId);
} catch (RuntimeException $e) {
if ($e->getCode() === 404) {
$pdo->prepare('UPDATE member_characters SET aion_fetched_at = ?, aion_error = ? WHERE id = ?')
->execute([date('Y-m-d H:i:s'), mb_substr($e->getMessage(), 0, 255), (int) $character['id']]);
$character['aion_error'] = $e->getMessage();
$character['aion_fetched_at'] = date('Y-m-d H:i:s');
return $character;
}
throw $e;
}
$portrait = armory_store_portrait((int) $character['id'], $data['portrait']);
$data['portrait'] = $portrait;
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
$level = $data['level'] >= 1 && $data['level'] <= PROFILE_MAX_LEVEL ? $data['level'] : $character['level'];
$class = $data['class'] ?? $character['class_name'];
$pdo->prepare(
'UPDATE member_characters SET name = ?, class_name = ?, level = ?, aion_data = ?, aion_fetched_at = ?, aion_error = NULL WHERE id = ?'
)->execute([mb_substr($data['name'], 0, 60), $class, $level, $json, date('Y-m-d H:i:s'), (int) $character['id']]);
return array_merge($character, [
'name' => mb_substr($data['name'], 0, 60), 'class_name' => $class, 'level' => $level,
'aion_data' => $json, 'aion_fetched_at' => date('Y-m-d H:i:s'), 'aion_error' => null,
]);
}
/** Gespeicherte Live-Daten eines Charakters (null = nicht verknuepft oder noch nie abgerufen). */
function armory_data(array $character): ?array
{
if (empty($character['aion_char_id']) || empty($character['aion_data'])) {
return null;
}
$data = json_decode((string) $character['aion_data'], true);
return is_array($data) ? $data : null;
}
/** Sind die Live-Daten alt genug, um sie zu erneuern? */
function armory_is_stale(array $character, int $age = ARMORY_TTL): bool
{
return !empty($character['aion_char_id'])
&& (empty($character['aion_fetched_at']) || strtotime((string) $character['aion_fetched_at']) < time() - $age);
}
/**
* Laedt eine Datei von NCSoft (Icons, Portraits). Weiterleitungen nur zu Servern von NCSoft
* (plaync.com, playnccdn.com), hoechstens zwei.
*/
function armory_download(string $url, int $maxBytes = 2 * 1024 * 1024): string
{
for ($hop = 0; $hop < 3; $hop++) {
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
if (parse_url($url, PHP_URL_SCHEME) !== 'https' || !preg_match('/(^|\.)(plaync\.com|playnccdn\.com)$/', $host)) {
throw new RuntimeException('Unerlaubte Adresse.');
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_USERAGENT => ARMORY_AGENT,
CURLOPT_HTTPHEADER => ['Accept: image/*'],
]);
$body = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$location = (string) curl_getinfo($ch, CURLINFO_REDIRECT_URL);
if ($body === false) {
throw new RuntimeException('Bild nicht erreichbar.');
}
if (in_array($status, [301, 302, 303, 307, 308], true) && $location !== '') {
$url = $location;
continue;
}
if ($status !== 200 || strlen((string) $body) > $maxBytes) {
throw new RuntimeException('Bild nicht verfuegbar (Status ' . $status . ').');
}
return (string) $body;
}
throw new RuntimeException('Zu viele Weiterleitungen.');
}
/** Prueft heruntergeladene Bilddaten und liefert die Endung (png, jpg, webp, gif) oder null. */
function armory_image_ext(string $bytes): ?string
{
$info = @getimagesizefromstring($bytes);
return $info ? ([IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_WEBP => 'webp', IMAGETYPE_GIF => 'gif'][$info[2]] ?? null) : null;
}
/**
* Speichert das Portrait aus dem Spiel als assets/uploads/armory/char<ID>.<ext> (ersetzt das alte).
*
* @return string Dateiname oder '' (kein Portrait)
*/
function armory_store_portrait(int $characterId, string $url): string
{
if ($url === '') {
return '';
}
try {
$bytes = armory_download($url);
$ext = armory_image_ext($bytes);
if ($ext === null) {
return '';
}
$name = 'char' . $characterId . '.' . $ext;
foreach (glob(ARMORY_ICON_DIR . 'char' . $characterId . '.*') ?: [] as $old) {
if (basename($old) !== $name) {
@unlink($old);
}
}
if (@file_put_contents(ARMORY_ICON_DIR . $name, $bytes) === false) {
return '';
}
return $name;
} catch (RuntimeException $e) {
return '';
}
}
/**
* Portrait-Dateien aus dem Spiel zu Profil-Charakteren - beim Loeschen von Charakteren bzw. Konten
* mit wegraeumen (die Datenbankzeilen fallen weg, die Dateien nicht).
*
* @param array<int, int|string> $characterIds
* @return array<int, string> Pfade
*/
function armory_portrait_files(array $characterIds): array
{
$files = [];
foreach ($characterIds as $id) {
foreach (glob(ARMORY_ICON_DIR . 'char' . (int) $id . '.*') ?: [] as $file) {
$files[] = $file;
}
}
return $files;
}
function armory_portrait_url(array $data): ?string
{
$name = (string) ($data['portrait'] ?? '');
return preg_match('/^char\d+\.(png|jpg|webp|gif)$/', $name) && is_file(ARMORY_ICON_DIR . $name)
? ARMORY_ICON_URL . $name . '?v=' . filemtime(ARMORY_ICON_DIR . $name) : null;
}
/** Dateiname eines Icons von NCSoft (nur aus ARMORY_ICON_BASE) oder null. */
function armory_icon_file(string $url): ?string
{
if (!str_starts_with($url, ARMORY_ICON_BASE)) {
return null;
}
$file = substr($url, strlen(ARMORY_ICON_BASE));
return preg_match('/^[A-Za-z0-9_\-]{1,100}\.png$/', $file) ? $file : null;
}
/** Adresse eines Icons bei uns: schon geladen direkt, sonst ueber armory_icon.php (laedt es einmalig). */
function armory_icon_url(string $url): ?string
{
$file = armory_icon_file($url);
if ($file === null) {
return null;
}
return is_file(ARMORY_ICON_DIR . $file) ? ARMORY_ICON_URL . $file : '/armory_icon.php?f=' . rawurlencode($file);
}
// ---- Infos zu einzelnen Gegenstaenden (Info-Blase) ----
/**
* Werte eines angelegten Gegenstands (mit Manasteinen des Charakters), zwischengespeichert in armory_cache.
*
* @return array<string, mixed>
*/
function armory_item(string $charId, int $serverId, int $itemId, int $enchant, int $slotPos): array
{
$key = 'item:' . sha1($charId . '|' . $serverId . '|' . $itemId . '|' . $enchant . '|' . $slotPos);
$stmt = db()->prepare('SELECT data FROM armory_cache WHERE cache_key = ? AND fetched_at > ?');
$stmt->execute([$key, date('Y-m-d H:i:s', time() - ARMORY_ITEM_TTL)]);
$cached = $stmt->fetchColumn();
if ($cached !== false && is_array($item = json_decode((string) $cached, true))) {
return $item;
}
$item = armory_request('https://' . ARMORY_API_HOST . '/api/character/equipment/item?' . http_build_query([
'id' => $itemId, 'enchantLevel' => $enchant, 'characterId' => $charId, 'serverId' => $serverId, 'slotPos' => $slotPos,
'lang' => ARMORY_LANG, 'region' => ARMORY_REGION,
]));
db()->prepare('INSERT INTO armory_cache (cache_key, data, fetched_at) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE data = VALUES(data), fetched_at = VALUES(fetched_at)')
->execute([$key, json_encode($item, JSON_UNESCAPED_UNICODE), date('Y-m-d H:i:s')]);
// Alte Eintraege gelegentlich wegraeumen
if (random_int(1, 50) === 1) {
db()->prepare('DELETE FROM armory_cache WHERE fetched_at < ?')->execute([date('Y-m-d H:i:s', time() - 7 * 86400)]);
}
return $item;
}
/** Inhalt der Info-Blase zu einem Gegenstand (gleiche Klassen wie die Lagerhaus-Blase, assets/js/item-tooltip.js). */
function armory_item_tip_html(array $item): string
{
$iconUrl = armory_icon_url((string) ($item['icon'] ?? ''));
$grade = armory_grade_class((string) ($item['grade'] ?? ''));
$enchant = (int) ($item['enchantLevel'] ?? 0);
$meta = array_filter([(string) ($item['gradeName'] ?? ''), (string) ($item['categoryName'] ?? '')]);
$levels = array_filter([
!empty($item['level']) ? 'Gegenstandsstufe ' . (int) $item['level'] : '',
!empty($item['equipLevel']) ? 'ab Stufe ' . (int) $item['equipLevel'] : '',
]);
$html = '<div class="item-tip-head">'
. ($iconUrl ? '<img class="gear-icon ' . e($grade) . '" src="' . e($iconUrl) . '" alt="" width="56" height="56">' : '')
. '<div class="item-tip-title"><strong class="' . e($grade) . '">' . e((string) ($item['name'] ?? '')) . ($enchant > 0 ? ' +' . $enchant : '') . '</strong>'
. ($meta ? '<span class="item-tip-sub">' . e(implode(' · ', $meta)) . '</span>' : '')
. ($levels ? '<span class="item-tip-sub">' . e(implode(' · ', $levels)) . '</span>' : '')
. '</div></div>';
$list = static function (string $title, array $rows): string {
if (!$rows) {
return '';
}
$out = '<div class="item-tip-section">' . e($title) . '</div><ul class="item-tip-stats">';
foreach ($rows as [$label, $value]) {
$out .= '<li><span>' . e($label) . '</span><span class="item-tip-value">' . e($value) . '</span></li>';
}
return $out . '</ul>';
};
$main = [];
foreach ((array) ($item['mainStats'] ?? []) as $stat) {
$extra = (string) ($stat['extra'] ?? '0');
$main[] = [(string) ($stat['name'] ?? ''), (string) ($stat['value'] ?? '') . ($extra !== '' && $extra !== '0' ? ' (+' . $extra . ')' : '')];
}
$sub = [];
foreach ((array) ($item['subStats'] ?? []) as $stat) {
$sub[] = [(string) ($stat['name'] ?? ''), (string) ($stat['value'] ?? '')];
}
$stones = [];
foreach ((array) ($item['magicStoneStat'] ?? []) as $stat) {
$stones[] = [(string) ($stat['name'] ?? ''), (string) ($stat['value'] ?? '')];
}
$html .= $list('Grundwerte', $main) . $list('Zusatzwerte', $sub) . $list('Manasteine', $stones);
// Goetterstein: Name und Effekt als Text (zu lang fuer die Werte-Spalte)
foreach ((array) ($item['godStoneStat'] ?? []) as $stat) {
if (is_array($stat) && !empty($stat['name'])) {
$html .= '<div class="item-tip-section">Götterstein</div><p class="item-tip-text"><strong>'
. e(preg_replace('/^Götterstein:\s*/u', '', (string) $stat['name'])) . '</strong><br>' . e((string) ($stat['desc'] ?? $stat['value'] ?? '')) . '</p>';
}
}
$info = [];
if (!empty($item['maxEnchantLevel'])) {
$info[] = ['Aufwertung', $enchant . ' / ' . (int) $item['maxEnchantLevel']];
}
if (!empty($item['sources'])) {
$info[] = ['Herkunft', implode(', ', array_map('strval', (array) $item['sources']))];
}
if ($info) {
$html .= '<dl class="item-tip-lines">';
foreach ($info as [$label, $value]) {
$html .= '<div><dt>' . e($label) . '</dt><dd>' . e($value) . '</dd></div>';
}
$html .= '</dl>';
}
return $html . '<div class="item-tip-source">Daten: aion2.plaync.com</div>';
}
// ---- Anzeige auf der Profilseite ----
/** Ein Slot im Ausruestungsraster (Icon, Seltenheit, Aufwertung, Info-Blase). */
function armory_slot_html(?array $item, string $label, string $silhouetteKey, int $characterId): string
{
if (!$item) {
return '<span class="gear-doll-slot" title="' . e($label . ': leer') . '">' . gear_slot_silhouette($silhouetteKey) . '</span>';
}
$iconUrl = armory_icon_url($item['icon']);
$tipUrl = '/armory_api.php?' . http_build_query(['action' => 'item', 'character' => $characterId, 'slot' => $item['slot_pos']]);
$html = '<span class="gear-doll-slot is-filled ' . e(armory_grade_class($item['grade'])) . '" tabindex="0"'
. ' data-item-tip="' . e($item['name']) . '" data-item-tip-url="' . e($tipUrl) . '" aria-label="' . e($label . ': ' . $item['name'] . ($item['enchant'] > 0 ? ' +' . $item['enchant'] : '')) . '">';
$html .= $iconUrl ? '<img src="' . e($iconUrl) . '" alt="" loading="lazy">' : '<span class="gear-doll-initial">' . e(mb_substr($item['name'], 0, 1)) . '</span>';
if ($item['exceed'] > 0) {
$html .= '<span class="gear-doll-exceed">★' . (int) $item['exceed'] . '</span>';
}
if ($item['enchant'] > 0) {
$html .= '<span class="gear-doll-enchant">+' . (int) $item['enchant'] . '</span>';
}
return $html . '</span>';
}
/** Kurzangabe "vor 12 Minuten" fuer den Stand der Daten. */
function armory_age_label(?string $fetchedAt): string
{
if (!$fetchedAt) {
return 'noch nie';
}
$minutes = max(0, intdiv(time() - (int) strtotime($fetchedAt), 60));
return match (true) {
$minutes < 1 => 'gerade eben',
$minutes < 60 => 'vor ' . $minutes . ' Min.',
$minutes < 1440 => 'vor ' . intdiv($minutes, 60) . ' Std.',
default => 'am ' . date('d.m.Y', (int) strtotime($fetchedAt)),
};
}
/** Kampfkraft in Tausend mit einer Nachkommastelle (98986 -> "98,9k"), darunter ganz. */
function armory_power_label(int $power): string
{
return $power < 1000 ? (string) $power : number_format(floor($power / 100) / 10, 1, ',', '.') . 'k';
}
/**
* Kurzinfo an der Charakterkarte (Stufe, Gearscore, Kampfkraft) - oeffnet das Popup mit allen
* Live-Daten (armory_modal_html). Leer, wenn der Charakter nicht verknuepft ist.
*/
function armory_summary_html(array $character): string
{
if (empty($character['aion_char_id'])) {
return '';
}
$id = (int) $character['id'];
$data = armory_data($character);
$html = '<button type="button" class="character-live" data-armory-open="' . $id . '" data-armory-summary="' . $id . '" aria-haspopup="dialog" title="Live aus dem Spiel – Details ansehen">';
if ($data === null) {
return $html . '<span class="character-live-loading">' . (!empty($character['aion_error']) ? 'Keine Daten aus dem Spiel' : 'Daten aus dem Spiel werden geladen …') . '</span></button>';
}
$stats = [['Stufe', (string) (int) $data['level'], '']];
if ($data['item_level'] !== null) {
$stats[] = ['Gearscore', number_format((int) $data['item_level'], 0, ',', '.'), ''];
}
$stats[] = ['Kampfkraft', armory_power_label((int) $data['combat_power']), number_format((int) $data['combat_power'], 0, ',', '.')];
foreach ($stats as [$label, $value, $exact]) {
$html .= '<span class="character-live-stat"><span>' . e($label) . '</span><strong' . ($exact !== '' ? ' title="' . e($exact) . '"' : '') . '>' . e($value) . '</strong></span>';
}
return $html . '<span class="character-live-more">Details ›</span></button>';
}
/** Popup mit den Live-Daten eines Charakters (geoeffnet ueber die Kurzinfo, assets/js/armory.js). */
function armory_modal_html(array $character, bool $canRefresh): string
{
$id = (int) $character['id'];
return '<div class="modal-overlay" id="armory-modal-' . $id . '" hidden><div class="modal modal-armory" role="dialog" aria-modal="true" aria-label="' . e((string) $character['name'] . ' – live aus dem Spiel') . '">'
. '<button type="button" class="modal-close icon-button" title="Schließen" aria-label="Schließen">' . icon('x') . '</button>'
. armory_panel_html($character, $canRefresh)
. '<p class="armory-source text-muted">Daten von aion2.plaync.com (NCSoft), über unseren Server abgerufen. Beim Draufzeigen auf einen Gegenstand erscheinen seine Werte.</p>'
. '</div></div>';
}
/**
* Live-Bereich eines verknuepften Charakters: Kopf mit Kampfkraft, Ausruestung, Werte, Daevanion.
* Wird auf member.php ausgegeben und nach einem Abgleich von armory_api.php ersetzt.
*
* @param array<string, mixed> $character Zeile aus member_characters
*/
function armory_panel_html(array $character, bool $canRefresh): string
{
$id = (int) $character['id'];
$data = armory_data($character);
$stale = armory_is_stale($character);
$html = '<section class="armory" id="arsenal-' . $id . '" data-armory="' . $id . '"' . ($stale ? ' data-armory-stale' : '') . '>';
$head = '<div class="armory-status text-muted"><span>Live aus dem Spiel · Stand ' . e(armory_age_label($character['aion_fetched_at'] ?? null)) . '</span>';
if ($canRefresh) {
$head .= ' <button type="button" class="armory-text-button" data-armory-refresh="' . $id . '">Aktualisieren</button>';
}
$head .= '</div>';
if ($data === null) {
$html .= $head . '<p class="text-muted armory-empty">' . (!empty($character['aion_error'])
? e((string) $character['aion_error'])
: 'Die Daten aus dem Spiel werden gerade geladen …') . '</p>';
return $html . '</section>';
}
$portrait = armory_portrait_url($data);
$html .= '<div class="armory-head">';
if ($portrait) {
$html .= '<img class="armory-portrait" src="' . e($portrait) . '" alt="" loading="lazy">';
}
$html .= '<div class="armory-head-info"><h3>' . e($data['name']) . ' ' . class_badge_html($data['class'], 22) . '</h3>'
. '<div class="text-muted">' . e(trim(($data['class'] ?? $data['class_label']) . ' · Stufe ' . (int) $data['level'] . ' · ' . armory_server_name((int) $data['server_id']))) . '</div>';
if (!empty($data['title'])) {
$html .= '<div class="armory-title ' . e(armory_grade_class($data['title']['grade'])) . '">„' . e($data['title']['name']) . '“</div>';
}
$html .= '</div><div class="armory-power">'
. '<div class="armory-power-value"><span>Kampfkraft</span><strong title="' . e(number_format((int) $data['combat_power'], 0, ',', '.')) . '">' . e(armory_power_label((int) $data['combat_power'])) . '</strong></div>'
. ($data['item_level'] !== null ? '<div class="armory-power-value"><span>Gearscore</span><strong>' . e(number_format((int) $data['item_level'], 0, ',', '.')) . '</strong></div>' : '')
. '</div></div>';
$html .= $head;
if (!empty($character['aion_error'])) {
$html .= '<p class="armory-warning">' . e((string) $character['aion_error']) . ' Angezeigt wird der letzte Stand.</p>';
}
// Ausruestung wie im Gear-Planer (zwei pro Reihe), daneben Runen, Flügel und Begleiter
$html .= '<div class="armory-body"><div class="armory-gear"><div class="gear-doll armory-doll">';
foreach (GEAR_DOLL_ORDER as $slotKey) {
$html .= armory_slot_html($data['equipment'][$slotKey] ?? null, GEAR_SLOTS[$slotKey][0], $slotKey, $id);
}
$html .= '</div>';
$extras = [];
foreach (ARMORY_EXTRA_SLOTS as $slotName => $label) {
if (!empty($data['extra'][$slotName])) {
$extras[] = [$label, $data['extra'][$slotName]];
}
}
if ($extras || $data['wing'] || $data['pet']) {
$html .= '<ul class="armory-extras">';
foreach ($extras as [$label, $item]) {
$html .= '<li>' . armory_slot_html($item, $label, 'amulet', $id) . '<span><span class="text-muted">' . e($label) . '</span><span class="' . e(armory_grade_class($item['grade'])) . '">'
. e($item['name']) . ($item['enchant'] > 0 ? ' +' . (int) $item['enchant'] : '') . '</span></span></li>';
}
foreach (['wing' => 'Flügel', 'pet' => 'Begleiter'] as $key => $label) {
$entry = $data[$key];
if (!$entry) {
continue;
}
$iconUrl = armory_icon_url($entry['icon']);
$grade = armory_grade_class($entry['grade'] ?? null);
$html .= '<li><span class="gear-doll-slot is-filled ' . e($grade) . '">' . ($iconUrl ? '<img src="' . e($iconUrl) . '" alt="" loading="lazy">' : '') . '</span>'
. '<span><span class="text-muted">' . e($label) . '</span><span class="' . e($grade) . '">' . e($entry['name'])
. (!empty($entry['enchant']) ? ' +' . (int) $entry['enchant'] : '') . (!empty($entry['level']) ? ' · Stufe ' . (int) $entry['level'] : '') . '</span></span></li>';
}
$html .= '</ul>';
}
$html .= '</div>';
// Werte: Grundwerte und Gottheiten, Effekte im Tooltip
$html .= '<div class="armory-side">';
foreach (['Grundwerte' => ARMORY_BASE_STATS, 'Gottheiten' => ARMORY_GOD_STATS] as $title => $types) {
$rows = array_filter(array_map(static fn (string $type): ?array => $data['stats'][$type] ?? null, $types));
if (!$rows) {
continue;
}
$html .= '<h4>' . e($title) . '</h4><ul class="armory-stats">';
foreach ($rows as $stat) {
$html .= '<li' . ($stat['effects'] ? ' title="' . e(implode("\n", $stat['effects'])) . '"' : '') . ($stat['value'] === 0 ? ' class="is-zero"' : '') . '>'
. '<span>' . e($stat['name']) . '</span><strong>' . (int) $stat['value'] . '</strong></li>';
}
$html .= '</ul>';
}
if ($data['boards']) {
$html .= '<h4>Daevanion</h4><ul class="armory-boards">';
foreach ($data['boards'] as $board) {
$percent = $board['total'] > 0 ? (int) round($board['open'] * 100 / $board['total']) : 0;
$iconUrl = armory_icon_url($board['icon']);
$html .= '<li title="' . e($board['open'] . ' von ' . $board['total'] . ' Feldern') . '">'
. ($iconUrl ? '<img src="' . e($iconUrl) . '" alt="" width="22" height="22" loading="lazy">' : '')
. '<span class="armory-board-name">' . e($board['name']) . '</span>'
. '<span class="armory-board-bar"><span style="width: ' . $percent . '%"></span></span>'
. '<span class="armory-board-value">' . $percent . '&nbsp;%</span></li>';
}
$html .= '</ul>';
}
$html .= '</div></div>';
return $html . '</section>';
}