diff --git a/clan.php b/clan.php index 14f0626..3d53393 100644 --- a/clan.php +++ b/clan.php @@ -1,15 +1,25 @@ clan) { exit(err('Вы не состоите в клане!')); } try { - $clanRow = db::c()->query('SELECT * FROM `clans` WHERE `id` = ?i', $user->clan)->fetch_assoc(); - $polno = unserialize($clanRow['vozm']) ?? []; + $clanRow = $db->fetch('SELECT * FROM `clans` WHERE short_name = ?', $user->clan); } catch (Exception $e) { - echo "MYSQL_ERROR: Таблицы clans не существует! Вся панель — одна сплошная ошибка!"; + echo "
MYSQL_ERROR: Таблица clans сломана!
"; } define('COST_ADD_MEMBER', 100); define('COST_REMOVE_MEMBER', 30); @@ -24,93 +34,81 @@ $kolv = $_POST['kolv'] ?? null; $newClanStatus = $_POST['new_status'] ?? null; $vin = $_POST['vin'] ?? null; $tus = $_POST['tus'] ?? null; +$lock = true; // блокировка функций -if ($zamok) { - db::c()->query('UPDATE `clans` SET `zamok` = 1 WHERE `glava` = ?i', $_SESSION['uid']); +if ($zamok && !$lock) { + $db->execute('UPDATE `clans` SET `zamok` = 1 WHERE `glava` = ?', $user->id); $status = "Начат сбор средств на строительство Кланового Замка."; header("Location: clan.php"); } -if ($kr && $kolv > 0) { +if ($kr && $kolv > 0 && !$lock) { if ($user->money >= $kolv) { - db::c()->query('UPDATE `clans` SET `zbor` = `zbor` + ?i WHERE `id` = ?i', $kolv, $user->clan); - db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', $kolv, $user->id); + $db->execute('UPDATE clans SET zbor = zbor + ? WHERE id = ?', [$kolv, $user->clan]); + Bank::setWalletMoney($user->money -= $kolv, $user->id); header("Location: clan.php"); } else { $status = 'Не хватает денег!'; } } -if ($login && $action == 'add_member' && $polno[$user->id][0] == 1) { - $sok = db::c()->query('SELECT id, level, clan FROM users WHERE align = 0 AND login = "?s"', $login)->fetch_assoc(); - $proverka = db::c()->query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $sok['id'])->getNumRows(); +if ($login && $action == 'add_member') { + $sok = $db->fetch('SELECT id, level, clan FROM users WHERE align = 0 AND login = ?', $login); + $proverka = $db->fetch('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?', $sok['id']); if (!$proverka) { echo "Нет проверки!"; } elseif ($sok['clan']) { echo 'Персонаж уже состоит в клане!'; } elseif ($sok['level'] > 0 && $user->money >= COST_ADD_MEMBER) { - db::c()->query('UPDATE users SET money = money - ?i WHERE `id` = ?i', COST_ADD_MEMBER, $_SESSION['uid']); - db::c()->query('UPDATE users SET clan = "?s", align = ?i WHERE id = ?i', $clanRow['id'], $clanRow['align'], $sok['id']); - $status = 'Персонаж «' . $login . '» успешно принят в клан.'; + Bank::setWalletMoney($user->money - COST_ADD_MEMBER, $user->id); + $db->execute('UPDATE users SET clan = ?, align = ? WHERE id = ?', [$clanRow['id'], $clanRow['align'], $sok['id']]); + $status = "Персонаж «{$login}» успешно принят в клан."; } else { $status = 'Не хватает денег, или персонажа не существует.'; } } -if ($login && $action == 'remove_member' && $polno[$user->id][0] == 1) { - $sok = db::c()->query('SELECT id FROM users WHERE clan = "?s" AND login = "?s"', $clanRow['id'], $login)->fetch_assoc(); - if ($sok['id'] != $clanRow['glava'] && $user->money >= COST_REMOVE_MEMBER) { - db::c()->query('UPDATE users SET money = money - ?i WHERE id = ?i', COST_REMOVE_MEMBER, $_SESSION['uid']); - db::c()->query('UPDATE users SET clan = "?s", align = 0 WHERE id = ?i', '', $sok['id']); - $status = 'Персонаж «' . $login . '» покинул клан.'; + +if ($login) { + $sok = $db->fetch('SELECT id FROM users WHERE clan = ? AND login = ?', [$clanRow['id'], $login]); + if ($action == 'remove_member' && $sok['id'] != $clanRow['owner_id'] && $user->money >= COST_REMOVE_MEMBER) { + Bank::setWalletMoney($user->money - COST_REMOVE_MEMBER, $user->id); + $db->execute('UPDATE users SET clan = null, align = 0 WHERE id = ?', $sok['id']); + $status = "Персонаж «{$login}» покинул клан."; } -} -if ($login && $action == 'change_owner' && $clanRow['glava'] == $_SESSION['uid']) { - $sok = db::c()->query('SELECT id FROM users WHERE clan = "?s" AND login = "?s"', $clanRow['id'], $login)->fetch_assoc(); - db::c()->query('UPDATE clans SET glava = ?i WHERE id = ?i', $sok['id'], $clanRow['id']); - db::c()->query('UPDATE users SET status = "?s" WHERE id = ?i', '', $sok['id']); - db::c()->query('UPDATE users SET status = "?s" WHERE id = ?i', 'Боец', $_SESSION['uid']); - $clanRow['glava'] = $sok['id']; -} -if ($login && $action == 'edit_status') { - $sok = db::c()->query('SELECT id, status FROM users WHERE clan = "?s" AND login = "?s"', $clanRow['id'], $login)->fetch_assoc(); - if ($sok['id'] != $clanRow['glava']) { - if ($newClanStatus) { - $st = strip_tags(str_replace("<", "<", str_replace(">", ">", $newClanStatus)), ""); - db::c()->query('UPDATE users SET status = "?s" WHERE id = ?i', $st, $sok['id']); - $sok['status'] = $st; - } - if ($clanRow['glava'] == $_SESSION['uid']) { - if ($vin) { - $polno[$sok['id']][0] = 1; - } else { - $polno[$sok['id']][0] = 0; + if ($action == 'change_owner' && $clanRow['owner_id'] == $user->id) { + $db->execute('UPDATE clans SET owner_id = ? WHERE id = ?', [$sok['id'], $clanRow['id']]); + $clanRow['owner_id'] = $sok['id']; + } + if ($action == 'edit_status' && !$lock) { + if ($sok['id'] != $clanRow['owner_id']) { + if ($newClanStatus) { + $st = strip_tags(str_replace("<", "<", str_replace(">", ">", $newClanStatus)), ""); + $db->execute('UPDATE users SET status = ? WHERE id = ?', [$st, $sok['id']]); + $sok['status'] = $st; } - if ($tus) { - $polno[$sok['id']][1] = 1; - } else { - $polno[$sok['id']][1] = 0; - } - db::c()->query('UPDATE clans SET vozm = "?s" WHERE id = ?i', serialize($polno), $clanRow['id']); + } else { + $status = 'Главу клана редактировать запрещено!'; } - } else { - $status = 'Главу клана редактировать запрещено!'; } } -$clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `room`, `align`, (select `id` from `online` WHERE `date` >= ?i AND `id` = users.`id`) AS `online` FROM `users` WHERE `klan` = ?i ORDER BY `online` DESC , `login` ASC', (time() - 60), $clanRow['id']); -\Battles\Template::header('clan'); +$clan_memberlist = $db->fetchAll('SELECT id, login, level, align, (SELECT id FROM online WHERE date >= ? AND id = users.id) AS online FROM users WHERE clan = ? ORDER BY online DESC, login', [time() - 60, $clanRow['short_name']]); +Template::header('clan'); +$clanRow['zamok'] = null; //Замков нет! +$clanRow['rating'] = null; //рейтов тоже! +$clanRow['zbor'] = null; // И копилки. ?>
- +
fetch_assoc()): - if ($row['id'] == $clanRow['glava']) { - $row['status'] = 'Глава клана'; + $i = 0; + while ($i < count($clan_memberlist)): + if ($clan_memberlist[$i]['id'] == $clanRow['owner_id']) { + $clan_memberlist[$i]['status'] = 'Глава клана'; } - if (empty($row['status'])) { - $row['status'] = 'Боец'; + if (empty($clan_memberlist[$i]['status'])) { + $clan_memberlist[$i]['status'] = 'Боец'; } - if (empty($row['online'])) { + if (empty($clan_memberlist[$i]['online'])) { $rrm = 'Персонаж не в игре'; - } elseif ($row['room'] > 500 && $row['room'] < 561) { + } elseif ($clan_memberlist[$i]['room'] > 500 && $clan_memberlist[$i]['room'] < 561) { $rrm = 'Башня смерти'; } else { - $rrm = $rooms[$row['room']]; + $rrm = Rooms::$roomNames[$clan_memberlist[$i]['room']]; } ?> - - + + +

-

- Количество рейтинговых очков клана:
+

- id][0] == 1): ?> + id): ?>
@@ -125,18 +123,18 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
- id][1] == 1 || $clanRow['glava'] == $user->id): ?> - + id): ?> +
id): ?> - + id): ?>
Может принимать/выгонять членов клана
Может принимать/выгонять членов клана - + id): ?>
Может менять статус членов клана
Может менять статус членов клана @@ -154,7 +152,7 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo - id): ?> + id): ?>
@@ -197,26 +195,28 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
Местонахождение
full() ?>full() ?>
diff --git a/classes/Battles/Bank.php b/classes/Battles/Bank.php index b1c00a3..b624fd9 100644 --- a/classes/Battles/Bank.php +++ b/classes/Battles/Bank.php @@ -8,10 +8,8 @@ namespace Battles; use Config; -use db; use Exceptions\GameException; -use Krugozor\Database\Mysql\Exception; -use SQLite3; +use Battles\Database\DBPDO; use Throwable; class Bank @@ -19,6 +17,7 @@ class Bank public $user_id; private $money; private $user; + private $db; const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; @@ -34,18 +33,14 @@ class Bank public function __construct($row) { - $bank_row = db::c()->query('SELECT user_id, money FROM bank WHERE user_id = ?i', $row)->fetch_assoc(); - $this->user = db::c()->query('SELECT money FROM users WHERE id = ?i', $row)->fetch_object(); + $this->db = new DBPDO(); + $bank_row = $this->db->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $row); + $this->user = $this->db->fetch('SELECT money FROM users WHERE id = ?', $row); foreach ($this as $key => $value) { if (isset($bank_row[$key])) { $this->$key = $bank_row[$key]; } } - // Если ВДРУГ у человека нет счёта в банке - создаём. - if (empty($this->user_id)) { - db::c()->query('INSERT INTO bank (user_id) VALUES (?i)', $row); - $this->user_id = $row; - } } /** @@ -74,7 +69,6 @@ class Bank * @param int $senderId ID отправителя (ID игрока, если не указано иное). * * @return void - * @throws Exception */ private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = 0): void { @@ -100,11 +94,11 @@ class Bank * @param int $amount сумма. * * @return int - * @throws Exception + * @throws GameException */ public function sendMoney(int $receiver, int $amount): int { - $receiverWallet = db::c()->query('SELECT money FROM bank WHERE user_id = ?i', $receiver)->fetch_object(); + $receiverWallet = $this->db->fetch('SELECT money FROM bank WHERE user_id = ?', $receiver); if ($amount <= 0) { throw new GameException(self::ERROR_WRONG_AMOUNT); } @@ -133,14 +127,14 @@ class Bank * @param int $amount сумма. * * @return array - * @throws Exception + * @throws GameException */ public function depositMoney(int $amount): array { if ($amount <= 0) { throw new GameException(self::ERROR_WRONG_AMOUNT); } - $wallet = db::c()->query('SELECT money FROM users WHERE id = ?i', $this->user_id)->fetch_object(); + $wallet = $this->db->fetch('SELECT money FROM users WHERE id = ?', $this->user_id); if ($wallet->money < $amount) { throw new GameException(self::ERROR_NO_MONEY_IN_WALLET); } @@ -164,7 +158,7 @@ class Bank * @param int $amount сумма. * * @return array - * @throws Exception + * @throws GameException */ public function withdrawMoney(int $amount): array { @@ -197,12 +191,12 @@ class Bank * @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог. * * @return void - * @throws Exception */ public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void { try { - db::c()->query('UPDATE bank SET money = ?i WHERE user_id = ?i', $amount, $user_id); + $db = new DBPDO(); + $db->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]); if ($operationType) { (new Bank($user_id))->bankLogs(0, $amount, $operationType); } @@ -219,12 +213,12 @@ class Bank * @param int $user_id ID пользователя. * * @return void - * @throws Exception */ public static function setWalletMoney(int $amount, int $user_id): void { try { - db::c()->query('UPDATE users SET money = ?i WHERE `id` = ?i', $amount, $user_id); + $db = new DBPDO(); + $db->execute('UPDATE users SET money = ? WHERE id = ?', [$amount, $user_id]); } catch (Throwable $e) { echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; } diff --git a/classes/Battles/Database/DBPDO.php b/classes/Battles/Database/DBPDO.php new file mode 100644 index 0000000..f9f0eb1 --- /dev/null +++ b/classes/Battles/Database/DBPDO.php @@ -0,0 +1,110 @@ +connect(); + } + + + function prep_query($query) + { + return $this->pdo->prepare($query); + } + + + function connect():bool + { + if (!$this->pdo) { + + $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST . ';port=' . DATABASE_PORT . ';charset=utf8;'; + $user = DATABASE_USER; + $password = DATABASE_PASS; + + try { + $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); + return true; + } catch (PDOException $e) { + $this->error = $e->getMessage(); + die($this->error); + } + } else { + $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + return true; + } + } + + + function table_exists($table_name) + { + $stmt = $this->prep_query('SHOW TABLES LIKE ?'); + $stmt->execute(array($table_name)); + return $stmt->rowCount() > 0; + } + + + function execute($query, $values = null) + { + if ($values == null) { + $values = array(); + } else if (!is_array($values)) { + $values = array($values); + } + $stmt = $this->prep_query($query); + $stmt->execute($values); + return $stmt; + } + + function fetch($query, $values = null) + { + if ($values == null) { + $values = array(); + } else if (!is_array($values)) { + $values = array($values); + } + $stmt = $this->execute($query, $values); + return $stmt->fetch(PDO::FETCH_ASSOC); + } + + function fetchAll($query, $values = null, $key = null) + { + if ($values == null) { + $values = array(); + } else if (!is_array($values)) { + $values = array($values); + } + $stmt = $this->execute($query, $values); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Allows the user to retrieve results using a + // column from the results as a key for the array + if ($key != null && $results[0][$key]) { + $keyed_results = array(); + foreach ($results as $result) { + $keyed_results[$result[$key]] = $result; + } + $results = $keyed_results; + } + return $results; + } + + function lastInsertId() + { + return $this->pdo->lastInsertId(); + } + +} \ No newline at end of file diff --git a/config.php b/config.php index 6d0cb2f..634355f 100644 --- a/config.php +++ b/config.php @@ -26,6 +26,7 @@ require_once 'classes/Database/Mysql.php'; require_once 'classes/Database/Exception.php'; require_once 'classes/Database/Statement.php'; require_once 'classes/Database/db.php'; +require_once 'classes/Battles/Database/DBPDO.php'; /** * Автозагрузка классов с учётом неймспейсов.