diff --git a/classes/Battles/Bank.php b/classes/Battles/Bank.php
index 83f3a4b..b1c00a3 100644
--- a/classes/Battles/Bank.php
+++ b/classes/Battles/Bank.php
@@ -4,8 +4,16 @@
* Date: 03.07.2020
* Time: 07:24
*/
+
namespace Battles;
+use Config;
+use db;
+use Exceptions\GameException;
+use Krugozor\Database\Mysql\Exception;
+use SQLite3;
+use Throwable;
+
class Bank
{
public $user_id;
@@ -26,8 +34,8 @@ 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();
+ $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();
foreach ($this as $key => $value) {
if (isset($bank_row[$key])) {
$this->$key = $bank_row[$key];
@@ -35,7 +43,7 @@ class Bank
}
// Если ВДРУГ у человека нет счёта в банке - создаём.
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;
}
}
@@ -49,7 +57,7 @@ class Bank
*/
private function bankCommission(int $amount): int
{
- $bankCommission = round($amount * \Config::$bank_commission);
+ $bankCommission = round($amount * Config::$bank_commission);
if ($bankCommission < 1) {
return 1;
} else {
@@ -60,13 +68,13 @@ class Bank
/**
* Пишем банковское событие в лог в БД
*
- * @param int $receiverId ID получателя.
- * @param int $amount сумма.
+ * @param int $receiverId ID получателя.
+ * @param int $amount сумма.
* @param string $operationType тип банковской операции.
- * @param int $senderId ID отправителя (ID игрока, если не указано иное).
+ * @param int $senderId ID отправителя (ID игрока, если не указано иное).
*
* @return void
- * @throws \Krugozor\Database\Mysql\Exception
+ * @throws Exception
*/
private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = 0): void
{
@@ -82,32 +90,30 @@ class Bank
$receiverId = $this->user_id;
$text .= " Комиссия: " . $this->bankCommission($amount);
}
-
- \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);
+ GameLogs::addBankLog($senderId,$receiverId,$amount,$operationType,$text);
}
/**
* Перевод денег между банковскими счетами игроков с банковской комиссией.
*
* @param int $receiver ID получателя.
- * @param int $amount сумма.
+ * @param int $amount сумма.
*
* @return int
- * @throws \Krugozor\Database\Mysql\Exception
+ * @throws Exception
*/
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) {
- throw new \Exceptions\GameException(self::ERROR_WRONG_AMOUNT);
+ throw new GameException(self::ERROR_WRONG_AMOUNT);
}
if (!$receiverWallet) {
- throw new \Exceptions\GameException(self::ERROR_NO_BANK_ACCOUNT);
+ throw new GameException(self::ERROR_NO_BANK_ACCOUNT);
}
$amountWithComission = $amount + $this->bankCommission($amount);
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;
@@ -127,16 +133,16 @@ class Bank
* @param int $amount сумма.
*
* @return array
- * @throws \Krugozor\Database\Mysql\Exception
+ * @throws Exception
*/
public function depositMoney(int $amount): array
{
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) {
- throw new \Exceptions\GameException(self::ERROR_NO_MONEY_IN_WALLET);
+ throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
}
// Забираем деньги из кошелька получателя
$this->user->money -= $amount;
@@ -158,16 +164,16 @@ class Bank
* @param int $amount сумма.
*
* @return array
- * @throws \Krugozor\Database\Mysql\Exception
+ * @throws Exception
*/
- public function withdrawMoney(int $amount):array
+ public function withdrawMoney(int $amount): array
{
if ($amount <= 0) {
- throw new \Exceptions\GameException(self::ERROR_WRONG_AMOUNT);
+ throw new GameException(self::ERROR_WRONG_AMOUNT);
}
$amountWithComission = $amount + $this->bankCommission($amount);
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;
@@ -186,21 +192,21 @@ class Bank
/**
* Установить количество денег на банковском счету.
*
- * @param int $amount сумма.
- * @param int $user_id ID пользователя.
+ * @param int $amount сумма.
+ * @param int $user_id ID пользователя.
* @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог.
*
* @return void
- * @throws \Krugozor\Database\Mysql\Exception
+ * @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::c()->query('UPDATE bank SET money = ?i WHERE user_id = ?i', $amount, $user_id);
if ($operationType) {
(new Bank($user_id))->bankLogs(0, $amount, $operationType);
}
- } catch (\Throwable $e) {
+ } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
}
@@ -209,17 +215,17 @@ class Bank
/**
* Установить количество денег на руках.
*
- * @param int $amount сумма.
+ * @param int $amount сумма.
* @param int $user_id ID пользователя.
*
* @return void
- * @throws \Krugozor\Database\Mysql\Exception
+ * @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);
- } catch (\Throwable $e) {
+ db::c()->query('UPDATE users SET money = ?i WHERE `id` = ?i', $amount, $user_id);
+ } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
}
diff --git a/classes/Battles/GameLogs.php b/classes/Battles/GameLogs.php
new file mode 100644
index 0000000..fd91a19
--- /dev/null
+++ b/classes/Battles/GameLogs.php
@@ -0,0 +1,54 @@
+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();
+ }
+}
\ No newline at end of file
diff --git a/classes/Battles/Nick.php b/classes/Battles/Nick.php
index c5f4242..09c5d52 100644
--- a/classes/Battles/Nick.php
+++ b/classes/Battles/Nick.php
@@ -1,5 +1,6 @@
align)) {
return sprintf('', $this->align);
@@ -28,7 +29,7 @@ class Nick extends User
* Отображение иконки клана.
* @return string
*/
- private function getClan()
+ private function getClan():string
{
if (isset($this->clan)) {
return sprintf('
', $this->clan);
@@ -51,12 +52,11 @@ class Nick extends User
/**
* Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль.
*
- * @param int $showInvisibility - По умолчанию 0. Выбрать 1, если надо отображать невидимый статус.
+ * @param int $showInvisibility отображать логин даже если персонаж невидимка.
*
* @return string
- * @throws \Krugozor\Database\Mysql\Exception
*/
- public function full($showInvisibility = 0)
+ public function full($showInvisibility = 0):string
{
if ($showInvisibility && $this->getInvisibilityStatus()) {
return 'невидимка';
@@ -66,12 +66,12 @@ class Nick extends User
/**
* Возвращает строку с логином или невидимым статусом.
+ * @param int $showInvisibility отображать логин даже если персонаж невидимка.
* @return string
- * @throws \Krugozor\Database\Mysql\Exception
*/
- public function short()
+ public function short($showInvisibility = 0):string
{
- if ($this->getInvisibilityStatus()) {
+ if ($showInvisibility && $this->getInvisibilityStatus()) {
return 'невидимка';
} else {
return htmlspecialchars($this->login);
@@ -82,7 +82,7 @@ class Nick extends User
* Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем.
* @return string
*/
- public function battle()
+ public function battle():string
{
return $this->getAlign().$this->getClan().sprintf('%s [%s]
_hp_/_maxhp_', $this->login, $this->level, $this->login);
}
@@ -93,7 +93,7 @@ class Nick extends User
*
* @return string
*/
- public function battleShort($textstyle)
+ public function battleShort($textstyle):string
{
if ($this->getInvisibilityStatus()) {
return 'невидимка';
diff --git a/databases/logs.sqlite b/databases/logs.sqlite
new file mode 100644
index 0000000..536cafe
Binary files /dev/null and b/databases/logs.sqlite differ
diff --git a/enter.php b/enter.php
index e363222..9ea620e 100644
--- a/enter.php
+++ b/enter.php
@@ -1,4 +1,8 @@
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']);
@@ -52,7 +56,7 @@ if ($username && $password) {
$error = ERROR_EMPTY_CREDENTIALS;
}
-\Battles\Template::header('Входим...');
+Template::header('Входим...');
if ($error) {
echo sprintf(' ← на главную
Передача предметов | - +Передача предметов + |
---|---|
printImage(); ?> @@ -91,20 +103,15 @@ if ($_SESSION['receiverName']) { - | printInfo(); ?> - | -
Нечего передавать... | -Нечего передавать... |