1 && $x[0] === "'" && substr($x, -1) === "'") $x = substr($x, 1, -1); }); $v = $ini['votescript'] ?? []; if (empty($v['key'])) exit("Fill in the key in $file\n"); /** @return array decoded answer; throws when VoteScript cannot be reached */ function ask(array $v, string $method, array $form, string $http = 'POST'): array { $url = rtrim($v['url'], '/') . "/index.php?r=api/v1/$method" . ($http === 'GET' && $form ? '&' . http_build_query($form) : ''); $ctx = stream_context_create(['http' => ['method' => $http, 'header' => "X-Api-Key: {$v['key']}\r\nContent-Type: application/x-www-form-urlencoded", 'content' => $http === 'POST' ? http_build_query($form) : '', 'timeout' => 10, 'ignore_errors' => true, 'follow_location' => 0]]); $raw = @file_get_contents($url, false, $ctx); $d = $raw === false ? null : json_decode($raw, true); if (!is_array($d)) throw new RuntimeException('VoteScript cannot be reached'); preg_match('/ (\d{3})/', $http_response_header[0] ?? '', $m); $code = (int) ($m[1] ?? 0); if ($code === 401) throw new RuntimeException('The API key is wrong'); if ($code >= 500 || $code === 429) throw new RuntimeException($d['error'] ?? 'VoteScript error'); return $d; } function say(string $text): void { echo date('H:i:s '), preg_replace('/[\x00-\x1f]+/', ' ', $text), "\n"; } function connect(array $d): PDO { $o = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]; // A statement that sets a value the row already has counts as done. if (strncmp($d['dsn'], 'mysql:', 6) === 0) $o[PDO::MYSQL_ATTR_FOUND_ROWS] = true; return new PDO($d['dsn'], $d['user'] ?? '', $d['password'] ?? '', $o); } function isMysql(PDO $db): bool { return $db->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql'; } /** Only the named values a statement uses are bound; repeated names work on every driver. */ function run(PDO $db, string $sql, array $values): PDOStatement { $args = []; $sql = preg_replace_callback('/:(player|amount|key|name|arg2|arg)\b/', function ($m) use ($values, &$args) { $args[] = $values[$m[1]]; return '?'; }, $sql); $st = $db->prepare($sql); foreach ($args as $i => $a) $st->bindValue($i + 1, $a, is_int($a) ? PDO::PARAM_INT : PDO::PARAM_STR); $st->execute(); return $st; } /* ---------------------------------------------------------- reward types */ const TIMES = ['vip' => 'days', 'group' => 'days', 'permission' => 'days', 'title' => 'days', 'unlock' => 'days', 'until' => 'days', 'boost' => 'minutes', 'effect' => 'seconds', 'storage' => 'amount', 'xp' => 'amount', 'run' => 'amount', 'custom' => 'amount', 'teleport' => '', 'outfit' => '', 'mount' => '', 'spell' => '', 'badge' => '']; /** Too powerful for "any name the dashboard sends". */ const EXACT = ['group', 'permission', 'spell']; /** @return string[] type and arguments; a key without a known type is an item */ function parts(string $key): array { $p = explode('/', $key); return count($p) > 1 && isset(TIMES[$p[0]]) ? $p : ['item', $key]; } /** The line for a key: exact, then with fewer and fewer parts before /*; "default" only for plain keys. */ function lineFor(array $lines, string $key): string { if (isset($lines[$key]) && !in_array($key, ['check', 'each', 'default'], true)) return trim($lines[$key]); $p = parts($key); if ($p[0] === 'item') return trim($lines['default'] ?? ''); for ($n = count($p) - 1; $n > 0; $n--) { if ($n === 1 && in_array($p[0], EXACT, true)) break; $k = implode('/', array_slice($p, 0, $n)) . '/*'; if (isset($lines[$k])) return trim($lines[$k]); } return ''; } /** What the lines can pay, for VoteScript. Everything else stays waiting there. */ function typesOf(array $lines): string { $out = []; foreach ($lines as $k => $line) { $k = (string) $k; if (trim((string) $line) === '' || $k === 'check' || $k === 'each') continue; if ($k === 'default') { $out['item'] = 1; continue; } $p = parts($k); if ($p[0] === 'item') $out[preg_match('/^[A-Za-z0-9_.:\/-]{1,80}$/', $k) ? "item/$k" : 'item'] = 1; elseif (end($p) === '*') { if (count($p) > 2 || !in_array($p[0], EXACT, true)) $out[substr($k, 0, -2)] = 1; } else $out[$k] = 1; } if (isset($out['item']) || count($out) > 250) $out = array_filter($out, function ($k) { return strncmp($k, 'item/', 5) !== 0; }, ARRAY_FILTER_USE_KEY) + ['item' => 1]; return implode(',', array_keys($out)); } /** Values for a line, checked and kept inside [limits]. Null: not a value we accept. */ function valuesFor(array $i, string $player, array $limits): ?array { $p = parts((string) $i['key']); $n = min(2147483647, (int) $i['amount']); if ($n < 1) return null; if ($p[0] !== 'item') { if (!preg_match('#^[a-z]{2,16}(/-?[A-Za-z0-9_.:][A-Za-z0-9_.:,-]{0,79}){1,4}$#D', $i['key'])) return null; $unit = TIMES[$p[0]]; $max = (int) ($limits[$unit] ?? ['days' => 365, 'minutes' => 1440, 'seconds' => 3600, 'amount' => 100000000][$unit] ?? 1); if ($unit !== '' && $n > $max) { say("$player: {$i['key']} is kept at $max ([limits] $unit) instead of $n"); $n = $max; } } return ['player' => $player, 'amount' => $n, 'key' => (string) $i['key'], 'name' => (string) $i['name'], 'arg' => (string) ($p[1] ?? ''), 'arg2' => (string) ($p[2] ?? '')]; } /* -------------------------------------------------------------- mode game */ function gameTables(PDO $db): void { $db->exec("CREATE TABLE IF NOT EXISTS votescript_requests (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, player VARCHAR(40) NOT NULL, code VARCHAR(20) NOT NULL DEFAULT '', state TINYINT NOT NULL DEFAULT 0, votes INT NOT NULL DEFAULT 0, message VARCHAR(160) NOT NULL DEFAULT '', told TINYINT NOT NULL DEFAULT 0, ref VARCHAR(40) NOT NULL DEFAULT '', created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY state (state), KEY player (player)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); $db->exec("CREATE TABLE IF NOT EXISTS votescript_items (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, request_id INT UNSIGNED NOT NULL, player VARCHAR(40) NOT NULL, item_key VARCHAR(120) NOT NULL, name VARCHAR(80) NOT NULL, amount INT NOT NULL, given TINYINT NOT NULL DEFAULT 0, KEY player (player, given)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } /** What the game script says it can do, or '' when it is an older one. */ function gameTypes(PDO $db): string { try { $row = $db->query('SELECT types FROM votescript_types WHERE id = 1')->fetch(); return $row ? (string) $row['types'] : ''; } catch (PDOException $e) { return ''; } } function gamePass(PDO $db, array $v): void { $types = null; foreach ($db->query('SELECT * FROM votescript_requests WHERE state = 0 ORDER BY id LIMIT 50')->fetchAll() as $r) { if ($r['ref'] === '') { $r['ref'] = 'sql-' . bin2hex(random_bytes(14)); $db->prepare("UPDATE votescript_requests SET ref = ? WHERE id = ? AND ref = ''")->execute([$r['ref'], $r['id']]); } $types = $types ?? gameTypes($db); $d = ask($v, $r['code'] === '' ? 'claim' : 'claim-code', ['player' => $r['player'], 'ref' => $r['ref']] + ($types === '' ? [] : ['types' => $types]) + ($r['code'] === '' ? [] : ['code' => $r['code']])); $ok = !empty($d['ok']); $items = $ok ? $d['items'] : []; $votes = $ok ? (int) $d['votes'] : 0; $text = !$ok ? (string) ($d['error'] ?? 'Your votes could not be checked.') : ($votes || $items ? 'Thank you for voting! Rewards for ' . $votes . ($votes === 1 ? ' vote.' : ' votes.') : (empty($d['held']) ? 'You have no votes to claim.' : 'Your vote reward cannot be given on this server yet. It stays waiting.')); $db->beginTransaction(); $done = $db->prepare('UPDATE votescript_requests SET state = 1, votes = ?, message = ? WHERE id = ? AND state = 0'); $done->execute([$votes, mb_substr($text, 0, 160), $r['id']]); if ($done->rowCount() === 1) { $add = $db->prepare('INSERT INTO votescript_items (request_id, player, item_key, name, amount) VALUES (?, ?, ?, ?, ?)'); foreach ($items as $i) $add->execute([$r['id'], $r['player'], $i['key'], $i['name'], min(2147483647, (int) $i['amount'])]); } $db->commit(); say("{$r['player']}: $text"); } } /* --------------------------------------------------------------- mode sql */ function sqlTables(PDO $db): void { $t = 'player VARCHAR(40) NOT NULL PRIMARY KEY, ref VARCHAR(40) NOT NULL'; $d = 'ref VARCHAR(40) NOT NULL PRIMARY KEY, player VARCHAR(40) NOT NULL, paid VARCHAR(400) NOT NULL'; if (isMysql($db)) { $db->exec("CREATE TABLE IF NOT EXISTS votescript_open ($t) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); $db->exec("CREATE TABLE IF NOT EXISTS votescript_done ($d) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } else { $db->exec("IF OBJECT_ID('votescript_open') IS NULL CREATE TABLE votescript_open ($t)"); $db->exec("IF OBJECT_ID('votescript_done') IS NULL CREATE TABLE votescript_done ($d)"); } } function sqlPass(PDO $db, array $v, array $sql, array $limits): void { $open = $db->query('SELECT player, ref FROM votescript_open')->fetchAll(); $names = array_column($open, 'ref', 'player'); foreach (ask($v, 'pending', ['limit' => 100, 'types' => typesOf($sql)])['players'] as $p) $names += [$p['player'] => '']; foreach ($names as $player => $ref) { $player = (string) $player; try { payPlayer($db, $v, $sql, $limits, $player, (string) $ref); } catch (NotNow $e) { // Often: the account is online. Only this player waits. if ($db->inTransaction()) $db->rollBack(); say($e->getMessage()); } } } final class NotNow extends RuntimeException { } function payPlayer(PDO $db, array $v, array $sql, array $limits, string $player, string $ref): void { { if ($ref === '') { $check = trim($sql['check'] ?? ''); if ($check !== '' && run($db, $check, ['player' => $player, 'amount' => 0, 'key' => '', 'name' => '', 'arg' => '', 'arg2' => ''])->fetch() === false) return; $ref = 'pay-' . bin2hex(random_bytes(14)); // Before asking, so a crash repeats this claim instead of losing it. $db->prepare('INSERT INTO votescript_open (player, ref) VALUES (?, ?)')->execute([$player, $ref]); } $d = ask($v, 'claim', ['player' => $player, 'ref' => $ref, 'types' => typesOf($sql)]); $items = !empty($d['ok']) ? $d['items'] : []; $db->beginTransaction(); if ($items) { // One record per claim, in the same transaction as the payment. $st = $db->prepare('SELECT ref FROM votescript_done WHERE ref = ?'); $st->execute([$ref]); if ($st->fetch() === false) { $db->prepare('INSERT INTO votescript_done (ref, player, paid) VALUES (?, ?, ?)')->execute([$ref, $player, substr((string) json_encode($items), 0, 400)]); foreach ($items as $i) { $s = lineFor($sql, (string) $i['key']); $val = valuesFor($i, $player, $limits); if ($s === '' || $val === null) { say("no statement for reward key {$i['key']} ($player)"); continue; } $one = in_array($i['key'], array_map('trim', explode(',', $sql['each'] ?? '')), true); $times = $one ? $val['amount'] : 1; if ($times > 1000) throw new NotNow("$player: {$i['key']} is listed under each, so it would run $times times. Nothing was paid; lower the amount of this reward"); $n = 0; for ($t = 0; $t < $times; $t++) { $n = run($db, $s, ($one ? ['amount' => 1] : []) + $val)->rowCount(); if ($n === 0) break; } if ($n === 0) throw new NotNow("$player: the statement for {$i['key']} changed nothing (online, or no such account). Nothing was paid; tried again later"); if ($n > 1 && stripos($s, 'update') === 0) throw new RuntimeException("The statement for {$i['key']} would change $n rows for $player. Stopped; check your statement"); } say("$player: paid " . implode(', ', array_map(function ($i) { return $i['amount'] . ' x ' . $i['name']; }, $items))); } } $db->prepare('DELETE FROM votescript_open WHERE player = ?')->execute([$player]); $db->commit(); } } /* -------------------------------------------------------------- mode rcon */ final class Rcon { private $s; private $id = 0; public function __construct(array $c) { $this->s = @stream_socket_client("tcp://{$c['host']}:{$c['port']}", $no, $err, 5); if (!$this->s) throw new RuntimeException("RCON cannot be reached: $err"); stream_set_timeout($this->s, 5); $id = $this->write(3, (string) $c['password']); do { [$got, $type] = $this->read(); } while ($type !== 2); if ($got !== $id) throw new RuntimeException('The RCON password is wrong'); } public function command(string $text): string { $id = $this->write(2, $text); do { [$got, , $body] = $this->read(); } while ($got !== $id); return $body; } private function write(int $type, string $body): int { $id = ++$this->id; $p = pack('VV', $id, $type) . $body . "\0\0"; if (@fwrite($this->s, pack('V', strlen($p)) . $p) === false) throw new RuntimeException('RCON connection lost'); return $id; } private function read(): array { $take = function (int $n): string { $b = ''; while (strlen($b) < $n) { $c = fread($this->s, $n - strlen($b)); if ($c === false || $c === '') throw new RuntimeException('RCON connection lost'); $b .= $c; } return $b; }; $size = unpack('V', $take(4))[1]; if ($size < 10 || $size > 65536) throw new RuntimeException('RCON answered with something unexpected'); $d = $take($size); [, $id, $type] = unpack('V2', $d); return [$id === 0xFFFFFFFF ? -1 : $id, $type, rtrim(substr($d, 8), "\0")]; } } final class TShock { private $c; public function __construct(array $c) { $this->c = $c; } public function command(string $text): string { $url = rtrim($this->c['url'], '/') . '/v3/server/rawcmd?' . http_build_query(['cmd' => $text, 'token' => $this->c['token']]); $raw = @file_get_contents($url, false, stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]])); $d = $raw === false ? null : json_decode($raw, true); if (!is_array($d) || (string) ($d['status'] ?? '') !== '200') throw new RuntimeException('TShock: ' . ($d['error'] ?? 'no answer')); return implode(' ', array_map('strval', (array) ($d['response'] ?? []))); } } /** Unfinished work lives in a file that is replaced, never half-written. */ function state(string $file, ?array $set = null): array { if ($set !== null) { file_put_contents("$file.tmp", json_encode($set, JSON_PRETTY_PRINT), LOCK_EX); rename("$file.tmp", $file); return $set; } $d = is_file($file) ? json_decode((string) file_get_contents($file), true) : null; return (is_array($d) ? $d : []) + ['open' => [], 'items' => []]; } function rconPass(array $v, array $c, array $commands, array $limits, string $file, string $class): void { $st = state($file); foreach (ask($v, 'pending', ['limit' => 100, 'types' => typesOf($commands)])['players'] as $p) { if (!isset($st['open'][$p['player']])) $st['open'][$p['player']] = 'rc-' . bin2hex(random_bytes(14)); } if (!$st['open'] && !$st['items']) return; state($file, $st); foreach ($st['open'] as $player => $ref) { $d = ask($v, 'claim', ['player' => $player, 'ref' => $ref, 'types' => typesOf($commands)]); foreach (!empty($d['ok']) ? $d['items'] : [] as $i) $st['items'][] = ['id' => $ref . '/' . $i['key'], 'player' => (string) $player, 'key' => $i['key'], 'name' => $i['name'], 'amount' => (int) $i['amount'], 'sent' => 0]; unset($st['open'][$player]); // Claimed items and the finished reference are stored together. state($file, $st); } $rcon = null; foreach ($st['items'] as $n => $i) { if ($i['sent']) continue; // sent when we stopped: not repeated, see the log $command = lineFor($commands, (string) $i['key']); $val = valuesFor($i, (string) $i['player'], $limits); $safe = $val !== null && preg_match('/^[A-Za-z0-9_.:#-][A-Za-z0-9 _.:#-]{0,39}$/D', $i['player']) && preg_match('/^[A-Za-z0-9_.:,\/-]{1,100}$/D', $i['key']); if ($command === '' || !$safe) { say("skipped {$i['key']} for {$i['player']}: no command or unexpected characters"); unset($st['items'][$n]); state($file, $st); continue; } $rcon = $rcon ?: new $class($c); $st['items'][$n]['sent'] = 1; state($file, $st); // a crash right here cannot pay twice $answer = $rcon->command(strtr($command, ['{player}' => $i['player'], '{amount}' => (string) $val['amount'], '{key}' => $i['key'], '{arg}' => $val['arg'], '{arg2}' => $val['arg2'], '{name}' => preg_replace('/[^A-Za-z0-9 _-]/', '', $i['name'])])); $retry = trim($c['retry_if'] ?? ''); if ($retry !== '' && stripos($answer, $retry) !== false) { $st['items'][$n]['sent'] = 0; // the server says it was not given } else { say("{$i['player']}: {$i['amount']} x {$i['name']}" . ($answer === '' ? '' : " ($answer)")); unset($st['items'][$n]); } state($file, $st); } } $once = in_array('--once', $argv, true); $db = null; $wait = 5; do { try { $mode = $v['mode'] ?? 'sql'; if ($mode === 'rcon' || $mode === 'tshock') { rconPass($v, $ini[$mode] ?? [], $ini['commands'] ?? [], $ini['limits'] ?? [], "$dir/votescript-rcon.json", $mode === 'rcon' ? 'Rcon' : 'TShock'); } else { if (!$db) { $db = connect($ini['database'] ?? []); $mode === 'game' ? gameTables($db) : sqlTables($db); } $mode === 'game' ? gamePass($db, $v) : sqlPass($db, $v, $ini['sql'] ?? [], $ini['limits'] ?? []); } $wait = max(1, (int) ($v['every'] ?? 5)); } catch (Throwable $e) { try { if ($db && $db->inTransaction()) $db->rollBack(); } catch (Throwable $x) { $db = null; } if ($e instanceof PDOException) $db = null; fwrite(STDERR, date('H:i:s ') . $e->getMessage() . "\n"); $wait = min(60, $wait * 2); if ($once) exit(1); } if (!$once) sleep($wait); } while (!$once);