* * This file is subject to the MIT license that is bundled * with this source code in the LICENSE.md file. */ namespace Civ13; use Civ13\Exceptions\FileNotFoundException; use Civ13\Exceptions\InvalidConfigException; use Civ13\Exceptions\MissingSystemPermissionException; use Civ13\Exceptions\PartException; use Civ13\Exceptions\UserInputException; use Civ13\Exceptions\VerifierException; use Discord\Discord; use Discord\Builders\Components\ActionRow; use Discord\Builders\Components\Button; use Discord\Builders\MessageBuilder; use Discord\Helpers\Collection; use Discord\Helpers\CollectionInterface; use Discord\Parts\Channel\Channel; use Discord\Parts\Channel\Message; use Discord\Parts\Embed\Embed; use Discord\Parts\Guild\Role; use Discord\Parts\Interactions\Interaction; use Discord\Parts\Thread\Thread; use Discord\Parts\User\Member; use Monolog\Logger; use React\EventLoop\StreamSelectLoop; use React\EventLoop\TimerInterface; use React\Promise\PromiseInterface; use function React\Async\async; use function React\Promise\reject; use function React\Promise\resolve; class GameServer { /** * An array of admin permissions. * Each permission is represented by a key-value pair, where the key is the role name in Discord * and the value is an array containing the role name in-game and the permission level. * * @var array */ public const ADMIN_PERMISSIONS = [ 'Owner' => ['Host', '65535'], 'Chief Technical Officer' => ['Chief Technical Officer', '65535'], 'Host' => ['Host', '65535'], // Default Host permission, only used if a higher listed role is not found first 'Head Admin' => ['Head Admin', '16382'], // Deprecation TBD //'Manager' => ['Manager', '16382'], // Deprecated //'Supervisor' => ['Supervisor', '16382'], // Deprecated 'Ambassador' => ['Ambassador', '16382'], // Default High Staff permission, only used if a higher listed role is not found first 'Admin' => ['Admin', '16254'], //'Moderator' => ['Moderator', '25088'], // Deprecated //'Developer' => ['Developer', '7288'], // This Discord role doesn't exist //'Mentor' => ['Mentor', '16384'], // Deprecated ]; public Discord $discord; public Logger $logger; public StreamSelectLoop $loop; public bool $ready = false; private ?NativeLifecycle $nativeLifecycle = null; /** Opt-in confirmed `manage` controls for a shard_group region (docs/launcher-management.md). */ public ?\Civ13\Local\LauncherManagement $launcherManagement = null; /** Set whenever management is enabled, even if its configuration is invalid, so legacy lifecycle commands fail closed. */ private bool $launcherManagementRequired = false; /** Host script control: gaia_host.py for a scheduled-task host, or shard_group.py for one region of a shard group. */ private \Civ13\Local\GaiaHostControl|\Civ13\Local\ShardRegionControl|null $gaiaHost = null; /** Set when shard_group is configured but unusable: host controls then refuse instead of launching DreamDaemon. */ private ?string $hostUnavailable = null; /** shard_group "kill" action for Kill: "stop" (save if the world saves, then stop) or "kill" (forced, no save). */ private string $shardKillAction = 'stop'; /** * Key of the server whose shard group this world belongs to, when this world is a secondary region of it * (for example the TDM battle world of the TDM Barracks). The parent counts this world in its player-count * channel (its `shards` list) and alone takes Discord OOC; this world still relays its own game chat. */ public string $shardOf = ''; private ?\Civ13\Local\SystemdUnitControl $systemdUnit = null; private ?string $systemdUnavailable = null; // Resolved paths private readonly string $serverdata; private readonly string $discord2unban; private readonly string $discord2ban; private readonly string $admins; private readonly string $whitelist; private readonly string $factionlist; private readonly string $ranking_path; // Required settings public readonly string $basedir; // The base directory on the local filesystem. public readonly string $key; // The shorthand alias for the server. public readonly string $name; // The name. public readonly string $ip; // The IP. public readonly string $port; // The port. public readonly string $host; // The host (e.g. Taislin). public bool $supported; // Whether the server is supported by the remote webserver and will appear in data retrieved from it. public bool $enabled; // Whether the server is enabled and accessible by this bot. public bool $legacy; // Whether the server uses Civ13 legacy file cache or newer SQL methods. public bool $moderate; // Whether the server should moderate chat using the bot. public bool $panic_bunker; // Whether the server should only allow verified users to join. public bool $log_attacks; // Whether the server should log attacks to the attack channel. public bool $legacy_relay; // The method used to relay chat messages to the server (either 'file' or 'webhook'). // Discord Channel IDs public string $discussion; public string $playercount; public string $ooc; public string $lobby; public string $asay; public string $ic; public string $transit; public string $adminlog; public string $debug; public string $garbage; public string $runtime; public string $attack; // Resolved Discord Role IDs public ?Role $role = null; private ?\Civ13\Server\FileRelay $fileRelay = null; // Generated by the bot /** * @var Timerinterface[] */ public array $timers = []; public array $serverinfo = []; public array $players = []; public array $seen_players = []; public string $current_round = ''; public ?string $current_round_message_id = null; /** @var array */ public array $rounds = []; public string $engine = 'byond'; private ?\Civ13\Local\OpenDreamControl $engineControl = null; private bool $controlBusy = false; public string $bancheck_cache = ''; private ?ServerHeartbeat $heartbeat = null; public ?ServerPlayLink $playLink = null; /** @var array Shard region directory => its heartbeat. */ private array $shardHeartbeats = []; /** @var list}> Last local observation of every world in the group. */ private array $worlds = []; /** @var array Shard region directory => its display name. */ private array $shardNames = []; /** Display name of this server's own world in its group (the group file's region name). */ private string $regionName = ''; /** Civ13 shard group file (scripts/shard-group, for example D:/Civ13Regions/earth.json) whose regions are counted. */ private string $regionGroupFile = ''; /** @var array Shard directories that came from the group file (re-read when it changes). */ private array $groupShards = []; private ?string $regionGroupStamp = null; private ?RegionRoster $roster = null; /** * @param Civ13 $civ13 The bot instance (held by reference). * @param array $options Server config (held by reference); `basedir`, `key`, `name`, `ip`, `port`, `host` are required, the rest optional. */ public function __construct(public Civ13 &$civ13, array &$options) { $this->discord = &$civ13->discord; $this->logger = &$civ13->logger; $this->loop = $civ13->loop; $this->resolveOptions($options); $this->engine = $options['engine'] ?? 'byond'; if (!in_array($this->engine, ['byond', 'opendream'], true)) { throw new \InvalidArgumentException('Unknown server engine'); } if ($this->engine === 'opendream') { $control = $options['control'] ?? []; $executor = new \Civ13\Local\AsyncProcess($this->loop, $control['temporary_directory'] ?? sys_get_temp_dir()); $this->engineControl = new \Civ13\Local\OpenDreamControl( ['engine' => 'opendream', 'host' => $options['ip'], 'runtime_dir' => $options['basedir'], 'gameplay_port' => (int)$options['port'], 'topic_port' => $options['topic_port'] ?? null], $control['python'] ?? '', $control['controller'] ?? '', $control['profile'] ?? '', $executor, $control['enabled'] ?? false, $control['lifecycle_schema'] ?? null ); } $this->basedir = $options['basedir']; $this->key = $options['key']; $this->name = $options['name']; $this->ip = $options['ip']; $this->port = $options['port']; $this->host = $options['host']; try { $this->playLink = ServerPlayLink::fromConfig($options['play'] ?? null, $this->key, $this->engine); } catch (\InvalidArgumentException $error) { $this->logger->warning("GameServer {$this->key} Play link disabled: ".$error->getMessage()); } $this->supported = $options['supported'] ?? false; if (($options['enabled'] ?? false) && $this->basedir && ! is_dir($this->basedir)) { // Will cause issues $this->logger->error("GameServer {$this->key} has an invalid basedir: {$this->basedir}, disabling server."); $this->enabled = false; } else { $this->enabled = $options['enabled'] ?? false; } if (($options['gaia_host']['enabled'] ?? false) === true) { // Windows scheduled-task host driven by Civ13's scripts/gaia-host/gaia_host.py. $gaia = $options['gaia_host']; $this->gaiaHost = new \Civ13\Local\GaiaHostControl($gaia['python'] ?? '', $gaia['script'] ?? '', $gaia['config'] ?? '', new \Civ13\Local\AsyncProcess($this->loop, $gaia['temporary_directory'] ?? sys_get_temp_dir())); } if (($options['shard_group']['enabled'] ?? false) === true) { // One region of a shard group driven by Civ13's scripts/shard-group/shard_group.py (docs/shard-group.md). $shard = $options['shard_group']; try { if ($this->gaiaHost !== null) { throw new \InvalidArgumentException('enable either gaia_host or shard_group, not both'); } if (!in_array($shard['kill'] ?? 'stop', ['stop', 'kill'], true)) { throw new \InvalidArgumentException('shard_group kill must be stop or kill'); } $this->shardKillAction = $shard['kill'] ?? 'stop'; $this->gaiaHost = new \Civ13\Local\ShardRegionControl($shard['python'] ?? '', $shard['script'] ?? '', $shard['config'] ?? '', (string) ($shard['region'] ?? ''), new \Civ13\Local\AsyncProcess($this->loop, $shard['temporary_directory'] ?? sys_get_temp_dir())); } catch (\InvalidArgumentException $error) { // Never fall back to launching DreamDaemon beside the group's host: refuse host controls instead. $this->logger->error("GameServer {$options['key']} shard_group control unavailable: {$error->getMessage()}"); $this->hostUnavailable = $error->getMessage(); } } $this->launcherManagementRequired = ($options['shard_group']['management']['enabled'] ?? false) === true; // Additional launcher actions never inherit legacy role authority or implicit enablement. if (($options['shard_group']['management']['enabled'] ?? false) === true && $this->hostUnavailable === null && $this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { try { $this->launcherManagement = new \Civ13\Local\LauncherManagement((array) $shard['management'], (string) ($shard['python'] ?? ''), (string) ($shard['script'] ?? ''), (string) ($shard['config'] ?? ''), (string) ($shard['region'] ?? ''), new \Civ13\Local\AsyncProcess($this->loop, $shard['temporary_directory'] ?? sys_get_temp_dir()), null, "{$this->key}manage"); } catch (\InvalidArgumentException|\TypeError $error) { $this->logger->error("GameServer {$this->key}: launcher management configuration invalid; new controls remain disabled."); } } if (is_string($options['shard_of'] ?? null) && $options['shard_of'] !== '' && $options['shard_of'] !== $options['key']) { $this->shardOf = $options['shard_of']; } if (($options['systemd']['enabled'] ?? false) === true) { // Linux server owned by a systemd unit (Civ13 scripts/README.md, "Supervised hosting"). $systemd = $options['systemd']; try { $this->systemdUnit = new \Civ13\Local\SystemdUnitControl($systemd['unit'] ?? '', new \Civ13\Local\AsyncProcess($this->loop, $systemd['temporary_directory'] ?? sys_get_temp_dir()), $systemd['scope'] ?? 'system', $systemd['runtime_dir'] ?? null, $systemd['sudo'] ?? null); } catch (\InvalidArgumentException $error) { // Never fall back to launching DreamDaemon beside the unit: refuse host controls instead. $this->logger->error("GameServer {$this->key} systemd control unavailable: {$error->getMessage()}"); $this->systemdUnavailable = $error->getMessage(); } } if (($options['native_lifecycle']['enabled'] ?? false) === true) { if (PHP_OS_FAMILY !== 'Windows' && !getenv('CIVILIZATIONBOT_PROFILE')) { throw new \RuntimeException('Native supervisor adapter requires an explicit portable profile'); } $this->nativeLifecycle = new NativeLifecycle($options['native_lifecycle'], $options, $civ13->gitdir, $this->loop); } $this->legacy = $options['legacy'] ?? true; $this->moderate = $options['moderate'] ?? true; $this->panic_bunker = $options['panic_bunker'] ?? false; $this->log_attacks = $options['log_attacks'] ?? true; $this->legacy_relay = $options['legacy_relay'] ?? false; $this->discussion = $options['discussion'] ?? ''; $this->playercount = $options['playercount'] ?? ''; $this->ooc = $options['ooc'] ?? ''; $this->lobby = $options['lobby'] ?? ''; $this->asay = $options['asay'] ?? ''; $this->ic = $options['ic'] ?? ''; $this->transit = $options['transit'] ?? ''; $this->adminlog = $options['adminlog'] ?? ''; $this->debug = $options['debug'] ?? ''; $this->garbage = $options['garbage'] ?? ''; $this->runtime = $options['runtime'] ?? ''; $this->attack = $options['attack'] ?? ''; if ($this->enabled) { // Don't load variables from files if the server is disabled if (! $this->rounds = $this->civ13->VarLoad("{$this->key}_rounds.json") ?? []) { $this->rounds = []; $this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds); } if (! $current_round = $this->civ13->VarLoad("{$this->key}_current_round.json") ?? []) { $current_round = []; $this->civ13->VarSave("{$this->key}_current_round.json", $current_round); } if ($current_round = array_shift($current_round)) { $this->rounds[$this->current_round = $current_round]['interrupted'] = true; $this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds); } else { $this->logger->warning("No current round found for {$this->key}."); } } $this->serverdata = $this->basedir.Civ13::serverdata; // Other region worlds of this server's shard group (Civ13 scripts/shard-group), counted in the player-count channel. foreach (is_array($options['shards'] ?? null) ? $options['shards'] : [] as $shard) { if (! is_string($shard) || $shard === '') { continue; } $this->shardHeartbeats[rtrim($shard, '/\\')] = new ServerHeartbeat(rtrim($shard, '/\\').Civ13::serverdata); } // Or every region of a Civ13 shard group file, re-read when the group gains or loses regions. if (is_string($options['region_group'] ?? null) && $options['region_group'] !== '') { $this->regionGroupFile = $options['region_group']; $this->loadRegionGroup(); } $this->discord2unban = $this->basedir.Civ13::discord2unban; $this->discord2ban = $this->basedir.Civ13::discord2ban; $this->admins = $options['admin_file'] ?? $this->basedir.Civ13::admins; $this->whitelist = $this->basedir.Civ13::whitelist; $this->factionlist = $this->basedir.Civ13::factionlist; $this->ranking_path = $this->basedir.Civ13::ranking_path; $this->afterConstruct(); } /** Registers the server via {@see setup()} and, when enabled, defers its timers (player count, serverinfo, relay, round embed) until the bot is ready. */ protected function afterConstruct(): void { $this->setup(); if (! $this->enabled) { return; } // Don't start timers for disabled servers $this->civ13->deferUntilReady( function () { $this->logger->info("Getting player count for GameServer {$this->name}"); $this->__updateDiscordVariables(); $this->localServerPlayerCount(); // Populates $this->players $this->heartbeatTimer(); // Passive file progress, independent of player activity $this->playercountTimer(); // Update playercount channel every 10 minutes $this->serverinfoTimer(); // Hard check playercount and ckeys to scrutinizeCkey() every 3 minutes $this->relayTimer(); // File chat relay $this->currentRoundEmbedTimer(); // The bot has to set a round id first }, __METHOD__." ({$this->key})" ); } /** * This method is responsible for setting up the game server by performing the following tasks: * - Checking if the number of game servers exceeds the limit of 5 and logging a warning if it does. * - Adding the game server to the list of game servers in the Civ13 object. * - Adding the game server to the list of enabled game servers in the Civ13 object if it is enabled. * - Logging an informational message about the added game server. * - Setting the "ready" flag to true. */ private function setup() { if ($this->ready) { return; } if (count($this->civ13->gameservers) > 5) { $this->logger->warning('Configuring more than 5 gameservers are not supported and you will likely experience issues.'); } $this->civ13->gameservers[$this->key] = &$this; if ($this->enabled) { $this->civ13->enabled_gameservers[$this->key] = &$this; } $this->logger->info('Added '.($this->enabled ? 'enabled' : 'disabled')." game server: {$this->name} ({$this->key})"); $this->ready = true; } /** Caches the guild role whose name matches this server's name. */ private function __updateDiscordVariables() { if ($guild = $this->civ13->discord->guilds->get('id', $this->civ13->civ13_guild_id)) { if (! $this->role = $guild->roles->get('name', $this->name)) { $this->logger->error("Role not found for GameServer {$this->key}."); } } } /** Validates the option array: throws when a required key is missing and warns for missing optional keys. */ private function resolveOptions(array $options) { $requiredProperties = [ 'basedir', 'key', 'name', 'ip', 'port', 'host', ]; foreach ($requiredProperties as $property) { if (! isset($options[$property])) { throw new \RuntimeException("GameServer missing required property: $property"); } } if (array_key_exists('admin_file', $options) && !PortableProfile::absoluteAdminFile($options['admin_file'])) { throw new InvalidConfigException('admin_file must be an explicit absolute filesystem path'); } $optionalProperties = [ 'discussion', 'playercount', 'ooc', 'lobby', 'asay', 'ic', 'transit', 'adminlog', 'debug', 'garbage', 'runtime', 'attack', ]; foreach ($optionalProperties as $property) { if (! isset($options[$property])) { trigger_error("GameServer missing optional property: $property", E_USER_WARNING); } } } /** * Returns an array of the player count for each locally hosted server in the configuration file. * * @return int The total player count for this locally hosted server, or 0 if the server is not local. */ public function localServerPlayerCount(array $players = []): int { $status = $this->refreshLocalServerStatus(); return $status['data'] === null ? 0 : (int) self::heartbeatServerdata($status['data'])['playercount']; } /** Local evidence only; another host's configured directory must never be read. */ private function refreshLocalServerStatus(): array { if (! $this->enabled || $this->ip !== ($this->civ13->httpServiceManager->httpHandler->external_ip ?? null)) { $this->worlds = []; return ['state' => 'unknown', 'reason' => 'No enabled local heartbeat observation', 'age' => null, 'data' => null]; } $this->loadRegionGroup(); $status = ($this->heartbeat ??= new ServerHeartbeat($this->serverdata))->poll(); $this->players = self::heartbeatPlayers($status); $worlds = [['name' => $this->regionName !== '' ? $this->regionName : $this->name, 'state' => $status['state'], 'reason' => $status['reason'], 'players' => $this->players]]; // Shards share the 15-second poll so each heartbeat keeps its own progress evidence. foreach ($this->shardHeartbeats as $directory => $heartbeat) { $shard = $heartbeat->poll(); $worlds[] = ['name' => $this->shardNames[$directory] ?? self::regionLabel((string) $directory), 'state' => $shard['state'], 'reason' => $shard['reason'], 'players' => self::heartbeatPlayers($shard)]; } // One roster across the group: each ckey once, and a traveller between regions is not dropped. $this->worlds = ($this->roster ??= new RegionRoster())->observe($worlds, hrtime(true) / 1e9); return $status; } /** "D:/Civ13Regions/earth/northamerica" => "Northamerica", for a `shards` directory without a group name. */ private static function regionLabel(string $directory): string { return ucfirst(basename(str_replace('\\', '/', $directory))); } private static function samePath(string $a, string $b): bool { $normalize = fn (string $path): string => rtrim(str_replace('\\', '/', $path), '/'); return strcasecmp($normalize($a), $normalize($b)) === 0; } /** * Reads the shard group file (Civ13 scripts/shard-group: `root` plus `regions[].id/name`; each region * runs in /) and watches every region other than this server's own world. Only re-read when * the file changes; an unreadable or malformed file keeps the last good region list. */ private function loadRegionGroup(): void { if ($this->regionGroupFile === '') { return; } clearstatcache(true, $this->regionGroupFile); $stamp = @filemtime($this->regionGroupFile).':'.@filesize($this->regionGroupFile); if ($stamp === $this->regionGroupStamp) { return; } $bytes = @is_file($this->regionGroupFile) ? @file_get_contents($this->regionGroupFile, false, null, 0, 1048577) : false; $group = is_string($bytes) && strlen($bytes) <= 1048576 ? json_decode($bytes, true, 32) : null; if (! is_array($group) || ! is_string($group['root'] ?? null) || $group['root'] === '' || ! is_array($group['regions'] ?? null)) { if ($this->regionGroupStamp === null) { $this->logger->warning("GameServer {$this->key}: region_group {$this->regionGroupFile} is unreadable; counting this world only."); } $this->regionGroupStamp = $stamp; return; } $this->regionGroupStamp = $stamp; $root = rtrim($group['root'], '/\\'); $listed = []; foreach ($group['regions'] as $region) { if (! is_array($region) || ! is_string($region['id'] ?? null) || preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $region['id']) !== 1) { continue; } $directory = $root.'/'.$region['id']; $name = is_string($region['name'] ?? null) && trim($region['name']) !== '' ? trim($region['name']) : ucfirst($region['id']); if (self::samePath($directory, $this->basedir)) { $this->regionName = $name; continue; } foreach (array_keys($this->shardHeartbeats) as $known) { if (! isset($this->groupShards[$known]) && self::samePath((string) $known, $directory)) { $this->shardNames[$known] = $name; // Also listed in `shards`: keep that heartbeat, name it. continue 2; } } $listed[$directory] = true; $this->shardNames[$directory] = $name; $this->shardHeartbeats[$directory] ??= new ServerHeartbeat($directory.Civ13::serverdata); } foreach (array_keys($this->groupShards) as $gone) { if (! isset($listed[$gone])) { unset($this->shardHeartbeats[$gone], $this->shardNames[$gone]); } } $this->groupShards = $listed; } /** The group-wide "Online Players" field, grouped by region when this server heads a region group. */ private function addRosterField(Embed $embed): Embed { if ($this->roster === null || ! $this->worlds) { return $embed; } $grouped = count($this->shardHeartbeats) > 0; if (! $grouped && $this->roster->total() === 0) { return $embed; // A lone world with nobody on keeps its old, field-less embed. } [$name, $value] = $this->roster->field($grouped); return $embed->addFieldValues($name, $value, ! $grouped); } /** @return list */ private static function heartbeatPlayers(array $status): array { if ($status['data'] === null) { return []; } return array_values(array_filter(array_map( fn ($player) => Civ13::sanitizeInput($player), explode('&', self::heartbeatServerdata($status['data'])['ckey_list']) ))); } private static function heartbeatServerdata(string $data): array { // Only status readers normalize this optional field; leave other IPC consumers unchanged. return self::explodeServerdata(preg_replace('/;Approved only<\/b>: [^;]*/', '', $data)); } /** Sample passively every 15 seconds; never connect to BYOND or publish from this timer. */ public function heartbeatTimer(): TimerInterface { return $this->timers['heartbeat_timer'] ??= $this->loop->addPeriodicTimer(15, fn () => $this->refreshLocalServerStatus()); } /** * Relays game chat messages to specified paths. * * This method takes an array of paths and relays game chat messages to those paths. * If no paths are provided, it defaults to relaying to the #ooc-server and #asay-server paths. * * @param array $paths An associative array where keys are file paths and values are the corresponding chat channels IDs. * @return bool Returns true if all chat messages were successfully relayed, false otherwise. */ private function __gameChatFileRelay(array $paths): bool { // Nothing to relay (webhook mode) is not worth a log line every 10 seconds; failures log in gameChatFileRelay(). $result = true; foreach ($paths as $filepath => $channel) { if (! $this->gameChatFileRelay($this->basedir.$filepath, $channel)) { $result = false; } } return $result; } /** * Relays in-game chat messages to Discord and handles chat moderation. * * This function reads chat messages from a file and relays them to a Discord channel. * It also performs chat moderation by checking for blacklisted words and applying warnings and bans to players. * * @param string $file_path The path to the file containing the chat messages. * @param string $channel_id The ID of the Discord channel to relay the messages to. * @param bool|null $moderate (Optional) Whether to enable chat moderation. Defaults to false. * @param bool $ooc (Optional) Whether to include out-of-character (OOC) messages. Defaults to true. * @return bool Returns true if the chat messages were successfully relayed, false otherwise. */ public function gameChatFileRelay(string $file_path, string $channel_id, ?bool $ooc = true, ?bool $moderate = null): bool { if (! $this->legacy_relay) { return false; } $this->fileRelay ??= new \Civ13\Server\FileRelay( $this->civ13->filecache_path.'relay-checkpoints', fn (string $path, int $offset) => $this->logger->warning('Oversized server relay record discarded at byte '.$offset.' in '.$path) ); $this->fileRelay->relay($file_path, fn (string $line) => $this->civ13->sendMessage($channel_id, $line, 'relay.txt', true)) ->then(null, fn (\Throwable $error) => $this->logger->error('Server file relay failed: '.$error->getMessage())); return true; } /** * Relays game chat messages to a Discord channel using a webhook. * * @param string $ckey The ckey of the player sending the message. * @param string $message The message to be relayed. * @param string $channel_id The ID of the Discord channel to relay the message to. * @param bool|null $moderate Whether to moderate the message or not. Defaults to true. * @param bool|null $ooc Whether the message is out-of-character or not. Defaults to true. * @return PromiseInterface A promise that resolves with the message sent to the channel. */ public function gameChatWebhookRelay(string $message, string $channel_id, ?string $ckey = null, ?bool $ooc = true, ?bool $moderate = true): PromiseInterface { if ($this->legacy_relay) { return reject(new \LogicException('gameChatWebhookRelay() is not available for legacy relays.')); } if (! $message || ! is_string($channel_id) || ! is_numeric($channel_id)) { $this->logger->warning($err = 'gameChatWebhookRelay() was called with invalid parameters: '.json_encode(['ckey' => $ckey, 'message' => $message, 'channel_id' => $channel_id])); return reject(new \InvalidArgumentException($err)); } if (! $channel = $this->discord->getChannel($channel_id)) { $this->logger->warning($err = "gameChatWebhookRelay() was unable to retrieve the channel with ID `$channel_id`"); return reject(new PartException($err)); } if (! $this->ready || ! $this->civ13->ready) { $this->civ13->deferUntilReady( fn () => $this->gameChatWebhookRelay($message, $channel_id, $ckey, $ooc, $moderate), __METHOD__." ({$this->key})" ); return resolve(null); } return ($ckey) ? $this->__gameChatRelay($channel, ['ckey' => $ckey, 'message' => $message, 'server' => $this->key], $ooc, $moderate) : $this->civ13->sendMessage($channel_id, $message, 'message.txt', true); // Send the message as is if no ckey is provided return resolve(null); } /** * Relays game chat messages to a Discord channel. * * @param Channel|Thread|string $channel The Discord channel to send the message to. * @param array $array The array containing the chat message information. * @param bool $moderate (optional) Whether to apply moderation to the message. Default is true. * @param bool $ooc (optional) Whether the message is out-of-character (OOC) or in-character (IC). Default is true. * @return PromiseInterface A promise that resolves with the message sent to the channel. */ private function __gameChatRelay(Channel|Thread|string $channel, array $array, ?bool $ooc = true, ?bool $moderate = true): PromiseInterface { if (is_string($channel) && ! $channel = $this->discord->getChannel($channel)) { $this->logger->error($err = 'Channel not found for __gameChatRelay'); return reject(new PartException($err)); } if (! $array || ! isset($array['ckey']) || ! isset($array['message']) || ! isset($array['server']) || ! $array['ckey'] || ! $array['message'] || ! $array['server']) { $this->logger->warning($err = '__gameChatRelay() was called with an empty array or invalid content.'); return reject(new \InvalidArgumentException($err)); } if (isset($this->civ13->moderator) && $this->moderate && $moderate) { // The counters are passed by reference from the bot itself so repeat violations accumulate and persist. if ($ooc) { $this->civ13->moderator->moderate($this, $array['ckey'], $array['message'], $this->civ13->ooc_badwords, $this->civ13->ooc_badwords_warnings, 'ooc_badwords_warnings.json'); } else { $this->civ13->moderator->moderate($this, $array['ckey'], $array['message'], $this->civ13->ic_badwords, $this->civ13->ic_badwords_warnings, 'ic_badwords_warnings.json'); } } try { $item = $this->civ13->verifier->get('ss13', Civ13::sanitizeInput($array['ckey'])); } catch (VerifierException) { // The hosted list is not a current identity proof. Keep chat visible // as plain text without using retained or stale verification data. $this->logger->warning('Chat relay identity lookup unavailable; sending unverified display text'); $item = null; } if (! $item) { return $this->civ13->sendMessage($channel, $array['message'], 'relay.txt', true); } $embed = $this->civ13->createEmbed(false)->setDescription($array['message']); if ($user = $this->discord->users->get('id', $item['discord'])) { $embed->setAuthor("{$user->username} ({$user->id})", $user->avatar); } // else $this->discord->users->fetch('id', $item['discord']); // disabled to prevent rate limiting return $channel->sendMessage(Civ13::createBuilder(true)->addEmbed($embed)); } /** The 10-second file-chat relay timer (OOC + admin-say), created on first call. Null when the bot is not in the guild. */ public function relayTimer(): ?TimerInterface { if (! $this->discord->guilds->get('id', $this->civ13->civ13_guild_id)) { return null; } if (! (isset($this->timers['relay_timer'])) || (! $this->timers['relay_timer'] instanceof TimerInterface)) { $this->logger->debug("Starting file chat relay timer for {$this->key}"); if (! isset($this->timers['relay_timer'])) { $this->timers['relay_timer'] = $this->discord->getLoop()->addPeriodicTimer(10, fn () => $this->__gameChatFileRelay([Civ13::ooc_path => $this->ooc, Civ13::asay_path => $this->asay])); } } return $this->timers['relay_timer']; } /** The 3-minute timer that refreshes the player list and runs each ckey through the moderator, created on first call. */ public function serverinfoTimer(): TimerInterface { if (! isset($this->timers['serverinfo_timer'])) { $this->timers['serverinfo_timer'] = $this->discord->getLoop()->addPeriodicTimer(180, function () { if (! /*$playercount =*/ $this->localServerPlayerCount()) { return; } // No data available foreach ($this->players as $ckey) { if (is_null($ckey)) { continue; } if (isset($this->civ13->moderator)) { try { $this->civ13->moderator->scrutinizeCkey($ckey); } catch (\Throwable $e) { // A plain loop timer has no promise to reject; an escaping throw is a fatal error $this->logger->warning("Skipped scrutinizing `$ckey`: {$e->getMessage()}"); } } } }); } return $this->timers['serverinfo_timer']; // Check players every minute } /** Parses the cached `serverinfo` payload into the player list and returns it. */ public function serverinfoPlayers(): array { if (empty($data_json = $this->serverinfo)) { return []; } $this->players = []; foreach ($data_json as $server) { if (array_key_exists('ERROR', $server)) { continue; } //$stationname = $server['stationname'] ?? ''; // TODO: Compare this to the server's name as it appears on the Byond hub foreach (array_keys($server) as $key) { if (($p = explode('player', $key)) && isset($p[1]) && is_numeric($p[1])) { $this->players[] = $ckey = Civ13::sanitizeInput(urldecode($server[$key])); if (! array_key_exists($ckey, $this->rounds[$this->current_round]['players'])) { // TODO $this->rounds[$this->current_round]['players'][$ckey] = []; } } } } return $this->players; } /** * Creates and returns a periodic timer for updating the current round embed message. * If the timer does not already exist, it initializes the timer and sets it to update * the current round embed message every 60 seconds. * * @return TimerInterface The periodic timer for updating the current round embed message. */ public function currentRoundEmbedTimer(): TimerInterface { if (! isset($this->timers['current_round_embed'])) { $this->updateCurrentRoundEmbedMessageBuilder(); $this->timers['current_round_embed'] = $this->loop->addPeriodicTimer(60, async(fn () => $this->updateCurrentRoundEmbedMessageBuilder())); } return $this->timers['current_round_embed']; } /** * Updates the current round embed message builder. * * @param MessageBuilder|null $builder The message builder to used to perform the update the message. Defaults to null. * @return PromiseInterface A promise that resolves when the update is complete. */ public function updateCurrentRoundEmbedMessageBuilder(?MessageBuilder $builder = null): PromiseInterface { if (! $guild = $this->discord->guilds->get('id', $this->civ13->civ13_guild_id)) { $this->logger->error($err = "Could not find Guild with ID `{$this->civ13->civ13_guild_id}`"); return reject(new PartException($err)); } if (! $channel = $guild->channels->get('id', $this->playercount)) { $this->logger->error($err = "Could not find Channel with ID `{$this->playercount}`"); return reject(new PartException($err)); } if (! $builder = $this->createCurrentRoundEmbedMessageBuilder()) { // No round recorded yet (a new world before its first round_start): nothing to show, not an error. $this->logger->debug("No current round embed for {$this->key} yet"); return resolve(null); } $resend = function (?Message $message, callable $new) { if ($message) { $message->delete(); } return $new(new PartException("Failed to edit message current round message in {$this->key} ({$this->name})")); }; $send = fn (Message $message): bool => $this->civ13->VarSave($this->getRoundMessageIdFileName(), [$this->current_round_message_id = $message->id]); $new = fn (\Throwable $error): PromiseInterface => $this->civ13->then($channel->sendMessage($builder), $send); $edit = fn (?Message $message = null): ?PromiseInterface => $message ? $this->civ13->then($message->edit($builder), null, fn (\Throwable $error) => $resend($message, $new)) : null; return ($round_message_id = $this->getRoundMessageId()) ? $this->civ13->then($channel->messages->fetch($round_message_id), $edit, $new) : $this->civ13->then($channel->sendMessage($builder), $send, null); } /** * Creates the current round embed message builder. * * @return MessageBuilder|null The created message builder, or null if the round data is not available. */ public function createCurrentRoundEmbedMessageBuilder(): ?MessageBuilder { $status = $this->refreshLocalServerStatus(); if ($status['data'] === null) { return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->addRosterField($this->heartbeatEmbed($status)))); } if (! $round = $this->getRound($this->current_round)) { return $this->addPlayButton(Civ13::createBuilder()->addEmbed($this->addRosterField($this->heartbeatEmbed($status)))); } $round_embed_builder = function (array $round) use ($status): ?MessageBuilder { $data = self::heartbeatServerdata($status['data']); $embed = $this->heartbeatEmbed($status) ->setTitle($this->name) //->addFieldValues('Game ID', $game_id); ->addFieldValues('Start', RoundStartTimestamp::format($round['start'] ?? null), true) ->addFieldValues('End', $round['end'] ?? 'Ongoing/Unknown', true); if (isset($data[7])) { $embed->addFieldValues('Round Time', $this->parseRoundTime($data[7]), true); } if (isset($data[8])) { $embed->addFieldValues('Map', $data[8], true); } if (isset($data[9])) { $embed->addFieldValues('Epoch', $data[9], true); } if (isset($data[10])) { $embed->addFieldValues('Season', $data[10], true); } $this->addRosterField($embed); $embed->addFieldValues( 'Participating Players ('.count($players = array_keys($round['players'])).')', $players ? (strlen($participating_players = implode(', ', $players)) <= 1024 ? $participating_players : substr($participating_players, 0, 1021).'...') : 'None' ); try { $discord_ids = array_filter(array_map(fn ($c) => ($item = $this->civ13->verifier->get('ss13', $c)) ? "<@{$item['discord']}>" : null, $players)); } catch (VerifierException $e) { // Hosted verification is unavailable; keep the round embed without its verified list $discord_ids = []; } if ($discord_ids) { $embed->addFieldValues( 'Verified Players ('.count($discord_ids).')', strlen($verified_players = implode(', ', $discord_ids)) <= 1024 ? $verified_players : substr($verified_players, 0, 1021).'...' ); } return Civ13::createBuilder()->setContent("Round data for game_id `$this->current_round`")->addEmbed($embed); }; if (! $builder = $round_embed_builder($round)) { return null; } if ($log = str_replace('/', ';', "logs {$this->key}{$round['log']}")) { $builder->addComponent( ActionRow::new()->addComponent( Button::new(Button::STYLE_PRIMARY, $log) ->setLabel('Log') ->setEmoji('📝') ->setListener(fn ($interaction) => $interaction->acknowledge()->then(fn () => $this->interaction_log_handler($interaction)), $this->discord, $oneOff = false) ) ); } return $this->addPlayButton($builder); } /** Add the persistent URL component without a listener/custom id (survives bot restarts). */ public function addPlayButton(MessageBuilder $builder): MessageBuilder { if ($this->playLink !== null) { $builder->addComponent(ActionRow::new()->addComponent(Button::link($this->playLink->url)->setLabel('Play'))); } return $builder; } /** * Handles a "Log" button click: validates the Admin role, parses the `logs {path}` custom id, * navigates this server's log directory and follows up with the log file or "No logs found". */ protected function interaction_log_handler(Interaction $interaction): PromiseInterface { if (! $interaction->member->roles->has($this->civ13->role_ids['Admin'])) { return $interaction->sendFollowUpMessage(Civ13::createBuilder()->setContent('You do not have permission to use this command.'), true); } $tokens = explode(';', substr($interaction->data['custom_id'], strlen('logs '))); if (! isset($this->basedir) || ! file_exists($this->basedir.Civ13::log_basedir)) { $this->logger->warning($error = 'Either basedir or `'.Civ13::log_basedir.'` is not defined or does not exist'); return $interaction->sendFollowUpMessage(Civ13::createBuilder()->setContent($error), true); } unset($tokens[0]); $results = $this->civ13->FileNav($this->basedir.Civ13::log_basedir, $tokens); if (! $results[0]) { return $interaction->sendFollowUpMessage(Civ13::createBuilder()->setContent('No logs found.'), true); } return $interaction->sendFollowUpMessage(Civ13::createBuilder()->addFile($results[1], 'log.txt'), true); } /** The 10-minute timer that renames the player-count channel via {@see playercountChannelUpdate()}, created on first call. */ public function playercountTimer(): TimerInterface { // Update playercount channel every 10 minutes if (! isset($this->timers['playercount_timer'])) { $this->timers['playercount_timer'] = $this->loop->addPeriodicTimer(600, fn () => $this->playercountChannelUpdate()); } return $this->timers['playercount_timer']; } /* * This function parses the serverinfo data and updates the relevant Discord channel name with the current player counts * Prefix is used to differentiate between two different servers, however it cannot be used with more due to ratelimits on Discord * It is called on ready and every 5 minutes * * @param int $count The player count to update the channel with. * @return PromiseInterface A promise that resolves to the updated channel, or null if the channel didn't need to be updated. */ public function playercountChannelUpdate(): PromiseInterface { $this->refreshLocalServerStatus(); // A secondary region is counted by its parent's channel (the parent's `shards`); renaming here would fight it. if ($this->shardOf !== '') { return resolve(null); } // Players across the whole shard group, "offline" when no world is running, unchanged while unobserved. if (($label = PlayercountChannel::label($this->worlds)) === null) { return resolve(null); } if (! $channel = $this->discord->getChannel($this->playercount)) { $this->logger->warning($err = "Channel {$this->playercount} doesn't exist!"); return reject(new PartException($err)); } if (! $channel->created) { $this->logger->warning($err = "Channel {$channel->name} hasn't been created!"); return reject(new PartException($err)); } if (($name = PlayercountChannel::rename($channel->name, $label)) !== null) { $channel->name = $name; return $channel->guild->channels->save($channel); } return resolve(null); } /** * Sends an out-of-character (OOC) message. * * @param string $message The message to be sent. * @param string $sender The sender of the message. * @return bool Returns a PromiseInterface if the message is successfully sent, or false if sending the message fails. */ public function OOCMessage(string $message, string $sender): bool { return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2ooc, [$sender, $message]); } /** * Sends an admin message to the server. * * @param string $message The message to send. * @param string $sender The sender of the message. * @return bool Returns true if the message was sent successfully, false otherwise. */ public function AdminMessage(string $message, string $sender): PromiseInterface|bool { return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2admin, [$sender, $message]); } /** * Sends a direct message to a recipient using the specified sender and message. * * @param string $recipient The recipient of the direct message. * @param string $message The content of the direct message. * @param string $sender The sender of the direct message. * @return bool Returns true if the direct message was sent successfully, false otherwise. */ public function DirectMessage(string $message, string $sender, string $recipient): bool { return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2dm, [$sender, $recipient, $message]); } /** * Hosts the game server by executing necessary commands and setting up timers for hosting. * * @param Message|null $message An optional message object that can be used to react to the hosting action. */ public function Host(?Message $message = null): PromiseInterface { if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } if ($this->engine === 'opendream') { return $this->requestEngineControl('start'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost !== null) { return $this->gaiaHostRequest('start', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('start', $message); } if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { return $this->systemdRequest('start', $message); } OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::updateserverabspaths); if (file_exists($this->basedir.Civ13::serverdata)) { OSFunctions::execInBackground("rm -f {$this->basedir}".Civ13::serverdata); } OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::killsudos); if (! isset($this->civ13->timers["{$this->key}host"])) { $this->civ13->timers["{$this->key}host"] = $this->civ13->discord->getLoop()->addTimer(30, function () use ($message) { unset($this->civ13->timers["{$this->key}host"]); $promise = OSFunctions::execInBackground("nohup DreamDaemon {$this->basedir}".Civ13::dmb." {$this->port} -trusted -webclient -logself > /dev/null 2>&1 & disown"); if ($message) { $message->react('👍'); } }); } else { $this->logger->info("Server host timer already exists for {$this->key}."); } return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); } /** Shuts the server down (via `killciv13`), optionally announcing it in OOC first. */ public function Kill(?Message $message = null, bool $notify = true): PromiseInterface { if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } if ($this->engine === 'opendream') { return $this->requestEngineControl('stop'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { if ($notify) { $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } return $this->gaiaHostRequest($this->shardKillAction, $message); } if ($this->gaiaHost !== null) { if ($notify) { $this->OOCMessage('The server is saving and shutting down. Your character will be here when it comes back.', $this->civ13->discord->username ?? 'Server'); } return $this->gaiaHostRequest('stop', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('save-stop', $message); } if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { if ($notify) { $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } return $this->systemdRequest('stop', $message); } if ($notify) { $sender = (string) ((($message && $message->user_id) ? ($this->civ13->verifier->getVerifiedItem($message->user_id)['ss13'] ?? null) : null) ?? $this->civ13->discord->username ?? 'Server'); $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $sender); } $this->civ13->loop->addTimer(10, function () use ($message): void { OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::killciv13); if ($message) { $message->react('👍'); } }); return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); } /** Kills the server and re-hosts it 20s later, optionally announcing the restart in OOC. */ public function Restart(?Message $message = null, bool $notify = true): PromiseInterface { if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } if ($this->engine === 'opendream') { return $this->requestEngineControl('restart'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { if ($notify) { $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } return $this->gaiaHostRequest('restart', $message); } if ($this->gaiaHost !== null) { if ($notify) { $this->OOCMessage('The server is saving and restarting. Your character will be here when it comes back.', $this->civ13->discord->username ?? 'Server'); } return $this->gaiaHostRequest('restart', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('restart', $message); } if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { if ($notify) { $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } return $this->systemdRequest('restart', $message); } $this->Kill(null, false); $this->civ13->loop->addTimer(20, function () use ($message): void { $this->Host($message); }); if ($notify) { $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $message ? ($this->civ13->verifier->getVerifiedItem($message->author)['ss13'] ?? $this->civ13->discord->username) : $this->civ13->discord->username); } return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); } /** Pulls and compiles master while the server is stopped (gaia_host and shard_group hosts only). */ public function Update(?Message $message = null): PromiseInterface { if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost === null) { return reject(new \RuntimeException('Updating is only available for a gaia_host or shard_group server')); } return $this->gaiaHostRequest('update', $message); } /** Read-only host status line (scheduled-task hosts only). */ public function HostStatus(): PromiseInterface { if ($this->systemdUnit !== null) { return $this->systemdUnit->request('status')->then(static fn (array $status): string => \Civ13\Local\SystemdUnitControl::describe($status)); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost === null) { return reject(new \RuntimeException('Host status is only available for a gaia_host or shard_group server')); } $control = $this->gaiaHost; return $control->request('status')->then(static fn (array $status): string => $control::describe($status)); } /** The shard group file (Civ13 scripts/shard-group) this server heads, or '' when it has none. */ public function regionGroupFile(): string { return $this->regionGroupFile; } public function hasGaiaHost(): bool { return $this->gaiaHost !== null; } public function hasSystemdUnit(): bool { return $this->systemdUnit !== null; } /** Accepted means systemd queued the job; hoststatus shows the unit's state. */ private function systemdRequest(string $action, ?Message $message): PromiseInterface { if ($this->systemdUnit === null) { return reject(new \RuntimeException('systemd control unavailable: '.$this->systemdUnavailable)); } return $this->systemdUnit->request($action)->then(static function (array $result) use ($message): array { $message?->react('👍')->then(null, static fn (): null => null); return $result; }); } /** Accepted means the host script took the action; it finishes in the background. */ private function gaiaHostRequest(string $action, ?Message $message): PromiseInterface { return $this->gaiaHost->request($action)->then(static function (array $result) use ($message): mixed { $result['outcome'] = 'accepted'; // The action is already accepted; a failed reaction must not report it as failed. $message?->react('👍')->then(null, static fn (): null => null); return $result; }); } /** Success is acknowledged only after the supervisor supplies a bound completion result. */ private function nativeRequest(string $action, ?Message $message): PromiseInterface { if ($this->nativeLifecycle === null) { throw new \RuntimeException('Native lifecycle controls are unavailable on Windows'); } return $this->nativeLifecycle->request($action)->then(static function (array $result) use ($message): mixed { // The action is already accepted; a failed reaction must not report it as failed. $message?->react('👍')->then(null, static fn (): null => null); return $result; }); } /** * Swaps the current map to the specified map. * * @param string $mapto The name of the map to switch to. * @param string $admin The name of the admin requesting the map swap. * @return PromiseInterface A promise that resolves with a success message or rejects with an error message. */ public function MapSwap(string $mapto, string $admin): PromiseInterface { if ($this->engine === 'opendream') { return $this->requestEngineControl('mapswap', $mapto); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return reject(new \RuntimeException('Native map control is unavailable on Windows')); } $mapto = strtoupper($mapto); if (! file_exists($fp = $this->civ13->gitdir.Civ13::maps) || ! $file = @fopen($fp, 'r')) { $this->logger->error($err = "Unable to open `$fp` for reading."); return reject(new FileNotFoundException($err)); } $maps = []; while (($fp = fgets($file, 4096)) !== false) { $linesplit = explode(' ', trim(str_replace('"', '', $fp))); if (isset($linesplit[2]) && $map = trim($linesplit[2])) { $maps[] = $map; } } fclose($file); if (! in_array($mapto, $maps)) { return reject(new UserInputException("`$mapto` was not found in the map definitions.")); } $this->OOCMessage($msg = "Server is now changing map to `$mapto`.", $this->civ13->verifier->getVerifiedItem($admin)['ss13'] ?? $this->civ13->discord->username); if ($channel = $this->civ13->discord->getChannel($this->discussion)) { $msg = (isset($this->civ13->role_ids['mapswap']) ? "<@&{$this->civ13->role_ids['mapswap']}>, " : '')."{$this->name} $msg"; $channel->sendMessage($msg); } $this->loop->addTimer(10, fn () => OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::mapswap." $mapto")); return resolve($msg); } /** All normal message/slash callers use this adapter, with no native fallback. */ private function requestEngineControl(string $action, ?string $map = null): PromiseInterface { if (!$this->enabled || !$this->engineControl) { return reject(new \LogicException('Server controls unavailable')); } if ($this->controlBusy) { return reject(new \LogicException('Server operation already in progress')); } $this->controlBusy = true; try { $promise = $this->engineControl->request($action, $map); } catch (\Throwable $error) { $this->controlBusy = false; return reject($error); } return $promise->then(function ($result) { $this->controlBusy = false; return $result; }, function (\Throwable $error) { $this->controlBusy = false; throw $error; }); } /** Trims the bans and player-log files via {@see __cleanupLog()}. */ public function cleanupLogs(): bool { $bans = $this->__cleanupLog($this->basedir.Civ13::bans); $playerlogs = $this->__cleanupLog($this->basedir.Civ13::playerlogs); return $bans && $playerlogs; } /** * Rewrites the log file at `$path`, dropping entries older than the retention window. * * @return bool False when the file cannot be read. */ public function __cleanupLog(string $path): bool { if (! @file_exists($path)) { $this->logger->warning("Unable to open `$path`"); return false; } if (($original_file_contents = @file_get_contents($path)) === false) { $this->logger->warning("Unable to read `$path`"); return false; } $original_file_contents = str_replace('||||||', '|||', $original_file_contents); $new_file_contents = explode(PHP_EOL, $original_file_contents); $new_file_contents = array_unique($new_file_contents); $new_file_contents = implode(PHP_EOL, $new_file_contents); if ($original_file_contents === $new_file_contents) { return true; } // No changes were made // Write the results back to the file if (file_put_contents($path, $new_file_contents) === false) { $this->logger->warning("Unable to write to `$path`"); return false; } return true; } /** * Determines whether a ckey is currently banned from the server. * * This function is called when a user is verified to determine whether they should be given the banished role or have it taken away. * It checks the nomads_bans.txt and tdm_bans.txt files for the ckey. * * @param string $ckey The ckey to check for banishment. * @param bool $bypass (optional) If set to true, the function will not add or remove the banished role from the user. * @return bool Returns true if the ckey is found in either ban file, false otherwise. */ public function bancheck(string $ckey, bool $bypass = false, bool $use_cache = false): bool { return $this->legacy ? $this->legacyBancheck($ckey, $use_cache) : $this->sqlBancheck($ckey); } /** Whether `$id` (ckey) is permabanned, dispatching to the legacy-file or SQL check. */ public function permabancheck(string $id, bool $bypass = false): bool { if (! $id = Civ13::sanitizeInput($id)) { return false; } return $this->legacy ? $this->legacyPermabancheck($id) : $this->sqlPermabancheck($id); } /** * Checks if a player with the given ckey is permabanned based on legacy settings. * * @param string $ckey The ckey of the player to check. * @return bool Returns true if the player is permabanned, false otherwise. */ public function legacyPermabancheck(string $ckey): bool { if (! @file_exists($path = $this->basedir.Civ13::bans) || ! $file = @fopen($path, 'r')) { $this->logger->debug("Unable to open `$path`"); return false; } while (($fp = fgets($file, 4096)) !== false) { // str_replace(PHP_EOL, '', $fp); // Is this necessary? $linesplit = explode(';', trim(str_replace('|||', '', $fp))); // $split_ckey[0] is the ckey if (isset($linesplit[8]) && ($linesplit[8] === $ckey) && ($linesplit[0] === 'Server') && (str_ends_with($linesplit[7], '999 years'))) { fclose($file); return true; } } fclose($file); return false; } /** * Checks if a player with the given ckey is permabanned. * * @param string $ckey The ckey of the player to check. * @return bool Returns true if the player is permabanned, false otherwise. */ public function sqlPermabancheck(string $ckey): bool { // TODO, pending /tg/ SQL server implementation return false; } /** * Checks if a given ckey is banned based on legacy ban data. * * @param string $ckey The ckey to check for ban. * @return bool Returns true if the ckey is banned, false otherwise. */ public function legacyBancheck(string $ckey, bool $use_cache = false): bool { if (! $use_cache || ! $this->bancheck_cache) { $this->updateBanCache(); } foreach (explode(PHP_EOL, $this->bancheck_cache) as $line) { if (isset(($linesplit = explode(';', trim(str_replace('|||', '', $line))))[8]) && ($linesplit[8] === $ckey)) { return true; } } // $split_ckey[0] is the ckey return false; } /** Reloads `bancheck_cache` from the bans file. Returns the file contents, or null on failure. */ public function updateBanCache(): ?string { if (! @file_exists($path = $this->basedir.Civ13::bans)) { $this->logger->debug("Unable to open `$path`"); return null; } if (($file_contents = @file_get_contents($path)) === false) { $this->logger->debug("Unable to read `$path`"); return null; } return $this->bancheck_cache = $file_contents; } /** * Checks if a player with the given ckey is banned. * * @param string $ckey The ckey of the player to check. * @return bool Returns true if the player is banned, false otherwise. */ public function sqlBancheck(string $ckey): bool { // TODO, pending /tg/ SQL server implementation return false; } /** * Updates the ban log in the game server based on the player log. * * @param int|string|null $ckey The ckey of the player to update the ban log for. If null, all bans will be updated. * @param string|null $playerlog The player log content as a string. If not provided, the player log file for this server will be used. * @return PromiseInterface The updated ban log as a string, or a throwable string if there was an error. */ public function banlog_update(int|string|null $ckey = null, ?string $playerlog = ''): PromiseInterface { if (! touch($fp = $this->basedir.Civ13::playerlogs)) { $this->logger->warning($err = "Unable to open `$fp`"); return reject(new FileNotFoundException($err)); } if (! touch($fp = $this->basedir.Civ13::bans)) { $this->logger->warning($err = "Unable to open `$fp`"); return reject(new FileNotFoundException($err)); } if (! $playerlog && ! $playerlog = @file_get_contents($fp = $this->basedir.Civ13::playerlogs)) { $this->logger->warning("Unable to read `$fp`"); return reject(new FileNotFoundException("Unable to read `$fp`")); } if (! $banlog = @file_get_contents($fp = $this->basedir.Civ13::bans)) { $this->logger->warning("Unable to read `$fp`"); return reject(new FileNotFoundException("Unable to read `$fp`")); } $this->logger->debug("Updating ban log for {$this->name}. ".($ckey ? "ckey: $ckey" : 'All bans').'.'); $temp = []; $oldlist = []; foreach (explode('|||', $banlog) as $bsplit) { if (trim($bsplit) === '') { continue; } // Skip empty lines, including the line break after the final row $ban = explode(';', trim($bsplit)); if (isset($ban[8])) { if ($ckey && $ckey != $ban[8]) { continue; } if (isset($ban[9], $ban[10]) && $ban[9] != '0' && $ban[10] != '0') { $oldlist[] = $bsplit; } elseif ($ckey) { $temp[$ban[8]] = $bsplit; } else { $temp[] = $bsplit; // A full rewrite must keep every incomplete ban, including several for one ckey } } elseif (! $ckey) { $oldlist[] = $bsplit; } // A row without a ckey column cannot be backfilled: a full rewrite keeps every such row as-is, and a single-ckey update ignores it } /** * This function takes a player log's content as a string and updates the corresponding logs in the game server. * Each individual player log is a string separated by '|', and each log entry is separated by ';'. * The function searches for matching log entries in the game server and updates the corresponding values. */ $logs = explode('|', $playerlog); array_map(function ($lsplit) use (&$temp) { $log = explode(';', trim($lsplit)); array_walk_recursive($temp, function (&$arr) use ($log) { $a = explode(';', $arr); if (isset($a[8]) && $a[8] === $log[0]) { $a[9] = $log[2]; $a[10] = $log[1]; $arr = implode(';', $a); } }); }, $logs); $updated = array_values($temp); if (! $updated && ($ckey || ! $oldlist)) { return resolve(''); // Nothing to backfill or keep, so the bans file is left exactly as it is } /** * This function updates the bans list by merging the old list with the updated list. * If the updated list is empty, it returns the old list with line breaks replaced by '|||' and appended with a line break. * If the updated list is not empty, it merges the old list with the updated list, replaces line breaks with '|||', trims the result, and appends a line break. */ $final = $updated ? trim(preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", PHP_EOL, implode('|||'.PHP_EOL, array_merge($oldlist, $updated)))).'|||'.PHP_EOL : trim(preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", PHP_EOL, implode('|||'.PHP_EOL, $oldlist))).'|||'.PHP_EOL; $ckey ? file_put_contents($fp, $final, FILE_APPEND) : file_put_contents($fp, $final); return resolve($final); } /** The raw contents of this server's bans file, or false when it cannot be read. */ public function listbans(): string|false { if (! @touch($fp = $this->basedir.Civ13::bans)) { $this->logger->warning("Unable to open `$fp`"); return false; } if (! $banlog = @file_get_contents($fp)) { $this->logger->warning("Unable to read `$fp`"); return false; } return $banlog; } /** Adds this server's ban list to `$banlists` keyed by server name. */ public function merge_banlist(array $banlists): array { return ($banlist = $this->listbans()) ? array_merge($banlists, [$this->name => $banlist]) : $banlists; } /** Runs {@see __panicCheck()} for `$ckey` and posts the resulting ban reason to the staff channel. */ public function panicCheck(string $ckey): void { if (! $ban_reason = $this->__panicCheck($ckey)) { return; } if (! isset($this->civ13->channel_ids['staff_bot']) || ! $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { return; } $this->civ13->sendMessage($channel, $ban_reason); } /** * The panic-bunker ban reason for `$ckey` when the bunker is active and the player is unverified, * or false when no panic ban applies. */ private function __panicCheck(string $ckey): string|false { if (! $this->panic_bunker) { return false; } if (! isset($this->civ13->verifier)) { return false; } if ($this->civ13->verifier->getVerifiedItem($ckey)) { return false; } // Whether the ckey is verified if (! @file_exists($this->serverdata) || ! $data = @file_get_contents($this->serverdata)) { $this->logger->warning("Unable to open `{$this->serverdata}`"); return false; } if (self::explodeServerdata($data)[12] ?? true) { return false; } // Whether restart vote is allowed if (! $guild = $this->discord->guilds->get('id', $this->civ13->civ13_guild_id)) { return false; } if (! $admins = $guild->members->filter(fn (Member $member) => $member->roles->has($this->civ13->role_ids['Admin']))) { return false; } // Get a list of admins from the Discord server if (! $admins->reduce(function ($carry, $member) { /** @var bool $carry */ if ($carry) { return $carry; } /** @var Member $member */ if (! $item = $this->civ13->verifier->get('discord', $member->id)) { return $carry; } return in_array($item['ss13'], $this->players); }, false)) { return false; } return $this->ban(['ckey' => $ckey, 'duration' => '999 years', 'reason' => "Byond account `$ckey` must register and be approved to play. Verify at {$this->civ13->discord_formatted}"]); } /* * These functions determine which of the above methods should be used to process a ban or unban * Ban functions will return a string containing the results of the ban * Unban functions will return nothing, but may contain error-handling messages that can be passed to $logger->warning() */ public function ban(array $array /* = ['ckey' => '', 'duration' => '', 'reason' => ''] */, ?string $admin = null, bool $permanent = false): string { if (! isset($array['ckey'])) { return 'You must specify a ckey to ban.'; } if (! is_numeric($array['ckey']) && ! is_string($array['ckey'])) { return 'The ckey must be a Byond username or Discord ID.'; } if (! isset($array['duration'])) { return 'You must specify a duration to ban for.'; } if ($array['duration'] === '999 years') { $permanent = true; } if (! isset($array['reason'])) { return 'You must specify a reason for the ban.'; } foreach ([$array['duration'], $array['reason'], $admin ?? $this->discord->username] as $field) { if (!is_string($field) || $field === '' || strlen($field) > 8192 || str_contains($field, ':::') || preg_match('/[\r\n\x00]/', $field)) { return 'Invalid ban record field.'; } } if (is_numeric($array['ckey'] = Civ13::sanitizeInput($array['ckey']))) { if (! isset($this->civ13->verifier) || ! $item = $this->civ13->verifier->get('discord', $array['ckey'])) { return "Unable to find a ckey for <@{$array['ckey']}>. Please use the ckey instead of the Discord ID."; } $array['ckey'] = $item['ss13']; } if (!preg_match('/^[a-z0-9]{1,64}$/D', $array['ckey'])) { return 'Invalid ban ckey.'; } if (!$this->legacy) { return $this->sqlBan($array, $admin); } $result = $this->legacyBan($array, $admin); if (str_starts_with($result, 'Unable to open')) { return $result; } if (isset($this->civ13->verifier) && $member = $this->civ13->verifier->getVerifiedMember($array['ckey'])) { if (! $member->roles->has($this->civ13->role_ids['Banished'])) { $string = "Banned for {$array['duration']} with the reason {$array['reason']}"; $permanent ? $member->setRoles([$this->civ13->role_ids['Banished'], $this->civ13->role_ids['Permabanished']], $string) : $member->addRole($this->civ13->role_ids['Banished'], $string); } } if (! isset($this->timers['ban_cleanup_timer'])) { // One pending cleanup per server; cleared when it runs so the next ban schedules another $this->timers['ban_cleanup_timer'] = $this->civ13->discord->getLoop()->addTimer(300, function (): void { unset($this->timers['ban_cleanup_timer']); $this->cleanupLogs(); }); } return $result; } /** * Appends a ban to the `discord2ban` file and schedules a follow-up to backfill missing ban data. * * @param array{ckey: string, duration: string, reason: string} $array * @return string A human-readable confirmation (or error) line. */ private function legacyBan(array $array, ?string $admin = null): string { $admin = $admin ?? $this->discord->username; if (str_starts_with(strtolower($array['duration']), 'perm')) { $array['duration'] = '999 years'; } if (!\Civ13\Server\Ipc::append($this->discord2ban, [$admin, $array['ckey'], $array['duration'], $array['reason']])) { $this->logger->warning("Unable to open `{$this->discord2ban}`"); return "Unable to open `{$this->discord2ban}`".PHP_EOL; } $timer = "banlog_update_{$array['ckey']}"; if (! isset($this->timers[$timer])) { // One pending backfill per ckey; cleared when it runs $this->timers[$timer] = $this->civ13->discord->getLoop()->addTimer(360, function () use ($array, $timer): void { unset($this->timers[$timer]); if (($playerlog = @file_get_contents($this->basedir.Civ13::playerlogs)) === false) { return; } foreach ($this->civ13->enabled_gameservers as $gameserver) { $gameserver->banlog_update($array['ckey'], $playerlog); } }); } // Attempts to fill in any missing data for the ban return "`$admin` `Server` banned `{$array['ckey']}` from `{$this->name}` for `{$array['duration']}` with the reason `{$array['reason']}`".PHP_EOL; } /** SQL ban backend — not yet implemented. */ private function sqlBan(array $array, ?string $admin = null): string { return 'SQL methods are not yet implemented!'.PHP_EOL; } /** * Unbans a player with the specified ckey. * * @param string $ckey The ckey of the player to unban. * @param string|null $admin The name of the admin who is performing the unban. If not provided, the display name of the Discord user will be used. */ public function unban(string $ckey, ?string $admin = null): PromiseInterface { $admin ??= $this->discord->username; if (!preg_match('/^[a-z0-9]{1,64}$/D', $ckey)) { return reject(new \InvalidArgumentException('Invalid unban ckey.')); } if (!$this->legacy) { return reject(new \LogicException('SQL unban is not implemented.')); } return $this->legacyUnban($ckey, $admin)->then(function () use ($ckey, $admin): PromiseInterface { $roles = []; if (isset($this->civ13->verifier) && $member = $this->civ13->verifier->getVerifiedMember($ckey)) { if ($member->roles->has($this->civ13->role_ids['Banished'])) { $roles[] = $member->removeRole($this->civ13->role_ids['Banished'], "Unbanned by $admin"); } if ($member->roles->has($this->civ13->role_ids['Permabanished'])) { $roles[] = $member->removeRole($this->civ13->role_ids['Permabanished'], "Unbanned by $admin")->then(function () use (&$member, $admin) { return $member->addRole($this->civ13->role_ids['Verified'], "Unbanned by $admin"); }); } } foreach (explode(PHP_EOL, $this->bancheck_cache) as $line) { if ((count($linesplit = explode(';', trim(str_replace('|||', '', $line)))) >= 9) && ($linesplit[8] === $ckey)) { $this->bancheck_cache = str_replace($line, '', $this->bancheck_cache); } } return \React\Promise\all($roles); }); } /** * Appends an unban entry to the `discord2unban` file. * * @return PromiseInterface Rejected with {@see MissingSystemPermissionException} when the file cannot be opened. */ private function legacyUnban(string $ckey, ?string $admin = null): PromiseInterface { $admin = $admin ?? $this->discord->username; if (!\Civ13\Server\Ipc::append($this->discord2unban, [$admin, $ckey])) { $this->logger->warning($err = "Unable to open `$this->discord2unban`"); return reject(new MissingSystemPermissionException($err)); } return resolve(null); } /** SQL unban backend — not yet implemented. */ private function sqlUnban($array, ?string $admin = null): string { return 'SQL methods are not yet implemented!'.PHP_EOL; } /** * Retrieves the round message ID. * * This method attempts to return the round message ID for the current instance. * - If the property `$round_message_id` is already set, it returns its value. * - Otherwise, it tries to load the value from a serialized array stored in a JSON file * using the `VarLoad` method of the `$civ13` object, with a filename based on the instance's key. * If successful, it sets and returns the first element of the loaded array as `$round_message_id`. * - If neither is available, it returns null. * * @return string|null The round message ID if available, or null if not set or not found. */ public function getRoundMessageId(): ?string { if (isset($this->current_round_message_id)) { return $this->current_round_message_id; } if ($serialized_array = $this->civ13->VarLoad($this->getRoundMessageIdFileName())) { return $this->current_round_message_id = array_shift($serialized_array); } return null; } /** * Generates the filename for storing the round message ID associated with this game server instance. * * @return string */ public function getRoundMessageIdFileName(): string { return "{$this->key}_current_round_message_id.json"; } /** * Retrieves an array of collections containing information about rounds. * * @return CollectionInterface An array of collections, where each collection represents a server and its rounds. */ public function getRoundsCollection(): CollectionInterface // [string $server, collection $rounds] { return new Collection(array_filter(array_map(fn ($game_id, $round) => array_merge($round, ['game_id' => $game_id]), array_keys($this->rounds), $this->rounds)), 'game_id'); } /** * Logs a new round in the game. * * @param string $game_id The game ID. * @param string $time The current time. */ public function logNewRound(string $game_id, string $time): void { if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/D', $game_id)) { throw new \InvalidArgumentException('Invalid round identity.'); } // Repeated authenticated delivery must not erase the recorded players. if (isset($this->rounds[$game_id])) { if ($this->current_round !== $game_id) { throw new \LogicException('Historical round cannot become current.'); } if (!$this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds) || !$this->civ13->VarSave("{$this->key}_current_round.json", [$this->current_round])) { throw new MissingSystemPermissionException('Unable to persist round state.'); } return; } if (isset($this->rounds[$this->current_round])) { // If the round already exists and is not the current round $this->rounds[$this->current_round]['end'] ??= substr($time, 1, -1).' '.date('m/d/Y'); } // Set end time of previous round $this->rounds[$this->current_round = $game_id] = [ 'game_id' => $game_id, 'log' => '/'.date('Y/m-F/d-l').'.log', 'start' => substr($time, 1, -1).' '.date('m/d/Y'), 'end' => null, 'players' => [], 'interrupted' => false, ]; if (!$this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds) || !$this->civ13->VarSave("{$this->key}_current_round.json", [$this->current_round])) { throw new MissingSystemPermissionException('Unable to persist round state.'); } } /** * Logs the login of a player. * * @param string $ckey The player's ckey. * @param string $time The login time. * @param string $ip The player's IP address (optional). * @param string $cid The player's CID (optional). * @return PromiseInterface A promise that resolves with the message sent to the staff channel */ public function logPlayerLogin(string $ckey, string $time, string $ip = '', string $cid = ''): PromiseInterface { if (! $this->enabled) { return reject(new \LogicException('Game server is not enabled.')); } if (!preg_match('/^[a-z0-9]{1,64}$/D', $ckey)) { return reject(new \InvalidArgumentException('Invalid ckey provided.')); } if (! $this->current_round) { $this->logger->warning($err = "No current round found for {$this->key} logPlayerLogin."); return reject(new \LogicException($err)); } if (! in_array($ckey, $this->players, true)) { $this->players[] = $ckey; } $this->rounds[$this->current_round]['players'][$ckey] ??= [ // Initialize the player if they don't exist 'ip' => [], 'cid' => [], 'login' => $time, ]; if ($ip && ! in_array($ip, $this->rounds[$this->current_round]['players'][$ckey]['ip'] ?? [])) { $this->rounds[$this->current_round]['players'][$ckey]['ip'][] = $ip; } if ($cid && ! in_array($cid, $this->rounds[$this->current_round]['players'][$ckey]['cid'] ?? [])) { $this->rounds[$this->current_round]['players'][$ckey]['cid'][] = $cid; } if (!$this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds)) { return reject(new MissingSystemPermissionException('Unable to persist player login.')); } // Early return if the player is permitted to bypass restrictions if (isset($this->civ13->permitted[$ckey])) { return resolve(null); } $ip_data = $this->civ13->getIpData($ip); $conditions = [ 'Proxy' => isset($ip_data['proxy']) && $ip_data['proxy'], 'Hosting' => isset($ip_data['hosting']) && $ip_data['hosting'], ]; $ban_reason = array_reduce(array_keys($conditions), fn ($carry, $key) => $carry ?: ($conditions[$key] ? $key : null), null); if ($ban_reason && isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { return $this->civ13->sendMessage($channel, $this->civ13->ban(['ckey' => $ckey, 'duration' => '2 minutes', 'reason' => 'You cannot use a VPN or VPS hosting provider to play. Please disable it before reconnecting.'], null, null, true)." ($ban_reason)"); } return resolve(null); } /** * Logs the logout of a player. * * @param string $ckey The player's ckey. * @param string $time The login time. * * @return PromiseInterface */ public function logPlayerLogout(string $ckey, string $time): PromiseInterface { if (! $this->enabled) { return reject(new \LogicException('Game server is not enabled.')); } if (!preg_match('/^[a-z0-9]{1,64}$/D', $ckey)) { return reject(new \InvalidArgumentException('Invalid ckey provided.')); } if (in_array($ckey, $this->players)) { unset($this->players[array_search($ckey, $this->players)]); } if (! $this->current_round) { $this->logger->warning($err = "No current round found for {$this->key} logPlayerLogout"); return reject(new \LogicException($err)); } $this->rounds[$this->current_round]['players'][$ckey] ??= [ 'ip' => [], 'cid' => [], 'login' => $time, ]; $this->rounds[$this->current_round]['players'][$ckey]['logout'] = $time; if (!$this->civ13->VarSave("{$this->key}_rounds.json", $this->rounds)) { return reject(new MissingSystemPermissionException('Unable to persist player logout.')); } return resolve($this->rounds); } /** * Retrieves the rounds based on the provided criteria. * * @param string[] $ckeys An array of player keys to filter by (optional). * @param array|null $rounds The array of rounds (optional). * @return array The filtered array of rounds. */ public function getRounds(?array $ckeys = [], ?array $rounds = null): array { if (! $ckeys) { return $rounds ?? $this->rounds; } return array_filter($rounds ?? $this->rounds, function ($round) use ($ckeys) { foreach ($ckeys as $ckey) { if (! isset($round['players'][$ckey])) { return false; } } return true; }); } /** The stored data for round `$game_id`, or an empty array when unknown. */ public function getRound(string $game_id): array { return $this->rounds[$game_id] ?? []; } /** * Retrieves the rank for a given ckey from a file. * * @param string $ckey The ckey to search for. * @return false|string Returns the rank for the ckey as a string if found, or false if the file does not exist or cannot be accessed. */ public function getRank(string $ckey): string { $line_array = []; $return = ''; if (! @touch($this->ranking_path) || ! $search = @fopen($this->ranking_path, 'r')) { $this->logger->warning($return = "Unable to open `{$this->ranking_path}`"); return $return; } while (($fp = fgets($search, 4096)) !== false) { $line_array[] = $fp; } fclose($search); $found = false; $result = ''; foreach ($line_array as $line) { $sline = explode(';', trim(str_replace(PHP_EOL, '', $line))); if (count($sline) !== 2 || !is_numeric($sline[0]) || !preg_match('/^[a-z0-9]{1,64}$/D', $sline[1])) { continue; } if ($sline[1] == $ckey) { $found = true; $result .= "`{$sline[1]}` has a total rank of `{$sline[0]}`"; } } if (! $found) { return "No medals found for ckey `$ckey`."; } return $result; } /** * Retrieves the ranking from a file and returns it as a formatted string. * * @return PromiseInterface Returns the top 10 ranks as a string if found, or false if the file does not exist or cannot be opened. * @throws MissingSystemPermissionException If the file cannot be accessed or read. */ public function getRanking(): PromiseInterface { if (! @touch($path = $this->basedir.Civ13::ranking_path) || ! $search = @fopen($path, 'r')) { return reject(new MissingSystemPermissionException("Unable to open `$path`")); } $line_array = []; for ($scanned = 0; $scanned < 256 && count($line_array) < 10 && ($fp = fgets($search, 4096)) !== false; $scanned++) { $fields = explode(';', trim($fp)); if (count($fields) === 2 && is_numeric($fields[0]) && preg_match('/^[a-z0-9]{1,64}$/D', $fields[1])) { $line_array[] = $fp; } } fclose($search); $topsum = 0; return resolve(implode(PHP_EOL, array_map(function ($line) use (&$topsum) { $sline = explode(';', trim(str_replace(PHP_EOL, '', $line))); return '('.++$topsum."): `{$sline[1]}` with `{$sline[0]}` points."; }, array_slice($line_array, 0, 10)))); // Limit the array to only 10 values } /** * Recalculates the ranking based on the awards data. * * @return PromiseInterface A promise that resolves when the ranking has been successfully recalculated, or rejects with a MissingSystemPermissionException if there is an error accessing or writing to the necessary files. * * @throws MissingSystemPermissionException If the awards or ranking files cannot be accessed or written to. * * The function performs the following steps: * 1. Attempts to touch the awards and ranking files to ensure they are accessible. * 2. Reads the awards file line by line, skipping empty lines. * 3. Parses each line to extract user data and their corresponding medals. * 4. Calculates the score for each user based on their medals using predefined medal scores. * 5. Sorts the users by their scores in descending order. * 6. Writes the sorted ranking to the ranking file. */ public function recalculateRanking(): PromiseInterface { if (! @touch($awards = $this->basedir.Civ13::awards)) { return reject(new MissingSystemPermissionException("Unable to access `{$awards}`")); } if (! @touch($ranking_path = $this->basedir.Civ13::ranking_path)) { return reject(new MissingSystemPermissionException("Unable to access `{$ranking_path}`")); } if (($lines = file($awards, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) === false) { return reject(new MissingSystemPermissionException("Unable to read `$awards`")); } $result = []; foreach ($lines as $line) { $medal_s = 0; $duser = explode(';', trim($line)); $medalScores = [ 'long service medal' => 0.5, 'wounded badge' => 0.5, 'tank destroyer silver badge' => 0.75, 'wounded silver badge' => 0.75, 'wounded gold badge' => 1, 'assault badge' => 1.5, 'tank destroyer gold badge' => 1.5, 'combat medical badge' => 2, 'iron cross 1st class' => 3, 'iron cross 2nd class' => 5, ]; if (! isset($result[$duser[0]])) { $result[$duser[0]] = 0; } if (isset($duser[2]) && isset($medalScores[$duser[2]])) { $medal_s += $medalScores[$duser[2]]; } $result[$duser[0]] += $medal_s; } arsort($result); if (file_put_contents($ranking_path, implode(PHP_EOL, array_map(function ($ckey, $score) { return "$score;$ckey"; }, array_keys($result), $result))) === false) { return reject(new MissingSystemPermissionException("Unable to write to `$ranking_path`")); } return resolve(null); } /** * Reads the content of the sports teams file and returns it as a promise. * * @return PromiseInterface A promise that resolves with the content of the sports teams file. * @throws FileNotFoundException If the file does not exist or cannot be read. */ public function sportsteam(): PromiseInterface { if (! file_exists($fp = $this->civ13->enabled_gameservers['tdm']->basedir.Civ13::sportsteams)) { $this->logger->warning($err = "Unable to find `$fp`"); return reject(new FileNotFoundException($err)); } if (! $content = @file_get_contents($fp)) { $this->logger->warning($err = "Unable to read `$fp`"); return reject(new MissingSystemPermissionException($err)); } return resolve($content); } /** * This function is used to update the contents of files based on the roles of verified members. * The callback function is used to determine what to write to the file. * * @param callable $callback The callback function that determines what to write to the file. * @param array $file_paths An array of file paths to update. * @param array $required_roles An array of required roles for the members. * @return PromiseInterface A promise that resolves when the files are successfully updated, or rejects if there is an error. */ public function updateFilesFromMemberRoles(callable $callback, array $file_paths, array $required_roles): PromiseInterface { if (! isset($this->civ13->verifier)) { $this->logger->error($err = 'Unable to update files from member roles: Verifier is not set.'); return reject(new VerifierException($err)); } $beforeReplace = $callback instanceof \Civ13\Server\GuardedRoleFormatter ? $callback->beforeWrite(...) : null; $file_contents = ''; foreach ($this->civ13->verifier->verified as $item) { if ($member = $this->civ13->verifier->getVerifiedMember($item)) { $file_contents .= $callback($member, $item, $required_roles); } } try { foreach ($file_paths as $fp) { \Civ13\Server\Ipc::replace($fp, $file_contents, $beforeReplace); } } catch (\Throwable $error) { return reject($error); } return resolve(null); } /** * Updates the whitelist based on the member roles. * * @param array|null $required_roles The required roles for whitelisting. Default is ['Verified']. * @return PromiseInterface Resolves after every requested replacement completes; rejects on failure. */ public function whitelistUpdate(?array $required_roles = ['Verified']): PromiseInterface { $required_roles ??= ['Verified']; if (! $this->civ13->hasRequiredConfigRoles($required_roles)) { return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } if (! $this->enabled) { return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } $beforeReplace = null; // Read-only hosted mappings may not bypass AccessFileSync's transport authority gate. if (($this->civ13->verifier->readOnly ?? false) === true) { $records = iterator_to_array($this->civ13->verifier->verified, false); if (!$this->civ13->verifier->hostedAccessAuthority($records)) { return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } $beforeReplace = function () use ($records): void { $current = iterator_to_array($this->civ13->verifier->verified, false); if ($current !== $records || !$this->civ13->verifier->hostedAccessAuthority($current)) { throw new \RuntimeException('Role list update unavailable or inaccessible.'); } }; } if (! @touch($this->whitelist)) { $this->logger->warning("Unable to open `{$this->whitelist}`"); return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } $file_paths = []; $file_paths[] = $this->whitelist; $callback = function (Member $member, array $item, array $required_roles): string { $string = ''; foreach ($required_roles as $role) { if ($member->roles->has($this->civ13->role_ids[$role])) { $string .= "{$item['ss13']} = {$item['discord']}".PHP_EOL; } } return $string; }; if ($beforeReplace !== null) { $callback = new \Civ13\Server\GuardedRoleFormatter($callback, $beforeReplace); } return $this->updateFilesFromMemberRoles($callback, $file_paths, $required_roles); } /** * Updates the faction list based on the required roles. * * @param array|null $required_roles The required roles for updating the faction list. * @return PromiseInterface Resolves after every requested replacement completes; rejects on failure. */ public function factionlistUpdate(?array $required_roles = null): PromiseInterface { if (! $this->enabled) { return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } if (! $required_roles) { $required_roles = array_merge(Civ13::faction_teams, Civ13::faction_admins); } if (! $this->civ13->hasRequiredConfigRoles($required_roles)) { return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } if (! @touch($this->factionlist)) { $this->logger->warning("Unable to open `{$this->factionlist}`"); return reject(new \RuntimeException('Role list update unavailable or inaccessible.')); } $file_paths = []; $file_paths[] = $this->factionlist; $callback = function (Member $member, array $item, array $required_roles): string { return array_reduce($required_roles, function ($carry, $role) use ($member, $item) { return $member->roles->has($this->civ13->role_ids[$role]) ? $carry."{$item['ss13']};{$role}".PHP_EOL : $carry; }, ''); }; return $this->updateFilesFromMemberRoles($callback, $file_paths, $required_roles); } /** * Updates admin lists with required roles and permissions. * * @param array $required_roles An array of required roles and their corresponding permissions. * @return PromiseInterface A promise that resolves when the admin list is successfully updated, or rejects if there is an error. */ public function adminlistUpdate(?array $required_roles = null): PromiseInterface { if (! $this->enabled) { return reject(new \LogicException('Game server is not enabled.')); } if (! $required_roles) { $required_roles = self::ADMIN_PERMISSIONS; } if (! $this->civ13->hasRequiredConfigRoles(array_keys($required_roles))) { $this->logger->warning($err = 'Missing required roles for adminlist update.'); return reject(new InvalidConfigException($err)); } if (! @touch($this->admins)) { $this->logger->warning($err = "Unable to open `{$this->admins}`"); return reject(new MissingSystemPermissionException($err)); } $file_paths[] = $this->admins; $callback = function (Member $member, array $item, array $required_roles): string { $string = ''; $checked_ids = []; foreach (array_keys($required_roles) as $role) { if ($member->roles->has($this->civ13->role_ids[$role])) { if (! in_array($member->id, $checked_ids)) { // The DM loader splits on "|||\n", including on Windows. $string .= "{$item['ss13']};{$required_roles[$role][0]};{$required_roles[$role][1]}|||\n"; $checked_ids[] = $member->id; } } } return $string; }; return $this->updateFilesFromMemberRoles($callback, $file_paths, $required_roles); } /** The raw contents of this server's admins file, or false when it cannot be read. */ public function listadmins(): string|false { if (($admins = @file_get_contents($this->admins)) === false) { $this->logger->warning("Unable to read `{$this->admins}`"); return false; } return $admins; } /** * Formats an `H:i` round-time string as a compact `dhm` duration. */ public function parseRoundTime(string $time) { [$hours, $minutes] = array_map('intval', explode(':', $time) + [0, 0]); $days = floor($hours / 24); $hours = $hours % 24; return ($days ? $days.'d' : '').($hours ? $hours.'h' : '').$minutes.'m'; } /** * Generates a server status embed. * * @return Embed The generated server status embed. */ public function generateServerstatusEmbed(): ?Embed { if ($this->ip !== ($this->civ13->httpServiceManager->httpHandler->external_ip ?? null)) { return $this->toEmbed(); } // Don't try and access files if the server is not local $status = $this->refreshLocalServerStatus(); $embed = $this->heartbeatEmbed($status); if ($status['data'] === null) { return $this->addRosterField($embed); } $data = self::heartbeatServerdata($status['data']); if (isset($data['round_timer'])) { $embed->addFieldValues('Round Time', $this->parseRoundTime($data['round_timer']), true); } if (isset($data['map_name'])) { $embed->addFieldValues('Map', $data['map_name'], true); } // Appears twice in the data //if (isset($data[3])) $embed->addFieldValues('Gamemode', $data[3], true); if (isset($data['epoch'])) { $embed->addFieldValues('Epoch', $data['epoch'], true); } if ($this->shardHeartbeats) { // Every region of the group, grouped by region $this->addRosterField($embed); } elseif (isset($data['ckey_list'])) { // Player list $players = explode('&', $data['ckey_list']); $players = array_filter(array_map(fn ($player) => Civ13::sanitizeInput($player), $players)); if (! $players_list = implode(', ', $players)) { $players_list = 'N/A'; } $embed->addFieldValues('Players ('.count($players).')', $players_list, true); } if (isset($data['season'])) { $embed->addFieldValues('Season', $data['season'], true); } //if (isset($data[5])) $embed->addFieldValues('Realtime', $data[5], true); //if (isset($data[6])) $embed->addFieldValues('IP', $data[6], true); return $embed; } private function heartbeatEmbed(array $status): Embed { return $this->civ13->createEmbed() ->addFieldValues($this->name, match ($status['state']) { 'advancing' => 'Heartbeat advancing', 'stale' => 'Stale heartbeat', default => 'Unknown', }) ->addFieldValues('Observation', $status['reason'].($status['age'] === null ? '' : ' ('.ServerHeartbeat::formatAge($status['age']).' since last observed progress/baseline)'), false) ->addFieldValues('Host', $this->displayHost(), true); } /** Read only this locally configured server's host file; do not infer a fallback. */ private function displayHost(): string { $base = str_replace('\\', '/', $this->basedir); if ($this->ip !== ($this->civ13->httpServiceManager->httpHandler->external_ip ?? null) || $base === '' || str_starts_with($base, '//') || str_contains($base, '://')) { return 'Unavailable'; } $path = rtrim($this->basedir, '/\\').'/config/host.txt'; if (! @is_file($path) || ($value = @file_get_contents($path, false, null, 0, 1025)) === false || strlen($value) > 1024 || preg_match('//u', $value) !== 1) { return 'Unavailable'; } return trim($value) === '' ? 'Unavailable' : trim($value); } /** * Explodes the server data string into an array by removing specific substrings and splitting by semicolon. * * The input string is expected to contain the following information in the given format: * 0 => Server Status {Online/Offline} * 1 => Address byond://{ip_address} * 2 => Map: {map} * 3 => Gamemode: {gamemode} * 4 => Players: {playercount} * 5 => realtime={realtime} * 6 => world.address={ip} * 7 => round_timer={00:00} * 8 => map={map} * 9 => epoch={epoch} * 10 => season={season} * 11 => ckey_list={ckey&ckey} * 12 => allow_vote_restart={1/0} * * @param string $data The server data string to be exploded. * @return array The exploded server data as an array. */ public static function explodeServerdata(string $data): array { if (! $data) { return []; } $data = explode(';', str_replace([ 'Server Status: ', 'Address: ', 'Map: ', 'Gamemode: ', 'Players: ', 'round_timer=', 'map=', 'epoch=', 'season=', 'ckey_list=', 'allow_vote_restart=', '', '', ], '', $data)); $return = []; $return[0] = $return['status'] = $data[0] ?? 'N/A'; $return[1] = $return['ip'] = $data[1] ?? 'N/A'; $return[2] = $return['map'] = $data[2] ?? 'N/A'; $return[3] = $return['gamemode'] = $data[3] ?? 'N/A'; $return[4] = $return['playercount'] = $data[4] ?? 'N/A'; $return[5] = $return['realtime'] = $data[5] ?? 'N/A'; $return[6] = $return['world_address'] = $data[6] ?? 'N/A'; $return[7] = $return['round_timer'] = $data[7] ?? 'N/A'; $return[8] = $return['map_name'] = $data[8] ?? 'N/A'; $return[9] = $return['epoch'] = $data[9] ?? 'N/A'; $return[10] = $return['season'] = $data[10] ?? 'N/A'; $return[11] = $return['ckey_list'] = $data[11] ?? 'N/A'; $return[12] = $return['allow_vote_restart'] = $data[12] ?? 1; return $return; } /** A short embed with this server's URL, host and current player list. */ public function toEmbed(): Embed { return $this->civ13->createEmbed() ->setTitle($this->name) ->addFieldValues($this->engine === 'opendream' ? 'OpenDream gameplay endpoint' : 'Server URL', $this->engine === 'opendream' ? "{$this->ip}:{$this->port}" : "byond://{$this->ip}:{$this->port}", false) ->addFieldValues('Host', $this->displayHost(), true) ->addFieldValues('Health', 'Unknown (no local heartbeat evidence)', true) ->addFieldValues('Players (cached, unverified)', empty($this->players) ? 'N/A' : implode(', ', $this->players), true); } // Magic Methods /** * @inheritDoc * * Returns this server's key. */ public function __toString(): string { return $this->key; } /** * The server as an array of its public properties (minus the `civ13` back-reference). * * @return array */ public function __toArray(): array { $array = get_object_vars($this); unset($array['civ13'], $array['heartbeat'], $array['shardHeartbeats'], $array['worlds'], $array['shardNames'], $array['groupShards'], $array['regionGroupStamp'], $array['roster']); return $array; } /** * @inheritDoc */ public function __serialize(): array { return $this->__toArray(); } /** * @inheritDoc */ public function __debugInfo(): array { return $this->__toArray(); } /** * Cancels every timer this server registered. */ public function __destruct() { if (! isset($this->loop)) { return; } // Never fully constructed, so there is no loop holding timers foreach ($this->timers as $timer) { if ($timer instanceof TimerInterface) { $this->loop->cancelTimer($timer); } } } }