LuminaWebsite/includes/item_db.php

294 lines
13 KiB
PHP

<?php
declare(strict_types=1);
/**
* Spieldaten der Gegenstaende fuer die Info-Blasen im Lagerhaus und im Lumishop - von aion2hub.com
* (Global-Client, dieselbe Quelle wie der Gear-Planer, siehe includes/gear_source.php).
*
* Zu einem Namen aus dem Lagerhaus bzw. Lumishop sucht die Website den Gegenstand bei aion2hub
* (Suchseite /database?q=...), liest dessen Seite aus und merkt sich beides: die Zuordnung in
* item_db_names, die Werte in item_db. Abgerufen wird erst, wenn jemand auf den Gegenstand zeigt
* (item_info.php), danach hoechstens alle ITEM_DB_REFRESH_DAYS Tage; nicht Gefundenes wird nach
* ITEM_DB_RETRY_DAYS Tagen noch einmal gesucht. Insgesamt hoechstens ITEM_DB_FETCH_LIMIT Seiten pro
* Minute - aion2hub erlaubt die normalen Seiten (robots.txt), nur /api/ nicht.
*/
require_once __DIR__ . '/gear_source.php';
const ITEM_DB_REFRESH_DAYS = 30;
const ITEM_DB_RETRY_DAYS = 7;
const ITEM_DB_FETCH_LIMIT = 20;
const ITEM_DB_SEARCH_URL = 'https://aion2hub.com/database?q=';
// Seltenheiten, fuer die es eine Farbe gibt (CSS grade-*, wie im Gear-Planer)
const ITEM_DB_GRADES = ['common', 'rare', 'epic', 'unique', 'heroic', 'special'];
/** Das Tempolimit fuer Abrufe bei aion2hub ist erreicht - gleich noch einmal versuchen. */
class ItemDbBusyException extends RuntimeException
{
}
/** Laedt eine Seite von aion2hub - hoechstens ITEM_DB_FETCH_LIMIT pro Minute fuer die ganze Website. */
function item_db_fetch(string $url): string
{
if (rate_limit_count('aion2hub', 'site', 60) >= ITEM_DB_FETCH_LIMIT) {
throw new ItemDbBusyException('Gerade werden viele Gegenstände abgerufen.');
}
rate_limit_add('aion2hub', 'site');
return gear_source_fetch($url);
}
/** Name zum Vergleichen: klein, Leerraum vereinheitlicht, typografische Apostrophe gerade. */
function item_db_normalize(string $name): string
{
$name = str_replace(["\u{2019}", "\u{2018}", '`'], "'", $name);
return mb_strtolower(trim((string) preg_replace('/\s+/u', ' ', $name)));
}
/**
* Sucht einen Gegenstand bei aion2hub und liefert seine ID: der Treffer mit genau diesem Namen, sonst
* dessen gebundene Fassung ("Healing Potion" -> "Healing Potion (Bound)"). null = nicht gefunden.
*/
function item_db_search(string $name): ?int
{
$html = item_db_fetch(ITEM_DB_SEARCH_URL . rawurlencode($name));
preg_match_all('#<a\b[^>]*href="/database/items/(\d{6,12})"[^>]*>(.*?)</a>#s', $html, $links, PREG_SET_ORDER);
$wanted = item_db_normalize($name);
$bound = null;
foreach ($links as [, $id, $inner]) {
$tokens = gear_source_tokens($inner);
$found = item_db_normalize($tokens[0] ?? '');
if ($found === $wanted) {
return (int) $id;
}
if ($bound === null && $found === $wanted . ' (bound)') {
$bound = (int) $id;
}
}
return $bound;
}
/** Text aus einem HTML-Stueck (Kommentare und Tags weg, Entities aufgeloest, Zeilenumbrueche bleiben). */
function item_db_text(string $fragment): string
{
$fragment = str_replace(['<!-- -->', '<br>', '<br/>', '<br />'], ['', "\n", "\n", "\n"], $fragment);
$text = html_entity_decode(strip_tags($fragment), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return trim((string) preg_replace('/[ \t]+/u', ' ', $text));
}
/**
* Liest eine Gegenstandsseite von aion2hub aus: Kategorie, Name, Seltenheit, Merkmale (Slot, Art,
* Bindung ...), Stufe und benoetigte Stufe, Beschreibung, Grundwerte, Infos (Sockel, Stapel,
* Verkaufspreis ...) und die hoechste Aufwertung.
*
* @return array{id: int, category: string, name: string, grade: string, tags: string[], item_level: int,
* required_level: ?int, description: string, stats: array<int, array{0: string, 1: string}>,
* info: array<int, array{0: string, 1: string}>, enchant_max: int}
* @throws RuntimeException wenn die Seite nicht wie erwartet aussieht
*/
function item_db_parse(string $html, int $id): array
{
$tokens = gear_source_tokens($html);
$start = null;
for ($i = 0, $n = count($tokens); $i < $n - 4; $i++) {
if ($tokens[$i] === 'Item Database' && $tokens[$i + 1] === '/' && ($tokens[$i + 4] ?? '') === 'Copy link') {
$start = $i;
break;
}
}
if ($start === null) {
throw new RuntimeException('Die Seite sieht nicht wie eine Gegenstandsseite von aion2hub aus.');
}
$item = [
'id' => $id,
'category' => $tokens[$start + 2],
'name' => $tokens[$start + 3],
'grade' => '',
'tags' => [],
'item_level' => 0,
'required_level' => null,
'description' => '',
'stats' => [],
'info' => [],
'enchant_max' => 0,
];
// Merkmale unter dem Namen: Seltenheit, "Item Lv 43", "Requires Lv 37", Slot, Art, Bindung ...
$afterCopy = strpos($html, 'Copy link</button>');
if ($afterCopy !== false && preg_match('#<div class="mt-2\.5 flex flex-wrap[^"]*">(.*?)</div>#s', $html, $row, 0, $afterCopy)) {
preg_match_all('#<span\b[^>]*>(.*?)</span>#s', $row[1], $spans);
foreach ($spans[1] as $index => $span) {
$text = item_db_text($span);
if ($index === 0) {
$item['grade'] = $text;
} elseif (preg_match('/^Item Lv (\d+)$/', $text, $m)) {
$item['item_level'] = (int) $m[1];
} elseif (preg_match('/^Requires Lv (\d+)$/', $text, $m)) {
$item['required_level'] = (int) $m[1];
} elseif ($text !== '' && $text !== $item['category'] && count($item['tags']) < 6) {
$item['tags'][] = mb_substr($text, 0, 40);
}
}
}
if ($item['grade'] === '') {
$item['grade'] = $tokens[$start + 5];
}
// Beschreibung: kursiver Absatz unter dem Kopf
if (preg_match('#<p class="whitespace-pre-line border-l-2[^"]*">(.*?)</p>#s', $html, $m)) {
$item['description'] = mb_substr(item_db_text($m[1]), 0, 1000);
}
// Grundwerte
if (preg_match('#>Stats</div>\s*<ul[^>]*>(.*?)</ul>#s', $html, $m)) {
preg_match_all('#<li\b[^>]*>\s*<span[^>]*>(.*?)</span>\s*<span[^>]*>(.*?)</span>#s', $m[1], $rows, PREG_SET_ORDER);
foreach (array_slice($rows, 0, 20) as [, $label, $value]) {
$item['stats'][] = [mb_substr(item_db_text($label), 0, 60), mb_substr(item_db_text($value), 0, 30)];
}
}
// Infos: Sockel, Stapel, Verkaufspreis, Wirkung beim Benutzen ...
if (preg_match('#>Item Info</h2>.*?<dl[^>]*>(.*?)</dl>#s', $html, $m)) {
preg_match_all('#<dt[^>]*>(.*?)</dt>\s*<dd[^>]*>(.*?)</dd>#s', $m[1], $rows, PREG_SET_ORDER);
foreach (array_slice($rows, 0, 12) as [, $label, $value]) {
$item['info'][] = [mb_substr(item_db_text($label), 0, 60), mb_substr(item_db_text($value), 0, 80)];
}
}
// Hoechste Aufwertung: "Enchantable to / + / 15"
$enchant = array_search('Enchantable to', $tokens, true);
if ($enchant !== false && ($tokens[$enchant + 1] ?? '') === '+') {
$item['enchant_max'] = (int) ($tokens[$enchant + 2] ?? 0);
}
return $item;
}
/** Gespeicherter Gegenstand (item_db) samt ausgepackten Werten, oder null. */
function item_db_get(int $itemId): ?array
{
$stmt = db()->prepare('SELECT id, name, grade, category, data, fetched_at FROM item_db WHERE id = ?');
$stmt->execute([$itemId]);
$row = $stmt->fetch();
if (!$row) {
return null;
}
$data = json_decode((string) $row['data'], true);
return array_merge(is_array($data) ? $data : [], [
'id' => (int) $row['id'],
'name' => (string) $row['name'],
'grade' => (string) $row['grade'],
'category' => (string) $row['category'],
'fetched_at' => (string) $row['fetched_at'],
]);
}
function item_db_store(array $item): void
{
// Deutscher Name (Guide-Texte, includes/gear_guide.php) bleibt beim Auffrischen von aion2hub erhalten
if (!isset($item['name_de']) && ($old = item_db_get((int) $item['id'])) && !empty($old['name_de'])) {
$item['name_de'] = $old['name_de'];
}
$data = array_intersect_key($item, array_flip(['tags', 'item_level', 'required_level', 'description', 'stats', 'info', 'enchant_max', 'name_de']));
db()->prepare(
'INSERT INTO item_db (id, name, grade, category, data, fetched_at) VALUES (?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE name = VALUES(name), grade = VALUES(grade), category = VALUES(category),
data = VALUES(data), fetched_at = VALUES(fetched_at)'
)->execute([
$item['id'],
mb_substr($item['name'], 0, 150),
mb_substr($item['grade'], 0, 20),
mb_substr($item['category'], 0, 40),
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
]);
}
function item_db_map(string $name, ?int $itemId): void
{
db()->prepare(
'INSERT INTO item_db_names (name, item_id, checked_at) VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE item_id = VALUES(item_id), checked_at = VALUES(checked_at)'
)->execute([mb_substr($name, 0, 150), $itemId]);
}
/**
* Spieldaten zu einem Namen aus Lagerhaus oder Lumishop - aus dem Zwischenspeicher, sonst frisch von
* aion2hub. status: ok (item), missing (dort nicht gefunden), busy (Tempolimit, gleich noch einmal),
* error (message; hat es frueher schon geklappt, gilt stattdessen der alte Stand).
*
* @return array{status: string, item?: array<string, mixed>, message?: string}
*/
function item_db_lookup(string $name): array
{
$stmt = db()->prepare('SELECT item_id, checked_at FROM item_db_names WHERE name = ?');
$stmt->execute([$name]);
$map = $stmt->fetch() ?: null;
$itemId = $map && $map['item_id'] !== null ? (int) $map['item_id'] : null;
$mapAge = $map ? time() - (int) strtotime((string) $map['checked_at']) : PHP_INT_MAX;
if ($map && $itemId === null && $mapAge < ITEM_DB_RETRY_DAYS * 86400) {
return ['status' => 'missing'];
}
$cached = $itemId !== null ? item_db_get($itemId) : null;
if ($cached && $mapAge < ITEM_DB_REFRESH_DAYS * 86400
&& time() - (int) strtotime($cached['fetched_at']) < ITEM_DB_REFRESH_DAYS * 86400) {
return ['status' => 'ok', 'item' => $cached];
}
try {
if ($itemId === null || $mapAge >= ITEM_DB_REFRESH_DAYS * 86400) {
$itemId = item_db_search($name);
item_db_map($name, $itemId);
if ($itemId === null) {
return ['status' => 'missing'];
}
}
$item = item_db_parse(item_db_fetch(GEAR_SOURCE_ITEM_URL . $itemId), $itemId);
item_db_store($item);
return ['status' => 'ok', 'item' => $item];
} catch (ItemDbBusyException $e) {
return $cached ? ['status' => 'ok', 'item' => $cached] : ['status' => 'busy'];
} catch (RuntimeException $e) {
return $cached ? ['status' => 'ok', 'item' => $cached] : ['status' => 'error', 'message' => $e->getMessage()];
}
}
/**
* Inhalt der Info-Blase (assets/js/item-tooltip.js): Bild, Name in der Farbe der Seltenheit, Merkmale,
* Stufe, Beschreibung, Grundwerte und Infos - so, wie aion2hub sie aus dem Spielclient ausliest.
*/
function item_db_tip_html(array $item, string $iconHtml): string
{
$grade = strtolower((string) $item['grade']);
$meta = array_merge([(string) $item['grade']], (array) ($item['tags'] ?? []));
$levels = array_filter([
!empty($item['item_level']) ? 'Gegenstandsstufe ' . (int) $item['item_level'] : '',
!empty($item['required_level']) ? 'ab Stufe ' . (int) $item['required_level'] : '',
]);
$html = '<div class="item-tip-head">' . str_replace(' loading="lazy"', '', $iconHtml) . '<div class="item-tip-title">'
. '<strong' . (in_array($grade, ITEM_DB_GRADES, true) ? ' class="grade-' . e($grade) . '"' : '') . '>' . e((string) $item['name']) . '</strong>'
. '<span class="item-tip-sub">' . e(implode(' · ', array_filter($meta))) . '</span>'
. ($levels ? '<span class="item-tip-sub">' . e(implode(' · ', $levels)) . '</span>' : '')
. '</div></div>';
if (($item['description'] ?? '') !== '') {
// Platzhalter des Spielclients, die aion2hub nicht aufloest ("{abe:201120111:value02:divide100}%") -> "…%"
$description = (string) preg_replace('/\{[a-z_]+:[^{}]*\}/i', '…', (string) $item['description']);
$html .= '<p class="item-tip-text">' . nl2br(e($description)) . '</p>';
}
if (!empty($item['stats'])) {
$html .= '<ul class="item-tip-stats">';
foreach ($item['stats'] as [$label, $value]) {
$html .= '<li><span>' . e((string) $label) . '</span><span class="item-tip-value">' . e((string) $value) . '</span></li>';
}
$html .= '</ul>';
}
$info = (array) ($item['info'] ?? []);
if (!empty($item['enchant_max'])) {
$info[] = ['Enchantable to', '+' . (int) $item['enchant_max']];
}
if ($info) {
$html .= '<dl class="item-tip-lines">';
foreach ($info as [$label, $value]) {
$html .= '<div><dt>' . e((string) $label) . '</dt><dd>' . e((string) $value) . '</dd></div>';
}
$html .= '</dl>';
}
return $html . '<div class="item-tip-source">Daten: aion2hub.com</div>';
}