Первые телодвидения по #16

This commit is contained in:
Igor Barkov (iwork) 2021-01-28 17:57:55 +02:00
parent 1cfdabce70
commit 0099c235a7
4 changed files with 196 additions and 91 deletions

142
clan.php
View File

@ -1,15 +1,25 @@
<?php <?php
use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\Nick;
use Battles\Rooms;
use Battles\Template;
use Battles\User;
ob_start("ob_gzhandler"); ob_start("ob_gzhandler");
session_start(); session_start();
require_once 'functions.php'; require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
$db = new DBPDO();
$clanRow = [];
if (!$user->clan) { if (!$user->clan) {
exit(err('Вы не состоите в клане!')); exit(err('Вы не состоите в клане!'));
} }
try { try {
$clanRow = db::c()->query('SELECT * FROM `clans` WHERE `id` = ?i', $user->clan)->fetch_assoc(); $clanRow = $db->fetch('SELECT * FROM `clans` WHERE short_name = ?', $user->clan);
$polno = unserialize($clanRow['vozm']) ?? [];
} catch (Exception $e) { } catch (Exception $e) {
echo "MYSQL_ERROR: Таблицы clans не существует! Вся панель — одна сплошная ошибка!"; echo "<div>MYSQL_ERROR: Таблица clans сломана!</div>";
} }
define('COST_ADD_MEMBER', 100); define('COST_ADD_MEMBER', 100);
define('COST_REMOVE_MEMBER', 30); define('COST_REMOVE_MEMBER', 30);
@ -24,93 +34,81 @@ $kolv = $_POST['kolv'] ?? null;
$newClanStatus = $_POST['new_status'] ?? null; $newClanStatus = $_POST['new_status'] ?? null;
$vin = $_POST['vin'] ?? null; $vin = $_POST['vin'] ?? null;
$tus = $_POST['tus'] ?? null; $tus = $_POST['tus'] ?? null;
$lock = true; // блокировка функций
if ($zamok) { if ($zamok && !$lock) {
db::c()->query('UPDATE `clans` SET `zamok` = 1 WHERE `glava` = ?i', $_SESSION['uid']); $db->execute('UPDATE `clans` SET `zamok` = 1 WHERE `glava` = ?', $user->id);
$status = "Начат сбор средств на строительство Кланового Замка."; $status = "Начат сбор средств на строительство Кланового Замка.";
header("Location: clan.php"); header("Location: clan.php");
} }
if ($kr && $kolv > 0) { if ($kr && $kolv > 0 && !$lock) {
if ($user->money >= $kolv) { if ($user->money >= $kolv) {
db::c()->query('UPDATE `clans` SET `zbor` = `zbor` + ?i WHERE `id` = ?i', $kolv, $user->clan); $db->execute('UPDATE clans SET zbor = zbor + ? WHERE id = ?', [$kolv, $user->clan]);
db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', $kolv, $user->id); Bank::setWalletMoney($user->money -= $kolv, $user->id);
header("Location: clan.php"); header("Location: clan.php");
} else { } else {
$status = 'Не хватает денег!'; $status = 'Не хватает денег!';
} }
} }
if ($login && $action == 'add_member' && $polno[$user->id][0] == 1) { if ($login && $action == 'add_member') {
$sok = db::c()->query('SELECT id, level, clan FROM users WHERE align = 0 AND login = "?s"', $login)->fetch_assoc(); $sok = $db->fetch('SELECT id, level, clan FROM users WHERE align = 0 AND login = ?', $login);
$proverka = db::c()->query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $sok['id'])->getNumRows(); $proverka = $db->fetch('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?', $sok['id']);
if (!$proverka) { if (!$proverka) {
echo "Нет проверки!"; echo "Нет проверки!";
} elseif ($sok['clan']) { } elseif ($sok['clan']) {
echo 'Персонаж уже состоит в клане!'; echo 'Персонаж уже состоит в клане!';
} elseif ($sok['level'] > 0 && $user->money >= COST_ADD_MEMBER) { } 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']); Bank::setWalletMoney($user->money - COST_ADD_MEMBER, $user->id);
db::c()->query('UPDATE users SET clan = "?s", align = ?i WHERE id = ?i', $clanRow['id'], $clanRow['align'], $sok['id']); $db->execute('UPDATE users SET clan = ?, align = ? WHERE id = ?', [$clanRow['id'], $clanRow['align'], $sok['id']]);
$status = 'Персонаж «' . $login . '» успешно принят в клан.'; $status = "Персонаж «{$login}» успешно принят в клан.";
} else { } else {
$status = 'Не хватает денег, или персонажа не существует.'; $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 ($login) {
if ($sok['id'] != $clanRow['glava'] && $user->money >= COST_REMOVE_MEMBER) { $sok = $db->fetch('SELECT id FROM users WHERE clan = ? AND login = ?', [$clanRow['id'], $login]);
db::c()->query('UPDATE users SET money = money - ?i WHERE id = ?i', COST_REMOVE_MEMBER, $_SESSION['uid']); if ($action == 'remove_member' && $sok['id'] != $clanRow['owner_id'] && $user->money >= COST_REMOVE_MEMBER) {
db::c()->query('UPDATE users SET clan = "?s", align = 0 WHERE id = ?i', '', $sok['id']); Bank::setWalletMoney($user->money - COST_REMOVE_MEMBER, $user->id);
$status = 'Персонаж «' . $login . '» покинул клан.'; $db->execute('UPDATE users SET clan = null, align = 0 WHERE id = ?', $sok['id']);
$status = "Персонаж «{$login}» покинул клан.";
} }
} if ($action == 'change_owner' && $clanRow['owner_id'] == $user->id) {
if ($login && $action == 'change_owner' && $clanRow['glava'] == $_SESSION['uid']) { $db->execute('UPDATE clans SET owner_id = ? WHERE id = ?', [$sok['id'], $clanRow['id']]);
$sok = db::c()->query('SELECT id FROM users WHERE clan = "?s" AND login = "?s"', $clanRow['id'], $login)->fetch_assoc(); $clanRow['owner_id'] = $sok['id'];
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']); if ($action == 'edit_status' && !$lock) {
db::c()->query('UPDATE users SET status = "?s" WHERE id = ?i', 'Боец', $_SESSION['uid']); if ($sok['id'] != $clanRow['owner_id']) {
$clanRow['glava'] = $sok['id']; if ($newClanStatus) {
} $st = strip_tags(str_replace("&lt;", "<", str_replace("&gt;", ">", $newClanStatus)), "<B><I><U>");
if ($login && $action == 'edit_status') { $db->execute('UPDATE users SET status = ? WHERE id = ?', [$st, $sok['id']]);
$sok = db::c()->query('SELECT id, status FROM users WHERE clan = "?s" AND login = "?s"', $clanRow['id'], $login)->fetch_assoc(); $sok['status'] = $st;
if ($sok['id'] != $clanRow['glava']) {
if ($newClanStatus) {
$st = strip_tags(str_replace("&lt;", "<", str_replace("&gt;", ">", $newClanStatus)), "<B><I><U>");
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 ($tus) { } else {
$polno[$sok['id']][1] = 1; $status = 'Главу клана редактировать запрещено!';
} else {
$polno[$sok['id']][1] = 0;
}
db::c()->query('UPDATE clans SET vozm = "?s" WHERE id = ?i', serialize($polno), $clanRow['id']);
} }
} 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']); $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']]);
\Battles\Template::header('clan'); Template::header('clan');
$clanRow['zamok'] = null; //Замков нет!
$clanRow['rating'] = null; //рейтов тоже!
$clanRow['zbor'] = null; // И копилки.
?> ?>
<div> <div>
<button onclick="location.href='main.php'">Вернуться</button> <button onclick="location.href='main.php'">Вернуться</button>
<?php if (!empty($status)) {err($status);} ?> <?php if (!empty($status)) {
err($status);
} ?>
</div> </div>
<table style="width: 100%"> <table style="width: 100%">
<tr> <tr>
<td> <td>
<p style="width: 50%; vertical-align: top;" rowspan=2> <p style="width: 50%; vertical-align: top;" rowspan=2>
<h3><img src="./i/clan/<?= $clanRow['short'] ?>.png"><?= $clanRow['name'] ?></h3> <h3><img src="./i/clan/<?= $clanRow['short_name'] ?>.png"><?= $clanRow['full_name'] ?></h3>
Количество рейтинговых очков клана: <span
style="color: #428f21; font-size: larger;"><?= $clanRow['rating'] ?></span><br>
<?php if ($polno[$user->id][0] == 1): ?> <?php if ($clanRow['owner_id'] == $user->id): ?>
<div> <div>
<span id="add_member"> <span id="add_member">
<input type="submit" onclick="use('add_member')" value="Принять в клан"> <input type="submit" onclick="use('add_member')" value="Принять в клан">
@ -125,18 +123,18 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
</div> </div>
<?php endif; ?> <?php endif; ?>
<?php if ($polno[$user->id][1] == 1 || $clanRow['glava'] == $user->id): ?> <?php if ($clanRow['owner_id'] == $user->id): ?>
<?php if ($login && $action == 'edit_status' && $sok['id'] != $clanRow['glava']): ?> <?php if ($login && $action == 'edit_status' && $sok['id'] != $clanRow['owner_id']): ?>
<form method='post'> <form method='post'>
<input placeholder='Статус' name='new_status'> <input placeholder='Статус' name='new_status'>
<input type="hidden" name="login" value="<?= $login ?>"> <input type="hidden" name="login" value="<?= $login ?>">
<?php if ($clanRow['glava'] == $user->id): ?> <?php if ($clanRow['glava'] == $user->id): ?>
<?php if ($polno[$sok['id']][0] == 1): ?> <?php if ($clanRow['owner_id'] == $user->id): ?>
<br><input type=checkbox name=vin checked> Может принимать/выгонять членов клана <br><input type=checkbox name=vin checked> Может принимать/выгонять членов клана
<?php else: ?> <?php else: ?>
<br><input type=checkbox name=vin> Может принимать/выгонять членов клана <br><input type=checkbox name=vin> Может принимать/выгонять членов клана
<?php endif; ?> <?php endif; ?>
<?php if ($polno[$sok['id']][1] == 1): ?> <?php if ($clanRow['owner_id'] == $user->id): ?>
<br><input type=checkbox name=tus checked> Может менять статус членов клана <br><input type=checkbox name=tus checked> Может менять статус членов клана
<?php else: ?> <?php else: ?>
<br><input type=checkbox name=tus> Может менять статус членов клана <br><input type=checkbox name=tus> Может менять статус членов клана
@ -154,7 +152,7 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
<?php if ($clanRow['glava'] == $user->id): ?> <?php if ($clanRow['owner_id'] == $user->id): ?>
<div> <div>
<span id="change_owner"> <span id="change_owner">
<input type="submit" onclick="use('change_owner')" value="Сменить главу клана"> <input type="submit" onclick="use('change_owner')" value="Сменить главу клана">
@ -197,26 +195,28 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
<th>Местонахождение</th> <th>Местонахождение</th>
</tr> </tr>
<?php <?php
while ($row = $clan_memberlist->fetch_assoc()): $i = 0;
if ($row['id'] == $clanRow['glava']) { while ($i < count($clan_memberlist)):
$row['status'] = '<b style="color: #008080;">Глава клана</b>'; if ($clan_memberlist[$i]['id'] == $clanRow['owner_id']) {
$clan_memberlist[$i]['status'] = '<b style="color: #008080;">Глава клана</b>';
} }
if (empty($row['status'])) { if (empty($clan_memberlist[$i]['status'])) {
$row['status'] = 'Боец'; $clan_memberlist[$i]['status'] = 'Боец';
} }
if (empty($row['online'])) { if (empty($clan_memberlist[$i]['online'])) {
$rrm = 'Персонаж не в игре'; $rrm = 'Персонаж не в игре';
} elseif ($row['room'] > 500 && $row['room'] < 561) { } elseif ($clan_memberlist[$i]['room'] > 500 && $clan_memberlist[$i]['room'] < 561) {
$rrm = 'Башня смерти'; $rrm = 'Башня смерти';
} else { } else {
$rrm = $rooms[$row['room']]; $rrm = Rooms::$roomNames[$clan_memberlist[$i]['room']];
} }
?> ?>
<tr> <tr>
<td><?= Nick::id($row['id'])->full() ?></td> <td><?= Nick::id($clan_memberlist[$i]['id'])->full() ?></td>
<td><?= $row['status'] ?></td> <td><?= $clan_memberlist[$i]['status'] ?></td>
<td><i style="font-size: smaller;"><?= $rrm ?></i></td> <td><i style="font-size: smaller;"><?= $rrm ?></i></td>
</tr> </tr>
<?php $i++; ?>
<?php endwhile; ?> <?php endwhile; ?>
</table> </table>
</td> </td>

View File

@ -8,10 +8,8 @@
namespace Battles; namespace Battles;
use Config; use Config;
use db;
use Exceptions\GameException; use Exceptions\GameException;
use Krugozor\Database\Mysql\Exception; use Battles\Database\DBPDO;
use SQLite3;
use Throwable; use Throwable;
class Bank class Bank
@ -19,6 +17,7 @@ class Bank
public $user_id; public $user_id;
private $money; private $money;
private $user; private $user;
private $db;
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
@ -34,18 +33,14 @@ class Bank
public function __construct($row) public function __construct($row)
{ {
$bank_row = db::c()->query('SELECT user_id, money FROM bank WHERE user_id = ?i', $row)->fetch_assoc(); $this->db = new DBPDO();
$this->user = db::c()->query('SELECT money FROM users WHERE id = ?i', $row)->fetch_object(); $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) { foreach ($this as $key => $value) {
if (isset($bank_row[$key])) { if (isset($bank_row[$key])) {
$this->$key = $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 игрока, если не указано иное). * @param int $senderId ID отправителя (ID игрока, если не указано иное).
* *
* @return void * @return void
* @throws Exception
*/ */
private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = 0): void private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = 0): void
{ {
@ -100,11 +94,11 @@ class Bank
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return int * @return int
* @throws Exception * @throws GameException
*/ */
public function sendMoney(int $receiver, int $amount): int 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) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
@ -133,14 +127,14 @@ class Bank
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return array * @return array
* @throws Exception * @throws GameException
*/ */
public function depositMoney(int $amount): array public function depositMoney(int $amount): array
{ {
if ($amount <= 0) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); 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) { if ($wallet->money < $amount) {
throw new GameException(self::ERROR_NO_MONEY_IN_WALLET); throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
} }
@ -164,7 +158,7 @@ class Bank
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return array * @return array
* @throws Exception * @throws GameException
*/ */
public function withdrawMoney(int $amount): array public function withdrawMoney(int $amount): array
{ {
@ -197,12 +191,12 @@ class Bank
* @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог. * @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог.
* *
* @return void * @return void
* @throws Exception
*/ */
public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void
{ {
try { 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) { if ($operationType) {
(new Bank($user_id))->bankLogs(0, $amount, $operationType); (new Bank($user_id))->bankLogs(0, $amount, $operationType);
} }
@ -219,12 +213,12 @@ class Bank
* @param int $user_id ID пользователя. * @param int $user_id ID пользователя.
* *
* @return void * @return void
* @throws Exception
*/ */
public static function setWalletMoney(int $amount, int $user_id): void public static function setWalletMoney(int $amount, int $user_id): void
{ {
try { 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) { } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
} }

View File

@ -0,0 +1,110 @@
<?php
namespace Battles\Database;
const DATABASE_HOST = '192.168.20.5';
const DATABASE_NAME = 'battles';
const DATABASE_USER = 'battles';
const DATABASE_PASS = 'bottle-neck-horse';
const DATABASE_PORT = '32101';
use PDO, PDOException;
class DBPDO
{
public $pdo;
private $error;
function __construct()
{
$this->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();
}
}

View File

@ -26,6 +26,7 @@ require_once 'classes/Database/Mysql.php';
require_once 'classes/Database/Exception.php'; require_once 'classes/Database/Exception.php';
require_once 'classes/Database/Statement.php'; require_once 'classes/Database/Statement.php';
require_once 'classes/Database/db.php'; require_once 'classes/Database/db.php';
require_once 'classes/Battles/Database/DBPDO.php';
/** /**
* Автозагрузка классов с учётом неймспейсов. * Автозагрузка классов с учётом неймспейсов.