dev #38

Merged
lopar merged 22 commits from dev into master 2021-02-03 08:56:49 +00:00
4 changed files with 196 additions and 91 deletions
Showing only changes of commit 0099c235a7 - Show all commits

134
clan.php
View File

@ -1,15 +1,25 @@
<?php
use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\Nick;
use Battles\Rooms;
use Battles\Template;
use Battles\User;
ob_start("ob_gzhandler");
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
$db = new DBPDO();
$clanRow = [];
if (!$user->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 "<div>MYSQL_ERROR: Таблица clans сломана!</div>";
}
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 ($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("&lt;", "<", str_replace("&gt;", ">", $newClanStatus)), "<B><I><U>");
db::c()->query('UPDATE users SET status = "?s" WHERE id = ?i', $st, $sok['id']);
$db->execute('UPDATE users SET status = ? WHERE id = ?', [$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) {
$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 = 'Главу клана редактировать запрещено!';
}
}
}
$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; // И копилки.
?>
<div>
<button onclick="location.href='main.php'">Вернуться</button>
<?php if (!empty($status)) {err($status);} ?>
<?php if (!empty($status)) {
err($status);
} ?>
</div>
<table style="width: 100%">
<tr>
<td>
<p style="width: 50%; vertical-align: top;" rowspan=2>
<h3><img src="./i/clan/<?= $clanRow['short'] ?>.png"><?= $clanRow['name'] ?></h3>
Количество рейтинговых очков клана: <span
style="color: #428f21; font-size: larger;"><?= $clanRow['rating'] ?></span><br>
<h3><img src="./i/clan/<?= $clanRow['short_name'] ?>.png"><?= $clanRow['full_name'] ?></h3>
<?php if ($polno[$user->id][0] == 1): ?>
<?php if ($clanRow['owner_id'] == $user->id): ?>
<div>
<span id="add_member">
<input type="submit" onclick="use('add_member')" value="Принять в клан">
@ -125,18 +123,18 @@ $clan_memberlist = db::c()->query('SELECT `id`, `login`, `status`, `level`, `roo
</div>
<?php endif; ?>
<?php if ($polno[$user->id][1] == 1 || $clanRow['glava'] == $user->id): ?>
<?php if ($login && $action == 'edit_status' && $sok['id'] != $clanRow['glava']): ?>
<?php if ($clanRow['owner_id'] == $user->id): ?>
<?php if ($login && $action == 'edit_status' && $sok['id'] != $clanRow['owner_id']): ?>
<form method='post'>
<input placeholder='Статус' name='new_status'>
<input type="hidden" name="login" value="<?= $login ?>">
<?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> Может принимать/выгонять членов клана
<?php else: ?>
<br><input type=checkbox name=vin> Может принимать/выгонять членов клана
<?php endif; ?>
<?php if ($polno[$sok['id']][1] == 1): ?>
<?php if ($clanRow['owner_id'] == $user->id): ?>
<br><input type=checkbox name=tus checked> Может менять статус членов клана
<?php else: ?>
<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 if ($clanRow['glava'] == $user->id): ?>
<?php if ($clanRow['owner_id'] == $user->id): ?>
<div>
<span id="change_owner">
<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>
</tr>
<?php
while ($row = $clan_memberlist->fetch_assoc()):
if ($row['id'] == $clanRow['glava']) {
$row['status'] = '<b style="color: #008080;">Глава клана</b>';
$i = 0;
while ($i < count($clan_memberlist)):
if ($clan_memberlist[$i]['id'] == $clanRow['owner_id']) {
$clan_memberlist[$i]['status'] = '<b style="color: #008080;">Глава клана</b>';
}
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']];
}
?>
<tr>
<td><?= Nick::id($row['id'])->full() ?></td>
<td><?= $row['status'] ?></td>
<td><?= Nick::id($clan_memberlist[$i]['id'])->full() ?></td>
<td><?= $clan_memberlist[$i]['status'] ?></td>
<td><i style="font-size: smaller;"><?= $rrm ?></i></td>
</tr>
<?php $i++; ?>
<?php endwhile; ?>
</table>
</td>

View File

@ -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()})";
}

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/Statement.php';
require_once 'classes/Database/db.php';
require_once 'classes/Battles/Database/DBPDO.php';
/**
* Автозагрузка классов с учётом неймспейсов.