LuminaWebsite/includes/gear_source.php

753 lines
34 KiB
PHP
Raw Permalink 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: Werte der Gegenstaende von aion2hub.com holen und auslesen.
*
* aion2hub liest die Werte direkt aus dem Spielclient aus (Global-Client). Abgerufen wird nur
* auf Knopfdruck eines Admins und immer nur eine Seite auf einmal (siehe admin/gear_items.php) -
* die Schnittstelle /api/ der Seite ist fuer Bots gesperrt, die normalen Seiten und die Icons
* (/api/icon/) sind erlaubt. Die Beschreibungen der Skills samt offizieller deutscher Namen kommen
* von aion2.app (Daten aus der NCSOFT-Schnittstelle, deutscher Client), ebenfalls Seite fuer Seite.
*/
const GEAR_SOURCE_HOST = 'aion2hub.com';
const GEAR_SOURCE_ITEM_URL = 'https://aion2hub.com/database/items/';
const GEAR_SOURCE_ICON_URL = 'https://aion2hub.com/api/icon/items/';
const GEAR_SOURCE_AGENT = 'LuminaAscendensGearPlanner/1.0 (+Legion-Website, einzelne Abrufe auf Knopfdruck)';
// Skill-Beschreibungen auf Deutsch: https://aion2.app/de/db/skills/<Skill-ID> (dieselben IDs wie bei aion2hub)
const GEAR_SOURCE_INFO_HOST = 'aion2.app';
const GEAR_SOURCE_SKILL_INFO_URL = 'https://aion2.app/de/db/skills/';
// Symbole aus dem Spielclient unter ihrem Dateinamen (z.B. ICON_CH_SKILL_013.webp - den Namen nennt aion2.app nach der
// offiziellen Schnittstelle von NCSOFT). aion2hub liefert fuer manche Skills ein falsches Symbol, deshalb ersetzt
// "Beschreibungen uebernehmen" sie hiermit (gear_skill_icon_replace) - fehlt die Datei bei aion2.app (wie bei Zauber der
// Genesung), kommt dieselbe Datei von der questlog-CDN
const GEAR_SOURCE_SKILL_ICON_FILE_URL = 'https://aion2.app/db-item-icons/';
const GEAR_SOURCE_ICON_FALLBACK_HOST = 'cdn.questlog.gg';
const GEAR_SOURCE_SKILL_ICON_FALLBACK_URL = 'https://cdn.questlog.gg/aion-2/assets/Game/UI/Resource/Texture/Skill/';
/** Laedt eine Seite von aion2hub bzw. aion2.app oder ein Symbol der questlog-CDN (nur diese Hosts, kein Weiterleiten). */
function gear_source_fetch(string $url, string $accept = 'text/html,image/*'): string
{
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
$allowed = [GEAR_SOURCE_HOST, 'www.' . GEAR_SOURCE_HOST, GEAR_SOURCE_INFO_HOST, GEAR_SOURCE_ICON_FALLBACK_HOST];
if (parse_url($url, PHP_URL_SCHEME) !== 'https' || !in_array($host, $allowed, true)) {
throw new RuntimeException('Nur Adressen von ' . GEAR_SOURCE_HOST . ', ' . GEAR_SOURCE_INFO_HOST . ' und ' . GEAR_SOURCE_ICON_FALLBACK_HOST . ' sind erlaubt.');
}
$site = match (true) {
str_ends_with($host, GEAR_SOURCE_INFO_HOST) => GEAR_SOURCE_INFO_HOST,
$host === GEAR_SOURCE_ICON_FALLBACK_HOST => GEAR_SOURCE_ICON_FALLBACK_HOST,
default => GEAR_SOURCE_HOST,
};
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 => 15,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_USERAGENT => GEAR_SOURCE_AGENT,
CURLOPT_HTTPHEADER => ['Accept: ' . $accept],
]);
$body = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($body === false) {
throw new RuntimeException($site . ' nicht erreichbar: ' . $error);
}
if ($status === 404) {
throw new RuntimeException($site === GEAR_SOURCE_HOST ? 'Diesen Gegenstand gibt es bei aion2hub nicht.' : 'Diese Seite gibt es bei ' . $site . ' nicht.');
}
if ($status !== 200) {
throw new RuntimeException($site . ' antwortet mit Status ' . $status . '.');
}
return (string) $body;
}
/**
* Liest eine Skill-Seite von aion2.app (deutsch) aus: offizieller deutscher Name, Beschreibung mit den
* Werten bei Stufe 1, Merkmale ("Ziellos | Bewegung moeglich"), Details (Schadensart, Reichweite, Waffe …)
* und die Texte der Spezialisierungen bzw. Stigma-Boni in der Reihenfolge des Spiels. Dazu die Beschreibung
* als Vorlage mit den Werten je Stufe (tpl, vals - siehe gear_source_skill_levels) und der Dateiname des
* Skill-Symbols aus dem Spielclient (icon, leer wenn keins gefunden).
*
* @return array{name: string, desc: string, tags: string, details: array<string, string>, parts: array<int, array{0: int, 1: string}>, icon: string, tpl: string, vals: array<int, string[]>}
*/
function gear_source_parse_skill_info(string $html, int $skillId): array
{
if (!str_contains($html, '/db/skills/' . $skillId . '"')) {
throw new RuntimeException('Die Seite gehört nicht zu Skill #' . $skillId . ' - hat sich aion2.app geändert?');
}
$body = preg_replace('#<script\b.*?</script>#s', '', $html) ?? $html;
$text = static fn (string $fragment): string => trim(html_entity_decode(strip_tags(str_replace(['<!-- -->', '<br>', '<br/>'], ['', "\n", "\n"], $fragment)), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
if (!preg_match('#<h1[^>]*>(.*?)</h1>#s', $body, $name)) {
throw new RuntimeException('Skill #' . $skillId . ': kein Name auf der Seite - hat sich aion2.app geändert?');
}
// Beschreibung (text-sm) und Merkmale (text-xs) stehen in Absaetzen mit whitespace-pre-line
preg_match_all('#<p class="(text-(?:sm|xs))[^"]*whitespace-pre-line[^"]*">(.*?)</p>#s', $body, $paragraphs, PREG_SET_ORDER);
$desc = '';
$tags = '';
foreach ($paragraphs as [, $size, $inner]) {
if ($size === 'text-sm' && $desc === '') {
$desc = $text($inner);
} elseif ($size === 'text-xs' && $tags === '' && $desc !== '') {
$tags = $text($inner);
}
}
// Details: Paare aus Beschriftung und Wert hinter der Ueberschrift "Details"
$details = [];
$at = strpos($body, '>Details<');
if ($at !== false) {
preg_match_all('#<(?:dt|span|div)[^>]*>([^<]{1,40})</(?:dt|span|div)>\s*<(?:dd|span|div)[^>]*>(.*?)</(?:dd|span|div)>#s', substr($body, $at, 3000), $rows, PREG_SET_ORDER);
foreach ($rows as [, $label, $value]) {
$details[trim($label)] = mb_substr($text($value), 0, 60);
}
}
// Spezialisierungen / Stigma-Boni: "Level 8" und der Text daneben
preg_match_all('#>Level(?:<!-- -->)? (?:<!-- -->)?(\d+)</span><span class="text-sm[^"]*">(.*?)</span></div>#s', $body, $specs, PREG_SET_ORDER);
// Symbol des Skills (64 px - daneben stehen z.B. kleine Stigma-Symbole): Dateiname aus dem Spielclient
$icon = preg_match('#<img src="/db-item-icons/([A-Za-z0-9_\-]+\.(?:webp|png))"[^>]*\bwidth="64"#', $body, $iconMatch) ? $iconMatch[1] : '';
return [
'name' => mb_substr($text($name[1]), 0, 100),
'desc' => mb_substr($desc, 0, 1000),
'tags' => mb_substr($tags, 0, 200),
'details' => $details,
'parts' => array_map(static fn (array $m): array => [(int) $m[1], mb_substr($text($m[2]), 0, 200)], $specs),
'icon' => $icon,
] + gear_source_skill_levels($html);
}
/**
* Daten, die eine Next.js-Seite fuer React mitschickt: die Stuecke aus self.__next_f.push([1,"…"]),
* ausgepackt und aneinandergehaengt.
*/
function gear_source_next_payload(string $html): string
{
preg_match_all('#self\.__next_f\.push\(\[1,"((?:[^"\\\\]++|\\\\.)*+)"\]\)#', $html, $chunks);
$payload = '';
foreach ($chunks[1] as $chunk) {
$decoded = json_decode('"' . $chunk . '"');
$payload .= is_string($decoded) ? $decoded : '';
}
return $payload;
}
/**
* Beschreibung eines Skills je Stufe aus den Seitendaten von aion2.app. Dort steht sie als Vorlage mit
* Platzhaltern ("… {se_dmg:1801000011:SkillUIMinDmgSum}–{se_dmg:1801000011:SkillUIMaxDmgSum} Schaden …") und
* je Stufe den Werten dazu. Werte, die bei jeder Stufe gleich sind, kommen gleich in den Text, gleiche Spannen
* ("74–74") werden ein Wert; die uebrigen werden {0}, {1} … mit ihren Werten ab Stufe 1 in vals.
* Zahlen deutsch geschrieben (1.857, 0,7).
*
* @return array{tpl: string, vals: array<int, string[]>} tpl leer, wenn die Seite keine Stufenwerte hat
*/
function gear_source_skill_levels(string $html): array
{
$none = ['tpl' => '', 'vals' => []];
$payload = gear_source_next_payload($html);
$at = strpos($payload, '"levels":[{"level":');
if ($at === false) {
return $none;
}
// Das Objekt drumherum ({"locale":"de","levels":[…],"specs":[…],"description":"…",…}) beginnt an einer der
// oeffnenden Klammern kurz davor
$props = null;
$open = $at;
for ($try = 0; $try < 5 && $props === null; $try++) {
$open = strrpos(substr($payload, 0, $open), '{');
if ($open === false) {
return $none;
}
$end = gear_source_json_end($payload, $open);
$decoded = $end !== null ? json_decode(substr($payload, $open, $end - $open), true) : null;
$props = is_array($decoded) && is_array($decoded['levels'] ?? null) ? $decoded : null;
}
$tpl = is_string($props['description'] ?? null) ? trim($props['description']) : '';
if ($props === null || $tpl === '' || !$props['levels']) {
return $none;
}
$levels = array_values(array_filter($props['levels'], static fn ($level): bool => is_array($level)));
usort($levels, static fn (array $a, array $b): int => (int) ($a['level'] ?? 0) <=> (int) ($b['level'] ?? 0));
$levels = array_slice($levels, 0, 40);
// Werte je Platzhalter ab Stufe 1 ("?" wie bei aion2.app, wo ein Wert fehlt). Mit Teiler im Namen
// (":divide1000") teilt aion2.app nicht immer - steht derselbe Wert ohne Teiler daneben, wird hier geteilt.
// Zeiten (":time", in Sekunden) stehen ohne Einheit in der Vorlage - die setzt das Spiel dazu.
preg_match_all('/\{([^{}\s]+)\}/', $tpl, $found);
$series = [];
foreach (array_unique($found[1]) as $token) {
$divide = preg_match('/^(.+):divide(\d+)$/', $token, $d) && (int) $d[2] > 1 ? [$d[1], (int) $d[2]] : null;
$time = str_ends_with($token, ':time');
$series[$token] = array_map(static function (array $level) use ($token, $divide, $time): string {
$values = (array) ($level['token_values'] ?? []);
$value = $values[$token] ?? null;
if ($divide !== null && is_numeric($value) && (string) ($values[$divide[0]] ?? '') === (string) $value) {
$value = (string) ((float) $value / $divide[1]);
}
if ($time && is_numeric($value)) {
$seconds = (float) $value;
return $seconds >= 60 && fmod($seconds, 60) === 0.0
? gear_source_skill_value((string) ($seconds / 60)) . ' Min.'
: gear_source_skill_value((string) $value) . ' Sek.';
}
return gear_source_skill_value($value);
}, $levels);
}
$tpl = preg_replace_callback(
'/\{([^{}\s]+)\}\s*[–~-]\s*\{([^{}\s]+)\}/u',
static fn (array $m): string => ($series[$m[1]] ?? null) === ($series[$m[2]] ?? null) ? '{' . $m[1] . '}' : $m[0],
$tpl
) ?? $tpl;
$vals = [];
$index = [];
$tpl = preg_replace_callback('/\{([^{}\s]+)\}/', static function (array $m) use ($series, &$vals, &$index): string {
$values = $series[$m[1]] ?? ['?'];
if (count(array_unique($values)) === 1) {
return $values[0];
}
if (!isset($index[$m[1]])) {
$index[$m[1]] = count($vals);
$vals[] = $values;
}
return '{' . $index[$m[1]] . '}';
}, $tpl) ?? '';
return ['tpl' => mb_substr($tpl, 0, 1000), 'vals' => $vals];
}
/** Ein Wert von aion2.app deutsch geschrieben: "1857" => "1.857", "0.7" => "0,7" (anderes bleibt, wie es ist). */
function gear_source_skill_value(mixed $value): string
{
$value = trim((string) ($value ?? ''));
if (!preg_match('/^(-?)(\d+)(?:\.(\d+))?$/', $value, $m)) {
return $value === '' ? '?' : str_replace('|', '/', mb_substr($value, 0, 20));
}
return $m[1] . number_format((float) $m[2], 0, ',', '.') . (($m[3] ?? '') !== '' ? ',' . $m[3] : '');
}
/**
* Ende eines JSON-Objekts bzw. -Arrays, das bei $open ("{" oder "[") beginnt - Klammern in Texten zaehlen nicht mit.
* Gibt die Position nach der schliessenden Klammer zurueck oder null.
*/
function gear_source_json_end(string $text, int $open): ?int
{
$depth = 0;
$len = strlen($text);
for ($i = $open; $i < $len; $i++) {
$ch = $text[$i];
if ($ch === '"') {
// Text ueberspringen (mit \" darin)
for ($i++; $i < $len && $text[$i] !== '"'; $i++) {
if ($text[$i] === '\\') {
$i++;
}
}
continue;
}
if ($ch === '{' || $ch === '[') {
$depth++;
} elseif ($ch === '}' || $ch === ']') {
$depth--;
if ($depth === 0) {
return $i + 1;
}
}
}
return null;
}
/** Gegenstands-ID aus einer ID oder einem aion2hub-Link ("…/database/items/110130060"). */
function gear_source_parse_id(string $input): ?int
{
$input = trim($input);
if (preg_match('/^\d{6,12}$/', $input)) {
return (int) $input;
}
if (preg_match('#aion2hub\.com/database/items/(\d{6,12})#i', $input, $m)) {
return (int) $m[1];
}
return null;
}
// Kategorien der Datenbank, die der Gear-Planer kennt (Listen ohne Kategorie = alle drei)
const GEAR_SOURCE_CATEGORIES = ['Weapons', 'Armor', 'Accessories'];
/** Alle Gegenstands-IDs, die auf einer Listenseite von aion2hub verlinkt sind. */
function gear_source_list_ids(string $html): array
{
preg_match_all('#href="/database/items/(\d{6,12})"#', $html, $m);
return array_values(array_unique(array_map('intval', $m[1])));
}
/**
* Listen-Adresse (aion2hub.com/database?...) in die Listen je Kategorie aufteilen. Ohne
* Kategorie werden es Waffen, Ruestungen und Schmuck; weitere Filter (z.B. grade) bleiben.
*
* @return string[] Adressen ohne Seitenzahl
* @throws RuntimeException bei fremden Adressen oder Kategorien ohne Ausruestung
*/
function gear_source_list_urls(string $url): array
{
if (!preg_match('#^https://(www\.)?aion2hub\.com/database/?(\?.*)?$#i', trim($url))) {
throw new RuntimeException('Bitte eine Gegenstands-ID, einen Gegenstands-Link oder eine Listen-Seite von aion2hub.com/database eintragen.');
}
parse_str((string) parse_url(trim($url), PHP_URL_QUERY), $query);
unset($query['page'], $query['view']);
$query = array_filter($query, static fn ($value): bool => is_string($value) && $value !== '');
$categories = isset($query['cat']) ? [(string) $query['cat']] : GEAR_SOURCE_CATEGORIES;
foreach ($categories as $category) {
if (!in_array($category, GEAR_SOURCE_CATEGORIES, true)) {
throw new RuntimeException('Die Kategorie „' . $category . '“ enthält keine Ausrüstung - nur Weapons, Armor und Accessories lassen sich übernehmen.');
}
}
return array_map(
static fn (string $category): string => 'https://' . GEAR_SOURCE_HOST . '/database?' . http_build_query(['cat' => $category] + $query),
$categories
);
}
/**
* Eine Seite einer Liste: enthaltene IDs, Seitenzahl und Gesamtzahl ("1,844 items · page 1 of 31").
*
* @return array{ids: int[], page: int, pages: int, total: int}
*/
function gear_source_list_page(string $html): array
{
$text = implode(' ', gear_source_tokens($html));
preg_match('/page\s+(\d+)\s+of\s+(\d+)/i', $text, $pages);
preg_match('/([\d,]+)\s+items\s+·\s+page/i', $text, $total);
$ids = gear_source_list_ids($html);
return [
'ids' => $ids,
'page' => (int) ($pages[1] ?? 1),
'pages' => max(1, (int) ($pages[2] ?? 1)),
'total' => (int) str_replace(',', '', $total[1] ?? (string) count($ids)),
];
}
/** Seite in Textbausteine zerlegen (jedes HTML-Element wird zur Trennstelle). */
function gear_source_tokens(string $html): array
{
$html = preg_replace('#<(script|style|noscript)\b.*?</\1>#is', '', $html) ?? '';
$text = preg_replace('/<[^>]+>/', '|', $html) ?? '';
$text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$tokens = [];
foreach (explode('|', $text) as $token) {
$token = trim(preg_replace('/\s+/u', ' ', $token) ?? '');
if ($token !== '') {
$tokens[] = $token;
}
}
return $tokens;
}
/** "1,100" -> [1100, ''], "33%" -> [33, '%'], sonst null */
function gear_source_number(string $value): ?array
{
$value = trim($value);
if (!preg_match('/^(-?[\d,]+(?:\.\d+)?)\s*(%?)$/', $value, $m)) {
return null;
}
return [(float) str_replace(',', '', $m[1]), $m[2]];
}
/** "Min Attack 106, Max Attack 106" -> [['Min Attack', 106, ''], …] */
function gear_source_stat_list(string $text): array
{
$stats = [];
foreach (explode(',', $text) as $part) {
if (preg_match('/^\s*(.+?)\s+(-?[\d.]+)\s*(%?)\s*$/u', $part, $m)) {
$stats[] = [$m[1], (float) $m[2], $m[3]];
}
}
return $stats;
}
// ---- Skills (Klassenseiten, z.B. aion2hub.com/classes/chanter) ----
const GEAR_SOURCE_CLASS_URL = 'https://aion2hub.com/classes/';
const GEAR_SOURCE_SKILL_ICON_URL = 'https://aion2hub.com/api/skill-icon/';
// Klassen der Website => Adresse und Name bei aion2hub (ohne den Brawler, den es bei uns nicht gibt)
const GEAR_SOURCE_CLASSES = [
'Templer' => ['templar', 'Templar'],
'Gladiator' => ['gladiator', 'Gladiator'],
'Assassine' => ['assassin', 'Assassin'],
'Jäger' => ['ranger', 'Ranger'],
'Magier' => ['sorcerer', 'Sorcerer'],
'Beschwörer' => ['spiritmaster', 'Spiritmaster'],
'Kleriker' => ['cleric', 'Cleric'],
'Kantor' => ['chanter', 'Chanter'],
];
/**
* Liest die Skill-Liste einer Klassenseite aus: "<Klasse> skills", darunter "Active skills" und
* "Passive skills" als Karten (Icon /api/skill-icon/<ID>, Name, Art wie "Attack" - bei manchen
* fehlt die Art). Nur diese Kernliste stammt aus dem Global-Client; der Abschnitt danach
* ("More … skills (Korea/Taiwan client data)") ist ungeprueft und wird bewusst ausgelassen.
*
* Die aktiven Skills stehen dort in der Reihenfolge des Spiels: erst die 12 normalen (Meisterschaft,
* mit Skillpunkten gesteigert), dann "Dodge", danach die Stigma-Skills. Alles nach Dodge wird
* deshalb als kind "stigma" gefuehrt, Dodge selbst (ohne Stufen) ausgelassen. Abgeglichen mit den
* Meisterschafts- und Stigma-Listen aus dem Global-Client (Stand Launch Scale Test, alle 8 Klassen).
*
* @return array{class: string, source_version: string, skills: array<int, array{id: int, name: string, kind: string, category: string}>}
*/
function gear_source_parse_class_skills(string $html, string $expectedClass): array
{
$html = preg_replace('#<(script|style|noscript)\b.*?</\1>#is', '', $html) ?? '';
// Ueberschriften der Seite mit Position, um die Abschnitte abzugrenzen
preg_match_all('#<(h2|h3)\b[^>]*>(.*?)</\1>#is', $html, $headings, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
$core = null;
$coreEnd = strlen($html);
foreach ($headings as $heading) {
$text = trim(html_entity_decode(strip_tags($heading[2][0]), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
$position = $heading[0][1];
if ($core === null && $heading[1][0] === 'h2' && preg_match('/^(\S+) skills$/i', $text, $m)) {
$core = ['class' => $m[1], 'start' => $position + strlen($heading[0][0])];
} elseif ($core !== null && $heading[1][0] === 'h2') {
$coreEnd = $position;
break;
}
}
if ($core === null) {
throw new RuntimeException('Die Seite sieht nicht wie eine Klassenseite von aion2hub aus (keine Skill-Liste gefunden).');
}
if (strcasecmp($core['class'], $expectedClass) !== 0) {
throw new RuntimeException('Die Seite gehört zu einer anderen Klasse (' . $core['class'] . ').');
}
$section = substr($html, $core['start'], $coreEnd - $core['start']);
// "Core skill list — 26 active and 10 passive skills — from Global data (Launch Scale Test client, 2026-09-19)."
$intro = implode(' ', gear_source_tokens(substr($section, 0, (int) (stripos($section, '<h3') ?: strlen($section)))));
preg_match('/(\d+)\s+active\s+and\s+(\d+)\s+passive/i', $intro, $counts);
$version = preg_match('/from\s+(.+?)\.?$/i', $intro, $m) ? trim($m[1]) : '';
if (!str_contains($version, 'Global')) {
throw new RuntimeException('Keine Skill-Liste aus dem Global-Client gefunden - nicht übernommen.');
}
// Abschnitte "Active skills" / "Passive skills", darin je Karte: Icon-ID, dann Name und (optional) Art
$parts = preg_split('#<h3\b[^>]*>(.*?)</h3>#is', $section, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
$skills = [];
for ($i = 1; $i < count($parts) - 1; $i += 2) {
$title = strtolower(trim(html_entity_decode(strip_tags($parts[$i]), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
$kind = str_starts_with($title, 'active') ? 'active' : (str_starts_with($title, 'passive') ? 'passive' : null);
if ($kind === null) {
continue;
}
$cards = preg_split('#(?=<img\b[^>]*src="/api/skill-icon/\d+")#i', $parts[$i + 1]) ?: [];
foreach ($cards as $card) {
if (!preg_match('#^<img\b[^>]*src="/api/skill-icon/(\d{4,10})"#i', $card, $id)) {
continue;
}
$tokens = gear_source_tokens($card);
$name = $tokens[0] ?? '';
if ($name === '' || mb_strlen($name) > 100) {
throw new RuntimeException('Skill #' . $id[1] . ' ohne lesbaren Namen - hat sich die Seite geändert?');
}
$skills[(int) $id[1]] = [
'id' => (int) $id[1],
'name' => $name,
'kind' => $kind,
'category' => mb_substr($tokens[1] ?? '', 0, 30),
];
}
}
// Stimmen die Zahlen nicht mit der Angabe oben ueberein, hat sich der Aufbau der Seite geaendert
$active = count(array_filter($skills, static fn (array $s): bool => $s['kind'] === 'active'));
$passive = count($skills) - $active;
if (!$skills || ($counts && ((int) $counts[1] !== $active || (int) $counts[2] !== $passive))) {
throw new RuntimeException('Skill-Liste nicht vollständig gelesen (' . $active . ' aktive, ' . $passive . ' passive'
. ($counts ? ', laut Seite ' . (int) $counts[1] . ' und ' . (int) $counts[2] : '') . ') - hat sich die Seite geändert?');
}
// Aktive Skills nach "Dodge" sind Stigma-Skills
$dodge = null;
foreach ($skills as $id => $skill) {
if ($skill['kind'] === 'active' && strcasecmp($skill['name'], 'Dodge') === 0) {
$dodge = $id;
break;
}
}
if ($dodge === null) {
throw new RuntimeException('„Dodge“ steht nicht in der Skill-Liste - ohne ihn lassen sich normale und Stigma-Skills nicht trennen. Hat sich die Seite geändert?');
}
$afterDodge = false;
foreach ($skills as $id => $skill) {
if ($skill['kind'] === 'active' && $afterDodge) {
$skills[$id]['kind'] = 'stigma';
}
$afterDodge = $afterDodge || $id === $dodge;
}
// Dodge selbst (Ausweichen) hat keine Stufen - im Planer hat er nichts zu suchen
unset($skills[$dodge]);
return ['class' => $core['class'], 'source_version' => $version, 'skills' => array_values($skills)];
}
// ---- Spezialisierungen und Stigma-Boni (Build-Planer von aion2hub) ----
const GEAR_SOURCE_PLANNER_URL = 'https://aion2hub.com/tools/build-calculator';
/**
* Die JavaScript-Dateien des Build-Planers (/_next/static/chunks/…js) - in einer davon steckt der
* Datensatz der Spezialisierungen. Die Namen aendern sich mit jeder neuen Version der Seite.
*
* @return string[] Pfade wie "/_next/static/chunks/10aljxxtaqul-.js"
*/
function gear_source_planner_chunks(string $html): array
{
preg_match_all('#/_next/static/chunks/[A-Za-z0-9_~-]+\.js#', $html, $m);
return array_values(array_unique($m[0]));
}
/**
* Einen JavaScript-String (Inhalt zwischen den Anfuehrungszeichen) so auswerten wie der Browser. Springt
* von Backslash zu Backslash statt Zeichen fuer Zeichen - die Datei mit den Gegenstaenden hat ueber 4 MB.
*/
function gear_source_js_unescape(string $js, int $start, string $quote, ?int &$end = null): string
{
$out = '';
$len = strlen($js);
$stop = $quote . '\\';
$pendingHigh = null; // erste Haelfte eines UTF-16-Paars (😀)
$i = $start;
while ($i < $len) {
$plain = strcspn($js, $stop, $i);
if ($plain > 0) {
$out .= substr($js, $i, $plain);
$i += $plain;
$pendingHigh = null;
if ($i >= $len) {
break;
}
}
if ($js[$i] === $quote) {
$end = $i; // Position des schliessenden Anfuehrungszeichens
return $out;
}
$next = $js[++$i] ?? '';
if ($next === 'u') {
if (($js[$i + 1] ?? '') === '{') {
$end = strpos($js, '}', $i);
$code = hexdec(substr($js, $i + 2, (int) $end - $i - 2));
$i = (int) $end + 1;
} else {
$code = hexdec(substr($js, $i + 1, 4));
$i += 5;
}
if ($code >= 0xD800 && $code <= 0xDBFF) {
$pendingHigh = $code;
continue;
}
if ($pendingHigh !== null && $code >= 0xDC00 && $code <= 0xDFFF) {
$code = 0x10000 + (($pendingHigh - 0xD800) << 10) + ($code - 0xDC00);
}
$pendingHigh = null;
$out .= mb_chr((int) $code, 'UTF-8');
continue;
}
$pendingHigh = null;
if ($next === 'x') {
// \xHH ist wie \u00HH ein Zeichen, kein einzelnes Byte
$out .= mb_chr((int) hexdec(substr($js, $i + 1, 2)), 'UTF-8');
$i += 3;
continue;
}
$out .= match ($next) {
'n' => "\n", 'r' => "\r", 't' => "\t", 'b' => "\x08", 'f' => "\f", 'v' => "\v", '0' => "\0",
default => $next, // \\ \' \" und alles andere steht fuer sich selbst
};
$i++;
}
throw new RuntimeException('Datensatz im Build-Planer nicht vollständig - hat sich der Planer geändert?');
}
/**
* Liest aus einer JavaScript-Datei des Build-Planers den Datensatz der Spezialisierungen (Global-Client):
* JSON.parse('{"builtAt":…,"slotUnlock":{"Mastery":[8,12,20],…},"byParent":{"<Skill-ID>":{"acquire":
* "Mastery"|"Stigma","parts":[{"threshold":8,"effect":"+20% MP restored"},…]}}}'). Normale aktive Skills
* ("Mastery") haben fuenf Spezialisierungen, Stigmen vier Boni (5/10/15/20). null = nicht in dieser Datei.
*
* @return array{built_at: string, slot_unlock: int[], skills: array<int, array{kind: string, parts: array<int, array{t: int, e: string, kr: int}>}>}|null
*/
function gear_source_parse_planner_specs(string $js): ?array
{
$marker = strpos($js, '"slotUnlock":{"Mastery"');
if ($marker === false) {
return null;
}
$open = strrpos(substr($js, 0, $marker), "JSON.parse('");
if ($open === false) {
throw new RuntimeException('Spezialisierungen gefunden, aber nicht lesbar - hat sich der Planer geändert?');
}
$data = json_decode(gear_source_js_unescape($js, $open + strlen("JSON.parse('"), "'"), true);
return gear_source_planner_specs_from(is_array($data) ? $data : []);
}
/** Den ausgepackten Datensatz der Spezialisierungen in die Form von gear_source_parse_planner_specs bringen. */
function gear_source_planner_specs_from(array $data): array
{
if (!is_array($data['byParent'] ?? null)) {
throw new RuntimeException('Datensatz der Spezialisierungen nicht lesbar - hat sich der Planer geändert?');
}
$skills = [];
foreach ($data['byParent'] as $skillId => $entry) {
$kind = (string) ($entry['acquire'] ?? '');
if (!ctype_digit((string) $skillId) || !in_array($kind, ['Mastery', 'Stigma'], true) || !is_array($entry['parts'] ?? null)) {
continue;
}
$parts = [];
foreach ($entry['parts'] as $part) {
$effect = trim((string) ($part['effect'] ?? ''));
if ($effect === '' || !is_numeric($part['threshold'] ?? null)) {
continue;
}
// Reihenfolge wie im Spiel (I-V bzw. Bonus bei 5/10/15/20)
$parts[] = ['t' => (int) $part['threshold'], 'e' => mb_substr($effect, 0, 200), 'kr' => ($part['effectSrc'] ?? '') === 'kr' ? 1 : 0];
}
$skills[(int) $skillId] = ['kind' => $kind, 'parts' => $parts];
}
return [
'built_at' => (string) ($data['builtAt'] ?? ''),
'slot_unlock' => array_map('intval', (array) ($data['slotUnlock']['Mastery'] ?? [])),
'skills' => $skills,
];
}
/**
* Liest eine Gegenstandsseite von aion2hub aus.
*
* @return array{source_id: int, name: string, category: string, grade: string, item_level: int,
* required_level: ?int, slot: string, item_type: string, stats: array, soul_imprint: array,
* soul_imprint_count: int, soul_skills: array, manastone_slots: int, godstone_slots: int, enchant_max: int,
* enchant_stats: array, exceed_max: int, exceed_stats: array, source_version: string}
*/
function gear_source_parse_item(string $html): array
{
$t = gear_source_tokens($html);
$n = count($t);
// Kopf: "Item Database / <Kategorie> / <Name> / Copy link / <Seltenheit> / Item Lv / 86 / …"
$start = null;
for ($i = 0; $i < $n - 4; $i++) {
if ($t[$i] === 'Item Database' && $t[$i + 1] === '/' && ($t[$i + 4] ?? '') === 'Copy link') {
$start = $i;
break;
}
}
if ($start === null) {
throw new RuntimeException('Die Seite sieht nicht wie eine Gegenstandsseite von aion2hub aus.');
}
$item = [
'category' => $t[$start + 2],
'name' => $t[$start + 3],
'grade' => $t[$start + 5],
'item_level' => 0,
'required_level' => null,
'slot' => '',
'item_type' => '',
'stats' => [],
'soul_imprint' => [],
'soul_imprint_count' => 0,
'soul_skills' => [],
'manastone_slots' => 0,
'godstone_slots' => 0,
'enchant_max' => 0,
'enchant_stats' => [],
'exceed_max' => 0,
'exceed_stats' => [],
'source_version' => '',
'source_id' => 0,
];
$i = $start + 6;
if (($t[$i] ?? '') === 'Item Lv') {
$item['item_level'] = (int) $t[$i + 1];
$i += 2;
}
if (($t[$i] ?? '') === 'Requires Lv') {
$item['required_level'] = (int) $t[$i + 1];
$i += 2;
}
$item['slot'] = $t[$i] ?? '';
$item['item_type'] = $t[$i + 1] ?? '';
// Grundwerte: Paare nach "Stats" bis zum naechsten Abschnitt
$stop = ['Soul Imprint', 'Item Info', 'KR/TW', 'Upgrades', 'How to Obtain'];
$statsAt = array_search('Stats', array_slice($t, $i, 40, true), true);
if ($statsAt !== false) {
for ($j = $statsAt + 1; $j < $n - 1 && !in_array($t[$j], $stop, true); $j += 2) {
$number = gear_source_number($t[$j + 1]);
if ($number === null) {
break;
}
$item['stats'][] = [$t[$j], $number[0], $number[1]];
}
// Seelenpraegung: "— 4 of these can be selected", dann "Name / 21 ~ 31"
if (($t[$j] ?? '') === 'Soul Imprint' && preg_match('/(\d+) of these can be selected/', $t[$j + 1] ?? '', $m)) {
$item['soul_imprint_count'] = (int) $m[1];
for ($k = $j + 2; $k < $n - 1; $k += 2) {
if (!preg_match('/^(-?[\d,.]+)(%?) ~ (-?[\d,.]+)(%?)$/', $t[$k + 1], $r)) {
break;
}
$item['soul_imprint'][] = [$t[$k], (float) str_replace(',', '', $r[1]), (float) str_replace(',', '', $r[3]), $r[2]];
}
// Danach je Klasse die Skills, von denen einer als Seelenpraegung kommen kann: "Cleric / skill / Bolt, Divine
// Aura, …" und "One of the listed skills can roll as a sub-stat (Lv 1)". Ringe nennen aktive, Ruestung passive
// Skills. Namen mit * gibt es nur im Korea-Client, die Klasse Fighter (noch) nicht bei uns.
$classes = [];
for (; $k < $n - 2 && ($t[$k + 1] ?? '') === 'skill'; $k += 3) {
$class = class_from_text($t[$k]);
$names = array_values(array_filter(array_map('trim', explode(',', $t[$k + 2])), static fn (string $name): bool => $name !== '' && !str_ends_with($name, '*')));
if ($class !== null && $names) {
$classes[$class] = $names;
}
}
if ($classes) {
$level = preg_match('/sub-stat \(Lv (\d+)\)/', $t[$k] ?? '', $lv) ? (int) $lv[1] : 1;
$item['soul_skills'] = ['level' => max(1, $level), 'classes' => $classes];
}
}
}
// Sockel und Aufwertung stehen unter "Item Info" / "Upgrades" (nach dem Korea-Vergleich)
$info = array_search('Item Info', $t, true);
if ($info !== false) {
for ($j = $info + 1; $j < $n - 1 && $t[$j] !== 'How to Obtain'; $j++) {
if ($t[$j] === 'Manastone sockets') {
$item['manastone_slots'] = (int) $t[$j + 1];
} elseif ($t[$j] === 'Godstone sockets') {
$item['godstone_slots'] = (int) $t[$j + 1];
} elseif (($t[$j] === 'Enchantable to' || str_starts_with($t[$j], 'Exceed')) && ($t[$j + 1] ?? '') === '+') {
// "Enchantable to / + / 15 / At + / 15 / : / Min Attack 106, Max Attack 106"
$max = (int) ($t[$j + 2] ?? 0);
$stats = ($t[$j + 3] ?? '') === 'At +' && ($t[$j + 5] ?? '') === ':' ? gear_source_stat_list($t[$j + 6] ?? '') : [];
if ($t[$j] === 'Enchantable to') {
$item['enchant_max'] = $max;
$item['enchant_stats'] = $stats;
} else {
$item['exceed_max'] = $max;
$item['exceed_stats'] = $stats;
}
}
}
}
// Fusszeile: "Item # / 110130060 / · Global data (Launch Scale Test client, 2026-09-19)"
$foot = array_search('Item #', $t, true);
if ($foot !== false) {
$item['source_id'] = (int) ($t[$foot + 1] ?? 0);
$item['source_version'] = trim(ltrim((string) ($t[$foot + 2] ?? ''), '· '));
}
if (!str_contains($item['source_version'], 'Global')) {
throw new RuntimeException('Keine Werte aus dem Global-Client (nur Korea/Taiwan?) - nicht übernommen.');
}
if (!in_array($item['category'], ['Weapons', 'Armor', 'Accessories'], true)) {
throw new RuntimeException('Nur Waffen, Rüstungen und Schmuck lassen sich übernehmen (das ist: ' . $item['category'] . ').');
}
return $item;
}