Merge pull request 'dev-logs' (#30) from dev-logs into master

Reviewed-on: https://src.lopar.us/lopar/battles/pulls/30
This commit is contained in:
Ivor Barhansky 2021-01-27 14:08:51 +00:00
commit 4f8140a6c6
6 changed files with 139 additions and 68 deletions

View File

@ -4,8 +4,16 @@
* Date: 03.07.2020 * Date: 03.07.2020
* Time: 07:24 * Time: 07:24
*/ */
namespace Battles; namespace Battles;
use Config;
use db;
use Exceptions\GameException;
use Krugozor\Database\Mysql\Exception;
use SQLite3;
use Throwable;
class Bank class Bank
{ {
public $user_id; public $user_id;
@ -26,8 +34,8 @@ 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(); $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->user = db::c()->query('SELECT money FROM users WHERE id = ?i', $row)->fetch_object();
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];
@ -35,7 +43,7 @@ class Bank
} }
// Если ВДРУГ у человека нет счёта в банке - создаём. // Если ВДРУГ у человека нет счёта в банке - создаём.
if (empty($this->user_id)) { if (empty($this->user_id)) {
\db::c()->query('INSERT INTO bank (user_id) VALUES (?i)', $row); db::c()->query('INSERT INTO bank (user_id) VALUES (?i)', $row);
$this->user_id = $row; $this->user_id = $row;
} }
} }
@ -49,7 +57,7 @@ class Bank
*/ */
private function bankCommission(int $amount): int private function bankCommission(int $amount): int
{ {
$bankCommission = round($amount * \Config::$bank_commission); $bankCommission = round($amount * Config::$bank_commission);
if ($bankCommission < 1) { if ($bankCommission < 1) {
return 1; return 1;
} else { } else {
@ -60,13 +68,13 @@ class Bank
/** /**
* Пишем банковское событие в лог в БД * Пишем банковское событие в лог в БД
* *
* @param int $receiverId ID получателя. * @param int $receiverId ID получателя.
* @param int $amount сумма. * @param int $amount сумма.
* @param string $operationType тип банковской операции. * @param string $operationType тип банковской операции.
* @param int $senderId ID отправителя (ID игрока, если не указано иное). * @param int $senderId ID отправителя (ID игрока, если не указано иное).
* *
* @return void * @return void
* @throws \Krugozor\Database\Mysql\Exception * @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
{ {
@ -82,32 +90,30 @@ class Bank
$receiverId = $this->user_id; $receiverId = $this->user_id;
$text .= " Комиссия: " . $this->bankCommission($amount); $text .= " Комиссия: " . $this->bankCommission($amount);
} }
GameLogs::addBankLog($senderId,$receiverId,$amount,$operationType,$text);
\db::c()->query('INSERT INTO `bank_logs` (sender_id, receiver_id, amount_result, type, text)
VALUES (?i, ?i, ?i, "?s", "?s")', $senderId, $receiverId, $amount, $operationType, $text);
} }
/** /**
* Перевод денег между банковскими счетами игроков с банковской комиссией. * Перевод денег между банковскими счетами игроков с банковской комиссией.
* *
* @param int $receiver ID получателя. * @param int $receiver ID получателя.
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return int * @return int
* @throws \Krugozor\Database\Mysql\Exception * @throws Exception
*/ */
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 = db::c()->query('SELECT money FROM bank WHERE user_id = ?i', $receiver)->fetch_object();
if ($amount <= 0) { if ($amount <= 0) {
throw new \Exceptions\GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
if (!$receiverWallet) { if (!$receiverWallet) {
throw new \Exceptions\GameException(self::ERROR_NO_BANK_ACCOUNT); throw new GameException(self::ERROR_NO_BANK_ACCOUNT);
} }
$amountWithComission = $amount + $this->bankCommission($amount); $amountWithComission = $amount + $this->bankCommission($amount);
if ($amountWithComission > $this->money) { if ($amountWithComission > $this->money) {
throw new \Exceptions\GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
} }
// Снимаем сумму с комиссией у отправителя // Снимаем сумму с комиссией у отправителя
$this->money -= $amountWithComission; $this->money -= $amountWithComission;
@ -127,16 +133,16 @@ class Bank
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return array * @return array
* @throws \Krugozor\Database\Mysql\Exception * @throws Exception
*/ */
public function depositMoney(int $amount): array public function depositMoney(int $amount): array
{ {
if ($amount <= 0) { if ($amount <= 0) {
throw new \Exceptions\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 = db::c()->query('SELECT money FROM users WHERE id = ?i', $this->user_id)->fetch_object();
if ($wallet->money < $amount) { if ($wallet->money < $amount) {
throw new \Exceptions\GameException(self::ERROR_NO_MONEY_IN_WALLET); throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
} }
// Забираем деньги из кошелька получателя // Забираем деньги из кошелька получателя
$this->user->money -= $amount; $this->user->money -= $amount;
@ -158,16 +164,16 @@ class Bank
* @param int $amount сумма. * @param int $amount сумма.
* *
* @return array * @return array
* @throws \Krugozor\Database\Mysql\Exception * @throws Exception
*/ */
public function withdrawMoney(int $amount):array public function withdrawMoney(int $amount): array
{ {
if ($amount <= 0) { if ($amount <= 0) {
throw new \Exceptions\GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
$amountWithComission = $amount + $this->bankCommission($amount); $amountWithComission = $amount + $this->bankCommission($amount);
if ($this->money < $amountWithComission) { if ($this->money < $amountWithComission) {
throw new \Exceptions\GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
} }
// Снимаем сумму с комиссией у отправителя // Снимаем сумму с комиссией у отправителя
$this->money -= $amountWithComission; $this->money -= $amountWithComission;
@ -186,21 +192,21 @@ class Bank
/** /**
* Установить количество денег на банковском счету. * Установить количество денег на банковском счету.
* *
* @param int $amount сумма. * @param int $amount сумма.
* @param int $user_id ID пользователя. * @param int $user_id ID пользователя.
* @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог. * @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог.
* *
* @return void * @return void
* @throws \Krugozor\Database\Mysql\Exception * @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::c()->query('UPDATE bank SET money = ?i WHERE user_id = ?i', $amount, $user_id);
if ($operationType) { if ($operationType) {
(new Bank($user_id))->bankLogs(0, $amount, $operationType); (new Bank($user_id))->bankLogs(0, $amount, $operationType);
} }
} catch (\Throwable $e) { } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
} }
@ -209,17 +215,17 @@ class Bank
/** /**
* Установить количество денег на руках. * Установить количество денег на руках.
* *
* @param int $amount сумма. * @param int $amount сумма.
* @param int $user_id ID пользователя. * @param int $user_id ID пользователя.
* *
* @return void * @return void
* @throws \Krugozor\Database\Mysql\Exception * @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::c()->query('UPDATE users SET money = ?i WHERE `id` = ?i', $amount, $user_id);
} catch (\Throwable $e) { } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
} }

View File

@ -0,0 +1,54 @@
<?php
namespace Battles;
use SQLite3;
class GameLogs
{
/**
* Добавление записи в лог банковских операций.
* @param int $senderId отправитель средств.
* @param int $receiverId получатель средств.
* @param int $amount сумма на счету после проведения операции.
* @param string $type тип операции.
* @param string $text комментарий.
*/
public static function addBankLog(int $senderId, int $receiverId, int $amount, string $type, string $text)
{
$db = new SQLite3('databases/logs.sqlite');
$row = $db->prepare("INSERT INTO bank_logs (sender_id, receiver_id, amount, type, text) VALUES (?, ?, ?, ?, ?)");
$row->bindParam(1, $senderId, SQLITE3_INTEGER);
$row->bindParam(2, $receiverId, SQLITE3_INTEGER);
$row->bindParam(3, $amount, SQLITE3_INTEGER);
$row->bindParam(4, $type, SQLITE3_TEXT);
$row->bindParam(5, $text, SQLITE3_TEXT);
$row->execute();
$row->close();
}
/**
* Добавление записи в лог пользовательских операций (личное дело).
* @param int $userId кому добавляется запись.
* @param string $text текст записи.
* @param string $type тип записи.
* @param int $authorId кто добавляет запись. Использовать -1 для системной записи по умолчанию.
*/
public static function addUserLog(int $userId, string $text, string $type = '', int $authorId = 0)
{
if (empty($authorId)) {
$authorId = -1;
}
if (empty($type)) {
$type = "system";
}
$db = new SQLite3('databases/logs.sqlite');
$row = $db->prepare("INSERT INTO users_logs (user_id, author_id, type, text) VALUES (?,?,?,?)");
$row->bindParam(1, $userId, SQLITE3_INTEGER);
$row->bindParam(2, $authorId, SQLITE3_INTEGER);
$row->bindParam(3, $type, SQLITE3_TEXT);
$row->bindParam(4, $text, SQLITE3_TEXT);
$row->execute();
$row->close();
}
}

View File

@ -1,5 +1,6 @@
<?php <?php
namespace Battles; namespace Battles;
use db;
/** /**
* Разные способы отображения строки с логином персонажа. * Разные способы отображения строки с логином персонажа.
*/ */
@ -15,7 +16,7 @@ class Nick extends User
* Отображение иконки склонности. * Отображение иконки склонности.
* @return string * @return string
*/ */
private function getAlign() private function getAlign():string
{ {
if (isset($this->align)) { if (isset($this->align)) {
return sprintf('<img src="i/align_%s.gif">', $this->align); return sprintf('<img src="i/align_%s.gif">', $this->align);
@ -28,7 +29,7 @@ class Nick extends User
* Отображение иконки клана. * Отображение иконки клана.
* @return string * @return string
*/ */
private function getClan() private function getClan():string
{ {
if (isset($this->clan)) { if (isset($this->clan)) {
return sprintf('<img src="i/clan/%s.png">', $this->clan); return sprintf('<img src="i/clan/%s.png">', $this->clan);
@ -51,12 +52,11 @@ class Nick extends User
/** /**
* Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль. * Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль.
* *
* @param int $showInvisibility - По умолчанию 0. Выбрать 1, если надо отображать невидимый статус. * @param int $showInvisibility отображать логин даже если персонаж невидимка.
* *
* @return string * @return string
* @throws \Krugozor\Database\Mysql\Exception
*/ */
public function full($showInvisibility = 0) public function full($showInvisibility = 0):string
{ {
if ($showInvisibility && $this->getInvisibilityStatus()) { if ($showInvisibility && $this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return '<i>невидимка</i>';
@ -66,12 +66,12 @@ class Nick extends User
/** /**
* Возвращает строку с логином или невидимым статусом. * Возвращает строку с логином или невидимым статусом.
* @param int $showInvisibility отображать логин даже если персонаж невидимка.
* @return string * @return string
* @throws \Krugozor\Database\Mysql\Exception
*/ */
public function short() public function short($showInvisibility = 0):string
{ {
if ($this->getInvisibilityStatus()) { if ($showInvisibility && $this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return '<i>невидимка</i>';
} else { } else {
return htmlspecialchars($this->login); return htmlspecialchars($this->login);
@ -82,7 +82,7 @@ class Nick extends User
* Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем. * Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем.
* @return string * @return string
*/ */
public function battle() public function battle():string
{ {
return $this->getAlign().$this->getClan().sprintf('<b>%s</b> [%s] <a href="inf.php?%s" target="_blank"><img src="i/inf.gif" style="width:12px;height:11px"></a> <img src="i/herz.gif" alt="HP"> _hp_/_maxhp_', $this->login, $this->level, $this->login); return $this->getAlign().$this->getClan().sprintf('<b>%s</b> [%s] <a href="inf.php?%s" target="_blank"><img src="i/inf.gif" style="width:12px;height:11px"></a> <img src="i/herz.gif" alt="HP"> _hp_/_maxhp_', $this->login, $this->level, $this->login);
} }
@ -93,7 +93,7 @@ class Nick extends User
* *
* @return string * @return string
*/ */
public function battleShort($textstyle) public function battleShort($textstyle):string
{ {
if ($this->getInvisibilityStatus()) { if ($this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return '<i>невидимка</i>';

BIN
databases/logs.sqlite Normal file

Binary file not shown.

View File

@ -1,4 +1,8 @@
<?php <?php
use Battles\GameLogs;
use Battles\Template;
session_start(); session_start();
require_once "config.php"; require_once "config.php";
define('ERROR_NO_SUCH_USER', 'Такого пользователя не существует!'); define('ERROR_NO_SUCH_USER', 'Такого пользователя не существует!');
@ -26,7 +30,7 @@ if ($username && $password) {
if (!$error) { if (!$error) {
# Проверка на мультоводство по используемому кукису. # Проверка на мультоводство по используемому кукису.
if ($battle != null && $user_query['id'] != $battle) { if ($battle != null && $user_query['id'] != $battle) {
db::c()->query('INSERT INTO users_logs (user_id, type, text) VALUES (?i, "?s", "?s")', $user_query['id'], "multiaccounts", "Разные ID на входе. Возможно используются несколько аккаунтов."); GameLogs::addUserLog($user_query['id'],'Разные ID на входе. Возможно используются несколько аккаунтов.', 'multiaccounts');
} }
setcookie("battle", $user_query['id']); setcookie("battle", $user_query['id']);
@ -52,7 +56,7 @@ if ($username && $password) {
$error = ERROR_EMPTY_CREDENTIALS; $error = ERROR_EMPTY_CREDENTIALS;
} }
\Battles\Template::header('Входим...'); Template::header('Входим...');
if ($error) { if ($error) {
echo sprintf('<a href="/"> ← на главную</a><h1>%s</h1>', $error); echo sprintf('<a href="/"> ← на главную</a><h1>%s</h1>', $error);

View File

@ -1,7 +1,15 @@
<?php <?php
use Battles\Bank;
use Battles\GameLogs;
use Battles\InventoryItem;
use Battles\Nick;
use Battles\Template;
use Battles\User;
session_start(); session_start();
require_once 'functions.php'; require_once 'functions.php';
$user = $user ?? new \Battles\User($_SESSION['uid']); $user = $user ?? new User($_SESSION['uid']);
if ($_GET['change'] ?? 0) { if ($_GET['change'] ?? 0) {
unset($_SESSION['receiverName']); unset($_SESSION['receiverName']);
} }
@ -41,25 +49,30 @@ if ($_SESSION['receiverName']) {
$user->money -= 1; $user->money -= 1;
Bank::setWalletMoney($user->money, $user->id); Bank::setWalletMoney($user->money, $user->id);
db::c()->query('UPDATE `inventory` SET owner_id = ?i WHERE item_id= ?i AND owner_id = ?i', $receiverId, $sendItemId, $_SESSION['uid']); db::c()->query('UPDATE `inventory` SET owner_id = ?i WHERE item_id= ?i AND owner_id = ?i', $receiverId, $sendItemId, $_SESSION['uid']);
$statusMessage = 'Предмет "' . $res['name'] . '" передан персонажу ' . $receiverId; $statusMessage = 'Предмет "' . $res['name'] . '" передан персонажу ' . Nick::id($receiverId)->short(1);
$receiverLogMessage = 'Получен предмет "' . $res['name'] . '" от персонажа ' . Nick::id($_SESSION['uid'])->short(1);
db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, 'Почтовый перевод: ' . $res['name'] . ' от персонажа ' . $user['login'] . '.'); db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, 'Почтовый перевод: ' . $res['name'] . ' от персонажа ' . $user['login'] . '.');
// Пишем в лог отправителю.
GameLogs::addUserLog($_SESSION['uid'], $statusMessage, 'почта');
// Пишем в лог получателю.
GameLogs::addUserLog($receiverId, $receiverLogMessage, 'почта');
} }
} }
$queryItems = db::c()->query('SELECT * FROM inventory WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ?i', $user->id); $queryItems = db::c()->query('SELECT * FROM inventory WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ?i', $user->id);
while ($row = $queryItems->fetch_assoc()) { while ($row = $queryItems->fetch_assoc()) {
$iteminfo[] = new \Battles\InventoryItem($row); $iteminfo[] = new InventoryItem($row);
} }
} }
} }
\Battles\Template::header('Почта'); Template::header('Почта');
?> ?>
<div style="float: right"> <div style="float: right">
<button onclick="top.frames['gameframe'].location = 'city.php?cp'">Вернуться</button> <button onclick="top.frames['gameframe'].location = 'city.php?cp'">Вернуться</button>
</div> </div>
<h1>Почта</h1> <h1>Почта</h1>
<div style="text-align: center;"><span class="error"><?= $statusMessage ?></span></div> <div style="text-align: center;"><span class="error"><?= $statusMessage ?></span></div>
<legend>Услуги почты платные: 1 кредит.</legend> <legend>Услуги почты платные: 1 кредит.</legend>
<?php if ($_SESSION['receiverName'] ?? ''): ?> <?php if ($_SESSION['receiverName'] ?? ''): ?>
Получатель: <?= Nick::id($receiverId)->full() ?> Получатель: <?= Nick::id($receiverId)->full() ?>
<a href="?change">Сменить</a> <a href="?change">Сменить</a>
@ -78,11 +91,10 @@ if ($_SESSION['receiverName']) {
<input type="submit" value="Отправить"> <input type="submit" value="Отправить">
</fieldset> </fieldset>
</form> </form>
</td>
<td valign=top align=right> <td valign=top align=right>
<table class="zebra" WIDTH=100%" cellspacing="1" cellpadding="2"> <table class="zebra" WIDTH=100%" cellspacing="1" cellpadding="2">
<th colspan="2">Передача предметов</th> <th colspan="2">Передача предметов
<?php foreach ($iteminfo as $ii): ?> <?php foreach ($iteminfo as $ii): ?>
<tr> <tr>
<td bgcolor='#d3d3d3'> <td bgcolor='#d3d3d3'>
<?php $ii->printImage(); ?> <?php $ii->printImage(); ?>
@ -91,20 +103,15 @@ if ($_SESSION['receiverName']) {
<input type="hidden" name="item_id" value="<?= $ii->getId() ?>"> <input type="hidden" name="item_id" value="<?= $ii->getId() ?>">
<input type="submit" value="Передать за 1кр."> <input type="submit" value="Передать за 1кр.">
</form> </form>
</td>
<td bgcolor='#d3d3d3'> <td bgcolor='#d3d3d3'>
<?php $ii->printInfo(); ?> <?php $ii->printInfo(); ?>
</td>
</tr> <?php endforeach; ?>
<?php endforeach; ?> <?php if (empty($queryItems->getNumRows())): ?>
<?php if (empty($queryItems->getNumRows())): ?>
<tr> <tr>
<td align=center bgcolor=#C7C7C7>Нечего передавать...</td> <td align=center bgcolor=#C7C7C7>Нечего передавать...
</tr>
<?php endif ?> <?php endif ?>
</table> </table>
</td>
</tr>
</table> </table>
<?php else: ?> <?php else: ?>
<form method="post"> <form method="post">