socket = @stream_socket_client('tcp://'.$cfg['host'].':'.$cfg['query_port'], $errno, $errstr, 8); if (!$this->socket) { throw new RuntimeException("TS3 indisponivel: $errstr ($errno)"); } stream_set_timeout($this->socket, 8); try { $this->send('login client_login_name='.$this->escape((string)$cfg['user']).' client_login_password='.$this->escape((string)$cfg['password']), 'autenticacao'); $this->send('use sid='.(int)$cfg['server_id'], 'selecao do servidor virtual'); } catch (\Throwable $e) { fclose($this->socket); $this->socket = null; throw $e; } } private function escape(string $value): string { return str_replace(['\\', '/', ' ', '|', "\n", "\r", "\t"], ['\\\\', '\\/', '\\s', '\\p', '\\n', '\\r', '\\t'], $value); } private function readResponse(): string { $lines = []; while (is_resource($this->socket) && !feof($this->socket)) { $line = fgets($this->socket); if ($line === false) { throw new RuntimeException('Timeout lendo ServerQuery TS3 durante '.$this->stage); } $line = trim($line); if (str_starts_with($line, 'error ')) { if (!preg_match('/\bid=0(?:\s|$)/', $line)) { throw new RuntimeException('TS3 falhou em '.$this->stage.': '.$line); } return implode("\n", $lines); } if ($line !== '') $lines[] = $line; } throw new RuntimeException('Conexao TS3 encerrada durante '.$this->stage); } private function send(string $command, string $stage): string { $this->stage = $stage; if (!is_resource($this->socket) || fwrite($this->socket, $command."\n") === false) { throw new RuntimeException('Falha de escrita no TS3 durante '.$stage); } return $this->readResponse(); } private function clientDbId(string $uid): int { // Busca pelo UID usando a sintaxe ServerQuery clientdbfind. // Nunca usar busca por apelido para atribuir grupos. $response = $this->send('clientdbfind pattern='.$this->escape($uid).' -uid', 'busca do UID'); preg_match_all('/(?:^|[|\s])cldbid=(\d+)/', $response, $matches); $ids = array_values(array_unique(array_map('intval', $matches[1]))); if (count($ids) !== 1) { throw new RuntimeException('UID TS3 nao encontrado ou busca ambigua ('.count($ids).' resultados)'); } // Confere UID exato antes de permitir qualquer escrita. $info = $this->send('clientdbinfo cldbid='.$ids[0], 'validacao do UID'); if (!preg_match('/(?:^|\s)client_unique_identifier=([^\s]+)/', $info, $m)) { throw new RuntimeException('TS3 nao retornou UID para validar o jogador'); } if ($m[1] !== $this->escape($uid)) { throw new RuntimeException('UID do registro encontrado difere do solicitado; nenhuma alteracao efetuada'); } return $ids[0]; } private function groupsFor(int $dbid): array { $response = $this->send('servergroupsbyclient cldbid='.$dbid, 'consulta dos grupos'); preg_match_all('/(?:^|[|\s])sgid=(\d+)/', $response, $matches); return array_values(array_unique(array_map('intval', $matches[1]))); } public function sync(string $uid, bool $eligible, string $skill, bool $apply = false): array { $cfg = config('gigax_ts3_medals'); $all = array_values(array_filter(array_map('intval', array_merge([$cfg['eligible_group']], array_values($cfg['skill_groups']))))); if (count($all) !== 11 || count(array_unique($all)) !== 11) { throw new RuntimeException('Configure 11 IDs de Server Groups distintos no .env'); } if ($skill !== 'none' && !isset($cfg['skill_groups'][$skill])) { throw new RuntimeException('Skill invalida: '.$skill); } $dbid = $this->clientDbId($uid); $current = $this->groupsFor($dbid); $desired = $eligible ? [(int)$cfg['eligible_group']] : []; if ($skill !== 'none') $desired[] = (int)$cfg['skill_groups'][$skill]; $add = array_values(array_diff($desired, $current)); $remove = array_values(array_intersect(array_diff($all, $desired), $current)); if ($apply) { foreach ($add as $id) { $this->send('servergroupaddclient sgid='.$id.' cldbid='.$dbid, 'adicao do grupo '.$id); } foreach ($remove as $id) { $this->send('servergroupdelclient sgid='.$id.' cldbid='.$dbid, 'remocao do grupo '.$id); } } return compact('dbid', 'current', 'desired', 'add', 'remove', 'apply'); } public function __destruct() { if (is_resource($this->socket)) fclose($this->socket); } }