Куча мелочей, в том числе по #42.

This commit is contained in:
lopar 2021-08-25 04:44:36 +03:00
parent cbbbb8a3c6
commit 1f38e6bd61
21 changed files with 223 additions and 378 deletions

View File

@ -8,23 +8,24 @@ session_start();
require_once '../functions.php'; require_once '../functions.php';
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\GameConfigs; use Battles\GameConfigs;
use Battles\Moderation; use Battles\Moderation;
use Battles\Nick; use Battles\Nick;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
if (!$user->getAdmin()) { if (!User::$current->getAdmin()) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
exit; exit;
} }
if (isset($_GET['sleep'])) { if (isset($_GET['sleep'])) {
Moderation::muteChat($user->getId(), strtotime('15min')); Moderation::muteChat(User::$current->getId(), strtotime('15min'));
} }
if (isset($_POST['ldnick']) && isset($_POST['ldtext'])) { if (isset($_POST['ldnick']) && isset($_POST['ldtext'])) {
$u = new User($_POST['ldnick']); $u = new User($_POST['ldnick']);
Moderation::addToUserLog($u->getId(), $_POST['ldtext'], $user->getId()); Moderation::addToUserLog($u->getId(), $_POST['ldtext'], User::$current->getId());
unset($u); unset($u);
} }
@ -34,7 +35,7 @@ if (isset($_POST['syschatmsg'])) {
//clans to reg //clans to reg
$unregisteredClans = new class { $unregisteredClans = new class {
public $db; public DBPDO $db;
public function getList() public function getList()
{ {
@ -75,7 +76,7 @@ UNREGCLANLIST;
$bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id); $bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id);
} }
}; };
$unregisteredClans->db = $db; $unregisteredClans->db = DBPDO::$db;
$unregisteredClans->getList(); $unregisteredClans->getList();
if (isset($_GET['regclan'])) { if (isset($_GET['regclan'])) {
@ -91,19 +92,15 @@ if (isset($_GET['remclan'])) {
# Телеграф. # Телеграф.
if (!empty($_POST['receiver']) && !empty($_POST['tgmsg'])) { if (!empty($_POST['receiver']) && !empty($_POST['tgmsg'])) {
$receiver = $db->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']); $receiver = DBPDO::$db->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']);
telegraph($receiver->id, $_POST['tgmsg']); telegraph($receiver->id, $_POST['tgmsg']);
echo "Успешно."; echo "Успешно.";
} }
# Показывает невидимок. # Показывает невидимок.
$row = $db->ofetchAll('SELECT id,login FROM users LEFT JOIN users_effects ue on users.id = ue.owner_id WHERE type = 1022 ORDER BY `id` DESC'); $row = DBPDO::$db->ofetchAll('SELECT id,login FROM users LEFT JOIN users_effects ue on users.id = ue.owner_id WHERE type = 1022 ORDER BY `id` DESC');
$i = 0; foreach ($row as $r) {
$invisList = ''; $invisList .= '<b>[id] = ' .$r->id. ', ' .$r->login. '</b><br>';
while ($i < count($row)) {
$invisList .= '<b>[id] = ' . $row[$i]->id . ', ' . $row[$i]->login . ' </b><br>';
$i++;
} }
unset($i);
Template::header('ᐰdminка'); Template::header('ᐰdminка');

View File

@ -6,7 +6,6 @@ use Battles\Rooms;
use Battles\Template; use Battles\Template;
use Exceptions\GameException; use Exceptions\GameException;
ob_start("ob_gzhandler");
session_start(); session_start();
require_once "functions.php"; require_once "functions.php";
const SUCCESS = "Успешная операция!"; const SUCCESS = "Успешная операция!";

View File

@ -5,17 +5,17 @@ use Battles\GameConfigs;
use Battles\Nick; use Battles\Nick;
use Battles\Rooms; use Battles\Rooms;
use Battles\Template; use Battles\Template;
use Battles\User;
session_start(); session_start();
require_once 'functions.php'; require_once 'functions.php';
if (!User::$current->getClan()) {
if (!$user->getClan()) {
exit('Ошибка! Вы не состоите в клане!'); exit('Ошибка! Вы не состоите в клане!');
} }
Clan::$current = new Clan($user, $db); Clan::$current = new Clan();
if ($user->getClan() != Clan::$current->getClanShortName()) { if (User::$current->getClan() != Clan::$current->getClanShortName()) {
exit('Ошибка! Клана ' . $user->getClan() . ' не существует!'); exit('Ошибка! Клана ' . User::$current->getClan() . ' не существует!');
} }
Template::header('clan'); Template::header('clan');
@ -65,7 +65,7 @@ Template::header('clan');
<h3><img src="./i/clan/<?= Clan::$current->getClanShortName() ?>.png" <h3><img src="./i/clan/<?= Clan::$current->getClanShortName() ?>.png"
alt="<?= Clan::$current->getClanShortName() ?>"><?= Clan::$current->getClanName() ?></h3> alt="<?= Clan::$current->getClanShortName() ?>"><?= Clan::$current->getClanName() ?></h3>
<?php if (Clan::$current->getClanOwnerId() === $user->getId()): ?> <?php if (Clan::$current->getClanOwnerId() === User::$current->getId()): ?>
<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="Принять в клан">

View File

@ -17,7 +17,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) {
$eff = db::c()->query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $user->getId()); $eff = db::c()->query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $user->getId());
$name_check = db::c()->query('SELECT owner_id FROM clans WHERE full_name = "?s" OR short_name = "?s"', $clanFullName, $clanShortName); $name_check = db::c()->query('SELECT owner_id FROM clans WHERE full_name = "?s" OR short_name = "?s"', $clanFullName, $clanShortName);
$errorMessage = []; $errorMessage = [];
if (GameConfigs::CLAN_REGISTER_LOCK) { if (GameConfigs::CLAN['clan_register_lock']) {
$errorMessage[10] = 'Регистрация кланов закрыта! <BR>'; $errorMessage[10] = 'Регистрация кланов закрыта! <BR>';
} }
if ($user->getAlign()) { if ($user->getAlign()) {
@ -26,7 +26,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) {
if ($user->getClan()) { if ($user->getClan()) {
$errorMessage[1] = 'Вы уже состоите в клане!. <BR>'; $errorMessage[1] = 'Вы уже состоите в клане!. <BR>';
} }
if (GameConfigs::CLAN_REGISTER_COST >= $userBank->getMoney()) { if (GameConfigs::CLAN['clan_register_cost'] >= $userBank->getMoney()) {
$errorMessage[2] = 'Не хватает денег на регистрацию клана. <BR>'; $errorMessage[2] = 'Не хватает денег на регистрацию клана. <BR>';
} }
if (!$eff) { if (!$eff) {
@ -38,7 +38,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) {
if (!$errorMessage || $user->getAdmin()) { if (!$errorMessage || $user->getAdmin()) {
try { try {
db::c()->query('INSERT INTO clans (owner_id, full_name, short_name, info) VALUES (?i,"?s","?s","?s")', $user->getId(), $clanFullName, $clanShortName, $clanInfo); db::c()->query('INSERT INTO clans (owner_id, full_name, short_name, info) VALUES (?i,"?s","?s","?s")', $user->getId(), $clanFullName, $clanShortName, $clanInfo);
$userBank->setMoney($userBank->getMoney() - GameConfigs::CLAN_REGISTER_COST); $userBank->setMoney($userBank->getMoney() - GameConfigs::CLAN['clan_register_cost']);
Battles\Bank::setBankMoney($userBank->getMoney(), $user->getId(), 'clanRegister'); Battles\Bank::setBankMoney($userBank->getMoney(), $user->getId(), 'clanRegister');
// Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит. // Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит.
$userClan = new stdClass(); $userClan = new stdClass();

View File

@ -28,6 +28,7 @@ class Bank
'depositMoney' => 'Пополнение счёта.', 'depositMoney' => 'Пополнение счёта.',
'withdrawMoney' => 'Снятие денег со счёта.', 'withdrawMoney' => 'Снятие денег со счёта.',
'clanRegister' => 'Оплата стоимости регистрации клана.', 'clanRegister' => 'Оплата стоимости регистрации клана.',
'sellShop' => 'Продажа товара в магазине.'
]; ];
public function __construct(int $user_id) public function __construct(int $user_id)
@ -214,12 +215,9 @@ class Bank
*/ */
public static function setWalletMoney(int $amount, int $user_id): void public static function setWalletMoney(int $amount, int $user_id): void
{ {
try { $u = new User($user_id);
self::$db->execute('UPDATE users SET money = ? WHERE id = ?', [$amount, $user_id]); $u->setMoney($amount);
} catch (Throwable $e) { $u->saveMoney();
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
}
} }
public function getMoney(): int public function getMoney(): int

28
classes/Battles/Check.php Normal file
View File

@ -0,0 +1,28 @@
<?php
# Date: 15.03.2021 (21:53)
namespace Battles;
use Battles\Database\DBPDO;
class Check
{
private User $user;
private DBPDO $db;
/**
* Check constructor.
*
* @param User $user
*/
public function __construct(User $user, DBPDO $db)
{
$this->user = $user;
$this->db = $db;
}
public function Effects()
{
return $this->db->execute('delete from users_effects where remaining_time <= ?', strtotime('now'));
}
}

View File

@ -11,24 +11,24 @@ class Clan
private $clan; private $clan;
public static Clan $current; public static Clan $current;
public function __construct(User $user, DBPDO $db) public function __construct()
{ {
$this->db = $db; $this->db = DBPDO::$db;
$this->user = $user; $this->user = User::$current;
$this->clan = $this->db->ofetch('select * from clans where owner_id = ?', $this->user->getId()); $this->clan = $this->db->ofetch('select * from clans where owner_id = ?', $this->user->getId());
} }
public function addMember(string $login): string public function addMember(string $login): string
{ {
$target = new User($login);
$error = null; $error = null;
$check = $this->db->ofetch('select id, level, clan from users where login = ?', $login); if (!$this->getProverka($target->getId())) {
if (!$this->getProverka($check->id)) {
$error .= '<br>Нет проверки!'; $error .= '<br>Нет проверки!';
} }
if ($check->clan) { if ($target->getClan()) {
$error .= '<br>Персонаж уже состоит в клане!'; $error .= '<br>Персонаж уже состоит в клане!';
} }
if ($check->level < 1) { if ($target->getLevel() < 1) {
$error .= '<br>Персонаж 0 уровня не может быть принят!'; $error .= '<br>Персонаж 0 уровня не может быть принят!';
} }
if ($this->user->getMoney() < GameConfigs::CLAN['add_member_cost']) { if ($this->user->getMoney() < GameConfigs::CLAN['add_member_cost']) {
@ -39,21 +39,21 @@ class Clan
} }
$this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['add_member_cost']); $this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['add_member_cost']);
$this->user->saveMoney(); $this->user->saveMoney();
$this->db->execute('update users set clan = ? where id = ?', [$this->user->getClan(), $check->id]); $target->setClan($this->user->getClan());
return "Персонаж «{$login}» успешно принят в клан."; return "Персонаж «{$login}» успешно принят в клан.";
} }
public function removeMember(string $login): string public function removeMember(string $login): string
{ {
$target = new User($login);
$error = null; $error = null;
$check = $this->db->ofetch('select id, clan from users where login = ?', $login);
if ($this->user->getMoney() < GameConfigs::CLAN['remove_member_cost']) { if ($this->user->getMoney() < GameConfigs::CLAN['remove_member_cost']) {
$error .= '<br>Недостаточно денег!'; $error .= '<br>Недостаточно денег!';
} }
if ($check->id === $this->user->getId()) { if ($target->getId() === $this->user->getId()) {
$error .= '<br>Себя выгонять нельзя!'; $error .= '<br>Себя выгонять нельзя!';
} }
if ($check->clan !== $this->user->getClan()) { if ($target->getClan() !== $this->user->getClan()) {
$error .= '<br>Персонаж не состоит в этом клане!'; $error .= '<br>Персонаж не состоит в этом клане!';
} }
if ($error) { if ($error) {
@ -61,28 +61,28 @@ class Clan
} }
$this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['remove_member_cost']); $this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['remove_member_cost']);
$this->user->saveMoney(); $this->user->saveMoney();
$this->db->execute('update users set clan = null where id = ?', $check->id); $target->setClan(null);
return "Персонаж «{$login}» покинул клан."; return "Персонаж «{$login}» покинул клан.";
} }
public function changeOwner(string $login): string public function changeOwner(string $login): string
{ {
$target = new User($login);
$error = null; $error = null;
$check = $this->db->ofetch('select id, clan from users where login = ?', $login); if ($target->getId() === $this->user->getId()) {
if ($check->id === $this->user->getId()) {
$error .= '<br>Самоудовлетворяетесь? ;)'; $error .= '<br>Самоудовлетворяетесь? ;)';
} }
if ($check->clan !== $this->user->getClan()) { if ($target->getClan() !== $this->user->getClan()) {
$error .= '<br>Персонаж не состоит в этом клане!'; $error .= '<br>Персонаж не состоит в этом клане!';
} }
if ($error) { if ($error) {
return $error; return $error;
} }
$this->db->execute('update clans set owner_id = ? where owner_id = ?', [$check->id, $this->user->getId()]); $this->db->execute('update clans set owner_id = ? where owner_id = ?', [$target->getId(), $this->user->getId()]);
return 'Вы передали управление кланом персонажу «' . $login . '».'; return 'Вы передали управление кланом персонажу «' . $login . '».';
} }
public function setClanInfo(string $text) public function setClanInfo(string $text): string
{ {
$check = $this->db->ofetch('select id from users where clan = (select short_name from clans where owner_id = ?)', $this->user->getId()); $check = $this->db->ofetch('select id from users where clan = (select short_name from clans where owner_id = ?)', $this->user->getId());
if ($check->id !== $this->user->getId()) { if ($check->id !== $this->user->getId()) {
@ -94,8 +94,7 @@ class Clan
public function getMemberlist(): array public function getMemberlist(): array
{ {
$query = 'select id, (select 1 from clans where short_name = clan and owner_id = id) as clan_owner, room from users where clan = ? order by clan_owner desc, room, login'; return $this->db->ofetchAll('select id, (select 1 from clans where short_name = clan and owner_id = id) as clan_owner, room from users where clan = ? order by clan_owner desc, room, login', $this->user->getClan());
return $this->db->ofetchAll($query, $this->user->getClan());
} }
private function getProverka($user_id) private function getProverka($user_id)

View File

@ -9,6 +9,7 @@ class DBPDO
public $pdo; public $pdo;
private static $_instance = null; private static $_instance = null;
public static DBPDO $db;
function __construct() function __construct()
{ {

View File

@ -10,7 +10,7 @@ use Battles\User;
class Sharpen extends Magic class Sharpen extends Magic
{ {
private $magicDifficulty; private int $magicDifficulty;
/** /**
* Sharpen constructor. * Sharpen constructor.

View File

@ -15,72 +15,72 @@ class Moderation
GameLogs::addUserLog($userId, $message, "moderation"); GameLogs::addUserLog($userId, $message, "moderation");
} }
public static function muteChat(int $target, int $time): bool public static function muteChat(int $target, int $time)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[2]); self::addEffectStatusToUserLog($target, UserEffects::$effectName[2]);
return User::setUserEffect($target, 2, UserEffects::$effectName[2], $time); User::addUserEffect($target, 2, UserEffects::$effectName[2], $time);
} }
public static function unmuteChat(int $target): bool public static function unmuteChat(int $target)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[2] . self::STATUS_OFF); self::addEffectStatusToUserLog($target, UserEffects::$effectName[2] . self::STATUS_OFF);
return User::removeUserEffect($target, 2); User::removeUserEffect($target, 2);
} }
public static function muteForum(int $target, int $time): bool public static function muteForum(int $target, int $time)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[3]); self::addEffectStatusToUserLog($target, UserEffects::$effectName[3]);
return User::setUserEffect($target, 3, UserEffects::$effectName[3], $time); User::addUserEffect($target, 3, UserEffects::$effectName[3], $time);
} }
public static function unmuteForum(int $target): bool public static function unmuteForum(int $target)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[3] . self::STATUS_OFF); self::addEffectStatusToUserLog($target, UserEffects::$effectName[3] . self::STATUS_OFF);
return User::removeUserEffect($target, 3); User::removeUserEffect($target, 3);
} }
public static function hideUserInfo(int $target, int $time): bool public static function hideUserInfo(int $target, int $time)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[5]); self::addEffectStatusToUserLog($target, UserEffects::$effectName[5]);
return User::setUserEffect($target, 5, UserEffects::$effectName[5], $time); User::addUserEffect($target, 5, UserEffects::$effectName[5], $time);
} }
public static function unHideUserInfo(int $target): bool public static function unHideUserInfo(int $target)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[5] . self::STATUS_OFF); self::addEffectStatusToUserLog($target, UserEffects::$effectName[5] . self::STATUS_OFF);
return User::removeUserEffect($target, 5); User::removeUserEffect($target, 5);
} }
public static function blockUser(int $target): void public static function blockUser(int $target)
{ {
self::addEffectStatusToUserLog($target, "Блокировка"); self::addEffectStatusToUserLog($target, "Блокировка");
DBPDO::INIT()->execute('UPDATE battles.users SET block = 1 WHERE id = ?', $target); DBPDO::INIT()->execute('UPDATE battles.users SET block = 1 WHERE id = ?', $target);
} }
public static function unBlockUser(int $target): void public static function unBlockUser(int $target)
{ {
self::addEffectStatusToUserLog($target, "Блокировка" . self::STATUS_OFF); self::addEffectStatusToUserLog($target, "Блокировка" . self::STATUS_OFF);
DBPDO::INIT()->execute('UPDATE battles.users SET block = 0 WHERE block = 1 AND id = ?', $target); DBPDO::INIT()->execute('UPDATE battles.users SET block = 0 WHERE block = 1 AND id = ?', $target);
} }
public static function addToUserLog(int $target, string $message, int $senderId): void public static function addToUserLog(int $target, string $message, int $senderId)
{ {
GameLogs::addUserLog($target, $message, "moderation", $senderId); GameLogs::addUserLog($target, $message, "moderation", $senderId);
} }
public static function setAlign(int $target, int $align): void public static function setAlign(int $target, int $align)
{ {
DBPDO::INIT()->execute('UPDATE users SET align = ? WHERE id = ?', [$align, $target]); DBPDO::INIT()->execute('UPDATE users SET align = ? WHERE id = ?', [$align, $target]);
} }
public static function addChatSysMsg(string $message): void public static function addChatSysMsg(string $message)
{ {
DBPDO::INIT()->execute('INSERT INTO chat (user_id,msg,type) VALUES (-1,?,?)', [$message, 'sys']); DBPDO::INIT()->execute('INSERT INTO chat (user_id,msg,type) VALUES (-1,?,?)', [$message, 'sys']);
} }
public static function addUserCheck(int $target): bool public static function addUserCheck(int $target)
{ {
self::addEffectStatusToUserLog($target, UserEffects::$effectName[20]); self::addEffectStatusToUserLog($target, UserEffects::$effectName[20]);
return User::setUserEffect($target, 20, UserEffects::$effectName[20], strtotime('3days')); User::addUserEffect($target, 20, UserEffects::$effectName[20], strtotime('3days'));
} }
} }

View File

@ -91,6 +91,7 @@ SQL;
echo "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>"; echo "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>";
} }
//todo наличка после покупки отображается с задержкой.
public static function buyItem($id, User $buyer): string public static function buyItem($id, User $buyer): string
{ {
$db = new DBPDO(); $db = new DBPDO();

View File

@ -6,38 +6,49 @@ use Battles\Database\DBPDO;
class User class User
{ {
protected $id = 0; protected int $id = 0;
protected $login = '<em>Некто</em>'; protected string $login = '';
protected $pass; protected ?string $pass = null;
protected $email = '<em>неизвестно</em>'; protected ?string $email = null;
protected $realname; protected ?string $realname = null;
protected $borndate; protected ?string $borndate = null;
protected $info; protected ?string $info = null;
protected $level; protected int $level = 0;
protected $align; protected ?int $align = null;
protected $clan; protected ?string $clan = null;
protected $money; protected ?int $money = null;
protected $ip = 0; protected ?string $ip = null;
protected $admin = 0; protected ?int $admin = null;
protected $enter_game; protected int $room = 0;
protected $room; protected int $block = 0;
protected $block; protected string $shadow = '';
protected $shadow;
// Пока несуществующие, для совместимости. // Пока несуществующие, для совместимости.
protected $experience = 200; protected int $experience = 0;
protected $battle = 0; protected int $battle = 0;
protected $in_tower = 0; // Скорее башню похороним чем запустим... protected int $in_tower = 0; // Скорее башню похороним чем запустим...
protected $zayavka = 0; protected int $zayavka = 0;
protected static $db; protected static DBPDO $db;
public const INFO_CHAR_LIMIT = 1500; public const INFO_CHAR_LIMIT = 1500;
/**
* @var User Переменная инициализируемая при запуске, хранящая объект текущего пользователя.
*/
public static User $current;
/**
* @param int|string $user
*/
public function __construct($user) public function __construct($user)
{ {
self::$db = DBPDO::INIT(); self::$db = DBPDO::INIT();
$user_query = self::$db->fetch('SELECT * FROM users WHERE id = ? OR login = ?', [$user, $user]); $query = 'select * from users where login = ?';
if (is_numeric($user)) {
$query = 'select * from users where id = ?';
$user = (int)$user;
}
$user_query = self::$db->fetch($query, $user);
foreach ($this as $key => $value) { foreach ($this as $key => $value) {
if (isset($user_query[$key])) { if (isset($user_query[$key])) {
$this->$key = $user_query[$key]; $this->$key = $user_query[$key];
@ -51,12 +62,11 @@ class User
* @param string $name * @param string $name
* @param int $time * @param int $time
* @param string|null $json_modifiers_list (str, dex, int, end, intel, wis). * @param string|null $json_modifiers_list (str, dex, int, end, intel, wis).
* @return bool
*/ */
public static function setUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null): bool public static function addUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null)
{ {
$mods = json_decode($json_modifiers_list); $mods = json_decode($json_modifiers_list);
return self::$db->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time, mod_strength, mod_dexterity, mod_intuition, mod_endurance, mod_intelligence, mod_wisdom) VALUES (?,?,?,?,?,?,?,?,?,?)', [$userId, $type, $name, $time, $mods->str ?? null, $mods->dex ?? null, $mods->int ?? null, $mods->end ?? null, $mods->intel ?? null, $mods->wis ?? null]); self::$db->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time, mod_strength, mod_dexterity, mod_intuition, mod_endurance, mod_intelligence, mod_wisdom) VALUES (?,?,?,?,?,?,?,?,?,?)', [$userId, $type, $name, $time, $mods->str ?? null, $mods->dex ?? null, $mods->int ?? null, $mods->end ?? null, $mods->intel ?? null, $mods->wis ?? null]);
} }
public static function removeUserEffect(int $userId, int $type): bool public static function removeUserEffect(int $userId, int $type): bool
@ -67,34 +77,17 @@ class User
return false; return false;
} }
/**
* @return int
*/
public function getId(): int public function getId(): int
{ {
return $this->id; return $this->id;
} }
/**
* @return string
*/
public function getLogin(): string public function getLogin(): string
{ {
return $this->login; return $this->login;
} }
/** public function getPass(): string
* @param string $login
*/
public function setLogin(string $login): void
{
$this->login = $login;
}
/**
* @return mixed
*/
public function getPass()
{ {
return $this->pass; return $this->pass;
} }
@ -112,26 +105,7 @@ class User
self::$db->execute('UPDATE users SET pass = ? WHERE id = ?', [$this->pass, $this->id]); self::$db->execute('UPDATE users SET pass = ? WHERE id = ?', [$this->pass, $this->id]);
} }
/** public function getRealname(): string
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* @return mixed
*/
public function getRealname()
{ {
return $this->realname; return $this->realname;
} }
@ -144,26 +118,7 @@ class User
$this->realname = $realname; $this->realname = $realname;
} }
/** public function getInfo(): string
* @return mixed
*/
public function getBorndate()
{
return $this->borndate;
}
/**
* @param mixed $borndate
*/
public function setBorndate($borndate): void
{
$this->borndate = $borndate;
}
/**
* @return mixed
*/
public function getInfo()
{ {
return $this->info; return $this->info;
} }
@ -171,71 +126,46 @@ class User
/** /**
* @param mixed $info * @param mixed $info
*/ */
public function setInfo($info): void public function setInfo($info)
{ {
$this->info = $info; $this->info = $info;
} }
/**
* @return int
*/
public function getLevel(): int public function getLevel(): int
{ {
return $this->level; return $this->level;
} }
/**
* @param int $level
*/
public function setLevel(int $level): void
{
$this->level = $level;
}
/**
* @return int
*/
public function getAlign(): int public function getAlign(): int
{ {
return $this->align; return $this->align;
} }
/** public function getClan(): ?string
* @param int $align
*/
public function setAlign(int $align): void
{
$this->align = $align;
}
/**
* @return string
*/
public function getClan(): string
{ {
return $this->clan; return $this->clan;
} }
/** /**
* @param int $clan * @param string|null $short_name Короткое название клана. Передать null для очистки.
*/ */
public function setClan(string $clan): void public function setClan(?string $short_name)
{ {
$this->clan = $clan; if (is_null($short_name)) {
$this->clan = null;
self::$db->execute('update users set clan = null where id = ?', $this->id);
} else {
$this->clan = $short_name;
self::$db->execute('update users set clan = ? where id = ?', [$short_name, $this->id]);
}
} }
/**
* @return int
*/
public function getMoney(): int public function getMoney(): int
{ {
return $this->money; return $this->money;
} }
/** public function setMoney(int $money)
* @param int $money
*/
public function setMoney(int $money): void
{ {
$this->money = $money < 0 ? 0 : $money; $this->money = $money < 0 ? 0 : $money;
} }
@ -245,52 +175,12 @@ class User
self::$db->execute('update users set money = ? where id = ?', [$this->money, $this->id]); self::$db->execute('update users set money = ? where id = ?', [$this->money, $this->id]);
} }
/**
* @return mixed
*/
public function getIp()
{
return $this->ip;
}
/**
* @param mixed $ip
*/
public function setIp($ip): void
{
$this->ip = $ip;
}
/**
* @return int
*/
public function getAdmin(): int public function getAdmin(): int
{ {
return $this->admin; return $this->admin;
} }
/** public function getRoom(): int
* @return mixed
*/
public function getEnterGame()
{
return $this->enter_game;
}
/**
* @param mixed $enter_game
*/
public function setEnterGame($enter_game): void
{
$this->enter_game = $enter_game;
}
/**
* @return mixed
*/
public function getRoom()
{ {
return $this->room; return $this->room;
} }
@ -298,31 +188,17 @@ class User
/** /**
* @param mixed $room * @param mixed $room
*/ */
public function setRoom($room): void public function setRoom($room)
{ {
$this->room = $room; $this->room = $room;
} }
/** public function getBlock(): int
* @return mixed
*/
public function getBlock()
{ {
return $this->block; return $this->block;
} }
/** public function getShadow(): string
* @param mixed $block
*/
public function setBlock($block): void
{
$this->block = $block;
}
/**
* @return mixed
*/
public function getShadow()
{ {
return $this->shadow; return $this->shadow;
} }
@ -346,70 +222,26 @@ class User
self::$db->execute('UPDATE users SET shadow = ? WHERE id = ?', [$this->shadow, $this->id]); self::$db->execute('UPDATE users SET shadow = ? WHERE id = ?', [$this->shadow, $this->id]);
} }
/**
* @return int
*/
public function getExperience(): int public function getExperience(): int
{ {
return $this->experience; return $this->experience;
} }
/**
* @param int $experience
*/
public function setExperience(int $experience): void
{
$this->experience = $experience;
}
/**
* @return int
*/
public function getBattle(): int public function getBattle(): int
{ {
return $this->battle; return $this->battle;
} }
/**
* @param int $battle
*/
public function setBattle(int $battle): void
{
$this->battle = $battle;
}
/**
* @return int
*/
public function getInTower(): int public function getInTower(): int
{ {
return $this->in_tower; return $this->in_tower;
} }
/**
* @param int $in_tower
*/
public function setInTower(int $in_tower): void
{
$this->in_tower = $in_tower;
}
/**
* @return int
*/
public function getZayavka(): int public function getZayavka(): int
{ {
return $this->zayavka; return $this->zayavka;
} }
/**
* @param int $zayavka
*/
public function setZayavka(int $zayavka): void
{
$this->zayavka = $zayavka;
}
public function saveAnketa() public function saveAnketa()
{ {
self::$db->execute('UPDATE users SET realname = ?, info = ? WHERE id = ?', [$this->realname, $this->info, $this->id]); self::$db->execute('UPDATE users SET realname = ?, info = ? WHERE id = ?', [$this->realname, $this->info, $this->id]);
@ -422,32 +254,32 @@ class User
public function setInjury(int $type): bool public function setInjury(int $type): bool
{ {
if (!in_array($type,[11,12,13,14])) { if (!in_array($type, [11, 12, 13, 14])) {
return false; return false;
} }
$names1 = ['разбитый нос', 'сотрясение первой степени', 'потрепанные уши', 'прикушенный язык', 'перелом переносицы', 'растяжение ноги', 'растяжение руки', 'подбитый глаз', 'синяк под глазом', 'кровоточащее рассечение', 'отбитая «пятая точка»', 'заклинившая челюсть', 'выбитый зуб «мудрости»', 'косоглазие']; $names1 = ['разбитый нос', 'сотрясение первой степени', 'потрепанные уши', 'прикушенный язык', 'перелом переносицы', 'растяжение ноги', 'растяжение руки', 'подбитый глаз', 'синяк под глазом', 'кровоточащее рассечение', 'отбитая «пятая точка»', 'заклинившая челюсть', 'выбитый зуб «мудрости»', 'косоглазие'];
$names2 = ['отбитые почки', 'вывих «вырезано цензурой»', 'сотрясение второй степени', 'оторванное ухо', 'вывих руки', 'оторванные уши', 'поврежденный позвоночник', 'поврежденный копчик', 'разрыв сухожилия', 'перелом ребра', 'перелом двух ребер', 'вывих ноги', 'сломанная челюсть']; $names2 = ['отбитые почки', 'вывих «вырезано цензурой»', 'сотрясение второй степени', 'оторванное ухо', 'вывих руки', 'оторванные уши', 'поврежденный позвоночник', 'поврежденный копчик', 'разрыв сухожилия', 'перелом ребра', 'перелом двух ребер', 'вывих ноги', 'сломанная челюсть'];
$names3 = ['пробитый череп', 'разрыв селезенки', 'смещение позвонков', 'открытый перелом руки', 'открытый перелом «вырезано цензурой»', 'излом носоглотки', 'непонятные, но множественные травмы', 'сильное внутреннее кровотечение', 'раздробленная коленная чашечка', 'перелом шеи', 'смещение позвонков', 'открытый перелом ключицы', 'перелом позвоночника', 'вывих позвоночника', 'сотрясение третьей степени']; $names3 = ['пробитый череп', 'разрыв селезенки', 'смещение позвонков', 'открытый перелом руки', 'открытый перелом «вырезано цензурой»', 'излом носоглотки', 'непонятные, но множественные травмы', 'сильное внутреннее кровотечение', 'раздробленная коленная чашечка', 'перелом шеи', 'смещение позвонков', 'открытый перелом ключицы', 'перелом позвоночника', 'вывих позвоночника', 'сотрясение третьей степени'];
$param_names = ['str','dex','int','end','intel','wis',]; $param_names = ['str', 'dex', 'int', 'end', 'intel', 'wis',];
shuffle($param_names); shuffle($param_names);
switch ($type) { switch ($type) {
case 11: case 11:
shuffle($names1); shuffle($names1);
$name = UserEffects::$effectName[$type] . ': ' . $names1(0); $name = UserEffects::$effectName[$type] . ': ' . $names1(0);
self::setUserEffect($this->id, $type, $name, strtotime('30min'), json_encode([$param_names(0) => -1])); self::addUserEffect($this->id, $type, $name, strtotime('30min'), json_encode([$param_names(0) => -1]));
break; break;
case 12: case 12:
shuffle($names2); shuffle($names2);
$name = UserEffects::$effectName[$type] . ': ' . $names2(0); $name = UserEffects::$effectName[$type] . ': ' . $names2(0);
self::setUserEffect($this->id, $type, $name, strtotime('3hours'), json_encode([$param_names(0) => mt_rand(-3,-1), $param_names(1) => mt_rand(-3,-1)])); self::addUserEffect($this->id, $type, $name, strtotime('3hours'), json_encode([$param_names(0) => mt_rand(-3, -1), $param_names(1) => mt_rand(-3, -1)]));
break; break;
case 13: case 13:
shuffle($names3); shuffle($names3);
$name = UserEffects::$effectName[$type] . ': ' . $names3(0); $name = UserEffects::$effectName[$type] . ': ' . $names3(0);
self::setUserEffect($this->id, $type, $name, strtotime('12hours'), json_encode([$param_names(0) => mt_rand(-5,-1), $param_names(1) => mt_rand(-5,-1), $param_names(2) => mt_rand(-5,-1)])); self::addUserEffect($this->id, $type, $name, strtotime('12hours'), json_encode([$param_names(0) => mt_rand(-5, -1), $param_names(1) => mt_rand(-5, -1), $param_names(2) => mt_rand(-5, -1)]));
break; break;
default: //type 14 default: //type 14
self::setUserEffect($this->id, $type, UserEffects::$effectName[$type], strtotime('1day'), json_encode([$param_names(0) => -10])); self::addUserEffect($this->id, $type, UserEffects::$effectName[$type], strtotime('1day'), json_encode([$param_names(0) => -10]));
break; break;
} }

Binary file not shown.

View File

@ -1,5 +1,4 @@
<?php <?php
ob_start("ob_gzhandler");
session_start(); session_start();
if (isset($_POST['end'])) { if (isset($_POST['end'])) {
header("Location: main.php"); header("Location: main.php");
@ -162,7 +161,6 @@ $fbattle = new fbattle($user['battle']);
$dressed = db::c()->query('SELECT `id` FROM `inventory` WHERE `id` = ?i AND `dressed` = 1', $_GET['use'])->fetch_row(); $dressed = db::c()->query('SELECT `id` FROM `inventory` WHERE `id` = ?i AND `dressed` = 1', $_GET['use'])->fetch_row();
if ((int)$dressed[0] > 0) { if ((int)$dressed[0] > 0) {
$my_class = $fbattle->my_class; $my_class = $fbattle->my_class;
ob_start();
usemagic($_GET['use'], "" . $_POST['target']); usemagic($_GET['use'], "" . $_POST['target']);
$bb = explode("<!--", ob_get_clean()); $bb = explode("<!--", ob_get_clean());
$bb = str_replace('"', "&quot;", (strip_tags($bb[0]))); $bb = str_replace('"', "&quot;", (strip_tags($bb[0])));

View File

@ -12,18 +12,18 @@ use Battles\Travel;
use Battles\User; use Battles\User;
require_once 'config.php'; require_once 'config.php';
DBPDO::$db = new DBPDO();
if (empty($_SESSION['uid'])) { if (empty($_SESSION['uid'])) {
header("Location: index.php"); header("Location: index.php");
exit; exit;
} else { } else {
$user = new User($_SESSION['uid']); $user = new User($_SESSION['uid']);
User::$current = new User($_SESSION['uid']);
} }
if ($user->getId() && $user->getBlock()) { if (User::$current->getId() && User::$current->getBlock()) {
exit('user blocked!'); exit('user blocked!');
} }
$db = new DBPDO();
/* /*
* Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам. * Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам.
*/ */
@ -57,12 +57,12 @@ $fbattleCheckFiles = [
'zayavka.php', 'zayavka.php',
]; ];
//Может просто отовсюду? О_о //Может просто отовсюду? О_о
if ($user->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) { if (User::$current->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) {
header('location: fbattle.php'); header('location: fbattle.php');
exit; exit;
} }
$towerinCheckFiles = ['main.php', 'city.php', 'tower.php']; $towerinCheckFiles = ['main.php', 'city.php', 'tower.php'];
if ($user->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) { if (User::$current->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) {
header('location: towerin.php'); header('location: towerin.php');
exit; exit;
} }
@ -70,8 +70,8 @@ $roomsCheck = [22, 23, 25, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401,
// Если я в одной из этих комнат, // Если я в одной из этих комнат,
// [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь // [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь
// [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых // [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых
if (in_array($user->getRoom(), $roomsCheck) if (in_array(User::$current->getRoom(), $roomsCheck)
&& pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[$user->getRoom()] && pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::$current->getRoom()]
&& in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], Travel::$roomFileName), $roomsCheck)) { && in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], Travel::$roomFileName), $roomsCheck)) {
header('location: main.php'); header('location: main.php');
exit; exit;
@ -80,7 +80,7 @@ if (in_array($user->getRoom(), $roomsCheck)
$ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP); $ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
if (isset($_GET['goto']) && isset($_GET['tStamp']) && isset($_GET['vcode']) && $_GET['vcode'] == md5(sha1($_GET['goto'] . $_GET['tStamp']))) { if (isset($_GET['goto']) && isset($_GET['tStamp']) && isset($_GET['vcode']) && $_GET['vcode'] == md5(sha1($_GET['goto'] . $_GET['tStamp']))) {
db::c()->query('UPDATE `users`,`online` SET `users`.`room` = ?i, `online`.`room` = ?i WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $_GET['goto'], $_GET['goto'], $_SESSION['uid']); db::c()->query('UPDATE `users`,`online` SET `users`.`room` = ?i, `online`.`room` = ?i WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $_GET['goto'], $_GET['goto'], $_SESSION['uid']);
$user->setRoom(intval($_GET['goto'])); User::$current->setRoom(intval($_GET['goto']));
} }
function createbot($bot, $login = "") function createbot($bot, $login = "")
@ -139,11 +139,10 @@ function get_out($u)
function takeshopitem($item, $table = "shop", $present = '', $onlyonetrip = '', $fields = 0, $uid = 0, $koll = 1, $podzem = 0) function takeshopitem($item, $table = "shop", $present = '', $onlyonetrip = '', $fields = 0, $uid = 0, $koll = 1, $podzem = 0)
{ {
global $user;
$flds = []; $flds = [];
$goden = ''; $goden = '';
if (!$uid) { if (!$uid) {
$uid = $user->getId(); $uid = User::$current->getId();
} }
$r = db::c()->query('SHOW FIELDS FROM ?f', $table); $r = db::c()->query('SHOW FIELDS FROM ?f', $table);
@ -290,21 +289,20 @@ HTML;
*/ */
function echoscroll($slot) function echoscroll($slot)
{ {
global $user;
$all_magic = 0; $all_magic = 0;
if ($user->getBattle()) { if (User::$current->getBattle()) {
$script = 'fbattle'; $script = 'fbattle';
$bat = db::c()->query('SELECT `magic` FROM `battle` WHERE `id` = ?i', $user->getBattle())->fetch_assoc(); $bat = db::c()->query('SELECT `magic` FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc();
$all_magic = unserialize($bat['magic']); $all_magic = unserialize($bat['magic']);
} else { } else {
$script = 'main'; $script = 'main';
} }
$dress = db::c()->query('SELECT `id`, `magic`, `name`, `img`, `duration`, `maxdur` FROM `inventory` WHERE `id` = ?i', $user->$slot)->fetch_assoc(); $dress = db::c()->query('SELECT `id`, `magic`, `name`, `img`, `duration`, `maxdur` FROM `inventory` WHERE `id` = ?i', User::$current->$slot)->fetch_assoc();
$need_charge = db::c()->query('SELECT `needcharge` FROM `magic` WHERE `id` = ?i', $dress['magic'])->fetch_assoc(); $need_charge = db::c()->query('SELECT `needcharge` FROM `magic` WHERE `id` = ?i', $dress['magic'])->fetch_assoc();
if (($user->$slot > 0) && ($all_magic[$user->getId()] < 1 || empty($need_charge['needcharge']))) { if ((User::$current->$slot > 0) && ($all_magic[User::$current->getId()] < 1 || empty($need_charge['needcharge']))) {
$row['id'] = $user->$slot; $row['id'] = User::$current->$slot;
if ($dress['magic']) { if ($dress['magic']) {
$magic = db::c()->query('SELECT targeted FROM `magic` WHERE `id` = ?i', $dress['magic'])->fetch_assoc(); $magic = db::c()->query('SELECT targeted FROM `magic` WHERE `id` = ?i', $dress['magic'])->fetch_assoc();
echo "<a onclick=\""; echo "<a onclick=\"";
@ -321,7 +319,7 @@ function echoscroll($slot)
echo <<<ACTIVE_SCROLL echo <<<ACTIVE_SCROLL
<img class='tooltip' src="i/sh/{$dress['img']}" width='40' title="<b>{$dress['name']}</b><br> Прочность {$dress['duration']} / {$dress['maxdur']} " height='25' alt="Свиток"></a> <img class='tooltip' src="i/sh/{$dress['img']}" width='40' title="<b>{$dress['name']}</b><br> Прочность {$dress['duration']} / {$dress['maxdur']} " height='25' alt="Свиток"></a>
ACTIVE_SCROLL; ACTIVE_SCROLL;
} elseif (($user->$slot > 0) && ($all_magic[$user->getId()] >= 1) && $need_charge['needcharge'] > 0) { } elseif ((User::$current->$slot > 0) && ($all_magic[User::$current->getId()] >= 1) && $need_charge['needcharge'] > 0) {
echo <<<INACTIVE_SCROLL echo <<<INACTIVE_SCROLL
<img src="i/sh/magicclock.gif" width="40" height="25" title='Произведите размен ударами и магия снова станет доступна' alt="Свиток"> <img src="i/sh/magicclock.gif" width="40" height="25" title='Произведите размен ударами и магия снова станет доступна' alt="Свиток">
INACTIVE_SCROLL; INACTIVE_SCROLL;
@ -474,9 +472,8 @@ function ref_drop()
// использовать магию // использовать магию
function usemagic($id, $target) function usemagic($id, $target)
{ {
global $user; $row = db::c()->query('SELECT * FROM `inventory` WHERE `owner` = ?i AND id = ?i', User::$current->getId(), $id)->fetch_assoc_array();
$row = db::c()->query('SELECT * FROM `inventory` WHERE `owner` = ?i AND id = ?i', $user->getId(), $id)->fetch_assoc_array(); $bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc_array();
$bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', $user->getBattle())->fetch_assoc_array();
$all_magic = unserialize($bat['magic']); $all_magic = unserialize($bat['magic']);
$charge = 0; $charge = 0;
$magic = db::c()->query('SELECT * FROM `magic` WHERE `id` = ?i', $row['magic'])->fetch_assoc_array(); $magic = db::c()->query('SELECT * FROM `magic` WHERE `id` = ?i', $row['magic'])->fetch_assoc_array();
@ -490,7 +487,7 @@ function usemagic($id, $target)
$charge = $incmagic['needcharge']; $charge = $incmagic['needcharge'];
} }
//Переделать под новую базу //Переделать под новую базу
if (($all_magic[$user->getId()] < 1 || $charge == 0) && if (($all_magic[User::$current->getId()] < 1 || $charge == 0) &&
($user['sila'] >= $row['nsila'] && ($user['sila'] >= $row['nsila'] &&
$user['lovk'] >= $row['nlovk'] && $user['lovk'] >= $row['nlovk'] &&
$user['inta'] >= $row['ninta'] && $user['inta'] >= $row['ninta'] &&
@ -543,16 +540,16 @@ function usemagic($id, $target)
$charge = 0; $charge = 0;
} }
//ограничение по кол-ву за ход //ограничение по кол-ву за ход
if ($user->getBattle()) { if (User::$current->getBattle()) {
$bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', $user->getBattle())->fetch_assoc_array(); $bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc_array();
} }
if ($bat['magic'] == '') { if ($bat['magic'] == '') {
$all_magic = []; $all_magic = [];
} else { } else {
$all_magic = unserialize($bat['magic']); $all_magic = unserialize($bat['magic']);
} }
$all_magic[$user->getId()] += $charge; $all_magic[User::$current->getId()] += $charge;
db::c()->query('UPDATE `battle` SET `magic`= "?s" WHERE id = ?i', serialize($all_magic), $user->getBattle()); db::c()->query('UPDATE `battle` SET `magic`= "?s" WHERE id = ?i', serialize($all_magic), User::$current->getBattle());
} }
} }
return false; return false;
@ -560,9 +557,8 @@ function usemagic($id, $target)
function addch($text, $room = 0) function addch($text, $room = 0)
{ {
global $user;
if ($room == 0) { if ($room == 0) {
$room = $user->getRoom(); $room = User::$current->getRoom();
} }
if ($fp = @fopen("tmp/chat.txt", "a")) { //открытие if ($fp = @fopen("tmp/chat.txt", "a")) { //открытие
flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА
@ -576,9 +572,8 @@ function addch($text, $room = 0)
function addchp($text, $who, $room = 0) function addchp($text, $who, $room = 0)
{ {
global $user;
if ($room == 0) { if ($room == 0) {
$room = $user->getRoom(); $room = User::$current->getRoom();
} }
$fp = fopen("tmp/chat.txt", "a"); //открытие $fp = fopen("tmp/chat.txt", "a"); //открытие
flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА
@ -615,18 +610,15 @@ function err($t)
*/ */
function telegraph(int $userId, string $text) function telegraph(int $userId, string $text)
{ {
$db = DBPDO::INIT(); if (DBPDO::$db->ofetch('SELECT 1 FROM users WHERE id = ?', $userId)) {
if ($db->ofetch('SELECT 1 FROM users WHERE id = ?', $userId)) { DBPDO::$db->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']);
$db->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']);
} }
unset($db);
} }
function get_meshok() function get_meshok()
{ {
global $user;
$itemsWeight = db::c()->query('SELECT SUM(weight) AS all_weight FROM `inventory` WHERE owner_id = ?i AND on_sale = 0', $_SESSION['uid'])->fetch_assoc(); $itemsWeight = db::c()->query('SELECT SUM(weight) AS all_weight FROM `inventory` WHERE owner_id = ?i AND on_sale = 0', $_SESSION['uid'])->fetch_assoc();
return ($user->getStrength() * 4 + $itemsWeight['all_weight']); return (User::$current->getStrength() * 4 + $itemsWeight['all_weight']);
} }
/** /**

View File

@ -2,7 +2,6 @@
use Battles\Template; use Battles\Template;
ob_start("ob_gzhandler");
session_start(); session_start();
require_once "functions.php"; require_once "functions.php";
$errkom = ''; $errkom = '';

View File

@ -1,5 +1,4 @@
<?php <?php
ob_start("ob_gzhandler");
session_start(); session_start();
require_once "functions.php"; require_once "functions.php";

View File

@ -1,4 +1,6 @@
<?php <?php
use Battles\Database\DBPDO;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\InventoryItem; use Battles\InventoryItem;
@ -6,8 +8,8 @@ use Battles\Template;
use Battles\Travel; use Battles\Travel;
use Battles\UserInfo; use Battles\UserInfo;
use Battles\UserStats; use Battles\UserStats;
use Battles\User;
ob_start("ob_gzhandler");
session_start(); session_start();
$get = filter_input(INPUT_SERVER, 'QUERY_STRING'); $get = filter_input(INPUT_SERVER, 'QUERY_STRING');
if ($get == 'exit') { if ($get == 'exit') {
@ -16,7 +18,7 @@ if ($get == 'exit') {
} }
require_once 'functions.php'; require_once 'functions.php';
$user->setOnline(); User::$current->setOnline();
// Инициализируем входящие GET\POST переменные. // Инициализируем входящие GET\POST переменные.
$goto = $_GET['goto'] ?? null; $goto = $_GET['goto'] ?? null;
@ -40,7 +42,7 @@ if ($edit) {
$destruct = $_GET['destruct'] ?? null; $destruct = $_GET['destruct'] ?? null;
if ($ups) { if ($ups) {
$user->addOnePointToStat($ups); User::$current->addOnePointToStat($ups);
} }
if ($drop) { if ($drop) {
$items = new DressedItems($_SESSION['uid']); $items = new DressedItems($_SESSION['uid']);
@ -49,16 +51,16 @@ if ($edit) {
} }
//Пока что одеваем предмет отсюда. //Пока что одеваем предмет отсюда.
if ($dress) { if ($dress) {
$dressing = new InventoryItem($db->ofetch('select * from inventory where item_id = ? ', $dress)); $dressing = new InventoryItem(DBPDO::$db->ofetch('select * from inventory where item_id = ? ', $dress));
$dressing->dressItem(); $dressing->dressItem();
unset($dressing); unset($dressing);
} }
if ($destruct) { if ($destruct) {
$q = $db->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [$user->getId(), $destruct]); $q = DBPDO::$db->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [User::$current->getId(), $destruct]);
if ($q) { if ($q) {
if (empty($q->dressed_slot)) { if (empty($q->dressed_slot)) {
InventoryItem::destroyItem($destruct); InventoryItem::destroyItem($destruct);
GameLogs::addUserLog($user->getId(), $user->getLogin() . ' выбросил предмет ' . $q->name . ' id:(cap' . $destruct . ')'); GameLogs::addUserLog(User::$current->getId(), User::$current->getLogin() . ' выбросил предмет ' . $q->name . ' id:(cap' . $destruct . ')');
err('Предмет ' . $q->name . ' выброшен.'); err('Предмет ' . $q->name . ' выброшен.');
} else { } else {
err('Ошибка: нельзя выбросить одетый предмет!'); err('Ошибка: нельзя выбросить одетый предмет!');
@ -77,16 +79,16 @@ if ($edit) {
// Подготавливаем отображение инфы и предметов. // Подготавливаем отображение инфы и предметов.
$userInfo = new UserInfo($user->getId()); $userInfo = new UserInfo(User::$current->getId());
$userStats = new UserStats($user->getId()); $userStats = new UserStats(User::$current->getId());
$data = $db->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', $user->getId()); $data = DBPDO::$db->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', User::$current->getId());
$iteminfo = []; $iteminfo = [];
foreach ($data as $row) { foreach ($data as $row) {
$iteminfo = new InventoryItem($row); $iteminfo = new InventoryItem($row);
} }
//Обработчики нажатий на кнопки. //Обработчики нажатий на кнопки.
if ($_POST['battlefield'] ?? 0 && $user->getRoom() == 1) { if ($_POST['battlefield'] ?? 0 && User::$current->getRoom() == 1) {
header('Location: zayavka.php'); header('Location: zayavka.php');
exit(); exit();
} }
@ -94,11 +96,11 @@ if ($_POST['module_quest'] ?? 0) {
header('Location: module_quest.php'); header('Location: module_quest.php');
exit(); exit();
} }
if ($_POST['move_inside'] ?? 0 && $user->getRoom() == 20) { if ($_POST['move_inside'] ?? 0 && User::$current->getRoom() == 20) {
header('Location: main.php?goto=arena'); header('Location: main.php?goto=arena');
exit(); exit();
} }
if ($_POST['move_outside'] ?? 0 && $user->getRoom() == 1) { if ($_POST['move_outside'] ?? 0 && User::$current->getRoom() == 1) {
header('Location: main.php?goto=plo'); header('Location: main.php?goto=plo');
exit(); exit();
} }
@ -109,12 +111,12 @@ if ($_POST['main_page'] ?? 0) {
if ($edit === null) { if ($edit === null) {
/* === проверяем соответствие комнаты и скрипта === */ /* === проверяем соответствие комнаты и скрипта === */
if (in_array($user->getRoom(), [20, 21, 26, 48, 51, 52, 651, 2655, 2601, 2701, 2702, 2111])) { if (in_array(User::$current->getRoom(), [20, 21, 26, 48, 51, 52, 651, 2655, 2601, 2701, 2702, 2111])) {
header('Location: city.php'); header('Location: city.php');
exit(); exit();
} }
if (in_array($user->getRoom(), [22, 23, 25, 27, 29, 30, 31, 34, 45, 53, 61, 402, 403, 600, 601, 602, 603, 620, 621, 650, 660, 661, 662, 666, 760, 1051, 1052, 1055])) { if (in_array(User::$current->getRoom(), [22, 23, 25, 27, 29, 30, 31, 34, 45, 53, 61, 402, 403, 600, 601, 602, 603, 620, 621, 650, 660, 661, 662, 666, 760, 1051, 1052, 1055])) {
header('location: ' . Travel::$roomFileName[$user->getRoom()]); header('location: ' . Travel::$roomFileName[User::$current->getRoom()]);
exit(); exit();
} }
} }
@ -134,9 +136,9 @@ function del_efs($id, $type)
// Входим и выходим если можем. // Входим и выходим если можем.
if ($goto) { if ($goto) {
$imove = true; $imove = true;
$d = db::c()->query('SELECT SUM(weight) AS sum_weight FROM inventory WHERE owner_id = ?i AND on_sale = 0', $user->getId())->fetch_assoc(); $d = db::c()->query('SELECT SUM(weight) AS sum_weight FROM inventory WHERE owner_id = ?i AND on_sale = 0', User::$current->getId())->fetch_assoc();
$eff = db::c()->query('SELECT 1 FROM `users_effects` WHERE `owner_id` = ?i AND (`type` = 14 OR `type` = 13)', $user->getId()); $eff = db::c()->query('SELECT 1 FROM `users_effects` WHERE `owner_id` = ?i AND (`type` = 14 OR `type` = 13)', User::$current->getId());
//(масса: <?= $getItemsBonuses->getItemsWeight() . '/' . $user->strength * 4 //(масса: <?= $getItemsBonuses->getItemsWeight() . '/' . User::$current->strength * 4
if ($d['sum_weight'] > $userStats->getStrength() * 4 && $goto) { if ($d['sum_weight'] > $userStats->getStrength() * 4 && $goto) {
err('У вас переполнен рюкзак, вы не можете передвигаться...'); err('У вас переполнен рюкзак, вы не можете передвигаться...');
@ -146,15 +148,15 @@ if ($goto) {
err('У вас тяжелая травма, вы не можете передвигатся...'); err('У вас тяжелая травма, вы не можете передвигатся...');
$imove = false; $imove = false;
} }
if ($goto == 'plo' && !$user->getZayavka() && $imove && $user->getRoom() != 20) { if ($goto == 'plo' && !User::$current->getZayavka() && $imove && User::$current->getRoom() != 20) {
db::c()->query('UPDATE users, online SET users.room = 20, online.room = 20 WHERE online.user_id = users.id AND online.user_id = ?i', $user->getId()); db::c()->query('UPDATE users, online SET users.room = 20, online.room = 20 WHERE online.user_id = users.id AND online.user_id = ?i', User::$current->getId());
header('Location: city.php'); header('Location: city.php');
exit("<i>Топ-топ-топ...</i>"); exit("<i>Топ-топ-топ...</i>");
} else { } else {
err('Подали заявку на бой и убегаете из клуба? Нехорошо...'); err('Подали заявку на бой и убегаете из клуба? Нехорошо...');
} }
if ($goto == 'arena' && $user->getRoom() == 20 && $imove) { if ($goto == 'arena' && User::$current->getRoom() == 20 && $imove) {
db::c()->query('UPDATE users, online SET users.room = 1, online.room = 1 WHERE online.user_id = users.id AND online.user_id = ?i', $user->getId()); db::c()->query('UPDATE users, online SET users.room = 1, online.room = 1 WHERE online.user_id = users.id AND online.user_id = ?i', User::$current->getId());
header('Location: main.php'); header('Location: main.php');
exit("<i>Топ-топ-топ...</i>"); exit("<i>Топ-топ-топ...</i>");
} }
@ -165,8 +167,8 @@ if (isset($_GET['use'])) {
} }
if ($obraz) { if ($obraz) {
$user->setShadow($obraz); User::$current->setShadow($obraz);
$user->saveShadow(); User::$current->saveShadow();
} }
if ($setShadow) { if ($setShadow) {
@ -277,12 +279,12 @@ Template::header('Игра');
</td> </td>
<td style="vertical-align: top; width: 250px"> <!-- Второй столбец --> <td style="vertical-align: top; width: 250px"> <!-- Второй столбец -->
<div> <div>
<br>Уровень: <strong><?= $user->getLevel() ?></strong> <br>Уровень: <strong><?= User::$current->getLevel() ?></strong>
<br>Опыт: <strong><?= $user->getExperience() ?></strong> <br>Опыт: <strong><?= User::$current->getExperience() ?></strong>
<br>Побед: <strong>??</strong> <br>Побед: <strong>??</strong>
<br>Поражений: <strong>??</strong> <br>Поражений: <strong>??</strong>
<br>Ничьих: <strong>??</strong> <br>Ничьих: <strong>??</strong>
<br>Деньги: <strong><?= $user->getMoney() ?></strong> кр. <br>Деньги: <strong><?= User::$current->getMoney() ?></strong> кр.
<HR> <HR>
</div> </div>
<!--Параметры--> <!--Параметры-->
@ -305,8 +307,9 @@ Template::header('Игра');
увеличений: <?= $userStats->getFreeStatPoints() ?></small><br> увеличений: <?= $userStats->getFreeStatPoints() ?></small><br>
<?php endif; ?> <?php endif; ?>
<br> <br>
Здоровье: <?= $userStats->getHealth() ?><br> <!-- #18 Разобраться в прогрессбарах -->
Пыль: <?= $userStats->getMana() ?><br> Здоровье: <progress max="<?= $userStats->getMaxHealth() ?>" value="<?= $userStats->getHealth() ?>"><?= $userStats->getHealth() ?></progress><br>
Пыль: <progress max="<?= $userStats->getMaxMana() ?>" value="<?= $userStats->getMana() ?>"><?= $userStats->getMana() ?></progress><br>
Уворот: <?= $userStats->getFullStats()->evasion ?><br> Уворот: <?= $userStats->getFullStats()->evasion ?><br>
Точность: <?= $userStats->getFullStats()->accuracy ?><br> Точность: <?= $userStats->getFullStats()->accuracy ?><br>
Шанс крита: <?= $userStats->getFullStats()->criticals ?><br> Шанс крита: <?= $userStats->getFullStats()->criticals ?><br>
@ -327,14 +330,14 @@ Template::header('Игра');
<td style="vertical-align: top;"> <td style="vertical-align: top;">
<div class="button-container"> <!--Меню-кнопки--> <div class="button-container"> <!--Меню-кнопки-->
<FORM METHOD=POST ACTION="?edit=1" name=f1> <FORM METHOD=POST ACTION="?edit=1" name=f1>
<?php if ($user->getShadow() == '0.gif' || $user->getAdmin() == 1): ?> <?php if (User::$current->getShadow() == '0.gif' || User::$current->getAdmin() == 1): ?>
<INPUT class="button primary icon user" TYPE="submit" name="setshadow" value="Образы" <INPUT class="button primary icon user" TYPE="submit" name="setshadow" value="Образы"
title="Образы"> title="Образы">
<?php endif; ?> <?php endif; ?>
<div class="button-group"> <div class="button-group">
<?php if ($user->getRoom() == 20): ?> <?php if (User::$current->getRoom() == 20): ?>
<input class="button icon move" type="submit" name="move_inside" value="Войти внутрь"> <input class="button icon move" type="submit" name="move_inside" value="Войти внутрь">
<?php elseif ($user->getRoom() == 1): ?> <?php elseif (User::$current->getRoom() == 1): ?>
<input class="button primary" type="submit" name="battlefield" value="Поединки"> <input class="button primary" type="submit" name="battlefield" value="Поединки">
<input class="button icon move" type="submit" name="move_outside" value="Выйти на улицу"> <input class="button icon move" type="submit" name="move_outside" value="Выйти на улицу">
<?php endif; ?> <?php endif; ?>

View File

@ -27,7 +27,7 @@ $gravirovka_query = null;
if ($gravirovkaText && $itemId) { if ($gravirovkaText && $itemId) {
if ($user->getMoney() >= GRAV_COST) { if ($user->getMoney() >= GRAV_COST) {
if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) { if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) {
$db->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, $user->getId(), $itemId]); DBPDO::$db->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, $user->getId(), $itemId]);
$user->setMoney($user->getMoney() - GRAV_COST); $user->setMoney($user->getMoney() - GRAV_COST);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney($user->getMoney(), $user->getId());
$status = REPAIR_STATUS['OK_GRAV_ADDED']; $status = REPAIR_STATUS['OK_GRAV_ADDED'];
@ -41,7 +41,7 @@ if ($gravirovkaText && $itemId) {
// Снять гравировку. // Снять гравировку.
if ($gravirovkaRemove) { if ($gravirovkaRemove) {
if ($user->getMoney() >= GRAV_COST) { if ($user->getMoney() >= GRAV_COST) {
$db->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]); DBPDO::$db->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]);
$user->setMoney($user->getMoney() - GRAV_COST); $user->setMoney($user->getMoney() - GRAV_COST);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney($user->getMoney(), $user->getId());
$status = REPAIR_STATUS['OK_GRAV_REMOVED']; $status = REPAIR_STATUS['OK_GRAV_REMOVED'];
@ -52,9 +52,9 @@ if ($gravirovkaRemove) {
// Ремонт 0,5 кред за единицу. // Ремонт 0,5 кред за единицу.
// Пока что лимит ремонта поставлен на 25. Дальше можно обыграть. // Пока что лимит ремонта поставлен на 25. Дальше можно обыграть.
if ($action == 'repair' && $itemId) { if ($action == 'repair' && $itemId) {
$q = $db->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId); $q = DBPDO::$db->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId);
if ($user->getMoney() > ceil($q->duration / 2)) { if ($user->getMoney() > ceil($q->duration / 2)) {
$db->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]); DBPDO::$db->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]);
$user->setMoney($user->getMoney() - ceil($q->duration / 2)); $user->setMoney($user->getMoney() - ceil($q->duration / 2));
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney($user->getMoney(), $user->getId());
GameLogs::addUserLog($user->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.'); GameLogs::addUserLog($user->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.');
@ -64,10 +64,10 @@ if ($action == 'repair' && $itemId) {
} }
} }
if ($goto == 'remont') { if ($goto == 'remont') {
$remont_query = $db->ofetchAll('SELECT item_id, name, image, durability FROM inventory WHERE item_type < 12 AND dressed_slot = 0 AND on_sale = 0 AND durability < 25 AND owner_id = ? ORDER BY name', $user->getId()); $remont_query = DBPDO::$db->ofetchAll('SELECT item_id, name, image, durability FROM inventory WHERE item_type < 12 AND dressed_slot = 0 AND on_sale = 0 AND durability < 25 AND owner_id = ? ORDER BY name', $user->getId());
} }
if ($goto == 'gravirovka') { if ($goto == 'gravirovka') {
$gravirovka_query = $db->ofetchAll('SELECT item_id, name, image, text FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND item_type = 3 AND name NOT LIKE "%Букет%" AND on_sale = 0 OR text IS NOT NULL AND owner_id = ? AND dressed_slot = 0 AND on_sale = 0 ORDER BY name', [$user->getId(), $user->getId()]); $gravirovka_query = DBPDO::$db->ofetchAll('SELECT item_id, name, image, text FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND item_type = 3 AND name NOT LIKE "%Букет%" AND on_sale = 0 OR text IS NOT NULL AND owner_id = ? AND dressed_slot = 0 AND on_sale = 0 ORDER BY name', [$user->getId(), $user->getId()]);
} }
Template::header('Кузня'); Template::header('Кузня');
?> ?>

View File

@ -1,11 +1,11 @@
<?php <?php
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\Item; use Battles\Item;
use Battles\ShopItem; use Battles\ShopItem;
use Battles\Template; use Battles\Template;
ob_start();
session_start(); session_start();
require_once 'functions.php'; require_once 'functions.php';
$saleItems = false; $saleItems = false;
@ -71,12 +71,12 @@ switch ($shopCategoryTypeNumber) {
// MUST BE ARRAY! // MUST BE ARRAY!
$iteminfo = []; $iteminfo = [];
if (!$saleItems) { if (!$saleItems) {
$shopItems = $db->ofetchAll("select * from items inner join trade_offers on id = shop_item_id where shop_id = 1 and shop_item_quantity !=0"); $shopItems = DBPDO::$db->ofetchAll("select * from items inner join trade_offers on id = shop_item_id where shop_id = 1 and shop_item_quantity !=0");
foreach ($shopItems as $shopItemObject) { foreach ($shopItems as $shopItemObject) {
$iteminfo[] = new ShopItem($shopItemObject, 'buyshop'); $iteminfo[] = new ShopItem($shopItemObject, 'buyshop');
} }
} else { } else {
$inventoryItems = $db->ofetchall("select * from inventory where on_sale = 0 and dressed_slot = 0 and durability > 0 and owner_id = ?", $user->getId()); $inventoryItems = DBPDO::$db->ofetchall("select * from inventory where on_sale = 0 and dressed_slot = 0 and durability > 0 and owner_id = ?", $user->getId());
foreach ($inventoryItems as $inventoryItemObject) { foreach ($inventoryItems as $inventoryItemObject) {
$iteminfo[] = new ShopItem($inventoryItemObject, 'sellshop'); $iteminfo[] = new ShopItem($inventoryItemObject, 'sellshop');
} }

View File

@ -1,5 +1,4 @@
<?php <?php
ob_start("ob_gzhandler");
session_start(); session_start();
require_once "functions.php"; require_once "functions.php";
if ($user['in_tower'] != 1) { if ($user['in_tower'] != 1) {