Merge branch 'master' into dev-arena

This commit is contained in:
Igor Barkov (iwork) 2022-01-27 15:39:21 +02:00
commit 7596d115fa
82 changed files with 1575 additions and 2015 deletions

View File

@ -7,25 +7,23 @@
require_once '../functions.php'; require_once '../functions.php';
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO; use Battles\Database\Db;
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::$current->getAdmin()) { if (!User::getInstance()->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::$current->getId(), strtotime('15min')); Moderation::muteChat(User::getInstance()->getId(), strtotime('15min'));
} }
if (isset($_POST['ldnick']) && isset($_POST['ldtext'])) { if (isset($_POST['ldnick']) && isset($_POST['ldtext'])) {
$u = new User($_POST['ldnick']); Moderation::addToUserLog(User::getInstance($_POST['ldnick'])->getId(), $_POST['ldtext'], User::getInstance()->getId());
Moderation::addToUserLog($u->getId(), $_POST['ldtext'], User::$current->getId());
unset($u);
} }
if (isset($_POST['syschatmsg'])) { if (isset($_POST['syschatmsg'])) {
@ -37,11 +35,11 @@ $unregisteredClans = new class {
public function getList() public function getList()
{ {
$row = DBPDO::$db->ofetchAll('SELECT * FROM clans WHERE status = 0'); $row = Db::getInstance()->ofetchAll('SELECT * FROM clans WHERE status = 0');
$i = 0; $i = 0;
while ($i < count($row)) { while ($i < count($row)) {
$id = $row[$i]->owner_id; $id = $row[$i]->owner_id;
$login = Nick::id($row[$i]->owner_id)->short(1); $login = User::getInstance($row[$i]->owner_id)->getLogin();
$fullName = $row[$i]->full_name; $fullName = $row[$i]->full_name;
$shortName = $row[$i]->short_name; $shortName = $row[$i]->short_name;
$info = nl2br($row[$i]->info); $info = nl2br($row[$i]->info);
@ -64,13 +62,13 @@ UNREGCLANLIST;
public function allowRegister($id) public function allowRegister($id)
{ {
DBPDO::$db->execute('UPDATE clans SET status = 1 WHERE status = 0 AND owner_id = ?', $id); Db::getInstance()->execute('UPDATE clans SET status = 1 WHERE status = 0 AND owner_id = ?', $id);
} }
public function disallowRegister($id) public function disallowRegister($id)
{ {
$bank = new Bank($id); $bank = new Bank($id);
DBPDO::$db->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id); Db::getInstance()->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id);
$bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id); $bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id);
} }
}; };
@ -89,12 +87,12 @@ if (isset($_GET['remclan'])) {
# Телеграф. # Телеграф.
if (!empty($_POST['receiver']) && !empty($_POST['tgmsg'])) { if (!empty($_POST['receiver']) && !empty($_POST['tgmsg'])) {
$receiver = DBPDO::$db->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']); $receiver = Db::getInstance()->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']);
telegraph($receiver->id, $_POST['tgmsg']); telegraph($receiver->id, $_POST['tgmsg']);
echo "Успешно."; echo "Успешно.";
} }
# Показывает невидимок. # Показывает невидимок.
$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'); $row = Db::getInstance()->ofetchAll('SELECT id,login FROM users LEFT JOIN users_effects ue on users.id = ue.owner_id WHERE type = 1022 ORDER BY `id` DESC');
foreach ($row as $r) { foreach ($row as $r) {
$invisList .= '<b>[id] = ' .$r->id. ', ' .$r->login. '</b><br>'; $invisList .= '<b>[id] = ' .$r->id. ', ' .$r->login. '</b><br>';
} }

View File

@ -5,12 +5,13 @@
* Project name: Battles-Game * Project name: Battles-Game
*/ */
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "../functions.php"; require_once "../functions.php";
if (!$user->getAdmin()) { if (!User::getInstance()->getAdmin()) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
exit; exit;
} }
@ -21,7 +22,7 @@ $end = $_POST['end'] ?? null;
$del = $_POST['del'] ?? null; $del = $_POST['del'] ?? null;
if ($player) { if ($player) {
$row = DBPDO::$db->ofetch('select id, login from users where id = ? or login = ?', [$player, $player]); $row = Db::getInstance()->ofetch('select id, login from users where id = ? or login = ?', [$player, $player]);
$_SESSION['player_id'] = $row->id; $_SESSION['player_id'] = $row->id;
$_SESSION['player_name'] = $row->login; $_SESSION['player_name'] = $row->login;
unset($row); unset($row);
@ -46,7 +47,7 @@ if ($del) {
$item->undressItem(7); $item->undressItem(7);
} }
} }
DBPDO::$db->execute('delete from inventory where id = ?', $del); Db::getInstance()->execute('delete from inventory where id = ?', $del);
} }
Template::header('ᐰdminка инвентаря'); Template::header('ᐰdminка инвентаря');
?> ?>

View File

@ -3,6 +3,7 @@
use Battles\Bank; use Battles\Bank;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
const SMITH = 'оружейник'; const SMITH = 'оружейник';
@ -42,9 +43,9 @@ function setProfession($name, $type, $needMoney, $needLevel)
$profId = 22; $profId = 22;
} }
if (!empty($profId)) { if (!empty($profId)) {
$user->setMoney($user->getMoney() - $needMoney); User::getInstance()->setMoney(User::getInstance()->getMoney() - $needMoney);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
db::c()->query('UPDATE `users` SET ?f = ?i WHERE `id` = ?i', 'prof' . $type, $profId, $user->getId()); db::c()->query('UPDATE `users` SET ?f = ?i WHERE `id` = ?i', 'prof' . $type, $profId, User::getInstance()->getId());
$deloText = "{$user['login']} купил профессию «{$name}» в академии за {$needMoney} кр."; $deloText = "{$user['login']} купил профессию «{$name}» в академии за {$needMoney} кр.";
GameLogs::addUserLog($_SESSION['uid'], $deloText); GameLogs::addUserLog($_SESSION['uid'], $deloText);
$user['prof' . $type] = true; $user['prof' . $type] = true;
@ -66,7 +67,7 @@ if ($get == 'medic') {
} }
if ($get == 'exit') { if ($get == 'exit') {
db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 2702, `online`.`room` = 2702 WHERE `users`.`id` = ?i AND `online`.`id` = ?i', $user->getId(), $user->getId()); db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 2702, `online`.`room` = 2702 WHERE `users`.`id` = ?i AND `online`.`id` = ?i', User::getInstance()->getId(), User::getInstance()->getId());
header('Location: city.php'); header('Location: city.php');
} }
Template::header('Академия'); Template::header('Академия');
@ -79,8 +80,8 @@ Template::header('Академия');
<div><?= $status ?></div> <div><?= $status ?></div>
<div class="appblock appblock-main"> <div class="appblock appblock-main">
<span class="legend">Информация</span> <span class="legend">Информация</span>
<span class="wrap">Кредиты<span class="num"><?= $user->getMoney() ?></span></span> <span class="wrap">Кредиты<span class="num"><?= User::getInstance()->getMoney() ?></span></span>
<span class="wrap">Уровень персонажа<span class="num"><?= $user->getLevel() ?></span></span> <span class="wrap">Уровень персонажа<span class="num"><?= User::getInstance()->getLevel() ?></span></span>
</div> </div>
<div class="appblock"> <div class="appblock">
<span class="legend">Наёмник</span> <span class="legend">Наёмник</span>

View File

@ -5,11 +5,12 @@ use Battles\GameConfigs;
use Battles\Rooms; use Battles\Rooms;
use Battles\Template; use Battles\Template;
use Exceptions\GameException; use Exceptions\GameException;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
const SUCCESS = "Успешная операция!"; const SUCCESS = "Успешная операция!";
$bank = new Bank($user->getId()); $bank = new Bank(User::getInstance()->getId());
$status = ''; $status = '';
$toid = $_POST['to_id'] ?? 0; $toid = $_POST['to_id'] ?? 0;
@ -19,20 +20,20 @@ try {
// Зачисление кредитов на счёт. // Зачисление кредитов на счёт.
if ($submit === 'depositMoney' && $summa) { if ($submit === 'depositMoney' && $summa) {
$operation = $bank->depositMoney($summa); $operation = $bank->depositMoney($summa);
$user->setMoney($operation['walletMoney']); User::getInstance()->setMoney($operation['walletMoney']);
$bank->setMoney($operation['bankMoney']); $bank->setMoney($operation['bankMoney']);
$status = SUCCESS; $status = SUCCESS;
} }
// Снятие кредитов со счёта. // Снятие кредитов со счёта.
if ($submit === 'withdrawMoney' && $summa) { if ($submit === 'withdrawMoney' && $summa) {
$operation = $bank->withdrawMoney($summa); $operation = $bank->withdrawMoney($summa);
$user->setMoney($operation['walletMoney']); User::getInstance()->setMoney($operation['walletMoney']);
$bank->setMoney($operation['bankMoney']); $bank->setMoney($operation['bankMoney']);
$status = SUCCESS; $status = SUCCESS;
} }
// Перевод кредитов на другой счёт. // Перевод кредитов на другой счёт.
if ($submit === 'sendMoney' && $summa && $toid) { if ($submit === 'sendMoney' && $summa && $toid) {
$user->setMoney($bank->sendMoney($toid, $summa)); User::getInstance()->setMoney($bank->sendMoney($toid, $summa));
$status = SUCCESS; $status = SUCCESS;
} }
} catch (GameException $e) { } catch (GameException $e) {
@ -49,7 +50,7 @@ Template::header('Банк');
<div class="appblock appblock-main"> <div class="appblock appblock-main">
<span class="wrap">На счету: <span class="num"><?= $bank->getMoney() ?></span></span> <span class="wrap">На счету: <span class="num"><?= $bank->getMoney() ?></span></span>
<hr> <hr>
<span class="wrap">На руках: <span class="num"><?= $user->getMoney() ?></span></span> <span class="wrap">На руках: <span class="num"><?= User::getInstance()->getMoney() ?></span></span>
</div> </div>
<div class="appblock"> <div class="appblock">
<span class="legend">Работа со счётом</span> <span class="legend">Работа со счётом</span>

10
buy.php
View File

@ -1,11 +1,11 @@
<?php <?php
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\User; use Battles\User;
require_once "functions.php"; require_once "functions.php";
if (User::$current->getBattle()) { if (User::getInstance()->getBattle()) {
exit(); exit();
} }
const PRICES = [ const PRICES = [
@ -26,7 +26,7 @@ const PRICES = [
'unclone' => 25, 'unclone' => 25,
]; ];
$check_bonuses = DBPDO::$db->ofetch('select 1 from users_bonuses where user_id = ?', User::$current->getId()); $check_bonuses = Db::getInstance()->ofetch('select 1 from users_bonuses where user_id = ?', User::getInstance()->getId());
if (!$check_bonuses) { if (!$check_bonuses) {
exit('Запрещено: Вам нельзя покупать бонусы.'); exit('Запрещено: Вам нельзя покупать бонусы.');
@ -35,12 +35,12 @@ if (!$check_bonuses) {
function buy_bonus($name): bool function buy_bonus($name): bool
{ {
global $prices; global $prices;
$bank = new Bank(User::$current->getId()); $bank = new Bank(User::getInstance()->getId());
if ($bank->getMoney() <= PRICES[$name]) { if ($bank->getMoney() <= PRICES[$name]) {
return false; return false;
} }
$query = sprintf('update users_bonuses set %s = %s + 1 where user_id = ?', $name, $name); $query = sprintf('update users_bonuses set %s = %s + 1 where user_id = ?', $name, $name);
DBPDO::$db->execute($query, User::$current->getId()); Db::getInstance()->execute($query, User::getInstance()->getId());
$bank->setMoney($bank->getMoney() - $prices[$name]); $bank->setMoney($bank->getMoney() - $prices[$name]);
return true; return true;
} }

View File

@ -1,11 +1,11 @@
<?php <?php
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\User; use Battles\User;
require_once "functions.php"; require_once "functions.php";
if (!User::$current->getClan() || User::$current->getBattle()) { if (!User::getInstance()->getClan() || User::getInstance()->getBattle()) {
exit(); exit();
} }
const PRICES = [ const PRICES = [
@ -26,10 +26,10 @@ const PRICES = [
'unclone' => 25, 'unclone' => 25,
]; ];
$check_owner = DBPDO::$db->ofetch('select short_name from clans where owner_id = ?', User::$current->getId()); $check_owner = Db::getInstance()->execute('select short_name from clans where owner_id = ?', User::getInstance()->getId())->fetchColumn();
$check_bonuses = DBPDO::$db->ofetch('select 1 from clan_bonuses where short_name = ?', User::$current->getClan()); $check_bonuses = Db::getInstance()->execute('select count(*) from clan_bonuses where short_name = ?', User::getInstance()->getClan())->fetchColumn();
if (User::$current->getClan() !== $check_owner->short_name) { if (User::getInstance()->getClan() !== $check_owner) {
exit('Запрещено: Вы не глава клана.'); exit('Запрещено: Вы не глава клана.');
} }
if (!$check_bonuses) { if (!$check_bonuses) {
@ -38,14 +38,14 @@ if (!$check_bonuses) {
function buy_bonus($name): bool function buy_bonus($name): bool
{ {
global $prices; $bank = new Bank(User::getInstance()->getId());
$bank = new Bank(User::$current->getId());
if ($bank->getMoney() <= PRICES[$name]) { if ($bank->getMoney() <= PRICES[$name]) {
return false; return false;
} }
$query = sprintf('update clan_bonuses set %s = %s + 1 where short_name = ?', $name, $name); $query = sprintf('update clan_bonuses set %s = %s + 1 where short_name = ?', $name, $name);
DBPDO::$db->execute($query, User::$current->getClan()); Db::getInstance()->execute($query, User::getInstance()->getClan());
$bank->setMoney($bank->getMoney() - $prices[$name]); $bank->setMoney($bank->getMoney() - PRICES[$name]);
return true; return true;
} }

View File

@ -1,9 +1,9 @@
<?php <?php
use Battles\Template; use Battles\Template, Battles\User;
require_once('functions.php'); require_once('functions.php');
if ($user->getRoom() == 51) { if (User::getInstance()->getRoom() == 51) {
header('location: city.php'); header('location: city.php');
exit; exit;
} }
@ -26,8 +26,8 @@ $map_user = loadmap_cell();
if ($_GET['exit_forest'] == 'true') { if ($_GET['exit_forest'] == 'true') {
if ($forest['room']) { if ($forest['room']) {
#db::c()->query('DELETE FROM `forest_bots` WHERE `user` = ?i AND `group` = ?i', $user['id'], $forest['id']); #getInstance::c()->query('DELETE FROM `forest_bots` WHERE `user` = ?i AND `group` = ?i', $user['id'], $forest['id']);
#db::c()->query('DELETE FROM `forest_items` WHERE `user` = ?i AND `group` = ?i', $user['id'], $forest['id']); #getInstance::c()->query('DELETE FROM `forest_items` WHERE `user` = ?i AND `group` = ?i', $user['id'], $forest['id']);
db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 51, `online`.`room` = 51 WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $user['id']); db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 51, `online`.`room` = 51 WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $user['id']);
db::c()->query('DELETE FROM `forest` WHERE `user` = ?i', $user['id']); db::c()->query('DELETE FROM `forest` WHERE `user` = ?i', $user['id']);
unset($forest); unset($forest);

View File

@ -1,9 +1,9 @@
<?php <?php
use Battles\Template; use Battles\Template, Battles\User;
require_once "functions.php"; require_once "functions.php";
if ($user->getRoom() == 403) { if (User::getInstance()->getRoom() == 403) {
include "startpodzemel.php"; include "startpodzemel.php";
if ($_GET['act'] == "cexit") { if ($_GET['act'] == "cexit") {
$das = mysql_query("select glava,glav_id from `labirint` where user_id='" . $user['id'] . "'"); $das = mysql_query("select glava,glav_id from `labirint` where user_id='" . $user['id'] . "'");
@ -38,7 +38,7 @@ if ($user->getRoom() == 403) {
'Ключик №9', 'Ключик №9',
'Ключик №10' 'Ключик №10'
]; ];
db::c()->query('DELETE FROM inventory WHERE name IN ("?s") AND owner_id = ?i', implode(",", $items_to_delete), $user->getId()); db::c()->query('DELETE FROM inventory WHERE name IN ("?s") AND owner_id = ?i', implode(",", $items_to_delete), User::getInstance()->getId());
} }
} }
$e = mysql_query("DELETE FROM labirint WHERE user_id='" . $user['id'] . "'"); $e = mysql_query("DELETE FROM labirint WHERE user_id='" . $user['id'] . "'");
@ -51,7 +51,7 @@ if ($user->getRoom() == 403) {
{ {
$frt = mysql_query("select user_id from `labirint` where glava='" . $glava . "'"); $frt = mysql_query("select user_id from `labirint` where glava='" . $glava . "'");
while ($rbb = mysql_fetch_array($frt)) { while ($rbb = mysql_fetch_array($frt)) {
addchp('<b>' . $user->getLogin() . '</b> поднял предмет "' . $mis . '". ', '{[]}' . Nick::id($rbb["user_id"])->short() . '{[]}'); addchp('<b>' . User::getInstance()->getLogin() . '</b> поднял предмет "' . $mis . '". ', '{[]}' . Nick::id($rbb["user_id"])->short() . '{[]}');
} }
} }
} }

View File

@ -1,5 +1,8 @@
<?php <?php
if ($user->getRoom() == 403) {
use Battles\User;
if (User::getInstance()->getRoom() == 403) {
$s = db::c()->query('SELECT * FROM podzem2 WHERE name= "?s"', $mir['name'])->fetch_assoc(); $s = db::c()->query('SELECT * FROM podzem2 WHERE name= "?s"', $mir['name'])->fetch_assoc();
$rooms[0] = ""; $rooms[0] = "";

207
cave.php
View File

@ -9,141 +9,35 @@ use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
//require_once 'cave/cave_bots.php'; //require_once 'cave/cave_bots.php';
$userslots = ['sergi', 'kulon', 'perchi', 'weap', 'bron', 'r1', 'r2', 'r3', 'helm', 'shit', 'boots', 'rybax', 'plaw', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10']; $userslots = ['sergi', 'kulon', 'perchi', 'weap', 'bron', 'r1', 'r2', 'r3', 'helm', 'shit', 'boots', 'rybax', 'plaw', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10'];
function cancarry($m, $u) function cancarry($m, $uid)
{ {
global $user; if (!$uid) {
if (!$u) { $uid = User::getInstance()->getId();
$u = $user['id'];
} }
$bp = mysql_fetch_array(mysql_query("SELECT SUM(`massa`) AS `massa`, SUM(`gmeshok`) AS `gmeshok` FROM `inventory` WHERE `owner` = '$u[id]' AND `dressed` = 1 AND `setsale` = 0")); $weight = \Battles\Database\Db::getInstance()->execute('select sum(weight) from inventory where owner_id = ? and on_sale = 0', $uid)->fetchColumn();
$mw = 40 * $user['level'] + $user['vinos'] + $bp['gmeshok']; $maxWeight = \Battles\Database\Db::getInstance()->execute('select strength * 4 from users where id = ?', $uid)->fetchColumn();
if ($bp['massa'] + $m > $mw) { return $weight + $m > $maxWeight ? false : true;
return false;
}
return true;
} }
function placeinbackpack($qty, $userid = 0) function placeinbackpack($qty, $userid = null)
{ {
global $user; if (is_null($userid)) {
if (!$userid) { $userid = User::getInstance()->getId();
$userid = $user['id'];
} }
if ($userid == $user['id']) { $user1 = $userid === User::getInstance()->getId() ? User::getInstance() : User::getInstance($userid);
$user1 = $user; $count = \Battles\Database\Db::getInstance()->execute('select count(*) from inventory where owner_id = ? and on_sale = 0', $user1->getId())->fetchColumn();
} else { return $count + $qty <= $user1->getLevel() * 10 + 5;
$user1 = mysql_fetch_array(mysql_query("SELECT `id`, `level` FROM `users` WHERE `id` = '$user1[id]' LIMIT 1"));
}
$cnt = mysql_fetch_assoc(mysql_query("SELECT COUNT(`id`) AS `cnt` FROM `inventory` WHERE `owner` = '$user1[id]' AND `dressed` = 0 AND `setsale` = 0"));
return $cnt['cnt'] + $qty <= backpacksize($user1['id']);
} }
function backpacksize($u = 0) // x, $btl
{ // $l * 10 +5 // x, 0, $otherbots
$l = 0; function battlewithbot($b, $otherbots = [], $noredir = 0)
if ($u) {
$l = $u['level'];
}
if ($l == 0) {
return 75;
}
if ($l == 1) {
return 100;
}
if ($l == 2) {
return 125;
}
if ($l == 3) {
return 175;
}
if ($l == 4) {
return 225;
}
if ($l == 5) {
return 325;
}
if ($l == 6) {
return 425;
}
if ($l == 7) {
return 525;
}
if ($l == 8) {
return 625;
}
if ($l == 9) {
return 725;
}
if ($l == 10) {
return 825;
}
if ($l == 11) {
return 925;
}
if ($l >= 12) {
return 1025;
}
}
function battlewithbot($b, $name = '', $time = 3, $blood = 1, $group = 1, $battleid = 0, $otherbots = [], $noredir = 0, $userid = 0, $type = 1)
{ {
global $user; $user1 = User::getInstance();
if (!$userid) {
$user1 = $user;
} elseif (is_array($userid)) {
$user1 = $userid;
} else {
$user1 = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '$userid' LIMIT 1"));
}
$bot = mysql_fetch_array(mysql_query("SELECT `login`, `maxhp` FROM `users` WHERE `id` = '$b' LIMIT 1")); $bot = mysql_fetch_array(mysql_query("SELECT `login`, `maxhp` FROM `users` WHERE `id` = '$b' LIMIT 1"));
if (!$name) {
$name = $bot['login']; $name = $bot['login'];
}
if ($battleid) {
$botid = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `bots` WHERE `prototype` = '$b' AND `battle` = '$battleid' LIMIT 1"));
} elseif ($group) {
$arha = mysql_fetch_array(mysql_query("SELECT * FROM `bots` WHERE `prototype` = '$b' ORDER BY `id` DESC LIMIT 1"));
$battleid = $arha['battle'];
$botid = $arha['id'];
}
if (@$battleid > 0) {
$bd = mysql_fetch_array(mysql_query("SELECT * FROM `battle` WHERE `id` = '$battleid' LIMIT 1"));
$battle = unserialize($bd['teams']);
$t1 = explode(";", $bd['t1']);
$t2 = explode(";", $bd['t2']);
$ak = array_keys($battle[$t2[0]]);
$battle[$user1['id']] = $battle[$ak[0]];
foreach ($battle[$user1['id']] as $k => $v) {
$battle[$user1['id']][$k] = [0, 0, time()];
$battle[$k][$user1['id']] = [0, 0, time()];
}
if (in_array($botid, $t1)) {
$ttt = 2;
} else {
$ttt = 1;
}
if ($user1['invis'] == 1) {
GameLogs::addBattleLog($battleid, '<span class=date>' . date("H:i") . '</span> <b>невидимка</b> вмешался в поединок!<BR>');
} else {
GameLogs::addBattleLog($battleid, '<span class=date>' . date("H:i") . '</span> ' . Nick::id($user['id'])->short() . ' вмешался в поединок!<BR>');
}
mysql_query('UPDATE `battle` SET `teams` = \'' . serialize($battle) . '\', `t' . $ttt . '` = CONCAT(`t' . $ttt . '`,\';' . $user1['id'] . '\') WHERE `id` = ' . $battleid . ' LIMIT 1');
mysql_query("UPDATE `users` SET `battle` = " . $battleid . ", `zayavka` = 0 WHERE `id`= " . $user1['id'] . " LIMIT 1");
if (!$noredir) {
header("Location: fbattle.php");
}
} else {
mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$name', '$b', '', '" . $bot['maxhp'] . "')"); mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$name', '$b', '', '" . $bot['maxhp'] . "')");
$hps[$b] = $bot['maxhp']; $hps[$b] = $bot['maxhp'];
@ -178,7 +72,7 @@ function battlewithbot($b, $name = '', $time = 3, $blood = 1, $group = 1, $battl
$others .= "<span class=date>" . date("H:i") . "</span> <span class=B2>$botname</span> вмешался в поединок.<BR>"; $others .= "<span class=date>" . date("H:i") . "</span> <span class=B2>$botname</span> вмешался в поединок.<BR>";
$t2 .= ";$botid"; $t2 .= ";$botid";
} }
mysql_query("INSERT INTO `battle` (`id`, `coment`, `teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`, `date`) VALUES (NULL, '', '" . serialize($teams) . "', '" . $time . "', '$type', '0', '" . $user1['id'] . "', '" . $t2 . "', '" . time() . "', '" . time() . "', '$blood', '" . date("Y-m-d H:i") . "')"); mysql_query("INSERT INTO `battle` (`id`, `coment`, `teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`, `date`) VALUES (NULL, '', '" . serialize($teams) . "', '" . 3 . "', 1, 0, '" . $user1['id'] . "', '" . $t2 . "', '" . time() . "', '" . time() . "', 10, '" . date("Y-m-d H:i") . "')");
$battleid = mysql_insert_id(); $battleid = mysql_insert_id();
mysql_query("UPDATE `bots` SET `battle` = {$battleid} WHERE $cond"); mysql_query("UPDATE `bots` SET `battle` = {$battleid} WHERE $cond");
@ -193,7 +87,7 @@ function battlewithbot($b, $name = '', $time = 3, $blood = 1, $group = 1, $battl
if (!$noredir) { if (!$noredir) {
header("Location: fbattle.php"); header("Location: fbattle.php");
} }
}
return $battleid; return $battleid;
} }
@ -290,15 +184,15 @@ function makedeath()
{ {
global $user, $floor, $loses, $x, $y, $dir; global $user, $floor, $loses, $x, $y, $dir;
$cavedata = CAVE_DATA ?? []; $cavedata = CAVE_DATA ?? [];
if (!isset($cavedata[$user->getRoom()]['x' . $floor])) { if (!isset($cavedata[User::getInstance()->getRoom()]['x' . $floor])) {
$floor = 1; $floor = 1;
loadmap(); loadmap();
} }
mysql_query("UPDATE `caveparties` SET `floor` = $floor, `x` = '" . $cavedata[$user->getRoom()]['x' . $floor] . "', `y` = '" . $cavedata[$user->getRoom()]['y' . $floor] . "', `dir` = '" . $cavedata[$user->getRoom()]['dir' . $floor] . "', `loses` = (`loses`+1) WHERE `user` = '$user[id]' LIMIT 1"); mysql_query("UPDATE `caveparties` SET `floor` = $floor, `x` = '" . $cavedata[User::getInstance()->getRoom()]['x' . $floor] . "', `y` = '" . $cavedata[User::getInstance()->getRoom()]['y' . $floor] . "', `dir` = '" . $cavedata[User::getInstance()->getRoom()]['dir' . $floor] . "', `loses` = (`loses`+1) WHERE `user` = '$user[id]' LIMIT 1");
mysql_query('UPDATE `users` SET `hp` = 1 WHERE `id` = "' . $user['id'] . '" LIMIT 1'); mysql_query('UPDATE `users` SET `hp` = 1 WHERE `id` = "' . $user['id'] . '" LIMIT 1');
$x = $cavedata[$user->getRoom()]['x' . $floor]; $x = $cavedata[User::getInstance()->getRoom()]['x' . $floor];
$y = $cavedata[$user->getRoom()]['y' . $floor]; $y = $cavedata[User::getInstance()->getRoom()]['y' . $floor];
$dir = $cavedata[$user->getRoom()]['dir' . $floor]; $dir = $cavedata[User::getInstance()->getRoom()]['dir' . $floor];
updparties(); updparties();
$loses++; $loses++;
} }
@ -444,7 +338,7 @@ while ($rec = mysql_fetch_assoc($r)) {
$party[] = $rec; $party[] = $rec;
} }
if ($user->getRoom() == 621) { if (User::getInstance()->getRoom() == 621) {
$base = "/underdesigns/alchcave"; $base = "/underdesigns/alchcave";
} }
@ -525,19 +419,15 @@ if ($_GET['useitem']) {
$tx = $x; $tx = $x;
$ty = $y + 1; $ty = $y + 1;
} }
if (@$_GET['useitem']) { if ($_GET['useitem'] && file_exists("underground/objects/" . User::getInstance()->getRoom() . ".php")) {
if (file_exists("underground/objects/$user->getRoom().php")) { include "underground/objects/" . User::getInstance()->getRoom() . ".php";
include "underground/objects/$user->getRoom().php";
}
} }
[$t, $obj] = explode("/", $map[$ty * 2][$tx * 2]); [$t, $obj] = explode("/", $map[$ty * 2][$tx * 2]);
if ($t == "o") { if ($t == "o" && $obj == 500) {
if ($obj == 500) {
$report = "В этот сундук уже кто-то заглядывал"; $report = "В этот сундук уже кто-то заглядывал";
} }
}
mysql_query("UNLOCK TABLES"); mysql_query("UNLOCK TABLES");
} }
@ -623,7 +513,7 @@ if ($wander && !isset($_GET['attack'])) {
$ty = $v['y'] + 2; $ty = $v['y'] + 2;
} }
if ($user->getRoom() == 74 || $user->getRoom() == 76) { if (User::getInstance()->getRoom() == 74 || User::getInstance()->getRoom() == 76) {
if (strpos($map[$ty][$tx], 's/') !== false && !@$mapbots[$ty][$tx]) { if (strpos($map[$ty][$tx], 's/') !== false && !@$mapbots[$ty][$tx]) {
break; break;
} }
@ -691,8 +581,8 @@ if ($moved && (substr($map[$y * 2][$x * 2], 0, 1) === "e" || substr($map[$y * 2]
$tx = $x; $tx = $x;
$ty = $y; $ty = $y;
$tmp = explode("/", $map[$y * 2][$x * 2]); $tmp = explode("/", $map[$y * 2][$x * 2]);
if (file_exists("underground/events/$user->getRoom().php")) { if (file_exists("underground/events/" . User::getInstance()->getRoom() . ".php")) {
include("underground/events/$user->getRoom().php"); include("underground/events/" . User::getInstance()->getRoom() . ".php");
} }
} }
@ -717,7 +607,7 @@ if ($ambushes[$y * 2][$x * 2 - 2] && $map[$y * 2][$x * 2 - 1] == 0) {
if ($ax && $ay && $user['hp'] > 0) { if ($ax && $ay && $user['hp'] > 0) {
$cavedata = CAVE_DATA ?? []; $cavedata = CAVE_DATA ?? [];
if (!($cavedata[$user->getRoom()]['x' . $floor] == $x && $cavedata[$user->getRoom()]['y' . $floor] == $y)) { if (!($cavedata[User::getInstance()->getRoom()]['x' . $floor] == $x && $cavedata[User::getInstance()->getRoom()]['y' . $floor] == $y)) {
if ($ax < $x) { if ($ax < $x) {
$dir1 = 0; $dir1 = 0;
} elseif ($ax > $x) { } elseif ($ax > $x) {
@ -759,7 +649,7 @@ if ($_GET['takeitem']) {
$report = "Ваш рюкзак перегружен."; $report = "Ваш рюкзак перегружен.";
} else { } else {
$destiny = 0; $destiny = 0;
$taken = ShopItem::giveNewItem($it['item'], User::$current->getId()); $taken = ShopItem::giveNewItem($it['item'], User::getInstance()->getId());
if (@$taken['error']) { if (@$taken['error']) {
$report = $taken['error']; $report = $taken['error'];
} else { } else {
@ -826,7 +716,7 @@ if (@$_GET['attack']) {
} elseif (isset($rec['bot'])) { } elseif (isset($rec['bot'])) {
$btl = $rec['battle']; $btl = $rec['battle'];
if ($btl > 0) { if ($btl > 0) {
battlewithbot(CaveBots::$bots[$rec['bot']], "", "", 10, 0, 0, $btl); battlewithbot(CaveBots::$bots[$rec['bot']], $btl);
} else { } else {
$firstbot = CaveBots::$bots[$rec['bot']]; $firstbot = CaveBots::$bots[$rec['bot']];
$otherbots = []; $otherbots = [];
@ -843,7 +733,7 @@ if (@$_GET['attack']) {
$rec['cnt']--; $rec['cnt']--;
} }
} }
$btl = battlewithbot($firstbot, "", "", 10, 0, 0, 0, $otherbots); $btl = battlewithbot($firstbot, 0, $otherbots);
mysql_query("UPDATE `cavebots` SET `battle` = '$btl' WHERE `leader` = '$user[caveleader]' AND `x` = '$bx' AND `y` = $by AND `floor` = '$floor'"); mysql_query("UPDATE `cavebots` SET `battle` = '$btl' WHERE `leader` = '$user[caveleader]' AND `x` = '$bx' AND `y` = $by AND `floor` = '$floor'");
} }
} }
@ -882,7 +772,7 @@ if (@$_GET['exit']) {
} }
} }
mysql_query("DELETE FROM `inventory` WHERE `owner` = '$user[id]' AND `foronetrip` = 1"); mysql_query("DELETE FROM `inventory` WHERE `owner` = '$user[id]' AND `foronetrip` = 1");
gotoroom($user->getRoom() - 1); gotoroom(User::getInstance()->getRoom() - 1);
} }
$standingon = $map[$y * 2][$x * 2]; $standingon = $map[$y * 2][$x * 2];
@ -1294,10 +1184,10 @@ Template::header('cave');
el2.style.visibility = "visible"; el2.style.visibility = "visible";
} }
</script> </script>
<div id=hint3 class=ahint></div> <div id=hint3 class=ahint></div>
<div style="z-index: 100; background-color: #E4F2DF; border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute; left: 0; top: 0; visibility: hidden; cursor:pointer;" <div style="z-index: 100; background-color: #E4F2DF; border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute; left: 0; top: 0; visibility: hidden; cursor:pointer;"
id="oMenu"></div> id="oMenu"></div>
<div style="z-index: 100; background-color: #E4F2DF; border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute; left: 0; top: 0; visibility: hidden; cursor:pointer;" <div style="z-index: 100; background-color: #E4F2DF; border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute; left: 0; top: 0; visibility: hidden; cursor:pointer;"
id="oMenu2"></div> id="oMenu2"></div>
<? <?
@ -1450,9 +1340,9 @@ function drawmap($map1, $players, $x, $y, $direction)
$ret .= drawobject2($aMap[$yy][$xx], $x, $y); $ret .= drawobject2($aMap[$yy][$xx], $x, $y);
} }
$rrm = $user->getRoom(); $rrm = User::getInstance()->getRoom();
if (isset($dialogs[CaveBots::$bots[$data[1]]]) && (CaveBots::$bots[$data[1]] == 11147 && $user->getRoom() == 74)) { if (isset($dialogs[CaveBots::$bots[$data[1]]]) && (CaveBots::$bots[$data[1]] == 11147 && User::getInstance()->getRoom() == 74)) {
$ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? "onclick=\"speakattackmenu(event);\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />"; $ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? "onclick=\"speakattackmenu(event);\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
} else { } else {
$ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? " onclick=\"document.location.href='cave.php?attack=1';\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />"; $ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? " onclick=\"document.location.href='cave.php?attack=1';\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
@ -1542,7 +1432,7 @@ function drawmap($map1, $players, $x, $y, $direction)
$left = $imgdata[$x][$y]["x"][1]; $left = $imgdata[$x][$y]["x"][1];
$top = $imgdata[$x][$y]["y"] + $ht; $top = $imgdata[$x][$y]["y"] + $ht;
} }
$rrm = $user->getRoom(); $rrm = User::getInstance()->getRoom();
if (!isset($imgmap[$obj])) { if (!isset($imgmap[$obj])) {
$ret .= " $ret .= "
@ -1587,7 +1477,7 @@ function drawmap($map1, $players, $x, $y, $direction)
$left = $imgdata[$x][$y]["x"][1]; $left = $imgdata[$x][$y]["x"][1];
$top = $imgdata[$x][$y]["y"] + $ht; $top = $imgdata[$x][$y]["y"] + $ht;
} }
$rrm = $user->getRoom(); $rrm = User::getInstance()->getRoom();
if (!isset($imgmap[$obj])) { if (!isset($imgmap[$obj])) {
$ret .= " $ret .= "
" . ($y == 1 && $x == 3 ? "<a href=\"cave.php?useitem=1\">" : "") . " " . ($y == 1 && $x == 3 ? "<a href=\"cave.php?useitem=1\">" : "") . "
@ -1748,7 +1638,7 @@ function drawmap($map1, $players, $x, $y, $direction)
} }
$objInWall = explode('/', $map[3][$wall]); $objInWall = explode('/', $map[3][$wall]);
if ($objInWall[1] == "o") { if ($objInWall[1] == "o") {
if ($user->getRoom() == 83 && !(!$direction && (($x == 13 && $y == 4) || ($x == 12 && $y == 4)))) { // исключение 2-ух клеток в комнате 82 if (User::getInstance()->getRoom() == 83 && !(!$direction && (($x == 13 && $y == 4) || ($x == 12 && $y == 4)))) { // исключение 2-ух клеток в комнате 82
$ret .= drawobject('//' . $objInWall[2], 3, $i); $ret .= drawobject('//' . $objInWall[2], 3, $i);
} }
} }
@ -1914,11 +1804,12 @@ progress_update();
} }
?> ?>
<table width="100%" border="0" cellspacing="0" cellpadding="0"> <table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr> <tr>
<td valign="top" align="left"> <td valign="top" align="left">
<br> <br>
<table width="400" border="0" cellspacing="1" cellpadding="0" bgcolor="#000000" style="margin-left: 21px;"> <table width="400" border="0" cellspacing="1" cellpadding="0" bgcolor="#000000"
style="margin-left: 21px;">
<? <?
foreach ($party as $k => $v) { foreach ($party as $k => $v) {
if ($v["user"] == $user["id"]) { if ($v["user"] == $user["id"]) {
@ -1971,10 +1862,10 @@ progress_update();
<td width=540> <td width=540>
<div style="text-align:right;padding-right:30px"> <div style="text-align:right;padding-right:30px">
<font style='font-size:14px; color:#8f0000'><b><? <font style='font-size:14px; color:#8f0000'><b><?
$dMap = unserialize(mysql_result(mysql_query("SELECT `map` FROM `cavemaps` WHERE `floor` = $floor AND `room` = " . ($user->getRoom() - 1)), 0, 0)); $dMap = unserialize(mysql_result(mysql_query("SELECT `map` FROM `cavemaps` WHERE `floor` = $floor AND `room` = " . (User::getInstance()->getRoom() - 1)), 0, 0));
$cPlace = $dMap[$y * 2][$x * 2]; $cPlace = $dMap[$y * 2][$x * 2];
$tmp = explode("/", $cPlace); $tmp = explode("/", $cPlace);
if ($user->getRoom() == 621) { if (User::getInstance()->getRoom() == 621) {
if ($floor == 1) { if ($floor == 1) {
echo 'Проклятый Рудник, 1 этаж'; echo 'Проклятый Рудник, 1 этаж';
} elseif ($floor == 2) { } elseif ($floor == 2) {
@ -1993,7 +1884,7 @@ progress_update();
?> ?>
</td> </td>
</tr> </tr>
</table> </table>
<? <?
if ($user["login"] == "Rallo Tabs") { if ($user["login"] == "Rallo Tabs") {

24
ch.php
View File

@ -1,15 +1,15 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
DBPDO::$db->execute('update online set real_time = ? where user_id = ?', [time(), User::$current->getId()]); Db::getInstance()->execute('update online set real_time = ? where user_id = ?', [time(), User::getInstance()->getId()]);
if (isset($_GET['online']) && $_GET['online'] != null) { if (isset($_GET['online']) && $_GET['online'] != null) {
if ($_GET['room'] && (int)$_GET['room'] < 500) { if ($_GET['room'] && (int)$_GET['room'] < 500) {
$user->setRoom($_GET['room']); User::getInstance()->setRoom($_GET['room']);
} }
if ($u->i()['caveleader'] > 0) { if ($u->i()['caveleader'] > 0) {
$data = db::c()->query(' $data = db::c()->query('
@ -35,13 +35,13 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
ORDER BY ORDER BY
`u`.`login` `u`.`login`
'); ');
$ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[$user->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>"; $ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>";
$ch1 = '_active'; $ch1 = '_active';
$ch2 = '_passive'; $ch2 = '_passive';
$ch3 = '_passive'; $ch3 = '_passive';
$ch4 = '_passive'; $ch4 = '_passive';
$ch5 = '_passive'; $ch5 = '_passive';
} elseif ($user->getRoom() == 760) { } elseif (User::getInstance()->getRoom() == 760) {
$forest = db::c()->query('SELECT `id`, `room`, `time`, `user`, `data` FROM `forest` WHERE `user` = "' . $user['id'] . '" LIMIT 1')->fetch_assoc(); $forest = db::c()->query('SELECT `id`, `room`, `time`, `user`, `data` FROM `forest` WHERE `user` = "' . $user['id'] . '" LIMIT 1')->fetch_assoc();
$sp = db::c()->query('SELECT `id`, `room`, `user` FROM `forest` WHERE `room` = "' . $forest['room'] . '"'); $sp = db::c()->query('SELECT `id`, `room`, `user` FROM `forest` WHERE `room` = "' . $forest['room'] . '"');
while ($pl = $sp->fetch_assoc()) { while ($pl = $sp->fetch_assoc()) {
@ -100,18 +100,18 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
WHERE WHERE
`o`.`id` = `u`.`id` AND `o`.`id` = `u`.`id` AND
(`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND (`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND
`o`.`room` = "' . $user->getRoom() . '" `o`.`room` = "' . User::getInstance()->getRoom() . '"
ORDER BY ORDER BY
`u`.`login` `u`.`login`
'); ');
$ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[$user->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>"; $ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>";
$ch1 = '_active'; $ch1 = '_active';
$ch2 = '_passive'; $ch2 = '_passive';
$ch3 = '_passive'; $ch3 = '_passive';
$ch4 = '_passive'; $ch4 = '_passive';
$ch5 = '_passive'; $ch5 = '_passive';
} }
Template::header(sprintf('%s (%s)', $rooms[$user->getRoom()], mysql_num_rows($data))); Template::header(sprintf('%s (%s)', $rooms[User::getInstance()->getRoom()], mysql_num_rows($data)));
?> ?>
<script> <script>
function fastshow(content) { function fastshow(content) {
@ -366,7 +366,7 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
$ks++; $ks++;
$lastpost = $math[1]; $lastpost = $math[1];
unset($math[3]); unset($math[3]);
} elseif ((strpos($math[3], "private") === FALSE) /*&& ($user->getRoom() == $math[4])*/) { } elseif ((strpos($math[3], "private") === FALSE) /*&& (User::getInstance()->getRoom() == $math[4])*/) {
$times = ''; $times = '';
$soundON = ''; $soundON = '';
if ((strpos($math[3], "[" . $user['login'] . "]") > 0) || ($math[2] == $user['login'])) { if ((strpos($math[3], "[" . $user['login'] . "]") > 0) || ($math[2] == $user['login'])) {
@ -414,7 +414,7 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
$_GET['text'] = preg_replace('/private \[klan-([a-zA-Z]*)\]/', '', $_GET['text']); $_GET['text'] = preg_replace('/private \[klan-([a-zA-Z]*)\]/', '', $_GET['text']);
if (empty($user->getClan())) { if (empty(User::getInstance()->getClan())) {
$_GET['text'] = str_replace('private [klan]', '', $_GET['text']); $_GET['text'] = str_replace('private [klan]', '', $_GET['text']);
$_GET['text'] = str_replace('private [klan]', 'private [klan-' . $user['klan'] . ']', $_GET['text']); $_GET['text'] = str_replace('private [klan]', 'private [klan-' . $user['klan'] . ']', $_GET['text']);
} else { } else {
@ -461,7 +461,7 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
if ($action != 1) { if ($action != 1) {
$file = 'tmp/chat.txt'; $file = 'tmp/chat.txt';
if (filesize("tmp/chat.txt") > 100 * 1024) { if (filesize("tmp/chat.txt") > 100 * 1024) {
$line = "\r\n:[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . $user->getRoom() . "]\r\n"; $line = "\r\n:[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . User::getInstance()->getRoom() . "]\r\n";
// Пишем содержимое в файл, // Пишем содержимое в файл,
// используя флаг FILE_APPEND flag для дописывания содержимого в конец файла // используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время // и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
@ -469,7 +469,7 @@ if (isset($_GET['online']) && $_GET['online'] != null) {
file_put_contents($file, $line, FILE_APPEND | LOCK_EX); file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
echo "1"; echo "1";
} else { } else {
$line = ":[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . $user->getRoom() . "]\r\n"; $line = ":[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . User::getInstance()->getRoom() . "]\r\n";
file_put_contents($file, $line, FILE_APPEND | LOCK_EX); file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
echo "2"; echo "2";
} }

View File

@ -6,11 +6,11 @@
*/ */
use Battles\Chat; use Battles\Chat;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
require_once "config.php"; require_once "config.php";
$chat = new Chat(new DBPDO()); $chat = new Chat(Db::getInstance());
if (!empty($_POST['msg'])) { if (!empty($_POST['msg'])) {
$chat->addMessage($_POST['msg']); $chat->addMessage($_POST['msg']);
} }

View File

@ -1,4 +1,7 @@
<? <?
use Battles\User;
include('config.php'); include('config.php');
function addch($text, $who, $room) { function addch($text, $who, $room) {
@ -33,12 +36,12 @@ if($_GET['id'] == 1) {
} elseif($_GET['id'] == 6) { } elseif($_GET['id'] == 6) {
$user = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `room` FROM `users` WHERE `id` = "'.(int)$_GET['user'].'" LIMIT 1')); $user = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `room` FROM `users` WHERE `id` = "'.(int)$_GET['user'].'" LIMIT 1'));
if(isset($user['id'])) { if(isset($user['id'])) {
addch('<font color=red>Внимание!</font> Ваш бой не может начаться по причине <b>Группа не набрана</b>', $user['login'], $user->getRoom()); addch('<font color=red>Внимание!</font> Ваш бой не может начаться по причине <b>Группа не набрана</b>', $user['login'], User::getInstance()->getRoom());
} }
} elseif($_GET['id'] == 7) { } elseif($_GET['id'] == 7) {
$user = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `room` FROM `users` WHERE `id` = "'.(int)$_GET['user'].'" LIMIT 1')); $user = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `room` FROM `users` WHERE `id` = "'.(int)$_GET['user'].'" LIMIT 1'));
if(isset($user['id'])) { if(isset($user['id'])) {
addch('<font color=red>Внимание!</font> Ваш бой начался.', $user['login'], $user->getRoom()); addch('<font color=red>Внимание!</font> Ваш бой начался.', $user['login'], User::getInstance()->getRoom());
} }
} else { } else {
exit; exit;

113
city.php
View File

@ -3,193 +3,194 @@
* Центральная площадь * Центральная площадь
*/ */
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
if ($user->getZayavka()) { if (User::getInstance()->getZayavka()) {
exit; exit;
} }
$online = DBPDO::$db->fetchColumn('select count(*) from online where real_time >= ?', time()-60); $online = Db::getInstance()->fetchColumn('select count(*) from online where real_time >= ?', time()-60);
$location = explode('/', filter_input(INPUT_SERVER, 'QUERY_STRING')); $location = explode('/', filter_input(INPUT_SERVER, 'QUERY_STRING'));
switch ($location[0]) { switch ($location[0]) {
default: default:
break; break;
case 'cp': case 'cp':
Battles\Travel::toRoom(20,$user->getRoom()); Battles\Travel::toRoom(20,User::getInstance()->getRoom());
break; break;
case 'strah': case 'strah':
Battles\Travel::toRoom(21,$user->getRoom()); Battles\Travel::toRoom(21,User::getInstance()->getRoom());
break; break;
case 'bps': case 'bps':
Battles\Travel::toRoom(26,$user->getRoom()); Battles\Travel::toRoom(26,User::getInstance()->getRoom());
break; break;
case 'ps': case 'ps':
Battles\Travel::toRoom(51,$user->getRoom()); Battles\Travel::toRoom(51,User::getInstance()->getRoom());
break; break;
case 'zaliv': case 'zaliv':
Battles\Travel::toRoom(2111,$user->getRoom()); Battles\Travel::toRoom(2111,User::getInstance()->getRoom());
break; break;
case 'zamk': case 'zamk':
Battles\Travel::toRoom(2601,$user->getRoom()); Battles\Travel::toRoom(2601,User::getInstance()->getRoom());
break; break;
case 'abog': case 'abog':
Battles\Travel::toRoom(2655,$user->getRoom()); Battles\Travel::toRoom(2655,User::getInstance()->getRoom());
break; break;
case 'torg': case 'torg':
Battles\Travel::toRoom(2702,$user->getRoom()); Battles\Travel::toRoom(2702,User::getInstance()->getRoom());
break; break;
case 'got': case 'got':
if ($user->getRoom() == 20) { if (User::getInstance()->getRoom() == 20) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level1': case 'level1':
Battles\Travel::toRoom(1,$user->getRoom()); Battles\Travel::toRoom(1,User::getInstance()->getRoom());
break; break;
case 'level7': case 'level7':
Battles\Travel::toRoom(21,$user->getRoom()); Battles\Travel::toRoom(21,User::getInstance()->getRoom());
break; break;
case 'level8': case 'level8':
Battles\Travel::toRoom(26,$user->getRoom()); Battles\Travel::toRoom(26,User::getInstance()->getRoom());
break; break;
case 'level13': case 'level13':
header('location: quest_room.php'); header('location: quest_room.php');
break; break;
case 'level222': case 'level222':
Battles\Travel::toRoom(2702,$user->getRoom()); Battles\Travel::toRoom(2702,User::getInstance()->getRoom());
break; break;
case 'level17': case 'level17':
Battles\Travel::toRoom(50,$user->getRoom()); Battles\Travel::toRoom(50,User::getInstance()->getRoom());
break; break;
case 'level2': case 'level2':
Battles\Travel::toRoom(22,$user->getRoom()); Battles\Travel::toRoom(22,User::getInstance()->getRoom());
break; break;
case 'level4': case 'level4':
Battles\Travel::toRoom(23,$user->getRoom()); Battles\Travel::toRoom(23,User::getInstance()->getRoom());
break; break;
case 'level6': case 'level6':
Battles\Travel::toRoom(27,$user->getRoom()); Battles\Travel::toRoom(27,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 21) { } elseif (User::getInstance()->getRoom() == 21) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level4': case 'level4':
Battles\Travel::toRoom(20,$user->getRoom()); Battles\Travel::toRoom(20,User::getInstance()->getRoom());
break; break;
case 'level3': case 'level3':
Battles\Travel::toRoom(2111,$user->getRoom()); Battles\Travel::toRoom(2111,User::getInstance()->getRoom());
break; break;
case 'level13': case 'level13':
Battles\Travel::toRoom(34,$user->getRoom()); Battles\Travel::toRoom(34,User::getInstance()->getRoom());
break; break;
case 'level5': case 'level5':
Battles\Travel::toRoom(29,$user->getRoom()); Battles\Travel::toRoom(29,User::getInstance()->getRoom());
break; break;
case 'level16': case 'level16':
Battles\Travel::toRoom(31,$user->getRoom()); Battles\Travel::toRoom(31,User::getInstance()->getRoom());
break; break;
case 'level14': case 'level14':
Battles\Travel::toRoom(30,$user->getRoom()); Battles\Travel::toRoom(30,User::getInstance()->getRoom());
break; break;
case 'level650': case 'level650':
Battles\Travel::toRoom(650,$user->getRoom()); Battles\Travel::toRoom(650,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 2111) { } elseif (User::getInstance()->getRoom() == 2111) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level1': case 'level1':
Battles\Travel::toRoom(21,$user->getRoom()); Battles\Travel::toRoom(21,User::getInstance()->getRoom());
break; break;
case 'level203': case 'level203':
Battles\Travel::toRoom(1055,$user->getRoom()); Battles\Travel::toRoom(1055,User::getInstance()->getRoom());
break; break;
case 'level1000': case 'level1000':
Battles\Travel::toRoom(620,$user->getRoom()); Battles\Travel::toRoom(620,User::getInstance()->getRoom());
break; break;
case 'room666': case 'room666':
//Нет на карте //Нет на карте
//Battles\Travel::toRoom(666,$user->getRoom()); //Battles\Travel::toRoom(666,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 2601) { } elseif (User::getInstance()->getRoom() == 2601) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level4': case 'level4':
Battles\Travel::toRoom(26,$user->getRoom()); Battles\Travel::toRoom(26,User::getInstance()->getRoom());
break; break;
case 'level55': case 'level55':
Battles\Travel::toRoom(2655,$user->getRoom()); Battles\Travel::toRoom(2655,User::getInstance()->getRoom());
break; break;
case 'level1': case 'level1':
Battles\Travel::toRoom(37,$user->getRoom()); Battles\Travel::toRoom(37,User::getInstance()->getRoom());
break; break;
case 'level1051': case 'level1051':
Battles\Travel::toRoom(1051,$user->getRoom()); Battles\Travel::toRoom(1051,User::getInstance()->getRoom());
break; break;
case 'level5': case 'level5':
Battles\Travel::toRoom(404,$user->getRoom()); Battles\Travel::toRoom(404,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 2701) { } elseif (User::getInstance()->getRoom() == 2701) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level1': case 'level1':
Battles\Travel::toRoom(2111,$user->getRoom()); Battles\Travel::toRoom(2111,User::getInstance()->getRoom());
break; break;
case 'level2': case 'level2':
Battles\Travel::toRoom(402,$user->getRoom()); Battles\Travel::toRoom(402,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 2702) { } elseif (User::getInstance()->getRoom() == 2702) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level10': case 'level10':
Battles\Travel::toRoom(20,$user->getRoom()); Battles\Travel::toRoom(20,User::getInstance()->getRoom());
break; break;
case 'level6': case 'level6':
Battles\Travel::toRoom(61,$user->getRoom()); Battles\Travel::toRoom(61,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 2655) { } elseif (User::getInstance()->getRoom() == 2655) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level10': case 'level10':
Battles\Travel::toRoom(2601,$user->getRoom()); Battles\Travel::toRoom(2601,User::getInstance()->getRoom());
break; break;
case 'level2055': case 'level2055':
Battles\Travel::toRoom(603,$user->getRoom()); Battles\Travel::toRoom(603,User::getInstance()->getRoom());
break; break;
} }
} elseif ($user->getRoom() == 26) { } elseif (User::getInstance()->getRoom() == 26) {
switch ($location[1]) { switch ($location[1]) {
default: default:
break; break;
case 'level4': case 'level4':
Battles\Travel::toRoom(20,$user->getRoom()); Battles\Travel::toRoom(20,User::getInstance()->getRoom());
break; break;
case 'level3': case 'level3':
Battles\Travel::toRoom(2601,$user->getRoom()); Battles\Travel::toRoom(2601,User::getInstance()->getRoom());
break; break;
case 'level660': case 'level660':
Battles\Travel::toRoom(660,$user->getRoom()); Battles\Travel::toRoom(660,User::getInstance()->getRoom());
break; break;
case 'level7': case 'level7':
Battles\Travel::toRoom(777,$user->getRoom()); Battles\Travel::toRoom(777,User::getInstance()->getRoom());
break; break;
case 'level56': case 'level56':
Battles\Travel::toRoom(401,$user->getRoom()); Battles\Travel::toRoom(401,User::getInstance()->getRoom());
break; break;
} }
} }
@ -197,7 +198,7 @@ switch ($location[0]) {
Template::header('city'); Template::header('city');
echo sprintf('<div style="text-align: right;">Сейчас в игре: %s игроков.></div>', $online); echo sprintf('<div style="text-align: right;">Сейчас в игре: %s игроков.></div>', $online);
if (in_array($user->getRoom(), [20, 21, 26, 2601, 2655, 2111, 2701, 2702])) { if (in_array(User::getInstance()->getRoom(), [20, 21, 26, 2601, 2655, 2111, 2701, 2702])) {
/* Улицы: /* Улицы:
* 20 Центральная * 20 Центральная
* 21 Страшилкина * 21 Страшилкина
@ -208,5 +209,5 @@ if (in_array($user->getRoom(), [20, 21, 26, 2601, 2655, 2111, 2701, 2702])) {
* 2701 С ещё одним ристалищем? * 2701 С ещё одним ристалищем?
* 2702 Торговая * 2702 Торговая
*/ */
Battles\City::showStreet($user->getRoom()); Battles\City::showStreet(User::getInstance()->getRoom());
} }

View File

@ -8,13 +8,12 @@ use Battles\Template;
use Battles\User; use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
if (!User::$current->getClan()) { if (!User::getInstance()->getClan()) {
exit('Ошибка! Вы не состоите в клане!'); exit('Ошибка! Вы не состоите в клане!');
} }
Clan::$current = new Clan(); if (User::getInstance()->getClan() != Clan::getInstance()->getClanShortName()) {
if (User::$current->getClan() != Clan::$current->getClanShortName()) { exit('Ошибка! Клана ' . User::getInstance()->getClan() . ' не существует!');
exit('Ошибка! Клана ' . User::$current->getClan() . ' не существует!');
} }
Template::header('clan'); Template::header('clan');
@ -48,23 +47,23 @@ Template::header('clan');
<?php if (!empty($_POST['login']) && !empty($_POST['action'])): ?> <?php if (!empty($_POST['login']) && !empty($_POST['action'])): ?>
<span class="error"> <span class="error">
<?php if ($_POST['action'] == 'add_member'): ?> <?php if ($_POST['action'] == 'add_member'): ?>
<?= Clan::$current->addMember($_POST['login']) ?> <?= Clan::getInstance()->addMember($_POST['login']) ?>
<?php endif; ?> <?php endif; ?>
<?php if ($_POST['action'] == 'remove_member'): ?> <?php if ($_POST['action'] == 'remove_member'): ?>
<?= Clan::$current->removeMember($_POST['login']) ?> <?= Clan::getInstance()->removeMember($_POST['login']) ?>
<?php endif; ?> <?php endif; ?>
<?php if ($_POST['action'] == 'change_owner'): ?> <?php if ($_POST['action'] == 'change_owner'): ?>
<?= Clan::$current->changeOwner($_POST['login']) ?> <?= Clan::getInstance()->changeOwner($_POST['login']) ?>
<?php endif; ?> <?php endif; ?>
</span> </span>
<?php endif; ?> <?php endif; ?>
</div> </div>
<div class="row"> <div class="row">
<div class="column left"> <div class="column left">
<h3><img src="./i/clan/<?= Clan::$current->getClanShortName() ?>.png" <h3><img src="./i/clan/<?= Clan::getInstance()->getClanShortName() ?>.png"
alt="<?= Clan::$current->getClanShortName() ?>"><?= Clan::$current->getClanName() ?></h3> alt="<?= Clan::getInstance()->getClanShortName() ?>"><?= Clan::getInstance()->getClanName() ?></h3>
<?php if (Clan::$current->getClanOwnerId() === User::$current->getId()): ?> <?php if (Clan::getInstance()->getClanOwnerId() === User::getInstance()->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="Принять в клан">
@ -93,7 +92,7 @@ Template::header('clan');
<th id='c1'>Имя</th> <th id='c1'>Имя</th>
<th id='c2'>Местонахождение</th> <th id='c2'>Местонахождение</th>
</tr> </tr>
<?php foreach (Clan::$current->getMemberlist() as $member): ?> <?php foreach (Clan::getInstance()->getMemberlist() as $member): ?>
<tr> <tr>
<td> <td>
<?php if ($member->clan_owner): ?> <?php if ($member->clan_owner): ?>

View File

@ -1,317 +0,0 @@
<?php
use Battles\Chat;
use Battles\GameLogs;
use Battles\Template;
require_once "functions.php";
$owntravma = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = " . $user['id'] . " AND (type=13 OR type=12 OR type=14) limit 1;"));
$klan = mysql_fetch_array(mysql_query("SELECT * FROM `clans` WHERE `id` = '{$user['klan']}' LIMIT 1;"));
$cc_date = mysql_fetch_array(mysql_query("SELECT * FROM `variables` WHERE `var`='cc_time' LIMIT 1;"));
$ccd = $cc_date['value'];
if ($_POST['admin_start']) {
$tm = time();
mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
exit("<script>location.href='clan_castle.php';</script>");
}
if ($_POST['admin_start1']) {
$tm = time() - 900;
mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
exit("<script>location.href='clan_castle.php';</script>");
}
if ($_POST['add_zay']) {
mysql_query("INSERT INTO `clan_castle` VALUES ('{$user['id']}','{$user['klan']}');");
exit("<script>location.href='clan_castle.php';</script>");
}
Template::header('Замок Мэра');
?>
<script>
function refreshPeriodic() {
location.href = 'clan_castle.php';
timerID = setTimeout("refreshPeriodic()", 30000);
}
timerID = setTimeout("refreshPeriodic()", 30000);
</script>
<TABLE border=0 width=600 cellspacing="0" cellpadding="0" align=left>
<tr>
<td><h3>Замок Мэра</td>
</tr>
<tr>
<td>
<FORM action="city.php" method=GET><INPUT TYPE="submit" value="Вернуться в Город" name="bps"></FORM>
</td>
</tr>
<tr>
<td>Добро пожаловать в Замок доброго и справедливого Мэра!
Если Вы заинтерисованы в обладании правами на Замок, либо считаете что обладаете достаточными способностями
для исполнения
обязанностей Мэра, приглашаем Вас и Ваших единомышлеников поселиться в Замке! <br/> <br/>
Внимание! Администрация не несет ответственности за возможные конфликты на основе спора о правах обладания
Замком,
целость и сохранность Ваших личных вещей, здоровье и жизни посетителей!<br/>
<?php
$own = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner'"));
if ($own['value'] > 0) {
$tmp_k = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$own['value']}'"));
}
echo '<br />Над Замком развевается флаг ';
if ($tmp_k['name']) {
echo '<strong>клана <img title="' . $tmp_k['name'] . '" src="i/clan/' . $tmp_k['name'] . '.png">' . $tmp_k['name'] . '</strong><br />';
} else {
echo '<strong>сил Хаоса</strong><br />';
}
if ($user->getAdmin()) {
echo '<FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Админ: запустить" name="admin_start"><br></FORM>';
echo '<FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Админ: старт боя" name="admin_start1"><br></FORM>';
}
if ($ccd >= time()) {
echo "Следующая битва: " . (date("j.m", $ccd)) . " в " . (date("H:i", $ccd));
} elseif ($ccd < time() && ($ccd + 900) >= time()) {
$zays = [];
echo "Заявили права на Замок Мэра:";
echo '<TABLE border=0 width=100% cellspacing="0" cellpadding="0" align=left>';
$all_c = mysql_query("SELECT * FROM `clan_castle`;");
while ($a_zay = mysql_fetch_array($all_c)) {
$zays[] = $a_zay['clan'];
$tmp_k = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$a_zay['clan']}' LIMIT 1;"));
echo '<tr><td><strong>Клан <img title="' . $tmp_k['name'] . '" src="i/clan/' . $tmp_k['name'] . '.png">' . $tmp_k['name'] . '</strong></td></tr>';
}
if (empty($zays)) {
echo '<tr><td><strong>Ждем смелых ...</strong></td></tr>';
}
echo '</TABLE>';
echo "<br/>Прием заявок до: <strong>" . (date("H:i", $ccd + 900)) . "</strong>";
$own = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
if ($klan['glava'] == $user['id'] && !in_array($user['klan'], $zays) && $user['klan'] != $own['value']) {
echo "<br />Прием заявок от глав кланов:";
echo '<tr><td><FORM action="clan_castle.php" method=POST><INPUT TYPE="submit" value="Заявиться" name="add_zay"></FORM></td></tr>';
}
} elseif (($ccd + 900) < time() && ($ccd + 90 + 900) >= time()) {
$zays = [];
$all_zay = mysql_query("SELECT * FROM `clan_castle`;");
while ($a_zay = mysql_fetch_array($all_zay)) {
$cur_c = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `klan`='{$a_zay['clan']}' AND `room`='45';"));
for ($cc = 0; $cc < $cur_c; $cc++) {
$zays[] = $a_zay['clan'];
}
}
$own = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
shuffle($zays);
$lucky = $zays[array_rand($zays)];
mysql_query("UPDATE `variables` SET `value`='{$lucky}' WHERE `var`='castle_att';");
$tmp_k = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$lucky}' LIMIT 1;"));
if ($own['value'] > 0) {
$tmp_o = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$own['value']}' LIMIT 1;"));
}
if ($tmp_k) {
echo 'Внимание!<img title="' . $tmp_k['name'] . '" src="i/clan/' . $tmp_k['name'] . '.png"><strong>' . $tmp_k['name'] . '</strong> собираются штурмовать замок';
}
if ($tmp_k && $own['value'] > 0) {
echo '<img title="' . $tmp_o['name'] . '" src="i/clan/' . $tmp_o['name'] . '.png"><strong>' . $tmp_o['name'] . '</strong>!';
}
if ($tmp_k && !$own['value'] > 0) {
echo '!';
}
} elseif (($ccd + 90 + 900) <= time()) {
$att = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_att' LIMIT 1;"));
$own = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'castle_owner' LIMIT 1;"));
$at_t = [];
$ow_t = [];
if ($att['value'] > 0) {
$att_r = mysql_query("SELECT `id` FROM `users` WHERE `klan`='{$att['value']}' AND `room`='45';");
while ($a = mysql_fetch_array($att_r)) {
$at_on = mysql_fetch_array(mysql_query("select `id` from `online` WHERE login_time >= " . (time() - 60) . " AND `id` = '{$a['id']}' LIMIT 1;"));
if ($at_on[0]) {
$at_t[] = $a['id'];
}
}
}
if ($own['value'] > 0) {
$def_r = mysql_query("SELECT `id` FROM `users` WHERE `klan`='{$own['value']}' AND `room`='45';");
while ($o = mysql_fetch_array($def_r)) {
$df_on = mysql_fetch_array(mysql_query("select `id` from `online` WHERE login_time >= " . (time() - 60) . " AND `id` = '{$o['id']}' LIMIT 1;"));
if ($df_on[0]) {
$ow_t[] = $o['id'];
}
}
}
if (empty($at_t)) {
echo "Смелых так и не нашлось...<br/>";
} elseif (empty($ow_t) && ($own['value'] > 0)) {
echo "Хозяева слили замок без боя...<br/>";
$cc_own = mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_owner' LIMIT 1;"));
$cc_k = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_own['value']}' LIMIT 1;"));
$cc_att = mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_att' LIMIT 1;"));
$cc_a = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_att['value']}' LIMIT 1;"));
Chat::addSYSMessage('Клан <img title="' . $cc_a['name'] . '" src="i/clan/' . $cc_a['name'] . '.png">' . $cc_a['name'] . ' без боя забрал у <strong>клана <img title="' . $cc_k['name'] . '" src="i/clan/' . $cc_k['name'] . '.gif">' . $cc_k['name'] . '</strong> Замок Мэра');
$c_prev = mysql_fetch_array(mysql_query("SELECT `glava`,`align` FROM `clans` WHERE `id`='{$own['value']}' LIMIT 1;"));
mysql_query("UPDATE `users` SET `align`='{$c_prev['align']}',`abil`='' WHERE `id`='{$c_prev['glava']}';");
mysql_query("UPDATE `variables` SET `value`='{$att['value']}' WHERE `var`='castle_owner';");
mysql_query("UPDATE `variables` SET `value`='0' WHERE `var`='castle_att';");
mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
$c_lead = mysql_fetch_array(mysql_query("SELECT `glava` FROM `clans` WHERE `id`='{$att['value']}' LIMIT 1;"));
$abil = [];
for ($i = 0; $i < 10; $i++) {
$abil[$i] = 9;
}
mysql_query("UPDATE `users` SET `align`='7.97',`abil`='" . serialize($abil) . "' WHERE `id`='{$c_lead['glava']}';");
mysql_query("DELETE FROM `clan_castle`");
} elseif ($own['value'] == 0) {
//побоище против ботов
//ставим ботов
$bots_raw = ["2897", "2897", "2897", "2897", "2897", "2897", "2897", "2897", "2897", "2897", "4150", "4150", "4156", "4156", "4156", "4156",
"2895", "2895", "4158", "4158", "4158", "4158", "4158", "2900"];
$bots = [];
foreach ($bots_raw as $bot_id) {
if ($bot_id > 0) {
$b_pers = mysql_fetch_array(mysql_query("SELECT `login`,`maxhp` FROM users WHERE id='{$bot_id}' LIMIT 1;"));
$bot_hp = $b_pers['maxhp'];
$bot_name = $b_pers['login'];
$nb = mysql_fetch_array(mysql_query("SELECT count(`id`) FROM `bots` WHERE `name` LIKE '" . $bot_name . "%';"));
mysql_query("INSERT INTO `bots` (`name`,`prototype`,`battle`,`hp`) values ('" . $bot_name . " " . ($nb[0] + 1) . "','" . $bot_id . "','','" . $bot_hp . "');");
$bots[] = mysql_insert_id();
}
}
//отаке!
$teams = [];
foreach ($at_t as $b) {
foreach ($bots as $gf) {
$teams[$gf][$b] = [0, 0, time()];
$teams[$b][$gf] = [0, 0, time()];
}
}
mysql_query("INSERT INTO `battle`
(
`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`,`blood`
)
VALUES
(
NULL,'','" . serialize($teams) . "','3','1','0','" . implode(";", $at_t) . "','" . implode(";", $bots) . "','" . time() . "','" . time() . "','0'
)");
$id = mysql_insert_id();
// создаем лог
$rr = "<b>";
foreach ($at_t as $k => $v) {
if ($k != 0) {
$rr .= ", ";
$rrc .= ", ";
}
$rr .= Nick::id($v)->full(1);
$rrc .= Nick::id($v)->short();
addchp('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}');
}
$rr .= "</b> и <b>";
$rrc .= "</b> и <b>";
foreach ($bots as $k => $v) {
if ($k != 0) {
$rr .= ", ";
$rrc .= ", ";
}
$rr .= Nick::id($v)->full(1);
$rrc .= Nick::id($v)->short();
}
$rr .= "</b>";
addch("<a href=logs.php?log=" . $id . " target=_blank>Поединок</a> между <B>" . $rrc . "</B> начался. ", $user->getRoom());
mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <BR>');");
GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <BR>");
$add_time = time();
// всех в БОЙ!!!
foreach ($at_t as $k => $v) {
mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
}
foreach ($bots as $k => $v) {
mysql_query("UPDATE `bots` SET `battle` ={$id} WHERE `id`= {$v}");
}
mysql_query("DELETE FROM `clan_castle`");
} elseif (!empty($at_t) && !empty($ow_t)) {
//побоище
$teams = [];
foreach ($at_t as $b) {
foreach ($ow_t as $gf) {
$teams[$gf][$b] = [0, 0, time()];
$teams[$b][$gf] = [0, 0, time()];
}
}
mysql_query("INSERT INTO `battle`
(
`id`,`coment`,`teams`,`timeout`,`type`,`status`,`t1`,`t2`,`to1`,`to2`,`blood`
)
VALUES
(
NULL,'','" . serialize($teams) . "','3','1','0','" . implode(";", $at_t) . "','" . implode(";", $ow_t) . "','" . time() . "','" . time() . "','0'
)");
$id = mysql_insert_id();
// создаем лог
$rr = "<b>";
foreach ($at_t as $k => $v) {
if ($k != 0) {
$rr .= ", ";
$rrc .= ", ";
}
$rr .= Nick::id($v)->full(1);
$rrc .= Nick::id($v)->short();
addchp('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}');
}
$rr .= "</b> и <b>";
$rrc .= "</b> и <b>";
foreach ($ow_t as $k => $v) {
if ($k != 0) {
$rr .= ", ";
$rrc .= ", ";
}
$rr .= Nick::id($v)->full(1);
$rrc .= Nick::id($v)->short();
addchp('<font color=red>Внимание!</font> Ваш бой начался!<BR>\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}');
}
$rr .= "</b>";
addch("<a href=logs.php?log=" . $id . " target=_blank>Поединок</a> между <B>" . $rrc . "</B> начался. ", $user->getRoom());
mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <BR>');");
GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <BR>");
$add_time = time();
// всех в БОЙ!!!
foreach ($at_t as $k => $v) {
mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
}
foreach ($ow_t as $k => $v) {
mysql_query("UPDATE users SET `battle` ={$id},`zayavka`=0 WHERE `id`= {$v}");
}
mysql_query("DELETE FROM `clan_castle`");
}
$tm = time() + 23 * 60 * 60;
mysql_query("UPDATE `variables` SET `value`='0' WHERE `var`='castle_att';");
mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';");
mysql_query("DELETE FROM `clan_castle`");
}
?>
</td>
</tr>
</table>
<div align=right><img width="260" src="i/castle.jpg"></div>

View File

@ -1,28 +1,30 @@
<?php <?php
// Здание регистратуры!
use Battles\Bank; use Battles\Bank;
use Battles\GameConfigs; use Battles\GameConfigs;
use Battles\Rooms; use Battles\Rooms;
use Battles\Template; use Battles\Template;
use Battles\User;
use Battles\Database\Db;
require_once 'functions.php'; require_once 'functions.php';
$userClan = db::c()->query('SELECT short_name, full_name, info FROM clans where owner_id = ?i', $user->getId())->fetch_object(); $userClan = Db::getInstance()->ofetch('select * from clans where owner_id = ?', User::getInstance()->getId());
$clanFullName = $_POST['clan_full_name'] ?? ''; $clanFullName = $_POST['clan_full_name'] ?? '';
$clanShortName = $_POST['clan_short_name'] ?? ''; $clanShortName = $_POST['clan_short_name'] ?? '';
$clanInfo = $_POST['clan_info'] ?? ''; $clanInfo = $_POST['clan_info'] ?? '';
$userBank = new Bank($user->getId()); $userBank = new Bank(User::getInstance()->getId());
if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { 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::getInstance()->execute('select count(*) from users_effects where type = 20 and owner_id = ?', User::getInstance()->getId())->fetchColumn();
$name_check = db::c()->query('SELECT owner_id FROM clans WHERE full_name = "?s" OR short_name = "?s"', $clanFullName, $clanShortName); $name_check = Db::getInstance()->execute('select count(*) from clans where full_name = ? or short_name = ?', [$clanFullName, $clanShortName])->fetchColumn();
$errorMessage = []; $errorMessage = [];
if (GameConfigs::CLAN['clan_register_lock']) { if (GameConfigs::CLAN['clan_register_lock']) {
$errorMessage[10] = 'Регистрация кланов закрыта! <BR>'; $errorMessage[10] = 'Регистрация кланов закрыта! <BR>';
} }
if ($user->getAlign()) { if (User::getInstance()->getAlign()) {
$errorMessage[0] = 'Вы уже имеете направленность!. <BR>'; $errorMessage[0] = 'Вы уже имеете направленность!. <BR>';
} }
if ($user->getClan()) { if (User::getInstance()->getClan()) {
$errorMessage[1] = 'Вы уже состоите в клане!. <BR>'; $errorMessage[1] = 'Вы уже состоите в клане!. <BR>';
} }
if (GameConfigs::CLAN['clan_register_cost'] >= $userBank->getMoney()) { if (GameConfigs::CLAN['clan_register_cost'] >= $userBank->getMoney()) {
@ -34,11 +36,11 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) {
if (!$name_check) { if (!$name_check) {
$errorMessage[4] = 'Клан с такими данными уже существует.<br>'; $errorMessage[4] = 'Клан с такими данными уже существует.<br>';
} }
if (!$errorMessage || $user->getAdmin()) { if (!$errorMessage || User::getInstance()->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::getInstance()->execute('insert into clans (owner_id, full_name, short_name, info) values (?,?,?,?)', [User::getInstance()->getId(), $clanFullName, $clanShortName, $clanInfo]);
$userBank->setMoney($userBank->getMoney() - GameConfigs::CLAN['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::getInstance()->getId(), 'clanRegister');
// Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит. // Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит.
$userClan = new stdClass(); $userClan = new stdClass();
$userClan->full_name = $clanFullName; $userClan->full_name = $clanFullName;
@ -61,10 +63,16 @@ if ($userClan): ?>
<div> <div>
<fieldset style="display: inline;"> <fieldset style="display: inline;">
<legend>Заявка на регистрацию</legend> <legend>Заявка на регистрацию</legend>
<label>
<input size=30 disabled value="<?= $userClan->full_name ?>"> <input size=30 disabled value="<?= $userClan->full_name ?>">
<input size=30 disabled value="<?= $userClan->short_name ?>"><BR> </label>
<label>
<input size=30 disabled value="<?= $userClan->short_name ?>">
</label><BR>
<BR> <BR>
<textarea cols=80 rows=10 disabled><?= nl2br($userClan->info) ?></textarea><BR> <label>
<textarea cols=80 rows=10 disabled><?= nl2br($userClan->info) ?></textarea>
</label><BR>
<button disabled>Заявка подана и рассматривается</button> <button disabled>Заявка подана и рассматривается</button>
</fieldset> </fieldset>
</div> </div>
@ -73,12 +81,18 @@ if ($userClan): ?>
<form method="post"> <form method="post">
<fieldset style="display: inline;"> <fieldset style="display: inline;">
<legend>Заявка на регистрацию</legend> <legend>Заявка на регистрацию</legend>
<label>
<input size=30 name="clan_full_name" placeholder="Название клана" value="<?= $clanFullName ?>"> <input size=30 name="clan_full_name" placeholder="Название клана" value="<?= $clanFullName ?>">
</label>
<label>
<input size=30 name="clan_short_name" maxlength="5" placeholder="Английская аббревиатура" <input size=30 name="clan_short_name" maxlength="5" placeholder="Английская аббревиатура"
value="<?= $clanShortName ?>"><BR> value="<?= $clanShortName ?>">
</label><BR>
<BR> <BR>
<textarea cols=80 rows=10 name="clan_info" <label>
placeholder="Информация о клане для энциклопедии"><?= nl2br($clanInfo) ?></textarea><BR> <textarea cols=80 rows=10 name="clan_info"
placeholder="Информация о клане для энциклопедии"><?= nl2br($clanInfo) ?></textarea>
</label><BR>
<input type="submit" value="Подать заявку"> <input type="submit" value="Подать заявку">
</fieldset> </fieldset>
</form> </form>

View File

@ -1,22 +1,25 @@
<?php <?php
/** /** Список кланов и игроков в клане?
* Copyright (c) 2018. * Copyright (c) 2018.
* Author: Igor Barkov <lopar.4ever@gmail.com> * Author: Igor Barkov <lopar.4ever@gmail.com>
* Project name: Battles-Game * Project name: Battles-Game
*/ */
\Battles\Template::header('Список кланов');
use Battles\Template;
Template::header('Список кланов');
include_once "config.php"; include_once "config.php";
$claninf = urldecode(filter_input(INPUT_SERVER,'QUERY_STRING')); $claninf = urldecode(filter_input(INPUT_SERVER,'QUERY_STRING'));
if ($claninf AND ($query = db::c()->query('SELECT * FROM `clans` WHERE `name` = "?s"', $claninf)->fetch_assoc())) { if ($claninf && ($query = db::c()->query('SELECT * FROM `clans` WHERE `name` = "?s"', $claninf)->fetch_assoc())) {
echo "<h1>{$query['name']}</h1><p>{$query['descr']}</p>"; echo "<h1>{$query['name']}</h1><p>{$query['descr']}</p>";
$clanlist = db::c()->query('SELECT `login`,`status` FROM `users` WHERE `klan` = ?i',$query['id']); $clanlist = \Battles\Database\Db::getInstance()->execute('select login from users where clan = ?', $claninf);
while ($member = $clanlist->fetch_assoc()) { while ($member = $clanlist->fetch()) {
echo "<img src=i/align_",$query['align'],".png> <img src=i/clan/",$query['short'],".png> ",$member['login']," - ",$member['status'],"<br>"; echo "<img src=i/align_",$query['align'],".png> <img src=i/clan/",$query['short'],".png> ",$member['login']," - ",$member['status'],"<br>";
} }
} else { } else {
echo "<h1>Список кланов</h1>"; echo "<h1>Список кланов</h1>";
$query = db::c()->query('SELECT `align`,`name`,`short` FROM `clans` ORDER BY `name` ASC'); $query = db::c()->query('SELECT `align`,`name`,`short` FROM `clans` ORDER BY `name`');
while ($clanrow = $query->fetch_assoc()) { while ($clanrow = $query->fetch_assoc()) {
$frm = "<img src='i/align_%s.png'> <img src='i/clan/%s.png'> <a href='?%s'>%s</a><br>"; $frm = "<img src='i/align_%s.png'> <img src='i/clan/%s.png'> <a href='?%s'>%s</a><br>";
echo sprintf($frm,$clanrow['align'],$clanrow['short'],$clanrow['name'],$clanrow['name']); echo sprintf($frm,$clanrow['align'],$clanrow['short'],$clanrow['name'],$clanrow['name']);

View File

@ -8,7 +8,7 @@
namespace Battles; namespace Battles;
use Exceptions\GameException; use Exceptions\GameException;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Throwable; use Throwable;
class Bank class Bank
@ -16,7 +16,6 @@ class Bank
public int $user_id = 0; public int $user_id = 0;
private int $money = 0; private int $money = 0;
private $user; private $user;
private static DBPDO $db;
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
@ -33,9 +32,8 @@ class Bank
public function __construct(int $user_id) public function __construct(int $user_id)
{ {
self::$db = DBPDO::INIT(); $bank_row = Db::getInstance()->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id);
$bank_row = self::$db->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id); $this->user = Db::getInstance()->fetch('SELECT money FROM users WHERE id = ?', $user_id);
$this->user = self::$db->fetch('SELECT money FROM users WHERE id = ?', $user_id);
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];
@ -70,9 +68,9 @@ class Bank
* *
* @return void * @return void
*/ */
private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = 0): void private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = null): void
{ {
if (!$senderId) { if (is_null($senderId)) {
$senderId = $this->user_id; $senderId = $this->user_id;
} }
$text = self::LOG[$operationType]; $text = self::LOG[$operationType];
@ -98,7 +96,7 @@ class Bank
*/ */
public function sendMoney(int $receiver, int $amount): int public function sendMoney(int $receiver, int $amount): int
{ {
$receiverWallet = self::$db->fetch('SELECT money FROM bank WHERE user_id = ?', $receiver); $receiverWallet = Db::getInstance()->ofetch('SELECT money FROM bank WHERE user_id = ?', $receiver);
if ($amount <= 0) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
@ -134,8 +132,8 @@ class Bank
if ($amount <= 0) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
$wallet = self::$db->fetch('SELECT money FROM users WHERE id = ?', $this->user_id); $walletMoney = Db::getInstance()->fetchColumn('SELECT money FROM users WHERE id = ?', $this->user_id);
if ($wallet->money < $amount) { if ($walletMoney < $amount) {
throw new GameException(self::ERROR_NO_MONEY_IN_WALLET); throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
} }
// Забираем деньги из кошелька получателя // Забираем деньги из кошелька получателя
@ -195,7 +193,7 @@ class Bank
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 {
self::$db->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]); Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]);
if ($operationType) { if ($operationType) {
GameLogs::addBankLog(0, 0, $amount, $operationType, self::LOG[$operationType]); GameLogs::addBankLog(0, 0, $amount, $operationType, self::LOG[$operationType]);
} }
@ -215,9 +213,8 @@ class Bank
*/ */
public static function setWalletMoney(int $amount, int $user_id): void public static function setWalletMoney(int $amount, int $user_id): void
{ {
$u = new User($user_id); User::getInstance($user_id)->setMoney($amount);
$u->setMoney($amount); User::getInstance($user_id)->saveMoney();
$u->saveMoney();
} }
public function getMoney(): int public function getMoney(): int

View File

@ -2,16 +2,16 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
use DateTime; use DateTime;
use Exception; use Exception;
class Chat class Chat
{ {
private DateTime $d; private DateTime $d;
private DBPDO $db; private Db $db;
public function __construct(DBPDO $db) public function __construct(Db $db)
{ {
$this->db = $db; $this->db = $db;
} }
@ -34,7 +34,7 @@ class Chat
or r.id is null or r.id is null
or s.id = ? or s.id = ?
order by chat.id'; order by chat.id';
$chatrows = $this->db->ofetchALL($query, [User::$current->getId(), User::$current->getId()]); $chatrows = $this->db->ofetchALL($query, [User::getInstance()->getId(), User::getInstance()->getId()]);
$wrappedMessage = null; $wrappedMessage = null;
foreach ($chatrows as $row) { foreach ($chatrows as $row) {
try { try {
@ -45,7 +45,7 @@ class Chat
$m = htmlspecialchars($row->msg); $m = htmlspecialchars($row->msg);
if ($row->type === 'sys' && empty($row->rid)) { if ($row->type === 'sys' && empty($row->rid)) {
$wrappedMessage .= sprintf('<span class="chatsys">%s %s</span><br>', $this->d->format('H:i'), $m); $wrappedMessage .= sprintf('<span class="chatsys">%s %s</span><br>', $this->d->format('H:i'), $m);
} elseif ($row->rid === User::$current->getId()) { } elseif ($row->rid === User::getInstance()->getId()) {
if ($row->type === 'sys') { if ($row->type === 'sys') {
$wrappedMessage .= sprintf('<span class="chatsys">%s [Система] → %s</span><br>', $this->d->format('H:i'), $m); $wrappedMessage .= sprintf('<span class="chatsys">%s [Система] → %s</span><br>', $this->d->format('H:i'), $m);
} elseif ($row->type == 'sms') { } elseif ($row->type == 'sms') {
@ -64,12 +64,12 @@ class Chat
public function addMessage(string $msg) public function addMessage(string $msg)
{ {
$this->db->execute('insert into chat (user_id, msg) values (?,?)', [User::$current->getId(), $msg]); $this->db->execute('insert into chat (user_id, msg) values (?,?)', [User::getInstance()->getId(), $msg]);
} }
public static function addSYSMessage( string $msg, ?int $receiver_id = null) public static function addSYSMessage( string $msg, ?int $receiver_id = null)
{ {
DBPDO::$db->execute('insert into chat (user_id, msg, receiver_id, type) values (?,?,?,?)', [User::$current->getId(), $msg, $receiver_id, 'sys']); Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (?,?,?,?)', [User::getInstance()->getId(), $msg, $receiver_id, 'sys']);
} }
} }

View File

@ -3,19 +3,19 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Check class Check
{ {
private User $user; private User $user;
private DBPDO $db; private Db $db;
/** /**
* Check constructor. * Check constructor.
* *
* @param User $user * @param User $user
*/ */
public function __construct(User $user, DBPDO $db) public function __construct(User $user, Db $db)
{ {
$this->user = $user; $this->user = $user;
$this->db = $db; $this->db = $db;

View File

@ -2,104 +2,105 @@
# Date: 23.08.2021 (23:05) # Date: 23.08.2021 (23:05)
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Clan class Clan
{ {
private DBPDO $db; private static ?self $_instance = null;
private User $user;
private $clan; private $clan;
public static Clan $current;
public function __construct() private function __construct()
{ {
$this->db = DBPDO::$db; $this->clan = Db::getInstance()->ofetch('select * from clans where owner_id = ?', User::getInstance()->getId());
$this->user = User::$current; }
$this->clan = $this->db->ofetch('select * from clans where owner_id = ?', $this->user->getId());
public static function getInstance(): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
} }
public function addMember(string $login): string public function addMember(string $login): string
{ {
$target = new User($login);
$error = null; $error = null;
if (!$this->getProverka($target->getId())) { if (!$this->getProverka(User::getInstance($login)->getId())) {
$error .= '<br>Нет проверки!'; $error .= '<br>Нет проверки!';
} }
if ($target->getClan()) { if (User::getInstance($login)->getClan()) {
$error .= '<br>Персонаж уже состоит в клане!'; $error .= '<br>Персонаж уже состоит в клане!';
} }
if ($target->getLevel() < 1) { if (User::getInstance($login)->getLevel() < 1) {
$error .= '<br>Персонаж 0 уровня не может быть принят!'; $error .= '<br>Персонаж 0 уровня не может быть принят!';
} }
if ($this->user->getMoney() < GameConfigs::CLAN['add_member_cost']) { if (User::getInstance()->getMoney() < GameConfigs::CLAN['add_member_cost']) {
$error .= '<br>Недостаточно денег!'; $error .= '<br>Недостаточно денег!';
} }
if ($error) { if ($error) {
return $error; return $error;
} }
$this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['add_member_cost']); User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['add_member_cost']);
$this->user->saveMoney(); User::getInstance()->saveMoney();
$target->setClan($this->user->getClan()); User::getInstance($login)->setClan(User::getInstance()->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;
if ($this->user->getMoney() < GameConfigs::CLAN['remove_member_cost']) { if (User::getInstance()->getMoney() < GameConfigs::CLAN['remove_member_cost']) {
$error .= '<br>Недостаточно денег!'; $error .= '<br>Недостаточно денег!';
} }
if ($target->getId() === $this->user->getId()) { if (User::getInstance($login)->getId() === User::getInstance()->getId()) {
$error .= '<br>Себя выгонять нельзя!'; $error .= '<br>Себя выгонять нельзя!';
} }
if ($target->getClan() !== $this->user->getClan()) { if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) {
$error .= '<br>Персонаж не состоит в этом клане!'; $error .= '<br>Персонаж не состоит в этом клане!';
} }
if ($error) { if ($error) {
return $error; return $error;
} }
$this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['remove_member_cost']); User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['remove_member_cost']);
$this->user->saveMoney(); User::getInstance()->saveMoney();
$target->setClan(null); User::getInstance($login)->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;
if ($target->getId() === $this->user->getId()) { if (User::getInstance($login)->getId() === User::getInstance()->getId()) {
$error .= '<br>Самоудовлетворяетесь? ;)'; $error .= '<br>Самоудовлетворяетесь? ;)';
} }
if ($target->getClan() !== $this->user->getClan()) { if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) {
$error .= '<br>Персонаж не состоит в этом клане!'; $error .= '<br>Персонаж не состоит в этом клане!';
} }
if ($error) { if ($error) {
return $error; return $error;
} }
$this->db->execute('update clans set owner_id = ? where owner_id = ?', [$target->getId(), $this->user->getId()]); Db::getInstance()->execute('update clans set owner_id = ? where owner_id = ?', [User::getInstance($login)->getId(), User::getInstance()->getId()]);
return 'Вы передали управление кланом персонажу «' . $login . '».'; return 'Вы передали управление кланом персонажу «' . $login . '».';
} }
public function setClanInfo(string $text): string 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()); $checkId = Db::getInstance()->fetchColumn('select id from users where clan = (select short_name from clans where owner_id = ?)', User::getInstance()->getId());
if ($check->id !== $this->user->getId()) { if ($checkId !== User::getInstance()->getId()) {
return 'Ошибка доступа!'; return 'Ошибка доступа!';
} }
$this->db->execute('update clans set info = ? where owner_id = ?', [$text, $check->id]); Db::getInstance()->execute('update clans set info = ? where owner_id = ?', [$text, $checkId]);
return 'Описание клана изменено!'; return 'Описание клана изменено!';
} }
public function getMemberlist(): array public function getMemberlist(): array
{ {
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 Db::getInstance()->fetchAll('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', User::getInstance()->getClan());
} }
private function getProverka($user_id) private function getProverka($user_id)
{ {
return $this->db->fetch('select 1 from users_effects where type = 20 and owner_id = ?', $user_id); return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = 20 and owner_id = ?', $user_id);
} }
public function getClanOwnerId(): ?int public function getClanOwnerId(): ?int

View File

@ -1,154 +0,0 @@
<?php
namespace Battles\Database;
use Battles\GameConfigs;
use PDO, PDOException;
class DBPDO
{
public $pdo;
private static $_instance = null;
public static DBPDO $db;
function __construct()
{
$this->connect();
}
public static function INIT(): DBPDO
{
if (!self::$_instance) {
self::$_instance = new DBPDO();
}
return self::$_instance;
}
function prep_query($query)
{
return $this->pdo->prepare($query);
}
function connect():bool
{
if (!$this->pdo) {
$dsn = 'mysql:dbname=' . GameConfigs::DATABASE_NAME . ';host=' . GameConfigs::DATABASE_HOST . ';port=' . GameConfigs::DATABASE_PORT . ';charset=utf8;';
$user = GameConfigs::DATABASE_USER;
$password = GameConfigs::DATABASE_PASS;
try {
$this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));
return true;
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return true;
}
}
function table_exists($table_name)
{
$stmt = $this->prep_query('SHOW TABLES LIKE ?');
$stmt->execute(array($table_name));
return $stmt->rowCount() > 0;
}
function execute($query, $values = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->prep_query($query);
$stmt->execute($values);
return $stmt;
}
function fetch($query, $values = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function fetchAll($query, $values = null, $key = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if ($key != null && $results[0][$key]) {
$keyed_results = array();
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
}
$results = $keyed_results;
}
return $results;
}
function ofetch($query, $values = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_OBJ);
}
function ofetchAll($query, $values = null, $key = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if ($key != null && $results[0][$key]) {
$keyed_results = (object) array();
foreach ($results as $result) {
$keyed_results->$result[$key] = $result;
}
$results = $keyed_results;
}
return $results;
}
function lastInsertId()
{
return $this->pdo->lastInsertId();
}
function fetchColumn($query, $values = null) {
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
return $stmt->fetchColumn();
}
}

View File

@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
namespace Battles\Database;
use Battles\GameConfigs;
use PDO, PDOException;
class Db
{
private PDO $pdo;
private static ?self $_instance = null;
private function __construct()
{
$this->connect();
}
private function connect(): void
{
$dsn = 'mysql:dbname=' . GameConfigs::DATABASE_NAME . ';host=' . GameConfigs::DATABASE_HOST . ';port=' . GameConfigs::DATABASE_PORT . ';charset=utf8;';
$user = GameConfigs::DATABASE_USER;
$password = GameConfigs::DATABASE_PASS;
try {
$this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance(): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function execute($query, $values = null)
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->pdo->prepare($query);
$stmt->execute($values);
return $stmt;
}
public function fetch($query, $values = null)
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function fetchAll($query, $values = null, $key = null): array
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if (!is_null($key) && $results[0][$key]) {
$keyed_results = array();
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
}
$results = $keyed_results;
}
return $results;
}
public function ofetch($query, $values = null)
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_OBJ);
}
public function ofetchAll($query, $values = null, $key = null): object
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if (!is_null($key) && $results[0][$key]) {
$keyed_results = (object)[];
foreach ($results as $result) {
$keyed_results->$result[$key] = $result;
}
$results = $keyed_results;
}
return $results;
}
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
public function fetchColumn($query, $values = null)
{
if (is_null($values)) {
$values = [];
} elseif (!is_array($values)) {
$values = [$values];
}
$stmt = $this->execute($query, $values);
return $stmt->fetchColumn();
}
}

View File

@ -7,7 +7,7 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
use stdClass; use stdClass;
class DressedItems class DressedItems
@ -22,13 +22,13 @@ class DressedItems
*/ */
public function __construct(int $user_id) public function __construct(int $user_id)
{ {
self::$db = DBPDO::INIT(); self::$db = Db::getInstance();
$this->USERID = $user_id; $this->USERID = $user_id;
} }
public static function getDressedItemBySlot($itemSlot, $ownerId) public static function getDressedItemBySlot($itemSlot, $ownerId)
{ {
return self::$db->fetch('SELECT *, COUNT(1) AS count FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]); return self::$db->ofetch('SELECT *, COUNT(1) AS count FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]);
} }
public function getItemsInSlots(): stdClass public function getItemsInSlots(): stdClass

View File

@ -81,7 +81,7 @@ class GameLogs
public static function addBattleLog(int $battle_id, string $text) public static function addBattleLog(int $battle_id, string $text)
{ {
$db = new SQLite3(__DIR__ . '../../Database/battle.logs.db'); $db = new SQLite3(__DIR__ . '../../Database/battle.logs.getInstance');
$row = $db->prepare('insert into newbattles (battle_id, text) values (?,?)'); $row = $db->prepare('insert into newbattles (battle_id, text) values (?,?)');
$row->bindParam(1, $battle_id, SQLITE3_INTEGER); $row->bindParam(1, $battle_id, SQLITE3_INTEGER);
$row->bindParam(2, $text, SQLITE3_TEXT); $row->bindParam(2, $text, SQLITE3_TEXT);

View File

@ -1,13 +1,12 @@
<?php <?php
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class InventoryItem extends Item class InventoryItem extends Item
{ {
private $present; private $present;
private $owner_id; private $owner_id;
private $db;
private const TOO_MANY_ITEMS_IN_SLOTS = 'Критическая ошибка: Переполнение слота!'; private const TOO_MANY_ITEMS_IN_SLOTS = 'Критическая ошибка: Переполнение слота!';
private const UNKNOWN_ITEM_TYPE = 'Неизвестный тип предмета!'; private const UNKNOWN_ITEM_TYPE = 'Неизвестный тип предмета!';
private const REQUIREMENTS_NOT_MET = 'Персонаж не соответствует требованиям!'; private const REQUIREMENTS_NOT_MET = 'Персонаж не соответствует требованиям!';
@ -22,7 +21,6 @@ class InventoryItem extends Item
parent::__construct($row); parent::__construct($row);
$this->owner_id = $row->owner_id; $this->owner_id = $row->owner_id;
$this->present = $row->present; $this->present = $row->present;
$this->db = DBPDO::INIT();
} }
public function printInfo() public function printInfo()
@ -37,13 +35,13 @@ class InventoryItem extends Item
{ {
if (in_array($this->item_type, range(1, 12))) { if (in_array($this->item_type, range(1, 12))) {
echo <<<HTML echo <<<HTML
<a href=/main.php?edit=1&dress={$this->item_id} title='Надеть'> <a href=/main.php?edit=1&dress=$this->item_id title='Надеть'>
<img src="/i/sh/{$this->image}" class="item-wrap-normal" alt=""> <img src="/i/sh/$this->image" class="item-wrap-normal" alt="">
</a> </a>
HTML; HTML;
} else { } else {
echo <<<IMG echo <<<IMG
<img src="/i/sh/{$this->image}" class="item-wrap-normal" alt=""> <img src="/i/sh/$this->image" class="item-wrap-normal" alt="">
IMG; IMG;
} }
} }
@ -79,8 +77,8 @@ IMG;
// считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами // считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами
// Count добавленный в первый запрос возвращает одну строку в любом случае. // Count добавленный в первый запрос возвращает одну строку в любом случае.
// fetch возвращает одну строку в любом случае. // fetch возвращает одну строку в любом случае.
$weared = $this->db->ofetchAll('SELECT dressed_slot FROM inventory WHERE dressed_slot != 0 AND item_type = ? AND owner_id = ?', [$this->item_type, $this->owner_id]); $weared = Db::getInstance()->ofetchAll('SELECT dressed_slot FROM inventory WHERE dressed_slot != 0 AND item_type = ? AND owner_id = ?', [$this->item_type, $this->owner_id]);
$wearedCount = $this->db->ofetch('select count(dressed_slot) as c from inventory where dressed_slot !=0 and item_type = ? and owner_id = ?', [$this->item_type, $this->owner_id]); $wearedCount = Db::getInstance()->ofetch('select count(dressed_slot) as c from inventory where dressed_slot !=0 and item_type = ? and owner_id = ?', [$this->item_type, $this->owner_id]);
// Если в слоте есть предмет(ы), забиваем их массив одетых в слот предметов. // Если в слоте есть предмет(ы), забиваем их массив одетых в слот предметов.
if ($wearedCount) { if ($wearedCount) {
foreach ($weared as $item) { foreach ($weared as $item) {
@ -95,11 +93,11 @@ IMG;
//работаем с нормальными слотами //работаем с нормальными слотами
if ($wearedCount->c == 1) { if ($wearedCount->c == 1) {
//если слот занят, снимаем старый предмет и одеваем новый предмет //если слот занят, снимаем старый предмет и одеваем новый предмет
$this->db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $this->owner_id]); Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $this->owner_id]);
$this->db->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); Db::getInstance()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]);
} elseif (!$wearedCount->c) { } elseif (!$wearedCount->c) {
//если слот пуст, одеваем новый предмет //если слот пуст, одеваем новый предмет
$this->db->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); Db::getInstance()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]);
} else { } else {
/* проверка на переполнение слотов */ /* проверка на переполнение слотов */
$error = self::TOO_MANY_ITEMS_IN_SLOTS; $error = self::TOO_MANY_ITEMS_IN_SLOTS;
@ -113,11 +111,11 @@ IMG;
// Сортируем массив свободных слотов по возрастанию. // Сортируем массив свободных слотов по возрастанию.
sort($emptyRingSlots); sort($emptyRingSlots);
// Одеваем предмет в первый свободный слот. // Одеваем предмет в первый свободный слот.
$this->db->execute('update inventory set dressed_slot = ? where item_id = ?', [$emptyRingSlots[0], $this->item_id]); Db::getInstance()->execute('update inventory set dressed_slot = ? where item_id = ?', [$emptyRingSlots[0], $this->item_id]);
} elseif ($wearedCount->c == 3) { } elseif ($wearedCount->c == 3) {
// Cнимаем предмет из последнего слота 11 и одеваем новый предмет // Cнимаем предмет из последнего слота 11 и одеваем новый предмет
$this->db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11'); Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11');
$this->db->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id); Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id);
} else { } else {
/* проверка на переполнение слотов */ /* проверка на переполнение слотов */
$error = self::TOO_MANY_ITEMS_IN_SLOTS; $error = self::TOO_MANY_ITEMS_IN_SLOTS;
@ -132,7 +130,7 @@ IMG;
public static function destroyItem($itemId) public static function destroyItem($itemId)
{ {
DBPDO::INIT()->execute('delete from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?', [$_SESSION['uid'], $itemId]); Db::getInstance()->execute('delete from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?', [$_SESSION['uid'], $itemId]);
} }
/** Надеюсь, временная заглушка, которая объединяет get_meshok() и другую выдачу одной строкой. /** Надеюсь, временная заглушка, которая объединяет get_meshok() и другую выдачу одной строкой.
@ -141,7 +139,7 @@ IMG;
public static function getWeightData(): string public static function getWeightData(): string
{ {
$query = 'select sum(weight) as `all`, strength * 4 as max from inventory left join users u on owner_id = id where owner_id = ?'; $query = 'select sum(weight) as `all`, strength * 4 as max from inventory left join users u on owner_id = id where owner_id = ?';
$weight = DBPDO::$db->ofetch($query, User::$current->getId()); $weight = Db::getInstance()->ofetch($query, User::getInstance()->getId());
$css = $weight->all > $weight->max ? ' style="color:maroon;"' : ''; $css = $weight->all > $weight->max ? ' style="color:maroon;"' : '';
return "<span$css>$weight->all / $weight->max</span>"; return "<span$css>$weight->all / $weight->max</span>";
} }

View File

@ -1,7 +1,7 @@
<?php <?php
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Item class Item
{ {
@ -193,6 +193,6 @@ class Item
public static function getItemById($item_id): Item public static function getItemById($item_id): Item
{ {
return new Item(DBPDO::$db->ofetch('select * from items where id = ?', $item_id)); return new Item(Db::getInstance()->ofetch('select * from items where id = ?', $item_id));
} }
} }

View File

@ -3,7 +3,7 @@
// Магия лечения травм // Магия лечения травм
namespace Battles\Magic; namespace Battles\Magic;
use Battles\UserEffects, Battles\Database\DBPDO, Battles\User; use Battles\UserEffects, Battles\Database\Db, Battles\User;
class CureInjury extends Magic class CureInjury extends Magic
{ {
@ -18,7 +18,7 @@ class CureInjury extends Magic
*/ */
public function __construct(int $target, int $injuryType) public function __construct(int $target, int $injuryType)
{ {
$db = DBPDO::INIT(); $db = Db::getInstance();
$this->target = $target; $this->target = $target;
if (!$this->isUsable()) { if (!$this->isUsable()) {
return $this->status; return $this->status;
@ -46,13 +46,13 @@ class CureInjury extends Magic
*/ */
private function isUsable(): bool private function isUsable(): bool
{ {
$caster = new User($_SESSION['uid']); $this->target = $this->target == $_SESSION['uid'] ? User::getInstance() : User::getInstance($this->target);
if ($this->target == $_SESSION['uid']) {
$this->target = $caster;
} else {
$this->target = new User($this->target);
}
$this->login = $this->target->getLogin(); $this->login = $this->target->getLogin();
return ($this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isNotInBattle($caster)); return ($this->isVisible(User::getInstance(), $this->target) && $this->isNotDead(User::getInstance()) && $this->enoughMana(User::getInstance()) && $this->isNotInBattle(User::getInstance()));
}
public static function cast($target, $type): self
{
return new self($target, $type);
} }
} }

View File

@ -2,7 +2,7 @@
// Магия восстановления здоровья // Магия восстановления здоровья
use Battles\Magic\Magic; use Battles\Magic\Magic;
use Battles\User; use Battles\User;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Healing extends Magic class Healing extends Magic
{ {
@ -30,7 +30,7 @@ class Healing extends Magic
if ($healHealthAmount > $this->target->maxHealth) { if ($healHealthAmount > $this->target->maxHealth) {
$healHealthAmount = $this->target->maxHealth; $healHealthAmount = $this->target->maxHealth;
} }
DBPDO::INIT()->execute('UPDATE users SET health = ? WHERE id = ?', [$healHealthAmount, $this->target->id]); Db::getInstance()->execute('UPDATE users SET health = ? WHERE id = ?', [$healHealthAmount, $this->target->id]);
$targetName = $this->target->login; $targetName = $this->target->login;
return "Вы восстановили ${healHealthAmount} здоровья персонажу ${targetName}."; return "Вы восстановили ${healHealthAmount} здоровья персонажу ${targetName}.";
} }
@ -41,12 +41,7 @@ class Healing extends Magic
*/ */
private function isUsable(): bool private function isUsable(): bool
{ {
$caster = new User($_SESSION['uid']); $this->target = $this->target == $_SESSION['uid'] ? User::getInstance() : User::getInstance($this->target);
if ($this->target == $_SESSION['uid']) { return $this->isVisible(User::getInstance(), $this->target) && $this->isNotDead(User::getInstance()) && $this->enoughMana(User::getInstance()) && $this->isSuccess(User::getInstance());
$this->target = $caster;
} else {
$this->target = new User($this->target);
}
return $this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isSuccess($caster);
} }
} }

View File

@ -3,7 +3,7 @@
namespace Battles\Magic; namespace Battles\Magic;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\Item; use Battles\Item;
use Battles\User; use Battles\User;
@ -27,20 +27,19 @@ class Sharpen extends Magic
} }
$item = DressedItems::getDressedItemBySlot(Item::ITEM_TYPE_WEAPON, $_SESSION['uid']); $item = DressedItems::getDressedItemBySlot(Item::ITEM_TYPE_WEAPON, $_SESSION['uid']);
// Проверяем, что в названии предмета нет цифр и плюсов. // Проверяем, что в названии предмета нет цифр и плюсов.
if (preg_match('/[\W\S]+\+\[?[\d]]?/', $item['name'])) { if (preg_match('/[\W\S]+\+\[?[\d]]?/', $item->name)) {
return 'Этот предмет точить нельзя!'; return 'Этот предмет точить нельзя!';
} }
$newMinPhysicalDamage = $item['add_min_physical_damage'] + $sharpenStrength; $newMinPhysicalDamage = $item->add_min_physical_damage + $sharpenStrength;
$newMaxPhysicalDamage = $item['add_max_physical_damage'] + $sharpenStrength; $newMaxPhysicalDamage = $item->add_max_physical_damage + $sharpenStrength;
$newItemName = $item['name'] . " [+$sharpenStrength]"; $newItemName = $item->name . " [+$sharpenStrength]";
DBPDO::INIT()->execute('UPDATE battles.inventory SET name = ?, add_min_physical_damage = ?, add_max_physical_damage = ? WHERE item_id = ? ', [$newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item['item_id']]); Db::getInstance()->execute('UPDATE battles.inventory SET name = ?, add_min_physical_damage = ?, add_max_physical_damage = ? WHERE item_id = ? ', [$newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item->item_id]);
return "У вас получилось изготовить предмет $newItemName!"; return "У вас получилось изготовить предмет $newItemName!";
} }
private function isUsable(): bool private function isUsable(): bool
{ {
$caster = new User($_SESSION['uid']); return $this->isNotInBattle(User::getInstance()) && $this->isSuccess(User::getInstance(), $this->magicDifficulty);
return $this->isNotInBattle($caster) && $this->isSuccess($caster, $this->magicDifficulty);
} }
} }

View File

@ -7,7 +7,7 @@
namespace Battles\Models; namespace Battles\Models;
use Battles\Database\DBPDO; use Battles\Database\Db;
class EffectsModel class EffectsModel
{ {
@ -16,7 +16,7 @@ class EffectsModel
public function __construct(int $user_id) public function __construct(int $user_id)
{ {
$this->DB = DBPDO::INIT()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id); $this->DB = Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id);
} }
/** /**

View File

@ -6,7 +6,7 @@
*/ */
namespace Battles\Models; namespace Battles\Models;
use Battles\Database\DBPDO; use Battles\Database\Db;
class PresentsModel class PresentsModel
{ {
@ -15,7 +15,7 @@ class PresentsModel
public function __construct(int $user_id) public function __construct(int $user_id)
{ {
if (!$this->DB) { if (!$this->DB) {
$this->DB = DBPDO::INIT()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id); $this->DB = Db::getInstance()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id);
} }
} }

View File

@ -3,7 +3,7 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Moderation class Moderation
{ {
@ -54,13 +54,13 @@ class Moderation
public static function blockUser(int $target) public static function blockUser(int $target)
{ {
self::addEffectStatusToUserLog($target, "Блокировка"); self::addEffectStatusToUserLog($target, "Блокировка");
DBPDO::INIT()->execute('UPDATE battles.users SET block = 1 WHERE id = ?', $target); Db::getInstance()->execute('UPDATE battles.users SET block = 1 WHERE id = ?', $target);
} }
public static function unBlockUser(int $target) 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); Db::getInstance()->execute('UPDATE battles.users SET block = 0 WHERE block = 1 AND id = ?', $target);
} }
public static function addToUserLog(int $target, string $message, int $senderId) public static function addToUserLog(int $target, string $message, int $senderId)
@ -70,12 +70,12 @@ class Moderation
public static function setAlign(int $target, int $align) public static function setAlign(int $target, int $align)
{ {
DBPDO::INIT()->execute('UPDATE users SET align = ? WHERE id = ?', [$align, $target]); Db::getInstance()->execute('UPDATE users SET align = ? WHERE id = ?', [$align, $target]);
} }
public static function addChatSysMsg(string $message) public static function addChatSysMsg(string $message)
{ {
DBPDO::INIT()->execute('INSERT INTO chat (user_id,msg,type) VALUES (-1,?,?)', [$message, 'sys']); Db::getInstance()->execute('INSERT INTO chat (user_id,msg,type) VALUES (-1,?,?)', [$message, 'sys']);
} }
public static function addUserCheck(int $target) public static function addUserCheck(int $target)

View File

@ -1,40 +1,41 @@
<?php <?php
namespace Battles; namespace Battles;
use Battles\Database\Db;
/** /**
* Разные способы отображения строки с логином персонажа. * Разные способы отображения строки с логином персонажа.
*/ */
const INVIS = '<i>невидимка</i>'; const INVIS = '<i>невидимка</i>';
class Nick extends User class Nick extends UserStats
{ {
private function getInvisibilityStatus() private function isInvisible()
{ {
return self::$db->fetch('SELECT 1 FROM users_effects WHERE type = 1022 AND owner_id = ?', $this->id); return Db::getInstance()->execute('SELECT count(*) FROM users_effects WHERE type = 1022 AND owner_id = ?', $this->id)->fetchColumn();
} }
/** /**
* Отображение иконки склонности. * Отображение иконки склонности.
* @return string * @return string
*/ */
private function getAlignToNickname():?string private function getAlignImage(): ?string
{ {
if ($this->align) { return $this->align ? "<img src='i/align_$this->align.gif' alt='Склонность'>" : null;
return sprintf('<img src="i/align_%s.gif">', $this->align);
} else {
return null;
}
} }
/** /**
* Отображение иконки клана. * Отображение иконки клана.
* @return string * @return string
*/ */
private function getClanToNickname():?string private function getClanImage(): ?string
{ {
if ($this->clan) { return $this->clan ? "<img src='i/clan/$this->clan.png' alt='Клан'>" : null;
return sprintf('<img src="i/clan/%s.png">', $this->clan);
} else {
return null;
} }
private function getInfolinkImage(): string
{
return "<a href='inf.php?$this->login' target='_blank'><img src='i/inf.gif' alt='Ссылка на профиль'></a>";
} }
/** /**
@ -43,7 +44,7 @@ class Nick extends User
* *
* @return Nick * @return Nick
*/ */
public static function id($playerId): Nick public static function id($playerId): self
{ {
return new self($playerId); return new self($playerId);
} }
@ -55,50 +56,27 @@ class Nick extends User
* *
* @return string * @return string
*/ */
public function full($showInvisibility = 0):string public function full(int $showInvisibility = 0): string
{ {
if (!$showInvisibility && $this->getInvisibilityStatus()) { return !$showInvisibility && $this->isInvisible() ? INVIS : $this->getAlignImage() . $this->getClanImage() . " <b>$this->login</b> [$this->level] " . $this->getInfolinkImage();
return INVIS;
}
return $this->getAlignToNickname().$this->getClanToNickname().sprintf('<b>%s</b> [%s] <a href="inf.php?%s" target="_blank"><img src="i/inf.gif" style="width:12px;height:11px"></a>', $this->login, $this->level, $this->login);
} }
/** /**
* Возвращает строку с логином или невидимым статусом. * Возвращает строку с логином.
* @param int $showInvisibility отображать логин даже если персонаж невидимка. * Избавиться от этого! Оставлено для совместимости.
* @return string * @return string
*/ */
public function short($showInvisibility = 0):string public function short(): string
{ {
if (!$showInvisibility && $this->getInvisibilityStatus()) { return $this->login;
return INVIS;
} else {
return htmlspecialchars($this->login);
}
} }
/** /**
* Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем. * Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем.
* @return string * @return string
*/ */
public function battle():string 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->full() . "<img src='i/herz.gif' alt='HP'> [$this->health/$this->maxHealth]";
}
/**
* Возвращает строку с логином и здоровьем, выделяя строку определённым стилем.
* @param $textstyle - Название стиля отображения логина персонажа (main.css) для цветового разделения команд.
*
* @return string
*/
public function battleShort($textstyle):string
{
if ($this->getInvisibilityStatus()) {
return INVIS;
}
else {
return sprintf('<span style="%s">%s</span> [_hp_/_maxhp_]', $textstyle, $this->login);
}
} }
} }

View File

@ -2,29 +2,34 @@
# Date: 29.08.2021 (21:34) # Date: 29.08.2021 (21:34)
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Shop class Shop
{ {
public const GENERAL_SHOP = 1; public const GENERAL_SHOP = 1;
public const BARTER_SHOP = 2; public const BARTER_SHOP = 2;
public const CATEGORY_SALE_ITEMS = -1; public const CATEGORY_SALE_ITEMS = -1;
public static Shop $current;
public int $categoryType = 0; public int $categoryType = 0;
private int $shopId; private int $shopId;
public function __construct($shop_id) { private function __construct($shop_id)
{
$this->shopId = $shop_id; $this->shopId = $shop_id;
} }
public static function id($shopid): self
{
return new self($shopid);
}
private function showGoods(): string private function showGoods(): string
{ {
if ($this->categoryType) { if ($this->categoryType) {
$stmt = DBPDO::$db->ofetchAll('select * from items inner join trade_offers on id = shop_item_id where shop_id = ? and shop_item_quantity !=0 and item_type = ?', [$this->shopId, $this->categoryType]); $stmt = Db::getInstance()->ofetchAll('select * from items inner join trade_offers on id = shop_item_id where shop_id = ? and shop_item_quantity !=0 and item_type = ?', [$this->shopId, $this->categoryType]);
$stmt2 = DBPDO::$db->ofetchAll('select * from inventory where on_sale != 0 and present is null and item_type = ?', $this->categoryType); $stmt2 = Db::getInstance()->ofetchAll('select * from inventory where on_sale != 0 and present is null and item_type = ?', $this->categoryType);
} else { } else {
$stmt = DBPDO::$db->ofetchAll('select * from items inner join trade_offers on id = shop_item_id where shop_id = ? and shop_item_quantity !=0', $this->shopId); $stmt = Db::getInstance()->ofetchAll('select * from items inner join trade_offers on id = shop_item_id where shop_id = ? and shop_item_quantity !=0', $this->shopId);
$stmt2 = DBPDO::$db->ofetchAll('select * from inventory where on_sale != 0 and present is null'); $stmt2 = Db::getInstance()->ofetchAll('select * from inventory where on_sale != 0 and present is null');
} }
$iteminfo = []; $iteminfo = [];
@ -39,7 +44,7 @@ class Shop
private function showUserSellItems(): string private function showUserSellItems(): string
{ {
$stmt = DBPDO::$db->ofetchall('select * from inventory where on_sale = 0 and dressed_slot = 0 and durability > 0 and owner_id = ?', User::$current->getId()); $stmt = Db::getInstance()->ofetchall('select * from inventory where on_sale = 0 and dressed_slot = 0 and durability > 0 and owner_id = ?', User::getInstance()->getId());
$iteminfo = []; $iteminfo = [];
$operationType = 'sellshop'; $operationType = 'sellshop';

View File

@ -2,7 +2,7 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Models\PresentsModel; use Battles\Models\PresentsModel;
use Exceptions\GameException; use Exceptions\GameException;
@ -137,8 +137,8 @@ SQL;
public static function buyItem($id, User $buyer) public static function buyItem($id, User $buyer)
{ {
$check = DBPDO::$db->ofetch("select * from trade_offers where offer_id = ?", $id); $check = Db::getInstance()->ofetch("select * from trade_offers where offer_id = ?", $id);
$item = new Item(DBPDO::$db->fetch('select * from items where id = ?', $check->shop_item_id)); $item = new Item(Db::getInstance()->fetch('select * from items where id = ?', $check->shop_item_id));
$price = $item->calculateItemCost(); $price = $item->calculateItemCost();
if ( if (
@ -149,7 +149,7 @@ SQL;
return; return;
} }
DBPDO::$db->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]); Db::getInstance()->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]);
$deloText = $buyer->getLogin() . " купил товар «" . $item->name . "» id:(" . $check->shop_item_id . ") в магазине за " . $price . "."; $deloText = $buyer->getLogin() . " купил товар «" . $item->name . "» id:(" . $check->shop_item_id . ") в магазине за " . $price . ".";
GameLogs::addUserLog($buyer->getId(), $deloText); GameLogs::addUserLog($buyer->getId(), $deloText);
self::$status = "Предмет " . $item->name . " куплен за " . $price . "."; self::$status = "Предмет " . $item->name . " куплен за " . $price . ".";
@ -162,7 +162,7 @@ SQL;
} }
$allowItemRemove = true; $allowItemRemove = true;
foreach (json_decode($json_list) as $item) { foreach (json_decode($json_list) as $item) {
$row = DBPDO::$db->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $user_id]); $row = Db::getInstance()->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $user_id]);
if ($row->s < $item->quantity) { if ($row->s < $item->quantity) {
$allowItemRemove = false; $allowItemRemove = false;
} }
@ -174,20 +174,20 @@ SQL;
foreach (json_decode($json_list) as $item) { foreach (json_decode($json_list) as $item) {
$query = 'delete from inventory where name = ? and owner_id = ? limit ' . (int)$item->quantity; $query = 'delete from inventory where name = ? and owner_id = ? limit ' . (int)$item->quantity;
// У-у-у, сука! https://phpdelusions.net/pdo#limit // У-у-у, сука! https://phpdelusions.net/pdo#limit
DBPDO::$db->execute($query, [Item::getItemById($item->item_id)->name, $user_id]); Db::getInstance()->execute($query, [Item::getItemById($item->item_id)->name, $user_id]);
} }
return true; return true;
} }
private static function checkAndPayTheBills(int $price, User $user): bool private static function checkAndPayTheBills(int $price, User $user): bool
{ {
if ($user->getMoney() > $price) { if (User::getInstance()->getMoney() > $price) {
$user->setMoney($user->getMoney() - $price); User::getInstance()->setMoney(User::getInstance()->getMoney() - $price);
$user->saveMoney(); User::getInstance()->saveMoney();
return true; return true;
} }
try { try {
$bank = new Bank($user->getId()); $bank = new Bank(User::getInstance()->getId());
$bank->withdrawMoney($price); $bank->withdrawMoney($price);
return true; return true;
} catch (GameException $e) { } catch (GameException $e) {
@ -205,24 +205,23 @@ SQL;
if ($current_quantity === -1) { if ($current_quantity === -1) {
return true; return true;
} }
DBPDO::$db->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_quantity != -1 and shop_item_id = ? ", $item_id); Db::getInstance()->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_quantity != -1 and shop_item_id = ? ", $item_id);
return true; return true;
} }
public static function sellItem($id, User $seller, $bankTrade = 0) public static function sellItem($id, User $seller, $bankTrade = 0)
{ {
$db = new DBPDO(); $item = Db::getInstance()->ofetch('select * from inventory where item_id = ?', $id);
$item = $db->ofetch('select * from inventory where item_id = ?', $id);
$sellingItemName = $item->name; $sellingItemName = $item->name;
// Продажа за цену от нуля до половины стоимости. // Продажа за цену от нуля до половины стоимости.
$sellingPrice = $item->price > 1 ? mt_rand(0, $item->price / 2) : mt_rand(0, 1); $sellingPrice = $item->price > 1 ? mt_rand(0, $item->price / 2) : mt_rand(0, 1);
$db->execute('delete from inventory where item_id = ?', $id); Db::getInstance()->execute('delete from inventory where item_id = ?', $id);
if ($bankTrade) { if ($bankTrade) {
$bank = new Bank($seller->getId()); $bank = new Bank($seller->getId());
$bank->setMoney($bank->getMoney() + $sellingPrice); $bank->setMoney($bank->getMoney() + $sellingPrice);
Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'sellShop'); Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'sellShop');
} else { } else {
$db->execute('update users set money = money - ? where id = ?', [$sellingPrice, $_SESSION['uid']]); Db::getInstance()->execute('update users set money = money - ? where id = ?', [$sellingPrice, $_SESSION['uid']]);
} }
$deloText = "{$seller->getLogin()} продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр."; $deloText = "{$seller->getLogin()} продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр.";
GameLogs::addUserLog($seller->getId(), $deloText); GameLogs::addUserLog($seller->getId(), $deloText);
@ -280,12 +279,12 @@ FORM;
*/ */
public static function giveNewItem(int $item_id, int $to): array public static function giveNewItem(int $item_id, int $to): array
{ {
$check = DBPDO::$db->ofetch('select 1 from items where id = ?', $item_id); $check = Db::getInstance()->ofetch('select 1 from items where id = ?', $item_id);
if (!$check) { if (!$check) {
return []; return [];
} }
DBPDO::$db->execute(self::BUY_QUERY, [$to, $item_id]); Db::getInstance()->execute(self::BUY_QUERY, [$to, $item_id]);
$return = DBPDO::$db->ofetch('select image, name from inventory where item_id = ?', DBPDO::$db->lastInsertId()); $return = Db::getInstance()->ofetch('select image, name from inventory where item_id = ?', Db::getInstance()->lastInsertId());
return [ return [
'img' => $return->image, 'img' => $return->image,
'name' => $return->name, 'name' => $return->name,

View File

@ -2,7 +2,7 @@
# Date: 26.10.2020 (16:08) # Date: 26.10.2020 (16:08)
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class Travel class Travel
{ {
@ -62,17 +62,17 @@ class Travel
*/ */
public static function toRoom(int $roomId, int $roomIdCurrent): void public static function toRoom(int $roomId, int $roomIdCurrent): void
{ {
$db = DBPDO::INIT(); UserStats::getInstance()->
$itemsWeight = $db->fetch('SELECT SUM(weight) - (select strength * 5 from users where id = ?) AS weight_overflow FROM inventory WHERE owner_id = ? AND on_sale = 0', [$_SESSION['uid'], $_SESSION['uid']]); $itemsWeightOverflow = Db::getInstance()->fetchColumn('SELECT SUM(weight) - (select strength * 4 from users where id = ?) AS weight_overflow FROM inventory WHERE owner_id = ? AND on_sale = 0', [$_SESSION['uid'], $_SESSION['uid']]);
$eff = $db->fetch('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']); $eff = Db::getInstance()->fetchColumn('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']);
$errors = []; $errors = [];
if ($itemsWeight['weight_overflow'] > 0) { if ($itemsWeightOverflow > 0) {
$errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...'; $errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...';
} }
if ($eff['type'] == 10) { if ($eff == 10) {
$errors[1] = 'Вы парализованы и не можете передвигаться...'; $errors[1] = 'Вы парализованы и не можете передвигаться...';
} }
if ($eff['type'] == 13 || $eff['type'] == 14) { if ($eff == 13 || $eff == 14) {
$errors[2] = 'У вас тяжелая травма, вы не можете передвигаться...'; $errors[2] = 'У вас тяжелая травма, вы не можете передвигаться...';
} }
if ($errors) { if ($errors) {
@ -80,7 +80,7 @@ class Travel
echo sprintf('<span class="error">%s</span>', $error); echo sprintf('<span class="error">%s</span>', $error);
} }
} elseif (in_array($roomId, self::allowedRoomMoves($roomIdCurrent))) { } elseif (in_array($roomId, self::allowedRoomMoves($roomIdCurrent))) {
$db->execute('UPDATE users, online SET users.room = ?, online.room = ? WHERE `online`.`user_id` = `users`.`id` AND `online`.`user_id` = ?', [$roomId, $roomId, $_SESSION['uid']]); Db::getInstance()->execute('UPDATE users, online SET users.room = ?, online.room = ? WHERE `online`.`user_id` = `users`.`id` AND `online`.`user_id` = ?', [$roomId, $roomId, $_SESSION['uid']]);
header('location: ' . self::$roomFileName[$roomId]); header('location: ' . self::$roomFileName[$roomId]);
exit; exit;
} }

View File

@ -2,10 +2,12 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
class User class User
{ {
private static ?self $_instance = null;
protected int $id = 0; protected int $id = 0;
protected string $login = ''; protected string $login = '';
protected ?string $pass = null; protected ?string $pass = null;
@ -29,26 +31,20 @@ class User
protected int $battle = 0; protected int $battle = 0;
protected int $in_tower = 0; // Скорее башню похороним чем запустим... protected int $in_tower = 0; // Скорее башню похороним чем запустим...
protected int $zayavka = 0; protected int $zayavka = 0;
protected static DBPDO $db;
public const INFO_CHAR_LIMIT = 1500; public const INFO_CHAR_LIMIT = 1500;
/**
* @var User Переменная инициализируемая при запуске, хранящая объект текущего пользователя.
*/
public static User $current;
/** protected function __construct($user = null)
* @param int|string $user
*/
public function __construct($user)
{ {
self::$db = DBPDO::INIT(); if (is_null($user)) {
$user = $_SESSION['uid'];
}
$query = 'select * from users where login = ?'; $query = 'select * from users where login = ?';
if (is_numeric($user)) { if (is_numeric($user)) {
$query = 'select * from users where id = ?'; $query = 'select * from users where id = ?';
$user = (int)$user; $user = (int)$user;
} }
$user_query = self::$db->fetch($query, $user); $user_query = Db::getInstance()->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];
@ -56,6 +52,14 @@ class User
} }
} }
public static function getInstance($user = null): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self($user);
}
return self::$_instance;
}
/** /**
* @param int $userId * @param int $userId
* @param int $type * @param int $type
@ -66,13 +70,13 @@ class User
public static function addUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null) 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);
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]); Db::getInstance()->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
{ {
if (self::$db->fetch('SELECT 1 FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type])) { if (Db::getInstance()->fetchColumn('SELECT 1 FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type])) {
self::$db->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]); Db::getInstance()->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]);
} }
return false; return false;
} }
@ -157,12 +161,12 @@ class User
public function setMoney(int $money) public function setMoney(int $money)
{ {
$this->money = $money < 0 ? 0 : $money; $this->money = max($money, 0);
} }
public function saveMoney() public function saveMoney()
{ {
self::$db->execute('update users set money = ? where id = ?', [$this->money, $this->id]); Db::getInstance()->execute('update users set money = ? where id = ?', [$this->money, $this->id]);
} }
public function getAdmin(): int public function getAdmin(): int
@ -229,7 +233,7 @@ class User
public function setOnline() public function setOnline()
{ {
self::$db->execute('update online set real_time = ? where user_id = ?', [time(), $this->getId()]); Db::getInstance()->execute('update online set real_time = ? where user_id = ?', [time(), $this->getId()]);
} }
public function setInjury(int $type): bool public function setInjury(int $type): bool
@ -285,6 +289,6 @@ class User
$this->admin, $this->admin,
$this->id //where $this->id //where
]; ];
DBPDO::$db->execute($query, $vals); Db::getInstance()->execute($query, $vals);
} }
} }

View File

@ -2,7 +2,7 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Models\EffectsModel; use Battles\Models\EffectsModel;
class UserInfo extends UserStats class UserInfo extends UserStats
@ -10,8 +10,6 @@ class UserInfo extends UserStats
use Rooms; use Rooms;
private int $bankMoney; private int $bankMoney;
//Тот, кто смотрит на информацию.
private User $watcher;
public function __construct($user) public function __construct($user)
{ {
@ -172,7 +170,7 @@ HTML;
while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) { while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) {
$log .= sprintf('<code>%s</code><br>', date('d.m.Y H:i ', strtotime($userLogRow['date'])) . $userLogRow['text']); $log .= sprintf('<code>%s</code><br>', date('d.m.Y H:i ', strtotime($userLogRow['date'])) . $userLogRow['text']);
} }
$adminData = $this->watcher->getAdmin() ? $this->showAdminOnlyData() : null; $adminData = User::getInstance()->getAdmin() ? $this->showAdminOnlyData() : null;
return <<<INFO return <<<INFO
<div class="secret-info"> <div class="secret-info">
E-Mail: $this->email<br> E-Mail: $this->email<br>
@ -216,7 +214,7 @@ INFO;
echo $this->realname ? "Имя: $this->realname" : ""; echo $this->realname ? "Имя: $this->realname" : "";
echo $this->info ? "<br>" . nl2br($this->info) : ""; echo $this->info ? "<br>" . nl2br($this->info) : "";
echo '</div><!-- u-i-c-l -->'; echo '</div><!-- u-i-c-l -->';
if ($this->watcher->getAdmin() || $this->watcher->getAlign() == 1) { if (User::getInstance()->getAdmin() || User::getInstance()->getAlign() == 1) {
echo $this->showPrivateData(); echo $this->showPrivateData();
} }
} }
@ -225,9 +223,9 @@ INFO;
{ {
$effects = new EffectsModel($this->id); $effects = new EffectsModel($this->id);
if ($this->block && (!$this->watcher->getAdmin() || !$this->watcher->getAlign() == 1)) { if ($this->block && (!User::getInstance()->getAdmin() || !User::getInstance()->getAlign() == 1)) {
echo "<span class='error'>Персонаж $this->login заблокирован!</span>"; echo "<span class='error'>Персонаж $this->login заблокирован!</span>";
} elseif ($effects->getHideUserInfoStatus() && (!$this->watcher->getAdmin() || !$this->watcher->getAlign() == 1)) { } elseif ($effects->getHideUserInfoStatus() && (!User::getInstance()->getAdmin() || !User::getInstance()->getAlign() == 1)) {
if ($effects->getHideUserInfoStatus() == -1) { if ($effects->getHideUserInfoStatus() == -1) {
$date = 'навсегда'; $date = 'навсегда';
} else { } else {
@ -256,7 +254,7 @@ INFO;
public function showUserEffects(): string public function showUserEffects(): string
{ {
$effs = DBPDO::INIT()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $this->id); $effs = Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $this->id);
$img = UserEffects::$effectImage; $img = UserEffects::$effectImage;
$r = ''; $r = '';
foreach ($effs as $effect) { foreach ($effs as $effect) {
@ -271,14 +269,4 @@ INFO;
} }
return $r; return $r;
} }
/**
* @param mixed $watcher_id
*/
public function setWatcher(int $watcher_id): void
{
$this->watcher = new User($watcher_id);
}
} }

View File

@ -3,7 +3,7 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Exceptions\GameException; use Exceptions\GameException;
class UserStats extends User class UserStats extends User
@ -86,7 +86,7 @@ class UserStats extends User
throw new GameException(self::ERROR_STAT_IS_MAXIMUM); throw new GameException(self::ERROR_STAT_IS_MAXIMUM);
} else { } else {
$query = "UPDATE users SET {$stat_name} = {$stat_name} + 1, free_stat_points = free_stat_points - 1 WHERE id = ?"; $query = "UPDATE users SET {$stat_name} = {$stat_name} + 1, free_stat_points = free_stat_points - 1 WHERE id = ?";
self::$db->execute($query, $this->id); Db::getInstance()->execute($query, $this->id);
} }
} }
@ -161,7 +161,7 @@ class UserStats extends User
public function getFullStats(): object public function getFullStats(): object
{ {
$stats = self::$db->ofetch(" $stats = Db::getInstance()->ofetch("
select select
strength, strength,
dexterity, dexterity,
@ -170,7 +170,7 @@ class UserStats extends User
intelligence, intelligence,
wisdom wisdom
from users where id = $this->id"); from users where id = $this->id");
$itemBonuses = self::$db->ofetch(" $itemBonuses = Db::getInstance()->ofetch("
select select
sum(add_strength) as item_strength, sum(add_strength) as item_strength,
sum(add_dexterity) as item_dexterity, sum(add_dexterity) as item_dexterity,
@ -184,7 +184,7 @@ class UserStats extends User
sum(add_min_physical_damage) as item_min_physical_damage, sum(add_min_physical_damage) as item_min_physical_damage,
sum(add_max_physical_damage) as item_max_physical_damage sum(add_max_physical_damage) as item_max_physical_damage
from inventory where dressed_slot != 0 and owner_id = $this->id"); from inventory where dressed_slot != 0 and owner_id = $this->id");
$effectBonuses = self::$db->ofetch(" $effectBonuses = Db::getInstance()->ofetch("
select select
sum(mod_strength) as effect_strength, sum(mod_strength) as effect_strength,
sum(mod_dexterity) as effect_dexterity, sum(mod_dexterity) as effect_dexterity,
@ -238,6 +238,6 @@ class UserStats extends User
$this->level, $this->level,
$this->id //where $this->id //where
]; ];
DBPDO::$db->execute($query, $vals); Db::getInstance()->execute($query, $vals);
} }
} }

View File

@ -12,7 +12,7 @@
* маркеры - т.н. "заполнители", а сами данные передаются "позже", в качестве последующих аргументов основного метода, * маркеры - т.н. "заполнители", а сами данные передаются "позже", в качестве последующих аргументов основного метода,
* выполняющего SQL-запрос - Mysql::query($sql [, $arg, $...]): * выполняющего SQL-запрос - Mysql::query($sql [, $arg, $...]):
* *
* $db->query('SELECT * FROM `table` WHERE `name` = "?s" AND `age` = ?i', $_POST['name'], $_POST['age']); * $getInstance->query('SELECT * FROM `table` WHERE `name` = "?s" AND `age` = ?i', $_POST['name'], $_POST['age']);
* *
* Аргументы SQL-запроса, прошедшие через систему placeholders данного класса, экранируются специальными функциями * Аргументы SQL-запроса, прошедшие через систему placeholders данного класса, экранируются специальными функциями
* экранирования, в зависимости от типа заполнителей. Т.е. вам теперь нет необходимости заключать переменные в функции * экранирования, в зависимости от типа заполнителей. Т.е. вам теперь нет необходимости заключать переменные в функции
@ -45,8 +45,8 @@
* Например, попытка передать в качестве аргумента значение 55.5 или '55.5' для заполнителя целочисленного типа ?i * Например, попытка передать в качестве аргумента значение 55.5 или '55.5' для заполнителя целочисленного типа ?i
* приведет к выбросу исключения: * приведет к выбросу исключения:
* *
* $db->setTypeMode(Mysql::MODE_STRICT); // устанавливаем строгий режим работы * $getInstance->setTypeMode(Mysql::MODE_STRICT); // устанавливаем строгий режим работы
* $db->query('SELECT ?i', 55.5); // Попытка указать для заполнителя типа int значение типа double в шаблоне запроса SELECT ?i * $getInstance->query('SELECT ?i', 55.5); // Попытка указать для заполнителя типа int значение типа double в шаблоне запроса SELECT ?i
* *
* Это утверждение не относится к числам (целым и с плавающей точкой), заключенным в строки. * Это утверждение не относится к числам (целым и с плавающей точкой), заключенным в строки.
* С точки зрения библиотеки, строка '123' и значение 123 являются типом int. * С точки зрения библиотеки, строка '123' и значение 123 являются типом int.
@ -140,7 +140,7 @@
* заполнителей скалярного типа, таких как ?i, ?d и ?s. Это сделано по идеологическим соображениям, * заполнителей скалярного типа, таких как ?i, ?d и ?s. Это сделано по идеологическим соображениям,
* автоподстановка кавычек может стать ограничением для возможностей SQL. * автоподстановка кавычек может стать ограничением для возможностей SQL.
* Например, выражение * Например, выражение
* $db->query('SELECT "Total: ?s"', '200'); * $getInstance->query('SELECT "Total: ?s"', '200');
* вернёт строку * вернёт строку
* 'Total: 200' * 'Total: 200'
* Если бы кавычки, ограничивающие строковой литерал, ставились бы автоматически, * Если бы кавычки, ограничивающие строковой литерал, ставились бы автоматически,
@ -151,20 +151,23 @@
* Тем не менее, для перечислений ?as, ?ai, ?ap, ?As, ?Ai и ?Ap ограничивающие кавычки ставятся принудительно, т.к. * Тем не менее, для перечислений ?as, ?ai, ?ap, ?As, ?Ai и ?Ap ограничивающие кавычки ставятся принудительно, т.к.
* перечисления всегда используются в запросах, где наличие кавчек обязательно или не играет роли (а так ли это?): * перечисления всегда используются в запросах, где наличие кавчек обязательно или не играет роли (а так ли это?):
* *
* $db->query('INSERT INTO `test` SET ?As', array('name' => 'Маша', 'age' => '23', 'adress' => 'Москва')); * $getInstance->query('INSERT INTO `test` SET ?As', array('name' => 'Маша', 'age' => '23', 'adress' => 'Москва'));
* -> INSERT INTO test SET `name` = "Маша", `age` = "23", `adress` = "Москва" * -> INSERT INTO test SET `name` = "Маша", `age` = "23", `adress` = "Москва"
* *
* $db->query('SELECT * FROM table WHERE field IN (?as)', array('55', '12', '132')); * $getInstance->query('SELECT * FROM table WHERE field IN (?as)', array('55', '12', '132'));
* -> SELECT * FROM table WHERE field IN ("55", "12", "132") * -> SELECT * FROM table WHERE field IN ("55", "12", "132")
* *
* Также исключения составляют заполнители типа ?f, предназначенные для передачи в запрос имен таблиц и полей. * Также исключения составляют заполнители типа ?f, предназначенные для передачи в запрос имен таблиц и полей.
* Аргумент заполнителя ?f всегда обрамляется обратными кавычками (`): * Аргумент заполнителя ?f всегда обрамляется обратными кавычками (`):
* *
* $db->query('SELECT ?f FROM ?f', 'my_field', 'my_table'); * $getInstance->query('SELECT ?f FROM ?f', 'my_field', 'my_table');
* -> SELECT `my_field` FROM `my_table` * -> SELECT `my_field` FROM `my_table`
*/ */
namespace Krugozor\Database\Mysql; namespace Krugozor\Database\Mysql;
use mysqli;
use mysqli_result;
class Mysql class Mysql
{ {
/** /**
@ -172,7 +175,7 @@ class Mysql
* Если тип заполнителя не совпадает с типом аргумента, то будет выброшено исключение. * Если тип заполнителя не совпадает с типом аргумента, то будет выброшено исключение.
* Пример такой ситуации: * Пример такой ситуации:
* *
* $db->query('SELECT * FROM `table` WHERE `id` = ?i', '2+мусор'); * $getInstance->query('SELECT * FROM `table` WHERE `id` = ?i', '2+мусор');
* *
* - в данной ситуации тип заполнителя ?i - число или числовая строка, * - в данной ситуации тип заполнителя ?i - число или числовая строка,
* а в качестве аргумента передаётся строка '2+мусор' не являющаяся ни числом, ни числовой строкой. * а в качестве аргумента передаётся строка '2+мусор' не являющаяся ни числом, ни числовой строкой.
@ -187,7 +190,7 @@ class Mysql
* к нужному типу - к типу заполнителя. * к нужному типу - к типу заполнителя.
* Пример такой ситуации: * Пример такой ситуации:
* *
* $db->query('SELECT * FROM `table` WHERE `id` = ?i', '2+мусор'); * $getInstance->query('SELECT * FROM `table` WHERE `id` = ?i', '2+мусор');
* *
* - в данной ситуации тип заполнителя ?i - число или числовая строка, * - в данной ситуации тип заполнителя ?i - число или числовая строка,
* а в качестве аргумента передаётся строка '2+мусор' не являющаяся ни числом, ни числовой строкой. * а в качестве аргумента передаётся строка '2+мусор' не являющаяся ни числом, ни числовой строкой.
@ -397,7 +400,7 @@ class Mysql
throw new Exception(__METHOD__ . ': ' . $this->mysqli->error . '; SQL: ' . $this->query); throw new Exception(__METHOD__ . ': ' . $this->mysqli->error . '; SQL: ' . $this->query);
} }
if (is_object($result) && $result instanceof \mysqli_result) { if (is_object($result) && $result instanceof mysqli_result) {
return new Statement($result); return new Statement($result);
} }
@ -425,7 +428,7 @@ class Mysql
* Применяется для случаев, когда SQL-запрос формируется частями. * Применяется для случаев, когда SQL-запрос формируется частями.
* *
* Пример: * Пример:
* $db->prepare('WHERE `name` = "?s" OR `id` IN(?ai)', 'Василий', array(1, 2)); * $getInstance->prepare('WHERE `name` = "?s" OR `id` IN(?ai)', 'Василий', array(1, 2));
* Результат: * Результат:
* WHERE `name` = "Василий" OR `id` IN(1, 2) * WHERE `name` = "Василий" OR `id` IN(1, 2)
* *
@ -548,7 +551,7 @@ class Mysql
private function connect() private function connect()
{ {
if (!is_object($this->mysqli) || !$this->mysqli instanceof mysqli) { if (!is_object($this->mysqli) || !$this->mysqli instanceof mysqli) {
$this->mysqli = @new \mysqli($this->server, $this->user, $this->password, null, $this->port, $this->socket); $this->mysqli = @new mysqli($this->server, $this->user, $this->password, null, $this->port, $this->socket);
if ($this->mysqli->connect_error) { if ($this->mysqli->connect_error) {
throw new Exception(__METHOD__ . ': ' . $this->mysqli->connect_error); throw new Exception(__METHOD__ . ': ' . $this->mysqli->connect_error);

View File

@ -2,6 +2,7 @@
use Battles\GameLogs; use Battles\GameLogs;
use Battles\Nick; use Battles\Nick;
use Battles\User;
class Tournament class Tournament
{ {
@ -160,8 +161,8 @@ class Tournament
// кидаем в бой // кидаем в бой
mysql_query("UPDATE `users` SET `battle` = {$id} WHERE `id` = " . $user1 . " OR `id` = " . $user2); mysql_query("UPDATE `users` SET `battle` = {$id} WHERE `id` = " . $user1 . " OR `id` = " . $user2);
// создаем лог // создаем лог
$rr = "<b>" . Nick::id($user['id'])->full(1) . "</b> и <b>" . Nick::id($jert['id'])->full(1) . "</b>"; $rr = "<b>" . Nick::id(User::getInstance()->getId())->full(1) . "</b> и <b>" . Nick::id($jert['id'])->full(1) . "</b>";
addch("<a href=logs.php?log=" . $id . " target=_blank>Бой</a> между <B><b>" . Nick::id($user['id'])->short() . "</b> и <b>" . Nick::id($jert['id'])->short() . "</b> начался. ", $user->getRoom()); addch("<a href=logs.php?log=" . $id . " target=_blank>Бой</a> между <B><b>" . Nick::id(User::getInstance()->getId())->short() . "</b> и <b>" . Nick::id($jert['id'])->short() . "</b> начался. ", User::getInstance()->getRoom());
GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " решили выяснить кто из них сильнее. <i>(турнир)</i><BR>"); GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " решили выяснить кто из них сильнее. <i>(турнир)</i><BR>");
return $id; return $id;
} }

View File

@ -1,5 +1,7 @@
<?php <?php
use Battles\User;
class Quests class Quests
{ {
public $free_x = 28, $data = [], $error = ''; public $free_x = 28, $data = [], $error = '';
@ -569,7 +571,7 @@ TASK;
mysql_query('UPDATE `users` SET `money` = "' . $user['money'] . '", `exp` = "' . $user['exp'] . '", `doblest` = "' . $user['doblest'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1'); mysql_query('UPDATE `users` SET `money` = "' . $user['money'] . '", `exp` = "' . $user['exp'] . '", `doblest` = "' . $user['doblest'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1');
$this->error = 'Вы успешно сдали задание!'; $this->error = 'Вы успешно сдали задание!';
$text = '<font style="color: Red;">Внимание!</font> За успешно выполненное задание Вы получили : ' . $c; $text = '<font style="color: Red;">Внимание!</font> За успешно выполненное задание Вы получили : ' . $c;
$this->msg($text, '{[]}' . $user['login'] . '{[]}', $user->getRoom()); $this->msg($text, '{[]}' . $user['login'] . '{[]}', User::getInstance()->getRoom());
} else { } else {
$this->error = 'Не все условия задания были выполнены ...'; $this->error = 'Не все условия задания были выполнены ...';
} }

View File

@ -6,7 +6,7 @@
* Project name: Battles-Game * Project name: Battles-Game
*/ */
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\User; use Battles\User;
include_once 'classes/Database/db.php'; include_once 'classes/Database/db.php';
@ -39,17 +39,6 @@ spl_autoload_register(function ($className) {
} }
}); });
/**
* Глобальные переменные. Промежуточное решение для совместимости.
*/
if (empty(DBPDO::$db)) {
DBPDO::$db = new DBPDO();
}
if (empty(User::$current) && $_SESSION['uid']) {
User::$current = new User($_SESSION['uid']);
}
// Для нападалок. Сперва комнаты в которых нельзя напасть, потом персонажи на которых нельзя напасть. // Для нападалок. Сперва комнаты в которых нельзя напасть, потом персонажи на которых нельзя напасть.
const UNKILABLE = [ const UNKILABLE = [
'rooms' => [620, 621, 1051, 1052], 'rooms' => [620, 621, 1051, 1052],

View File

@ -187,10 +187,31 @@ if ($tur_data['endtime'] < time() && $tur_data['id']) {
mysql_query("UPDATE `users` SET `sila` = (`sila`-'" . $eff['sila'] . "'), `lovk` = (`lovk`-'" . $eff['lovk'] . "'), `inta` = (`inta`-'" . $eff['inta'] . "'), `maxhp` = (`maxhp`-'" . $eff['hp'] . "') WHERE `id` = '" . $eff['owner'] . "' LIMIT 1"); mysql_query("UPDATE `users` SET `sila` = (`sila`-'" . $eff['sila'] . "'), `lovk` = (`lovk`-'" . $eff['lovk'] . "'), `inta` = (`inta`-'" . $eff['inta'] . "'), `maxhp` = (`maxhp`-'" . $eff['hp'] . "') WHERE `id` = '" . $eff['owner'] . "' LIMIT 1");
} }
if ($u['id'] != 233 && $u['id'] != 234 && $u['id'] != 235) { $pers = db::c()->query('SELECT * FROM users WHERE id = ?i', $u['id'])->fetch_assoc_array();
settravma($u['id'], 100, 86400, 1); DressedItems::undressAllItems($pers['id']);
db::c()->query('UPDATE inventory SET owner = ?i WHERE owner = ?i', $pers['id'], $pers['id'] + _BOTSEPARATOR_);
###
$row = db::c()->query('SELECT * FROM `effects` WHERE `owner` = ?i', $pers['id'] + _BOTSEPARATOR_);
$travm = [11, 12, 13, 14];
while ($efs = $row->fetch_assoc()) {
if (in_array($efs['type'], $travm)) {
$pers['sila'] -= $efs['sila'];
$pers['lovk'] -= $efs['lovk'];
$pers['inta'] -= $efs['inta'];
$pers['vinos'] -= $efs['vinos'];
} else {
$pers['sila'] += $efs['sila'];
$pers['lovk'] += $efs['lovk'];
$pers['inta'] += $efs['inta'];
$pers['vinos'] += $efs['vinos'];
$pers['maxhp'] += $efs['hp'];
} }
get_out($u['id']); $efs['owner'] = $_SESSION['uid'];
mysql_query('UPDATE `effects` SET `owner` = "' . $efs['owner'] . '" WHERE `id` = "' . $efs['id'] . '" LIMIT 1');
mysql_query('UPDATE `users` SET `sila` = "' . $pers['sila'] . '", `lovk` = "' . $pers['lovk'] . '", `inta` = "' . $pers['inta'] . '", `vinos` = "' . $pers['vinos'] . '", `maxhp` = "' . $pers['maxhp'] . '" WHERE `id` = "' . $pers['id'] . '" LIMIT 1');
mysql_query("UPDATE `users` SET `in_tower` = 0, `room` = '31' WHERE `id` = '" . $u['id'] . "' LIMIT 1"); mysql_query("UPDATE `users` SET `in_tower` = 0, `room` = '31' WHERE `id` = '" . $u['id'] . "' LIMIT 1");
mysql_query("UPDATE `online` SET `room` = '31' WHERE `id` = '" . $u['id'] . "' LIMIT 1"); mysql_query("UPDATE `online` SET `room` = '31' WHERE `id` = '" . $u['id'] . "' LIMIT 1");
} }

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\Template; use Battles\Template;
@ -19,7 +19,7 @@ $battle = $_COOKIE['battle'] ?? '';
$error = ""; $error = "";
if ($username && $password) { if ($username && $password) {
$user_query = DBPDO::$db->ofetch('SELECT id, login, pass, room, block, session_id FROM users WHERE login = ?', $username); $user_query = Db::getInstance()->ofetch('SELECT id, login, pass, room, block, session_id FROM users WHERE login = ?', $username);
if (!$user_query->id) { if (!$user_query->id) {
$error = ERROR_NO_SUCH_USER; $error = ERROR_NO_SUCH_USER;
@ -43,14 +43,14 @@ if ($username && $password) {
setcookie("uid", $user_query->id, time() + 43200, "/", GAMEDOMAIN); setcookie("uid", $user_query->id, time() + 43200, "/", GAMEDOMAIN);
setcookie("hashcode", md5($user_query->id . $user_query->pass . $username), time() + 43200, "/", GAMEDOMAIN); setcookie("hashcode", md5($user_query->id . $user_query->pass . $username), time() + 43200, "/", GAMEDOMAIN);
$onl = DBPDO::$db->ofetch('SELECT 1 FROM online WHERE user_id = ?', $user_query->id); $onl = Db::getInstance()->ofetch('SELECT 1 FROM online WHERE user_id = ?', $user_query->id);
if ($onl) { if ($onl) {
DBPDO::$db->execute('UPDATE online SET login_time = ? WHERE user_id = ?', [time(), $user_query->id]); Db::getInstance()->execute('UPDATE online SET login_time = ? WHERE user_id = ?', [time(), $user_query->id]);
} else { } else {
DBPDO::$db->execute('INSERT INTO online (user_id, login_time, room, real_time) VALUES (?,?,?,?)', [$user_query->id, time(), $user_query->room, time()]); Db::getInstance()->execute('INSERT INTO online (user_id, login_time, room, real_time) VALUES (?,?,?,?)', [$user_query->id, time(), $user_query->room, time()]);
} }
DBPDO::$db->execute('UPDATE users SET session_id = ?, enter_game = 1 WHERE id = ?', [session_id(), $user_query->id]); Db::getInstance()->execute('UPDATE users SET session_id = ?, enter_game = 1 WHERE id = ?', [session_id(), $user_query->id]);
session_start(); session_start();

View File

@ -1,6 +1,7 @@
<?php <?php
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
@ -62,8 +63,8 @@ if ($_GET['ext'] == 1) {
} }
if (in_array($user->getRoom(), CANAL_ENTERS)) { if (in_array(User::getInstance()->getRoom(), CANAL_ENTERS)) {
$podzemroom = $user->getRoom() + 1; $podzemroom = User::getInstance()->getRoom() + 1;
$cavedata = [620 => ['x1' => 3, 'y1' => 2, 'dir1' => 2]]; $cavedata = [620 => ['x1' => 3, 'y1' => 2, 'dir1' => 2]];
$podzemdata = [621 => ['name1' => 'Проклятый Рудник', 'name2' => 'Проклятого Рудника']]; $podzemdata = [621 => ['name1' => 'Проклятый Рудник', 'name2' => 'Проклятого Рудника']];
$warning = $_GET["warning"] ?? ''; $warning = $_GET["warning"] ?? '';
@ -89,7 +90,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
if (($user['align'] == '2.99') && $wait_sec > $new_t) { if (($user['align'] == '2.99') && $wait_sec > $new_t) {
$wait_sec = 1; $wait_sec = 1;
mysql_query("UPDATE `visit_podzem` SET `time` = 1 WHERE `login` = '$user[login]' AND `time` > 0 AND `room` = '$user->getRoom()' LIMIT 1"); mysql_query("UPDATE `visit_podzem` SET `time` = 1 WHERE `login` = '$user[login]' AND `time` > 0 AND `room` = 'User::getInstance()->getRoom()' LIMIT 1");
} }
if ($wait_sec > $new_t && $_GET['donate']) { if ($wait_sec > $new_t && $_GET['donate']) {
@ -199,7 +200,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
return $i; return $i;
} }
$Q = mysql_query("SELECT * FROM `vxod` WHERE `room` = '$user->getRoom()'"); $Q = mysql_query("SELECT * FROM `vxod` WHERE `room` = 'User::getInstance()->getRoom()'");
while ($DATA = mysql_fetch_array($Q)) { while ($DATA = mysql_fetch_array($Q)) {
$cr = $DATA['glav_id']; $cr = $DATA['glav_id'];
$z_login[$i] = $DATA['login']; $z_login[$i] = $DATA['login'];
@ -275,7 +276,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
exit(); exit();
} }
$time = date("H:i"); $time = date("H:i");
$SQL2 = mysql_query("INSERT INTO `vxod` (`date`, `login`, `glav_id`, `comment`, `pass`, `room`) VALUES('$time', '$login', '$user_id', '" . mysql_real_escape_string($_GET['cmt']) . "', '" . mysql_real_escape_string($_GET['pass']) . "', '$user->getRoom()')"); $SQL2 = mysql_query("INSERT INTO `vxod` (`date`, `login`, `glav_id`, `comment`, `pass`, `room`) VALUES('$time', '$login', '$user_id', '" . mysql_real_escape_string($_GET['cmt']) . "', '" . mysql_real_escape_string($_GET['pass']) . "', 'User::getInstance()->getRoom()')");
$SQL2 = mysql_query("INSERT INTO `vxodd` (`login`, `glav_id`, `lvl`) VALUES('$login', '$user_id', '$user_lvl')"); $SQL2 = mysql_query("INSERT INTO `vxodd` (`login`, `glav_id`, `lvl`) VALUES('$login', '$user_id', '$user_lvl')");
if ($SQL2) { if ($SQL2) {
echo "<script>location.href='main.php?act=none'</script>"; echo "<script>location.href='main.php?act=none'</script>";
@ -305,7 +306,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
} }
$den = mysql_query("SELECT `id` FROM `vxodd` WHERE `glav_id` = '" . $_GET['naw_id'] . "'"); $den = mysql_query("SELECT `id` FROM `vxodd` WHERE `glav_id` = '" . $_GET['naw_id'] . "'");
if (mysql_num_rows($den) >= (in_array($user->getRoom() + 1, CAVE_ROOMS) ? 5 : 4)) { if (mysql_num_rows($den) >= (in_array(User::getInstance()->getRoom() + 1, CAVE_ROOMS) ? 5 : 4)) {
echo "<script>location.href='?warning=5'</script>"; echo "<script>location.href='?warning=5'</script>";
exit(); exit();
} }
@ -353,7 +354,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
} }
if ($_GET['start']) { if ($_GET['start']) {
if (in_array($user->getRoom() + 1, CAVE_ROOMS)) { if (in_array(User::getInstance()->getRoom() + 1, CAVE_ROOMS)) {
$nc = 1; $nc = 1;
$locs = []; $locs = [];
} }
@ -375,8 +376,8 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
mysql_query("update `users` SET `money` = (`money-$nana[fee]) WHERE `id` = '$esth[id]' LIMIT 1"); mysql_query("update `users` SET `money` = (`money-$nana[fee]) WHERE `id` = '$esth[id]' LIMIT 1");
$user['money'] += $nana['fee']; $user['money'] += $nana['fee'];
$esth['money'] -= $nana['fee']; $esth['money'] -= $nana['fee'];
adddelo($user['id'], "Персонаж $user[login] получил $nana[fee] кр. за поход по локации \"" . $rooms[$user->getRoom() + 1] . "\" от персонажа $esth[login] ($user[money]).", 1); adddelo($user['id'], "Персонаж $user[login] получил $nana[fee] кр. за поход по локации \"" . $rooms[User::getInstance()->getRoom() + 1] . "\" от персонажа $esth[login] ($user[money]).", 1);
adddelo($esth['id'], "Персонаж $esth[login] заплатил $nana[fee] кр. за поход по локации \"" . $rooms[$user->getRoom() + 1] . "\" персонажу $user[login] ($esth[money]).", 1); adddelo($esth['id'], "Персонаж $esth[login] заплатил $nana[fee] кр. за поход по локации \"" . $rooms[User::getInstance()->getRoom() + 1] . "\" персонажу $user[login] ($esth[money]).", 1);
} }
if ($esth['level'] > $level) { if ($esth['level'] > $level) {
$level = $esth['level']; $level = $esth['level'];
@ -389,12 +390,12 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) {
$vrem = 30 * 60 + time(); $vrem = 30 * 60 + time();
$cavedata = CAVE_DATA ?? []; $cavedata = CAVE_DATA ?? [];
mysql_query("INSERT INTO `caveparties` SET `user` = '$esth[id]', `leader` = '$user[id]', `login` = '$esth[login]', `shadow` = '0.png', `x` = '" . $cavedata[$user->getRoom() + 1]['x1'] . "', `y` = '" . $cavedata[$user->getRoom() + 1]['y1'] . "', `dir` = '" . $cavedata[$user->getRoom() + 1]['dir1'] . "', `floor` = 1"); mysql_query("INSERT INTO `caveparties` SET `user` = '$esth[id]', `leader` = '$user[id]', `login` = '$esth[login]', `shadow` = '0.png', `x` = '" . $cavedata[User::getInstance()->getRoom() + 1]['x1'] . "', `y` = '" . $cavedata[User::getInstance()->getRoom() + 1]['y1'] . "', `dir` = '" . $cavedata[User::getInstance()->getRoom() + 1]['dir1'] . "', `floor` = 1");
mysql_query("UPDATE `users`, `online` SET " . ($nc ? "`users`.`caveleader` = '$user[id]', " : "") . " `users`.`room` = '" . ($user->getRoom() + 1) . "', `online`.`room` = '" . ($user->getRoom() + 1) . "' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $esth['id'] . "'"); mysql_query("UPDATE `users`, `online` SET " . ($nc ? "`users`.`caveleader` = '$user[id]', " : "") . " `users`.`room` = '" . (User::getInstance()->getRoom() + 1) . "', `online`.`room` = '" . (User::getInstance()->getRoom() + 1) . "' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $esth['id'] . "'");
} }
if ($nc) { if ($nc) {
$r = mysql_query("SELECT * FROM `cavemaps` WHERE `room` = '$user->getRoom()'"); $r = mysql_query("SELECT * FROM `cavemaps` WHERE `room` = 'User::getInstance()->getRoom()'");
while ($rec = mysql_fetch_assoc($r)) { while ($rec = mysql_fetch_assoc($r)) {
$map = unserialize($rec['map']); $map = unserialize($rec['map']);
foreach ($map as $k => $v) { foreach ($map as $k => $v) {

View File

@ -1,12 +1,12 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
require_once 'config.php'; require_once 'config.php';
$userLoginStatus = DBPDO::$db->ofetch('select enter_game from users where id = ?', $_SESSION['uid']); $userLoginStatus = Db::getInstance()->ofetch('select enter_game from users where id = ?', $_SESSION['uid']);
if (!empty($userLoginStatus->enter_game)) { if (!empty($userLoginStatus->enter_game)) {
DBPDO::$db->execute('update users set enter_game = 0 where enter_game = 1 and id = ?', $_SESSION['uid']); Db::getInstance()->execute('update users set enter_game = 0 where enter_game = 1 and id = ?', $_SESSION['uid']);
} }
Template::header('Окно игры'); Template::header('Окно игры');

View File

@ -3,9 +3,10 @@
use Battles\GameLogs; use Battles\GameLogs;
use Battles\Nick; use Battles\Nick;
use Battles\Template; use Battles\Template;
use Battles\User
require_once "functions.php"; require_once "functions.php";
if ($user->getRoom() == 51) { if (User::getInstance()->getRoom() == 51) {
header('location: city.php'); header('location: city.php');
exit; exit;
} }

View File

@ -1,7 +1,11 @@
<?php <?php
use Battles\Nick;
use Battles\Template;
use Battles\User;
require_once 'config.php'; require_once 'config.php';
$user = \Battles\User::$current; $sleep = db::c()->query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', User::getInstance()->getId(), time())->fetch_assoc();
$sleep = db::c()->query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', $user['id'], time())->fetch_assoc();
$ps = $_GET['page'] ?? 0; $ps = $_GET['page'] ?? 0;
$isModerator = false; $isModerator = false;
$isAdmin = false; $isAdmin = false;
@ -72,7 +76,7 @@ function close_dangling_tags($html)
return $html; return $html;
} }
if (isset($_POST['add']) && isset($user['id'])) { if (isset($_POST['add']) && User::getInstance()->getId()) {
$icon = htmlentities($_POST['icon'], ENT_NOQUOTES, 'utf8'); $icon = htmlentities($_POST['icon'], ENT_NOQUOTES, 'utf8');
$text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8'); $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8');
@ -86,12 +90,8 @@ if (isset($_POST['add']) && isset($user['id'])) {
rtrim($_POST['text']); rtrim($_POST['text']);
if (empty($_POST['text']) || empty($_POST['title'])) { if (empty($_POST['text']) || empty($_POST['title'])) {
$error = "Заголовок или текст не могут быть пустыми!"; $error = "Заголовок или текст не могут быть пустыми!";
} elseif (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || ($user['align'] >= $minmax['min_align'] && $user['align'] <= $minmax['max_align']) || $isAdmin) { } elseif (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || (User::getInstance()->getAlign() >= $minmax['min_align'] && User::getInstance()->getAlign() <= $minmax['max_align']) || $isAdmin) {
if ($user['invis'] == 1) { $userPost = Nick::id(User::getInstance()->getId())->full();
$userPost = '<b>Невидимка</b>';
} else {
$userPost = Nick::id($user['id'])->full(1);
}
if ($isModerator == false) $text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>'); if ($isModerator == false) $text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>');
db::c()->query('INSERT INTO `forum` (`type`, `topic`, `text`, `parent`, `author`, `date`, `min_align`, `max_align`, `icon`) VALUES (2,"?s","?s",?i,"?s","?s","?s","?s","?s")', $text2, $text1, $_GET['conf'], $userPost, date('d.m.y H:i:s'), $min_align, $max_align, $icon); db::c()->query('INSERT INTO `forum` (`type`, `topic`, `text`, `parent`, `author`, `date`, `min_align`, `max_align`, `icon`) VALUES (2,"?s","?s",?i,"?s","?s","?s","?s","?s")', $text2, $text1, $_GET['conf'], $userPost, date('d.m.y H:i:s'), $min_align, $max_align, $icon);
@ -105,7 +105,7 @@ if (isset($_POST['add']) && isset($user['id'])) {
unset($_POST['add']); unset($_POST['add']);
} }
if (isset($_POST['add2']) && isset($user['id'])) { if (isset($_POST['add2']) && User::getInstance()->getId()) {
$text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8'); $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8');
$text1 = parse_bb_code(preg_replace("/\n/", "<br />", $_POST['text'])); $text1 = parse_bb_code(preg_replace("/\n/", "<br />", $_POST['text']));
@ -120,12 +120,8 @@ if (isset($_POST['add2']) && isset($user['id'])) {
$error = "Не надо так делать"; $error = "Не надо так делать";
} }
if (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || ($user['align'] >= $minmax['min_align'] && $user['align'] <= $minmax['max_align']) && $minmax['close'] == "0" || $isAdmin) { if (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || (User::getInstance()->getAlign() >= $minmax['min_align'] && User::getInstance()->getAlign() <= $minmax['max_align']) && $minmax['close'] == "0" || $isAdmin) {
if ($user['invis'] == 1) { $userPost = Nick::id(User::getInstance()->getId())->full();
$userPost = '<b>Невидимка</b>';
} else {
$userPost = Nick::id($user['id'])->full(1);
}
if ($isModerator == false) { if ($isModerator == false) {
$text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>'); $text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>');
@ -165,11 +161,7 @@ if (isset($_GET['dt']) && $isModerator == true) {
} }
if (isset($_GET['com']) && isset($_GET['cpr']) && $isModerator == true) { if (isset($_GET['com']) && isset($_GET['cpr']) && $isModerator == true) {
if ($user['invis'] == 1) { $addText = Nick::id(User::getInstance()->getId())->full() . ": " . $_GET['cpr'];
$addText = "<br /><b>Невидимка</b>: " . $_GET['cpr'];
} else {
$addText = Nick::id($user['id'])->full(1) . ": " . $_GET['cpr'];
}
db::c()->query('UPDATE `forum` SET `text` = CONCAT(`text`,"?s") WHERE `id` = ?i', $addText, $_GET['com']); db::c()->query('UPDATE `forum` SET `text` = CONCAT(`text`,"?s") WHERE `id` = ?i', $addText, $_GET['com']);
echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>"; echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
exit(); exit();
@ -183,7 +175,7 @@ if (isset($_GET['do']) && $isModerator == true) {
} }
if ($_GET['do'] == "close") { if ($_GET['do'] == "close") {
$closeComment = "Обсуждение закрыл " . ($isAdmin) ? "<b>Администратор</b>" : Nick::id($user['id'])->full(1); $closeComment = "Обсуждение закрыл " . ($isAdmin) ? "<b>Администратор</b>" : Nick::id(User::getInstance()->getId())->full(1);
db::c()->query('UPDATE `forum` SET `close` = 1, `closepal` = "?s" WHERE `id` = "?s"', $closeComment, $_GET['topic']); db::c()->query('UPDATE `forum` SET `close` = 1, `closepal` = "?s" WHERE `id` = "?s"', $closeComment, $_GET['topic']);
echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>"; echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
exit(); exit();
@ -201,7 +193,7 @@ if (isset($_GET['do']) && $isModerator == true) {
exit(); exit();
} }
} }
\Battles\Template::header('Форум'); Template::header('Форум');
?> ?>
<link rel="stylesheet" href="css/wysibb/theme/default/wbbtheme.css"/> <link rel="stylesheet" href="css/wysibb/theme/default/wbbtheme.css"/>
<script type="text/javascript" language="JavaScript" src='js/forum.js'></script> <script type="text/javascript" language="JavaScript" src='js/forum.js'></script>
@ -209,17 +201,17 @@ if (isset($_GET['do']) && $isModerator == true) {
<tr valign="top"> <tr valign="top">
<td width="200"> <td width="200">
<br/> <br/>
<?php if (isset($user['id'])) echo "Игрок : " . Nick::id($user['id'])->full(1) . "<br />"; ?> <?php if (User::getInstance()->getId()) { echo "Игрок : " . Nick::id(User::getInstance()->getId())->full(1) . "<br>"; } ?>
<h4>Конференции</h4> <h4>Конференции</h4>
<?php <?php
if ((isset($_GET['conf']) && is_numeric($_GET['conf'])) || (isset($_GET['konftop']) && is_numeric($_GET['konftop'])) || $Movemess == 1) { if ((isset($_GET['conf']) && is_numeric($_GET['conf'])) || (isset($_GET['konftop']) && is_numeric($_GET['konftop'])) || $Movemess == 1) {
$data = db::c()->query('SELECT * FROM `forum` WHERE `parent` = 0 AND `type` = 1 ORDER BY `id` ASC'); $data = db::c()->query('SELECT * FROM `forum` WHERE `parent` = 0 AND `type` = 1 ORDER BY `id` ASC');
while ($row = $data->fetch_assoc()) { while ($row = $data->fetch_assoc()) {
if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) { if (($row['min_align'] == 0 && $row['max_align'] == 0) || (User::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $row['max_align']) || $isAdmin) {
$min = $row['min_align'] == 0; $min = $row['min_align'] == 0;
$max = $row['max_align'] == 0; $max = $row['max_align'] == 0;
if (!isset($user['id']) || (($user['align'] < $row['min_align']) || ($user['align'] > $row['max_align']) && !$min && !$max)) { if (!User::getInstance()->getId() || ((User::getInstance()->getAlign() < $row['min_align']) || (User::getInstance()->getAlign() > $row['max_align']) && !$min && !$max)) {
echo '<nobr><b>&nbsp;&nbsp;📕'; echo '<nobr><b>&nbsp;&nbsp;📕';
} else { } else {
echo '<nobr><b>&nbsp;&nbsp;📖&nbsp;'; echo '<nobr><b>&nbsp;&nbsp;📖&nbsp;';
@ -234,7 +226,7 @@ if (isset($_GET['do']) && $isModerator == true) {
<?php <?php
if (!isset($_GET['conf'])) { if (!isset($_GET['conf'])) {
$row = db::c()->query('SELECT * FROM `forum` WHERE `id` = "?s"', $_GET['topic'])->fetch_assoc(); $row = db::c()->query('SELECT * FROM `forum` WHERE `id` = "?s"', $_GET['topic'])->fetch_assoc();
if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) { if (($row['min_align'] == 0 && $row['max_align'] == 0) || (User::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $row['max_align']) || $isAdmin) {
$top = $row['parent']; $top = $row['parent'];
$parentCat = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $top)->fetch_assoc(); $parentCat = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $top)->fetch_assoc();
$icons = $row['icon']; $icons = $row['icon'];
@ -371,9 +363,9 @@ if (isset($_GET['do']) && $isModerator == true) {
if ($closed == 1) { if ($closed == 1) {
echo "<br /><div align=center>" . $closepal . "</div><br /><br />"; echo "<br /><div align=center>" . $closepal . "</div><br /><br />";
} else { } else {
if (!empty($user['block'])) { if (User::getInstance()->getBlock()) {
$error = "Вы заблокированы!"; $error = "Вы заблокированы!";
} elseif ($user['level'] < 2) { } elseif (User::getInstance()->getLevel() < 2) {
$error = "Персонажам до 2-го уровня запрещено писать на форуме!"; $error = "Персонажам до 2-го уровня запрещено писать на форуме!";
} elseif (isset($sleep['id'])) { } elseif (isset($sleep['id'])) {
$error = "Вы молчите!"; $error = "Вы молчите!";
@ -423,7 +415,7 @@ if (isset($_GET['do']) && $isModerator == true) {
} }
} else { } else {
if (is_numeric($_GET['conf']) && $row = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $_GET['conf'])->fetch_assoc()) { if (is_numeric($_GET['conf']) && $row = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $_GET['conf'])->fetch_assoc()) {
if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) { if (($row['min_align'] == 0 && $row['max_align'] == 0) || (User::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $row['max_align']) || $isAdmin) {
$confname = 'Конференция «' . $row['topic'] . '»'; $confname = 'Конференция «' . $row['topic'] . '»';
$pgs = db::c()->query('SELECT count(`id`) FROM `forum` WHERE `parent` = ?i ORDER BY `fix` DESC, `updated` DESC', $_GET['conf'])->fetch_row(); $pgs = db::c()->query('SELECT count(`id`) FROM `forum` WHERE `parent` = ?i ORDER BY `fix` DESC, `updated` DESC', $_GET['conf'])->fetch_row();
$pgs = $pgs[0] / 20; $pgs = $pgs[0] / 20;
@ -506,9 +498,9 @@ if (isset($_GET['do']) && $isModerator == true) {
echo $pages_str . "</p>"; echo $pages_str . "</p>";
if (!empty($user['block'])) { if (User::getInstance()->getBlock()) {
$error = "Вы заблокированы!"; $error = "Вы заблокированы!";
} elseif ($user['level'] < 2) { } elseif (User::getInstance()->getLevel() < 2) {
$error = "Персонажам до 2-го уровня запрещено писать на форуме!"; $error = "Персонажам до 2-го уровня запрещено писать на форуме!";
} elseif (isset($sleep['id'])) { } elseif (isset($sleep['id'])) {
$error = "Вы молчите!"; $error = "Вы молчите!";

View File

@ -5,7 +5,7 @@
* Project name: Battles-Game * Project name: Battles-Game
*/ */
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\InventoryItem; use Battles\InventoryItem;
use Battles\Travel; use Battles\Travel;
@ -17,11 +17,9 @@ require_once 'config.php';
if (empty($_SESSION['uid'])) { if (empty($_SESSION['uid'])) {
header("Location: index.php"); header("Location: index.php");
exit; exit;
} elseif (empty($user)) {
$user = new User($_SESSION['uid']);
} }
if (User::$current->getBlock()) { if (User::getInstance()->getBlock()) {
exit('user blocked!'); exit('user blocked!');
} }
@ -33,7 +31,6 @@ $fbattleCheckFiles = [
'c_haos.php', 'c_haos.php',
'c_park.php', 'c_park.php',
'city.php', 'city.php',
'clan_castle.php',
'enter_cave.php', 'enter_cave.php',
'library.php', 'library.php',
'atk.php', 'atk.php',
@ -57,12 +54,12 @@ $fbattleCheckFiles = [
'zayavka.php', 'zayavka.php',
]; ];
//Может просто отовсюду? О_о //Может просто отовсюду? О_о
if (User::$current->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) { if (User::getInstance()->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::$current->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) { if (User::getInstance()->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) {
header('location: towerin.php'); header('location: towerin.php');
exit; exit;
} }
@ -70,8 +67,8 @@ $roomsCheck = [22, 23, 25, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401,
// Если я в одной из этих комнат, // Если я в одной из этих комнат,
// [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь // [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь
// [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых // [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых
if (in_array(User::$current->getRoom(), $roomsCheck) if (in_array(User::getInstance()->getRoom(), $roomsCheck)
&& pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::$current->getRoom()] && pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::getInstance()->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;
@ -79,8 +76,8 @@ if (in_array(User::$current->getRoom(), $roomsCheck)
if (!empty($_GET['goto']) && !empty($_GET['tStamp']) && !empty($_GET['vcode']) && $_GET['vcode'] == md5(sha1($_GET['goto'] . $_GET['tStamp']))) { if (!empty($_GET['goto']) && !empty($_GET['tStamp']) && !empty($_GET['vcode']) && $_GET['vcode'] == md5(sha1($_GET['goto'] . $_GET['tStamp']))) {
$query = 'update users u, online o set u.room = ?, o.room = ? where user_id = id and user_id = ?'; $query = 'update users u, online o set u.room = ?, o.room = ? where user_id = id and user_id = ?';
DBPDO::$db->execute($query, [$_GET['goto'], $_GET['goto'], User::$current->getId()]); Db::getInstance()->execute($query, [$_GET['goto'], $_GET['goto'], User::getInstance()->getId()]);
User::$current->setRoom(intval($_GET['goto'])); User::getInstance()->setRoom(intval($_GET['goto']));
} }
function createbot($bot, $login = "") function createbot($bot, $login = "")
@ -109,34 +106,6 @@ $var_map = [
'cell_25' => 'Полесье', 'cell_25' => 'Полесье',
]; ];
function get_out($u)
{
$pers = db::c()->query('SELECT * FROM users WHERE id = ?i', $u)->fetch_assoc_array();
DressedItems::undressAllItems($pers['id']);
db::c()->query('UPDATE inventory SET owner = ?i WHERE owner = ?i', $pers['id'], $pers['id'] + _BOTSEPARATOR_);
###
$row = db::c()->query('SELECT * FROM `effects` WHERE `owner` = ?i', $pers['id'] + _BOTSEPARATOR_);
$travm = [11, 12, 13, 14];
while ($efs = $row->fetch_assoc()) {
if (in_array($efs['type'], $travm)) {
$pers['sila'] -= $efs['sila'];
$pers['lovk'] -= $efs['lovk'];
$pers['inta'] -= $efs['inta'];
$pers['vinos'] -= $efs['vinos'];
} else {
$pers['sila'] += $efs['sila'];
$pers['lovk'] += $efs['lovk'];
$pers['inta'] += $efs['inta'];
$pers['vinos'] += $efs['vinos'];
$pers['maxhp'] += $efs['hp'];
}
$efs['owner'] = $_SESSION['uid'];
//mysql_query('UPDATE `effects` SET `owner` = "' . $efs['owner'] . '" WHERE `id` = "' . $efs['id'] . '" LIMIT 1');
//mysql_query('UPDATE `users` SET `sila` = "' . $pers['sila'] . '", `lovk` = "' . $pers['lovk'] . '", `inta` = "' . $pers['inta'] . '", `vinos` = "' . $pers['vinos'] . '", `maxhp` = "' . $pers['maxhp'] . '" WHERE `id` = "' . $pers['id'] . '" LIMIT 1');
}
###
}
const _BOTSEPARATOR_ = 10000000; const _BOTSEPARATOR_ = 10000000;
function savecavedata($cavedata, $caveleader, $floor) function savecavedata($cavedata, $caveleader, $floor)
@ -185,19 +154,19 @@ HTML;
function echoscroll($slot) function echoscroll($slot)
{ {
$all_magic = 0; $all_magic = 0;
if (User::$current->getBattle()) { if (User::getInstance()->getBattle()) {
$script = 'fbattle'; $script = 'fbattle';
$bat = db::c()->query('SELECT `magic` FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc(); $bat = db::c()->query('SELECT `magic` FROM `battle` WHERE `id` = ?i', User::getInstance()->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::$current->$slot)->fetch_assoc(); $dress = db::c()->query('SELECT `id`, `magic`, `name`, `img`, `duration`, `maxdur` FROM `inventory` WHERE `id` = ?i', User::getInstance()->$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::$current->$slot > 0) && ($all_magic[User::$current->getId()] < 1 || empty($need_charge['needcharge']))) { if ((User::getInstance()->$slot > 0) && ($all_magic[User::getInstance()->getId()] < 1 || empty($need_charge['needcharge']))) {
$row['id'] = User::$current->$slot; $row['id'] = User::getInstance()->$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=\"";
@ -214,7 +183,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::$current->$slot > 0) && ($all_magic[User::$current->getId()] >= 1) && $need_charge['needcharge'] > 0) { } elseif ((User::getInstance()->$slot > 0) && ($all_magic[User::getInstance()->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;
@ -367,8 +336,9 @@ function ref_drop()
// использовать магию // использовать магию
function usemagic($id, $target) function usemagic($id, $target)
{ {
$row = db::c()->query('SELECT * FROM `inventory` WHERE `owner` = ?i AND id = ?i', User::$current->getId(), $id)->fetch_assoc_array(); $user = Db::getInstance()->fetch('select * from users where id = ?', $_SESSION['uid']);
$bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc_array(); $row = db::c()->query('SELECT * FROM `inventory` WHERE `owner` = ?i AND id = ?i', User::getInstance()->getId(), $id)->fetch_assoc_array();
$bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', User::getInstance()->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();
@ -382,7 +352,7 @@ function usemagic($id, $target)
$charge = $incmagic['needcharge']; $charge = $incmagic['needcharge'];
} }
//Переделать под новую базу //Переделать под новую базу
if (($all_magic[User::$current->getId()] < 1 || $charge == 0) && if (($all_magic[User::getInstance()->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'] &&
@ -430,22 +400,22 @@ function usemagic($id, $target)
} else { } else {
$query = 'update inventory set durability = durability + ? where item_id = ?'; $query = 'update inventory set durability = durability + ? where item_id = ?';
} }
DBPDO::$db->execute($query, [$bat, $row['id']]); Db::getInstance()->execute($query, [$bat, $row['id']]);
} }
if (!$charge) { if (!$charge) {
$charge = 0; $charge = 0;
} }
//ограничение по кол-ву за ход //ограничение по кол-ву за ход
if (User::$current->getBattle()) { if (User::getInstance()->getBattle()) {
$bat = DBPDO::$db->fetch('select * from battle where battle_id = ?', User::$current->getBattle()); $batMagic = Db::getInstance()->fetchColumn('select magic from battle where battle_id = ?', User::getInstance()->getBattle());
} }
if ($bat['magic'] == '') { if (empty($batMagic)) {
$all_magic = []; $all_magic = [];
} else { } else {
$all_magic = unserialize($bat['magic']); $all_magic = unserialize($batMagic);
} }
$all_magic[User::$current->getId()] += $charge; $all_magic[User::getInstance()->getId()] += $charge;
DBPDO::$db->execute('update battle set magic = ? where battle_id = ?', [serialize($all_magic), User::$current->getBattle()]); Db::getInstance()->execute('update battle set magic = ? where battle_id = ?', [serialize($all_magic), User::getInstance()->getBattle()]);
} }
} }
return false; return false;
@ -462,7 +432,7 @@ function usemagic($id, $target)
function addch($text, $room = 0) function addch($text, $room = 0)
{ {
if ($room == 0) { if ($room == 0) {
$room = User::$current->getRoom(); $room = User::getInstance()->getRoom();
} }
if ($fp = @fopen("tmp/chat.txt", "a")) { //открытие if ($fp = @fopen("tmp/chat.txt", "a")) { //открытие
flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА
@ -477,7 +447,7 @@ function addch($text, $room = 0)
function addchp($text, $who, $room = 0) function addchp($text, $who, $room = 0)
{ {
if ($room == 0) { if ($room == 0) {
$room = User::$current->getRoom(); $room = User::getInstance()->getRoom();
} }
$fp = fopen("tmp/chat.txt", "a"); //открытие $fp = fopen("tmp/chat.txt", "a"); //открытие
flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА
@ -500,8 +470,8 @@ function err($t)
*/ */
function telegraph(int $userId, string $text) function telegraph(int $userId, string $text)
{ {
if (DBPDO::$db->ofetch('SELECT 1 FROM users WHERE id = ?', $userId)) { if (Db::getInstance()->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::getInstance()->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']);
} }
} }
@ -542,33 +512,31 @@ function SolveExp($at_id, $def_id, $damage): float
$bot_def = false; $bot_def = false;
if ($at_id > _BOTSEPARATOR_) { if ($at_id > _BOTSEPARATOR_) {
$bots = DBPDO::$db->fetch('select * from bots where bot_id = ?', $at_id); $at_id = Db::getInstance()->fetchColumn('select prototype from bots where bot_id = ?', $at_id);
$at_id = $bots['prototype'];
$bot_active = true; $bot_active = true;
} }
$query = 'select greatest(1, sum(price)) as allprice from users left join inventory on users.id = inventory.owner_id where id = ?'; $query = 'select greatest(1, sum(price)) as allprice from users left join inventory on users.id = inventory.owner_id where id = ?';
$at = DBPDO::$db->fetch($query, $at_id); $atAllPrice = Db::getInstance()->fetchColumn($query, $at_id);
$def = DBPDO::$db->fetch($query, $def_id); $defAllPrice = Db::getInstance()->fetchColumn($query, $def_id);
$atInfo = new UserStats($at_id); $atInfo = new UserStats($at_id);
$defInfo = new UserStats($def_id); $defInfo = new UserStats($def_id);
$table_name = $at_id > _BOTSEPARATOR_ ? 'bots' : 'users'; $table_name = $at_id > _BOTSEPARATOR_ ? 'bots' : 'users';
$bt = DBPDO::$db->fetch('select blood, type, t1, t2 from battle where battle_id = (select battle from ? where id = ?)', [$table_name, $at_id]); $bt = Db::getInstance()->ofetch('select blood, type, t1, t2 from battle where battle_id = (select battle from ? where id = ?)', [$table_name, $at_id]);
if ($def_id > _BOTSEPARATOR_) { if ($def_id > _BOTSEPARATOR_) {
$bots = DBPDO::$db->fetch('select * from bots where bot_id = ?', $def_id); $def_id = Db::getInstance()->fetchColumn('select prototype from bots where bot_id = ?', $def_id);
$def_id = $bots['prototype'];
$bot_def = true; $bot_def = true;
} }
if ($bt['blood']) { if ($bt->blood) {
$expmf = $mods['bloodb']; $expmf = $mods['bloodb'];
} }
$filebtl = '/tmp/' . $at_id . '.btl'; $filebtl = '/tmp/' . $at_id . '.btl';
if ($bt['type'] == 1 && file_exists($filebtl)) { if ($bt->type == 1 && file_exists($filebtl)) {
$btfl = fopen($filebtl, 'r'); $btfl = fopen($filebtl, 'r');
$contents = fread($btfl, filesize($filebtl)); $contents = fread($btfl, filesize($filebtl));
fclose($btfl); fclose($btfl);
@ -614,7 +582,7 @@ function SolveExp($at_id, $def_id, $damage): float
"25" => 919 "25" => 919
]; ];
$mfit = ($at['allprice'] / ($standart[$atInfo->getLevel()] / 3)); $mfit = ($atAllPrice / ($standart[$atInfo->getLevel()] / 3));
if ($mfit < 0.8) { if ($mfit < 0.8) {
$mfit = 0.8; $mfit = 0.8;
} }
@ -622,7 +590,7 @@ function SolveExp($at_id, $def_id, $damage): float
$mfit = 1.5; $mfit = 1.5;
} }
$pls = count(explode(";", $bt['t1'])) + count(explode(";", $bt['t2'])); $pls = count(explode(";", $bt->t1)) + count(explode(";", $bt->t2));
if ($pls > 2) { if ($pls > 2) {
$mfbot = $bot_active ? 0.3 : 1; $mfbot = $bot_active ? 0.3 : 1;
$mfbot2 = $bot_def ? 0.7 : 1; $mfbot2 = $bot_def ? 0.7 : 1;
@ -634,5 +602,5 @@ function SolveExp($at_id, $def_id, $damage): float
$expmf = 1; $expmf = 1;
} }
return round((($baseexp[$defInfo->getLevel()]) * ($def['allprice'] / (($at['allprice'] + $def['allprice']) / 2)) * ($damage / $defInfo->getMaxHealth()) * $expmf * $mfit * $mfbot * $mfbot2) / 3); return round((($baseexp[$defInfo->getLevel()]) * ($defAllPrice / (($atAllPrice + $defAllPrice) / 2)) * ($damage / $defInfo->getMaxHealth()) * $expmf * $mfit * $mfbot * $mfbot2) / 3);
} }

View File

@ -1,5 +1,9 @@
<?php <?php
/* Разрушенный замок на замковой улице. */ /* Разрушенный замок на замковой улице. */
use Battles\Template;
use Battles\User, Battles\Database\Db;
const CASTLE_MAX_LEVEL = 10; const CASTLE_MAX_LEVEL = 10;
require_once 'functions.php'; require_once 'functions.php';
$castleOwners = db::c()->query('SELECT * FROM `clans` WHERE `short` = (SELECT * FROM `variables` WHERE `var` = "?s")', 'gotzamok'); $castleOwners = db::c()->query('SELECT * FROM `clans` WHERE `short` = (SELECT * FROM `variables` WHERE `var` = "?s")', 'gotzamok');
@ -7,38 +11,36 @@ $castleOwners = db::c()->query('SELECT * FROM `clans` WHERE `short` = (SELECT *
if ($castleOwners['id'] == $user['klan']) { if ($castleOwners['id'] == $user['klan']) {
// если мой клан // если мой клан
if ($_GET['goto'] == 'arsenal') { if ($_GET['goto'] == 'arsenal') {
$user->setRoom(38); User::getInstance()->setRoom(38);
} }
if ($_GET['goto'] == 'home') { if ($_GET['goto'] == 'home') {
$user->setRoom(37); User::getInstance()->setRoom(37);
} }
if ($_GET['goto'] == 'dvor') { if ($_GET['goto'] == 'dvor') {
$user->setRoom(39); User::getInstance()->setRoom(39);
} }
if ($_GET['goto'] == 'master') { if ($_GET['goto'] == 'master') {
$user->setRoom(40); User::getInstance()->setRoom(40);
} }
if ($_GET['goto'] == 'rest') { if ($_GET['goto'] == 'rest') {
$user->setRoom(41); User::getInstance()->setRoom(41);
} }
if (in_array($_GET['goto'], ['arsenal', 'home', 'dvor', 'master', 'rest'])) { if (in_array($_GET['goto'], ['arsenal', 'home', 'dvor', 'master', 'rest'])) {
db::c()->query('UPDATE `users`,`online` SET `users`.`room` = ?i,`online`.`room` = ?i WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $user->getRoom(), $user->getRoom(), $user->getId()); db::c()->query('UPDATE `users`,`online` SET `users`.`room` = ?i,`online`.`room` = ?i WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', User::getInstance()->getRoom(), User::getInstance()->getRoom(), User::getInstance()->getId());
header('location: gotzamok.php'); header('location: gotzamok.php');
} else { } else {
$status = 'В этом замке нет такого места!'; $status = 'В этом замке нет такого места!';
} }
} }
switch ($user->getRoom()) { $i = User::getInstance()->getRoom();
case '37' : if ($i == '37') {
$backgroundImage = '689_small_550.jpg'; $backgroundImage = '689_small_550.jpg';
break; } elseif ($i == '41') {
case '41' :
$backgroundImage = 'ko.jpg'; $backgroundImage = 'ko.jpg';
break;
} }
if ($user->getRoom() == 38) { if (User::getInstance()->getRoom() == 38) {
$glava = db::c()->query('SELECT owner_id FROM `clans` WHERE `short` = "?s"', $user['klan'])->fetch_assoc(); $glava = db::c()->query('SELECT owner_id FROM `clans` WHERE `short` = "?s"', $user['klan'])->fetch_assoc();
// возврат шмотки // возврат шмотки
if ($_GET['back']) { if ($_GET['back']) {
@ -62,28 +64,36 @@ if ($user->getRoom() == 38) {
} }
} }
if ($user->getRoom() == 40) { if (User::getInstance()->getRoom() == 40) {
$at = db::c()->query('SELECT * FROM `variables` WHERE `var` = "?s"', 'gotzam_att')->fetch_assoc(); $at = db::c()->query('SELECT * FROM `variables` WHERE `var` = "?s"', 'gotzam_att')->fetch_assoc();
$def = db::c()->query('SELECT * FROM `variables` WHERE `var` = "?s"', 'gotzam_def')->fetch_assoc(); $def = db::c()->query('SELECT * FROM `variables` WHERE `var` = "?s"', 'gotzam_def')->fetch_assoc();
if ($_GET['up'] == 'at') { if ($_GET['up'] == 'at') {
if ($at[1] >= CASTLE_MAX_LEVEL) $status = 'Укрепление достигло максимального уровня!'; if ($at[1] >= CASTLE_MAX_LEVEL) {
$status = 'Укрепление достигло максимального уровня!';
}
elseif ((pow(52, $at[1] + 1)) <= $user['money']) { elseif ((pow(52, $at[1] + 1)) <= $user['money']) {
db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', pow(52, $at[1] + 1), $_SESSION['uid']); db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', pow(52, $at[1] + 1), $_SESSION['uid']);
db::c()->query('UPDATE `variables` SET `value` = `value` + 1 WHERE `var` = "?s"', 'gotzam_att'); db::c()->query('UPDATE `variables` SET `value` = `value` + 1 WHERE `var` = "?s"', 'gotzam_att');
$at += 1; $at += 1;
} else $status = 'Не хватает денег!'; } else {
$status = 'Не хватает денег!';
}
} }
if ($_GET['up'] == 'def') { if ($_GET['up'] == 'def') {
if ($def[1] >= CASTLE_MAX_LEVEL) $status = 'Укрепление достигло максимального уровня!'; if ($def[1] >= CASTLE_MAX_LEVEL) {
$status = 'Укрепление достигло максимального уровня!';
}
elseif ((pow(32, $def[1] + 1)) <= $user['money']) { elseif ((pow(32, $def[1] + 1)) <= $user['money']) {
db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', pow(52, $def[1] + 1), $_SESSION['uid']); db::c()->query('UPDATE `users` SET `money` = `money` - ?i WHERE `id` = ?i', pow(52, $def[1] + 1), $_SESSION['uid']);
db::c()->query('UPDATE `variables` SET `value` = `value` + 1 WHERE `var` = "?s"', 'gotzam_def'); db::c()->query('UPDATE `variables` SET `value` = `value` + 1 WHERE `var` = "?s"', 'gotzam_def');
$def += 1; $def += 1;
} else $status = 'Не хватает денег!'; } else {
$status = 'Не хватает денег!';
}
} }
} }
\Battles\Template::header('Клановый замок'); Template::header('Клановый замок');
?> ?>
<script src="js/main.js"></script> <script src="js/main.js"></script>
<style> <style>
@ -96,7 +106,9 @@ if ($user->getRoom() == 40) {
<div style="text-align: right;"> <div style="text-align: right;">
<button onClick="hrefToFrame('city.php?bps')">Вернуться</button> <button onClick="hrefToFrame('city.php?bps')">Вернуться</button>
</div> </div>
<div><?php if (!empty($status)) err($status); ?></div> <div><?php if (!empty($status)) {
err($status);
} ?></div>
<?php <?php
if ($castleOwners['id'] == $user['klan']) { ?> if ($castleOwners['id'] == $user['klan']) { ?>
@ -106,32 +118,32 @@ if ($castleOwners['id'] == $user['klan']) { ?>
<TD valign=top style="width:250px;"> <TD valign=top style="width:250px;">
<INPUT TYPE=button style="width:200px;" value="Перейти в приемную" <INPUT TYPE=button style="width:200px;" value="Перейти в приемную"
onClick="hrefToFrame('gotzamok.php?goto=home')"> onClick="hrefToFrame('gotzamok.php?goto=home')">
<? if ($user->getRoom() == 37): ?> <? if (User::getInstance()->getRoom() == 37): ?>
<img src='i/flag.gif'> <img src='i/flag.gif'>
<?php endif; ?><BR> <?php endif; ?><BR>
<INPUT TYPE=button style="width:200px;" value="Перейти в арсенал" <INPUT TYPE=button style="width:200px;" value="Перейти в арсенал"
onClick="hrefToFrame('gotzamok.php?goto=arsenal')"> onClick="hrefToFrame('gotzamok.php?goto=arsenal')">
<? if ($user->getRoom() == 38): ?> <? if (User::getInstance()->getRoom() == 38): ?>
<img src='i/flag.gif'> <img src='i/flag.gif'>
<?php endif; ?><BR> <?php endif; ?><BR>
<INPUT TYPE=button style="width:200px;" value="Перейти во внутренний двор" <INPUT TYPE=button style="width:200px;" value="Перейти во внутренний двор"
onClick="hrefToFrame('gotzamok.php?goto=dvor')"> onClick="hrefToFrame('gotzamok.php?goto=dvor')">
<? if ($user->getRoom() == 39): ?> <? if (User::getInstance()->getRoom() == 39): ?>
<img src='i/flag.gif'> <img src='i/flag.gif'>
<?php endif; ?><BR> <?php endif; ?><BR>
<INPUT TYPE=button style="width:200px;" value="Перейти в мастерские" <INPUT TYPE=button style="width:200px;" value="Перейти в мастерские"
onClick="hrefToFrame('gotzamok.php?goto=master')"> onClick="hrefToFrame('gotzamok.php?goto=master')">
<? if ($user->getRoom() == 40): ?> <? if (User::getInstance()->getRoom() == 40): ?>
<img src='i/flag.gif'> <img src='i/flag.gif'>
<?php endif; ?><BR> <?php endif; ?><BR>
<INPUT TYPE=button style="width:200px;" value="Перейти в опочивальни" <INPUT TYPE=button style="width:200px;" value="Перейти в опочивальни"
onClick="hrefToFrame('gotzamok.php?goto=rest')"> onClick="hrefToFrame('gotzamok.php?goto=rest')">
<? if ($user->getRoom() == 41): ?> <? if (User::getInstance()->getRoom() == 41): ?>
<img src='i/flag.gif'> <img src='i/flag.gif'>
<?php endif; ?><BR> <?php endif; ?><BR>
</td> </td>
<td valign=top> <td valign=top>
<?php if ($user->getRoom() == 38): ?> <?php if (User::getInstance()->getRoom() == 38): ?>
<h4>Арсенал</h4> <h4>Арсенал</h4>
<button onClick="hrefToFrame('gotzamok.php?do=zdat')">Сдать в арсенал</button> <button onClick="hrefToFrame('gotzamok.php?do=zdat')">Сдать в арсенал</button>
<div style="background: silver; border: 1px solid dimgray;"> <div style="background: silver; border: 1px solid dimgray;">
@ -174,7 +186,7 @@ if ($castleOwners['id'] == $user['klan']) { ?>
<?php <?php
endif; endif;
endif; endif;
if ($user->getRoom() == 40): ?> if (User::getInstance()->getRoom() == 40): ?>
<h4>Мастерские</h4> <h4>Мастерские</h4>
<div style="background: silver; border: 1px solid dimgray;"> <div style="background: silver; border: 1px solid dimgray;">
Здесь вы можете улучшить оборонные способности вашего замка. Здесь вы можете улучшить оборонные способности вашего замка.
@ -191,7 +203,7 @@ if ($castleOwners['id'] == $user['klan']) { ?>
</div> </div>
</div> </div>
<?php endif; <?php endif;
if ($user->getRoom() == 41): ?> if (User::getInstance()->getRoom() == 41): ?>
<h4>Комнаты отдыха</h4> <h4>Комнаты отдыха</h4>
<div style="background: silver; border: 1px solid dimgray;"> <div style="background: silver; border: 1px solid dimgray;">
Посиди в тишине, внутри стен. Тут нет врагов. Тут спокойно. Посиди в тишине, внутри стен. Тут нет врагов. Тут спокойно.
@ -200,4 +212,6 @@ if ($castleOwners['id'] == $user['klan']) { ?>
</td> </td>
</tr> </tr>
</table> </table>
<? } else $status = 'Ворота замка закрыты, привратник отказывается даже разговаривать с тобой...'; ?> <? } else {
$status = 'Ворота замка закрыты, привратник отказывается даже разговаривать с тобой...';
} ?>

View File

@ -1,7 +1,9 @@
<?php <?php
use Battles\Nick;
use Battles\ShopItem; use Battles\ShopItem;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
@ -9,20 +11,7 @@ $error = '';
function login($uid) function login($uid)
{ {
$user = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `align`, `level`, `klan` FROM `users` WHERE `id` = "' . mysql_real_escape_string($uid) . '" LIMIT 1')); return User::getInstance($uid)->getId() ? Nick::id(User::getInstance()->getId())->full() : 'Место свободно';
if (isset($user['id'])) {
$align_img = '<img src="i/align_' . ($user['align'] ? $user['align'] : 0) . '.gif" /> ';
if ($user['klan'] != '') {
$clan = mysql_fetch_array(mysql_query('SELECT `id`, `name` FROM `clans` WHERE `id` = "' . $user['klan'] . '" LIMIT 1'));
$clan_img = '<img title="' . $clan['name'] . '" src="i/clan/' . $clan['name'] . '.png" /> ';
} else {
$clan_img = '';
}
$r = $align_img . $clan_img . ' <b>' . $user['login'] . ' [' . $user['level'] . ']</b><a href="/inf.php?' . $user['id'] . '" target="_blank"><img src="/i/inf.gif" /></a>';
} else {
$r = 'Место свободно';
}
return $r;
} }

View File

@ -4,8 +4,7 @@ use Battles\Template;
use Battles\User; use Battles\User;
require_once 'config.php'; require_once 'config.php';
$user = User::$current; $hostel = mysql_fetch_array(mysql_query('SELECT `id`, `uid`, `type`, `time` FROM `hostel` WHERE `uid` = "' . User::getInstance()->getId() . '" LIMIT 1'));
$hostel = mysql_fetch_array(mysql_query('SELECT `id`, `uid`, `type`, `time` FROM `hostel` WHERE `uid` = "' . $user['id'] . '" LIMIT 1'));
$error = ''; $error = '';
$rs = ''; $rs = '';
$base = [1 => ['type' => 'Сумка'], 2 => ['type' => 'Сундук'], 3 => ['type' => 'Комната'], 4 => ['type' => 'Амбар']]; $base = [1 => ['type' => 'Сумка'], 2 => ['type' => 'Сундук'], 3 => ['type' => 'Комната'], 4 => ['type' => 'Амбар']];
@ -52,7 +51,7 @@ function select_arenda($u, $type, $redirect = false)
if ($_GET['exit'] == 1) { if ($_GET['exit'] == 1) {
if ($user['sleep'] == 0) { if ($user['sleep'] == 0) {
mysql_query('UPDATE `users`,`online` SET `users`.`room` = 26, `online`.`room` = 26 WHERE `users`.`id` = "' . $user['id'] . '" AND `online`.`id` = "' . $user['id'] . '"'); mysql_query('UPDATE `users`,`online` SET `users`.`room` = 26, `online`.`room` = 26 WHERE `users`.`id` = "' . User::getInstance()->getId() . '" AND `online`.`id` = "' . User::getInstance()->getId() . '"');
header('Location: city.php'); header('Location: city.php');
} else { } else {
$error = 'Вы спите ...'; $error = 'Вы спите ...';
@ -62,7 +61,7 @@ if ($_GET['exit'] == 1) {
if ($_GET['to_room'] == 1) { if ($_GET['to_room'] == 1) {
if (isset($hostel['id'])) { if (isset($hostel['id'])) {
if ($hostel['time'] > time()) { if ($hostel['time'] > time()) {
mysql_query('UPDATE `users`,`online` SET `users`.`room` = 661, `online`.`room` = 661 WHERE `users`.`id` = "' . $user['id'] . '" AND `online`.`id` = "' . $user['id'] . '"'); mysql_query('UPDATE `users`,`online` SET `users`.`room` = 661, `online`.`room` = 661 WHERE `users`.`id` = "' . User::getInstance()->getId() . '" AND `online`.`id` = "' . User::getInstance()->getId() . '"');
header('Location: hostel_room.php'); header('Location: hostel_room.php');
} else { } else {
$error = 'У Вас просрочена аренда. Оплатите что-бы продолжить пользоваться нашими услугами ...'; $error = 'У Вас просрочена аренда. Оплатите что-бы продолжить пользоваться нашими услугами ...';
@ -74,12 +73,12 @@ if ($_GET['to_room'] == 1) {
if ($_GET['pays'] && (int)$_GET['pays'] >= 1 && (int)$_GET['pays'] <= 4) { if ($_GET['pays'] && (int)$_GET['pays'] >= 1 && (int)$_GET['pays'] <= 4) {
if (isset($hostel['id'])) { if (isset($hostel['id'])) {
if ($user['money'] >= $cost[$hostel['type']][(int)$_GET['pays']]) { if (User::getInstance()->getMoney() >= $cost[$hostel['type']][(int)$_GET['pays']]) {
$time = $hostel['time'] + 60 * 60 * 24 * $times[(int)$_GET['pays']]; $time = $hostel['time'] + 60 * 60 * 24 * $times[(int)$_GET['pays']];
$user['money'] -= $cost[$hostel['type']][(int)$_GET['pays']]; User::getInstance()->setMoney(User::getInstance()->getMoney() -= $cost[$hostel['type']][(int)$_GET['pays']]);
$hostel['time'] = $time; $hostel['time'] = $time;
mysql_query('UPDATE `users` SET `money` = "' . $user['money'] . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1'); mysql_query('UPDATE `users` SET `money` = "' . User::getInstance()->getMoney() . '" WHERE `id` = "' . User::getInstance()->getId() . '" LIMIT 1');
mysql_query('UPDATE `hostel` SET `time` = "' . $time . '" WHERE `uid` = "' . $user['id'] . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1'); mysql_query('UPDATE `hostel` SET `time` = "' . $time . '" WHERE `uid` = "' . User::getInstance()->getId() . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1');
$error = 'Всё прошло успешно ...'; $error = 'Всё прошло успешно ...';
} else { } else {
$error = 'Недостаточно денег ...'; $error = 'Недостаточно денег ...';
@ -93,14 +92,14 @@ if (isset($_POST['select']) && isset($_POST['tariff'])) {
if ($_POST['tariff'] == 0) { if ($_POST['tariff'] == 0) {
$error = 'Выберите тариф ...'; $error = 'Выберите тариф ...';
} else { } else {
$error = select_arenda($user, (int)$_POST['tariff']); $error = select_arenda(User::getInstance(), (int)$_POST['tariff']);
} }
} }
if ($_GET['del'] == 1) { if ($_GET['del'] == 1) {
if (isset($hostel['id']) && $hostel['time'] > time()) { if (isset($hostel['id']) && $hostel['time'] > time()) {
mysql_query('DELETE FROM `hostel` WHERE `uid` = "' . $user['id'] . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1'); mysql_query('DELETE FROM `hostel` WHERE `uid` = "' . User::getInstance()->getId() . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1');
remove_hostel_items($user['id']); remove_hostel_items(User::getInstance()->getId());
$error = 'Вы успешно отказались от аренды ...'; $error = 'Вы успешно отказались от аренды ...';
unset($hostel); unset($hostel);
} elseif (isset($hostel['id']) && $hostel['time'] < time()) { } elseif (isset($hostel['id']) && $hostel['time'] < time()) {
@ -110,9 +109,9 @@ if ($_GET['del'] == 1) {
if (isset($_POST['deselect']) && isset($_POST['retariff'])) { if (isset($_POST['deselect']) && isset($_POST['retariff'])) {
if (isset($hostel['id']) && $hostel['time'] > time()) { if (isset($hostel['id']) && $hostel['time'] > time()) {
mysql_query('DELETE FROM `hostel` WHERE `uid` = "' . $user['id'] . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1'); mysql_query('DELETE FROM `hostel` WHERE `uid` = "' . User::getInstance()->getId() . '" AND `id` = "' . $hostel['id'] . '" LIMIT 1');
remove_hostel_items($user['id']); remove_hostel_items(User::getInstance()->getId());
select_arenda($user, (int)$_POST['retariff'], true); select_arenda(User::getInstance(), (int)$_POST['retariff'], true);
} elseif (isset($hostel['id']) && $hostel['time'] < time()) { } elseif (isset($hostel['id']) && $hostel['time'] < time()) {
$error = 'Нельзя сменить услугу если имеется задолежнность ...'; $error = 'Нельзя сменить услугу если имеется задолежнность ...';
} }
@ -120,21 +119,13 @@ if (isset($_POST['deselect']) && isset($_POST['retariff'])) {
if ($_GET['sleep'] && $user['sleep'] == 0) { if ($_GET['sleep'] && $user['sleep'] == 0) {
if ($user['sleep_time'] <= time()) { if ($user['sleep_time'] <= time()) {
if ($user['vip'] == 1) {
$sl = 8;
} elseif ($user['vip'] == 2) {
$sl = 12;
} elseif ($user['vip'] == 3) {
$sl = 18;
} else {
$sl = 2; $sl = 2;
} mysql_query('UPDATE `users` SET `sleep` = "' . (time() + 60 * 60 * $sl) . '", `sleep_time` = "' . (time() + 60 * 60 * 8) . '" WHERE `id` = "' . User::getInstance()->getId() . '" LIMIT 1');
mysql_query('UPDATE `users` SET `sleep` = "' . (time() + 60 * 60 * $sl) . '", `sleep_time` = "' . (time() + 60 * 60 * 8) . '" WHERE `id` = "' . $user['id'] . '" LIMIT 1'); mysql_query('INSERT INTO `effects` (`type`, `name`, `time`, `owner`) VALUES ("8", "Сон", "' . (time() + 60 * 60 * $sl) . '", "' . User::getInstance()->getId() . '")');
mysql_query('INSERT INTO `effects` (`type`, `name`, `time`, `owner`) VALUES ("8", "Сон", "' . (time() + 60 * 60 * $sl) . '", "' . $user['id'] . '")'); $ef = mysql_query('SELECT `id`, `time`, `type` FROM `effects` WHERE `owner` = "' . User::getInstance()->getId() . '" AND `type` != 11 AND `type` != 12 AND `type` != 13 AND `type` != 14 AND `type` != 5 AND `type` != 4 AND `type` != 2 AND `type` != 3 AND `type` != 8');
$ef = mysql_query('SELECT `id`, `time`, `type` FROM `effects` WHERE `owner` = "' . $user['id'] . '" AND `type` != 11 AND `type` != 12 AND `type` != 13 AND `type` != 14 AND `type` != 5 AND `type` != 4 AND `type` != 2 AND `type` != 3 AND `type` != 8');
while ($pl = mysql_fetch_array($ef)) { while ($pl = mysql_fetch_array($ef)) {
$tm = $pl['time'] - time(); $tm = $pl['time'] - time();
mysql_query('UPDATE `effects` SET `sleep` = "' . $tm . '" WHERE `id` = "' . $pl['id'] . '" AND `owner` = "' . $user['id'] . '"'); mysql_query('UPDATE `effects` SET `sleep` = "' . $tm . '" WHERE `id` = "' . $pl['id'] . '" AND `owner` = "' . User::getInstance()->getId() . '"');
} }
header('Location: hostel.php'); header('Location: hostel.php');
} else { } else {
@ -143,12 +134,12 @@ if ($_GET['sleep'] && $user['sleep'] == 0) {
} }
if ($_GET['unsleep'] && $user['sleep'] > 0) { if ($_GET['unsleep'] && $user['sleep'] > 0) {
mysql_query('UPDATE `users` SET `sleep` = "0" WHERE `id` = "' . $user['id'] . '" LIMIT 1'); mysql_query('UPDATE `users` SET `sleep` = "0" WHERE `id` = "' . User::getInstance()->getId() . '" LIMIT 1');
mysql_query('DELETE FROM `effects` WHERE `owner` = "' . $user['id'] . '" AND `type` = "8" LIMIT 1'); mysql_query('DELETE FROM `effects` WHERE `owner` = "' . User::getInstance()->getId() . '" AND `type` = "8" LIMIT 1');
$ef = mysql_query('SELECT `id`, `time`, `sleep` FROM `effects` WHERE `owner` = "' . $user['id'] . '" AND `sleep` != 0'); $ef = mysql_query('SELECT `id`, `time`, `sleep` FROM `effects` WHERE `owner` = "' . User::getInstance()->getId() . '" AND `sleep` != 0');
while ($pl = mysql_fetch_array($ef)) { while ($pl = mysql_fetch_array($ef)) {
$tm = time() + $pl['sleep']; $tm = time() + $pl['sleep'];
mysql_query('UPDATE `effects` SET `time` = "' . $tm . '", `sleep` = "0" WHERE `id` = "' . $pl['id'] . '" AND `owner` = "' . $user['id'] . '"'); mysql_query('UPDATE `effects` SET `time` = "' . $tm . '", `sleep` = "0" WHERE `id` = "' . $pl['id'] . '" AND `owner` = "' . User::getInstance()->getId() . '"');
} }
header('Location: hostel.php'); header('Location: hostel.php');
} }

View File

@ -1,18 +1,21 @@
<?php <?php
use Battles\User, Battles\Database\Db;
require_once "functions.php"; require_once "functions.php";
$hostel = \Battles\Database\DBPDO::$db->fetch('select * from hostel where uid = ?', \Battles\User::$current->getId()); $hostel = Db::getInstance()->execute('select id, time, type from hostel where uid = ?', User::getInstance()->getId());
$base = [1 => [8, 16, 24, 32], 2 => [15, 30, 45, 60], 3 => [25, 50, 75, 100], 4 => [40, 80, 120, 160]]; $base = [1 => [8, 16, 24, 32], 2 => [15, 30, 45, 60], 3 => [25, 50, 75, 100], 4 => [40, 80, 120, 160]];
if (isset($_POST['act']) && $_POST['act'] == 'pay' && isset($user['id']) && isset($hostel['id'])) { if (isset($_POST['act']) && $_POST['act'] == 'pay' && isset($user['id']) && !empty($hostel->fetchColumn())) {
echo '<fieldset class="hostelClientState">'; echo '<fieldset class="hostelClientState">';
echo '<legend>Предварительная оплата</legend>'; echo '<legend>Предварительная оплата</legend>';
echo '<div style="text-align: center;"><p class="NORMAL" style="margin: 5px 0">'; echo '<div style="text-align: center;"><p class="NORMAL" style="margin: 5px 0">';
echo 'Аренда оплачена по: <b>' . date('h:i d.m.y', $hostel['time']) . '</b> <small>(' . timeOut($hostel['time'] - time()) . ')</small></p></div>'; echo 'Аренда оплачена по: <b>' . date('h:i d.m.y', $hostel->fetchColumn(1)) . '</b> <small>(' . timeOut($hostel->fetchColumn(1) - time()) . ')</small></p></div>';
echo '<table align="center" class="periods"><caption style="text-align: left;">Выберите срок предоплаты.</caption> echo '<table align="center" class="periods"><caption style="text-align: left;">Выберите срок предоплаты.</caption>
<tbody> <tbody>
<tr class="caption"><th>Сутки</th><td title="7 дн.">7</td><td title="14 дн.">14</td><td title="21 дн.">21</td><td title="28 дн.">28</td></tr> <tr class="caption"><th>Сутки</th><td title="7 дн.">7</td><td title="14 дн.">14</td><td title="21 дн.">21</td><td title="28 дн.">28</td></tr>
<tr class="value"><th>Сумма</th><td title="7 дн."><a href="?pays=1">' . $base[$hostel['type']][0] . '</a></td><td title="14 дн."><a href="?pays=2">' . $base[$hostel['type']][1] . '</a></td><td title="21 дн."><a href="?pays=3">' . $base[$hostel['type']][2] . '</a></td><td title="28 дн."><a href="?pays=4">' . $base[$hostel['type']][3] . '</a></td></tr> <tr class="value"><th>Сумма</th><td title="7 дн."><a href="?pays=1">' . $base[$hostel->fetchColumn(2)][0] . '</a></td><td title="14 дн."><a href="?pays=2">' . $base[$hostel->fetchColumn(2)][1] . '</a></td><td title="21 дн."><a href="?pays=3">' . $base[$hostel->fetchColumn(2)][2] . '</a></td><td title="28 дн."><a href="?pays=4">' . $base[$hostel->fetchColumn(2)][3] . '</a></td></tr>
</tbody> </tbody>
</table> </table>
<div style="color: red; font-size: 9px; padding-top: 3px;"><b>Внимание!</b> При расторжении договора или смене тарифа, внесенная плата не возвращается</div></fieldset></div>'; <div style="color: red; font-size: 9px; padding-top: 3px;"><b>Внимание!</b> При расторжении договора или смене тарифа, внесенная плата не возвращается</div></fieldset></div>';

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\InventoryItem; use Battles\InventoryItem;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
@ -17,8 +17,8 @@ $vips = [1 => 0.15, 2 => 0.30, 3 => 0.45];
function get_meshok(): object function get_meshok(): object
{ {
$allweight = DBPDO::$db->ofetch('select sum(weight) as items_weight_sum from inventory where on_sale = 0 and owner_id = ?', User::$current->getId()); $allweight = Db::getInstance()->ofetch('select sum(weight) as items_weight_sum from inventory where on_sale = 0 and owner_id = ?', User::getInstance()->getId());
$stat = new UserInfo(User::$current->getId()); $stat = new UserInfo(User::getInstance()->getId());
return (object)[ return (object)[
'currentweight' => $allweight->items_weight_sum, 'currentweight' => $allweight->items_weight_sum,
'maxweight' => $stat->getMaxWeight() + $allweight->items_weight_sum, 'maxweight' => $stat->getMaxWeight() + $allweight->items_weight_sum,

View File

@ -8,7 +8,6 @@ include_once 'config.php';
$userInfo = new UserInfo(urldecode($_SERVER['QUERY_STRING'])); $userInfo = new UserInfo(urldecode($_SERVER['QUERY_STRING']));
$presentsModel = new PresentsModel($userInfo->getId()); $presentsModel = new PresentsModel($userInfo->getId());
$presentsList = $presentsModel->getAllPresents(); $presentsList = $presentsModel->getAllPresents();
$userInfo->setWatcher($_SESSION['uid']);
Template::header('Информация о ' . $userInfo->getLogin()); Template::header('Информация о ' . $userInfo->getLogin());
if (!$userInfo->getId()) { if (!$userInfo->getId()) {
echo sprintf('Ошибка: персонаж <em>%s</em> не найден...<p><a style="color: #99f;" href="javascript:window.history.go(-1);">←назад</a></p>', urldecode($_SERVER['QUERY_STRING'])); echo sprintf('Ошибка: персонаж <em>%s</em> не найден...<p><a style="color: #99f;" href="javascript:window.history.go(-1);">←назад</a></p>', urldecode($_SERVER['QUERY_STRING']));

View File

@ -94,51 +94,51 @@ var chat = {
}, },
lookSmiles:function() lookSmiles:function()
{ {
if($('#chbtn8').attr('class')=='db cp chatBtn8_1') if($('#chbtn8').attr('class')=='getInstance cp chatBtn8_1')
{ {
$('#ttSmiles').css('display',''); $('#ttSmiles').css('display','');
$('#chbtn8').attr('class','db cp chatBtn8_2'); $('#chbtn8').attr('class','getInstance cp chatBtn8_2');
}else{ }else{
$('#ttSmiles').css('display','none'); $('#ttSmiles').css('display','none');
$('#chbtn8').attr('class','db cp chatBtn8_1'); $('#chbtn8').attr('class','getInstance cp chatBtn8_1');
} }
}, },
filterMsg:function() filterMsg:function()
{ {
if($('#chbtn1').attr('class')=='db cp chatBtn1_1') if($('#chbtn1').attr('class')=='getInstance cp chatBtn1_1')
{ {
$('#chbtn1').attr('class','db cp chatBtn1_2'); this.filter = 1; $('#chbtn1').attr('class','getInstance cp chatBtn1_2'); this.filter = 1;
}else{ }else{
$('#chbtn1').attr('class','db cp chatBtn1_1'); this.filter = 0; $('#chbtn1').attr('class','getInstance cp chatBtn1_1'); this.filter = 0;
} }
}, },
systemMsg:function() systemMsg:function()
{ {
if($('#chbtn4').attr('class')=='db cp chatBtn4_1') if($('#chbtn4').attr('class')=='getInstance cp chatBtn4_1')
{ {
$('#chbtn4').attr('class','db cp chatBtn4_2'); this.citySys = 1; $.cookie('citySys',1); $('#chbtn4').attr('class','getInstance cp chatBtn4_2'); this.citySys = 1; $.cookie('citySys',1);
}else{ }else{
$('#chbtn4').attr('class','db cp chatBtn4_1'); this.citySys = 0; $.cookie('citySys',0); $('#chbtn4').attr('class','getInstance cp chatBtn4_1'); this.citySys = 0; $.cookie('citySys',0);
} }
}, },
soundChat:function() soundChat:function()
{ {
if($('#chbtn7').attr('class')=='db cp chatBtn7_1') if($('#chbtn7').attr('class')=='getInstance cp chatBtn7_1')
{ {
$('#chbtn7').attr('class','db cp chatBtn7_2'); this.sound = 1; $('#chbtn7').attr('class','getInstance cp chatBtn7_2'); this.sound = 1;
}else if($('#chbtn7').attr('class')=='db cp chatBtn7_2'){ }else if($('#chbtn7').attr('class')=='getInstance cp chatBtn7_2'){
$('#chbtn7').attr('class','db cp chatBtn7_3'); this.sound = 2; $('#chbtn7').attr('class','getInstance cp chatBtn7_3'); this.sound = 2;
}else{ }else{
$('#chbtn7').attr('class','db cp chatBtn7_1'); this.sound = 0; $('#chbtn7').attr('class','getInstance cp chatBtn7_1'); this.sound = 0;
} }
}, },
translitChat:function() translitChat:function()
{ {
if($('#chbtn6').attr('class')=='db cp chatBtn6_1') if($('#chbtn6').attr('class')=='getInstance cp chatBtn6_1')
{ {
$('#chbtn6').attr('class','db cp chatBtn6_2'); this.translit = 1; $('#chbtn6').attr('class','getInstance cp chatBtn6_2'); this.translit = 1;
}else{ }else{
$('#chbtn6').attr('class','db cp chatBtn6_1'); this.translit = 0; $('#chbtn6').attr('class','getInstance cp chatBtn6_1'); this.translit = 0;
} }
},subValSend:'', },subValSend:'',
subSend:function() subSend:function()
@ -409,7 +409,7 @@ var chat = {
if(top.cb_date[top.cb_select] == 4 || top.cb_date[top.cb_select] == 5) { if(top.cb_date[top.cb_select] == 4 || top.cb_date[top.cb_select] == 5) {
$('#canal'+top.cb_date[top.cb_select]).html(''); $('#canal'+top.cb_date[top.cb_select]).html('');
$('#textmsg').focus(); $('#textmsg').focus();
}; }
} }
}else{ }else{
$('#textmsg').val(''); $('#textmsg').val('');
@ -692,7 +692,7 @@ var chat = {
}, },
convert2:function(txt) convert2:function(txt)
{ {
var trn = new Array(); var trn = [];
trn = txt.split(' '); trn = txt.split(' ');
for(var i=0;i<trn.length;i++) { for(var i=0;i<trn.length;i++) {
if(trn[i].indexOf("//") < 0 && trn[i].indexOf('@') < 0 && trn[i].indexOf("www.") < 0 && !(trn[i].charAt(0)==":" && trn[i].charAt(trn[i].length-1)==":")) { if(trn[i].indexOf("//") < 0 && trn[i].indexOf('@') < 0 && trn[i].indexOf("www.") < 0 && !(trn[i].charAt(0)==":" && trn[i].charAt(trn[i].length-1)==":")) {

47
lab.php
View File

@ -1,4 +1,7 @@
<?php <?php
use Battles\Template;
require_once "functions.php"; require_once "functions.php";
if ($user['lab'] == 0) { if ($user['lab'] == 0) {
header("Location: index.php"); header("Location: index.php");
@ -17,7 +20,7 @@ $u_res = mysql_fetch_array(mysql_query("select * from `lab_user` where `id_user`
</script> </script>
<?php <?php
$room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string($user->getRoom()) . "';")); $room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "';"));
if ($_GET['healall'] == 1) { if ($_GET['healall'] == 1) {
$cost = $_GET['cost']; $cost = $_GET['cost'];
@ -123,7 +126,7 @@ if ($_GET['mobkill'] == 1) {
} }
$rand_hp1 = rand(1, 10); $rand_hp1 = rand(1, 10);
$rand_hp = $rand_hp1 * $user['level']; $rand_hp = $rand_hp1 * $user['level'];
$bot = mysql_fetch_array(mysql_query("select * from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1")); $bot = mysql_fetch_array(mysql_query("select * from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1"));
$hels = $bot['bot_hp'] - $rand_hp; $hels = $bot['bot_hp'] - $rand_hp;
if ($hels < 0) { if ($hels < 0) {
echo "<b>Вы убили моба!</b><br>"; echo "<b>Вы убили моба!</b><br>";
@ -134,11 +137,11 @@ if ($_GET['mobkill'] == 1) {
echo "Вы получили 1 записку!<br>"; echo "Вы получили 1 записку!<br>";
Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'"); Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'");
} }
mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1"); mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1");
//если просто убивалка //если просто убивалка
} else { } else {
Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'"); Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'");
mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1"); mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1");
} }
} else { } else {
echo "Вы отняли у моба -<b>" . $rand_hp . "</b> HP!<br>"; echo "Вы отняли у моба -<b>" . $rand_hp . "</b> HP!<br>";
@ -176,7 +179,7 @@ if ($_GET['exit'] && $room['exit'] == 1) {
if ($_GET['get']) { if ($_GET['get']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_inv` WHERE `id` = '" . mysql_real_escape_string($_GET['get']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_inv` WHERE `id` = '" . mysql_real_escape_string($_GET['get']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
switch ($data['type']) { switch ($data['type']) {
case 1: case 1:
@ -240,13 +243,13 @@ if ($_GET['get']) {
if ($_GET['drop']) { if ($_GET['drop']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($_GET['drop']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($_GET['drop']) . "' AND `id_user`='" . $user['id'] . "';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($data['id']) . "' AND `id_user`='" . $user['id'] . "' LIMIT 1;"); mysql_query("DELETE FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($data['id']) . "' AND `id_user`='" . $user['id'] . "' LIMIT 1;");
mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`,`id_user`) values ('" . mysql_real_escape_string($user->getRoom()) . "','" . mysql_real_escape_string($data['type']) . "','" . mysql_real_escape_string($data['value']) . "','" . mysql_real_escape_string($user['id']) . "');"); mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`,`id_user`) values ('" . mysql_real_escape_string(User::getInstance()->getRoom()) . "','" . mysql_real_escape_string($data['type']) . "','" . mysql_real_escape_string($data['value']) . "','" . mysql_real_escape_string($user['id']) . "');");
unset($data); unset($data);
} }
if ($_GET['nal1']) { if ($_GET['nal1']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal1']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal1']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';");
mysql_query("UPDATE `users` SET `money` = `money`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `money` = `money`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -258,7 +261,7 @@ if ($_GET['nal1']) {
if ($_GET['nal2']) { if ($_GET['nal2']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal2']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal2']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';");
mysql_query("UPDATE `users` SET `doblest` = `doblest`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `doblest` = `doblest`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -270,7 +273,7 @@ if ($_GET['nal2']) {
if ($_GET['nal3']) { if ($_GET['nal3']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal3']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal3']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';");
mysql_query("UPDATE `bank` SET `ekr` = `ekr`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `bank` SET `ekr` = `ekr`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -282,7 +285,7 @@ if ($_GET['nal3']) {
if ($_GET['nal4']) { if ($_GET['nal4']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal4']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal4']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';");
mysql_query("UPDATE `users` SET `exp` = `exp`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `exp` = `exp`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -298,28 +301,28 @@ if ($_GET['go']) {
switch ($_GET['go']) { switch ($_GET['go']) {
case "p1": case "p1":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p1']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p1']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p1']); User::getInstance()->setRoom($room['p1']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p2": case "p2":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p2']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p2']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p2']); User::getInstance()->setRoom($room['p2']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p3": case "p3":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p3']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p3']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p3']); User::getInstance()->setRoom($room['p3']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p4": case "p4":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p4']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p4']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p4']); User::getInstance()->setRoom($room['p4']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
} }
} }
$room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string($user->getRoom()) . "';")); $room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "';"));
if ($user['hp'] <= 0) { if ($user['hp'] <= 0) {
mysql_query("DELETE FROM `lab_trap` WHERE `id_user` = '" . $user['id'] . "'"); mysql_query("DELETE FROM `lab_trap` WHERE `id_user` = '" . $user['id'] . "'");
@ -334,12 +337,12 @@ if ($user['hp'] <= 0) {
} }
$data = mysql_query("SELECT * FROM `lab_inv` WHERE `id_room` = '" . mysql_real_escape_string($user->getRoom()) . "' AND `id_user`='" . $user['id'] . "';"); $data = mysql_query("SELECT * FROM `lab_inv` WHERE `id_room` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "' AND `id_user`='" . $user['id'] . "';");
$data2 = mysql_query("SELECT * FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "';"); $data2 = mysql_query("SELECT * FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "';");
$data3 = mysql_query("SELECT * FROM `users` WHERE `lab` = 1 AND `room` = '" . mysql_real_escape_string($room['id']) . "';"); $data3 = mysql_query("SELECT * FROM `users` WHERE `lab` = 1 AND `room` = '" . mysql_real_escape_string($room['id']) . "';");
$data4 = mysql_query("SELECT * FROM `lab_bots` WHERE `id_room` = '" . mysql_real_escape_string($room['id']) . "' AND `id_user`='" . $user['id'] . "';"); $data4 = mysql_query("SELECT * FROM `lab_bots` WHERE `id_room` = '" . mysql_real_escape_string($room['id']) . "' AND `id_user`='" . $user['id'] . "';");
$roow = mysql_fetch_array(mysql_query("SELECT * FROM `lab_trap` WHERE `id_room` = '" . mysql_real_escape_string($user->getRoom()) . "' AND `id_user`='" . $user['id'] . "';")); $roow = mysql_fetch_array(mysql_query("SELECT * FROM `lab_trap` WHERE `id_room` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "' AND `id_user`='" . $user['id'] . "';"));
if ($roow[0]) { if ($roow[0]) {
$msg .= 'В комнате была установлена ловушка...<br>'; $msg .= 'В комнате была установлена ловушка...<br>';
@ -366,19 +369,19 @@ if ((time() - $_SESSION['time']) > 3) {
} else { } else {
$tt = (time() - $_SESSION['time']); $tt = (time() - $_SESSION['time']);
} }
\Battles\Template::header('lab'); Template::header('lab');
echo Nick::id($user)->battle(); echo Nick::id($user)->battle();
echo " <a href=\"#\" onclick=\"javascript:if (confirm('Желаете выбраться из квестового лабиринта? Теряете все, что здесь нашли.')){ location.href='lab.php?eexit=1';}\">Выйти?</a>"; echo " <a href=\\";
echo "<table border=0 width=100%><tr><td colspan=4><font color=red>" . $msg; echo "<table border=0 width=100%><tr><td colspan=4><font color=red>" . $msg;
echo "</font>"; echo "</font>";
if ($room['exit'] == 1) { if ($room['exit'] == 1) {
echo "<font color=green><b>В комнате есть выход.</b></font> •<a href='?exit=1'>ВЫЙТИ!</a>•<br>"; echo "<font color=green><b>В комнате есть выход.</b></font> •<a href='?exit=1'>ВЫЙТИ!</a>•<br>";
} }
echo " <a href=\"#\" onclick=\"javascript:if (confirm('Использовать свиток возрата?')){ location.href='lab.php?svitexit=1';}\">Свиток возрата: <b>" . $u_res['exit_teleport'] . "</b></a> | <a href=\"#\" onclick=\"javascript:if (confirm('Использовать свиток оздоровления?')){ location.href='lab.php?svitheal=1';}\">Свиток оздоровления: <b>" . $u_res['svitok_heal'] . "</b></a><br>"; echo " <a href=\\" . $u_res['exit_teleport'] . "</b></a> | <a href=\\" . $u_res['svitok_heal'] . "</b></a><br>";
echo " <b>+</b> Бот-атаки: <b>" . $u_res['svitok_kill'] . "</b> <small><a href=\"#\" onclick=\"javascript:if (confirm('Купить 1 Бот-атаку за 0.15 кредит?')){ location.href='lab.php?buykill=1';}\">[купить]</a></small>"; echo " <b>+</b> Бот-атаки: <b>" . $u_res['svitok_kill'] . "</b> <small><a href=\\";
echo "<p>"; echo "<p>";
$log = mysql_query("select * from `lab_heal_log` order by `id` desc LIMIT 1"); $log = mysql_query("select * from `lab_heal_log` order by `id` desc LIMIT 1");
@ -389,7 +392,7 @@ for ($i = 0; $i < mysql_num_rows($log); $i++) {
} }
echo "" . $room['name'] . " (" . $user->getRoom() . ")</tr>"; echo "" . $room['name'] . " (" . User::getInstance()->getRoom() . ")</tr>";
echo "<tr><td><td><button style='width:50px; height:50px;' class='INPUT' disabled id=b1 onclick='location.href=\"lab.php?go=p1\";'>СЕВЕР</button><td><td rowspan=3 style='height:100px;'>&nbsp;<td rowspan=4 width=30% valign=top style='height:100px;'>"; echo "<tr><td><td><button style='width:50px; height:50px;' class='INPUT' disabled id=b1 onclick='location.href=\"lab.php?go=p1\";'>СЕВЕР</button><td><td rowspan=3 style='height:100px;'>&nbsp;<td rowspan=4 width=30% valign=top style='height:100px;'>";
$u_lab = mysql_query("select `login` from `users` where `lab`='1' and `bot`!='1'"); $u_lab = mysql_query("select `login` from `users` where `lab`='1' and `bot`!='1'");
$u_lab_kol = mysql_num_rows($u_lab); $u_lab_kol = mysql_num_rows($u_lab);

View File

@ -1,4 +1,7 @@
<?php <?php
use Battles\Template;
require_once "functions.php"; require_once "functions.php";
if ($user['lab'] == 0) { if ($user['lab'] == 0) {
header("Location: index.php"); header("Location: index.php");
@ -15,7 +18,7 @@ $u_res = mysql_fetch_array(mysql_query("select * from `lab_user` where `id_user`
setTimeout("document.all['b1'].disabled=false;document.all['b2'].disabled=false;document.all['b3'].disabled=false;document.all['b4'].disabled=false;", <?=(3 - $tt)?>000); setTimeout("document.all['b1'].disabled=false;document.all['b2'].disabled=false;document.all['b3'].disabled=false;document.all['b4'].disabled=false;", <?=(3 - $tt)?>000);
</script> </script>
<?php <?php
$room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string($user->getRoom()) . "';")); $room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "';"));
if ($_GET['healall'] == 1) { if ($_GET['healall'] == 1) {
$cost = $_GET['cost']; $cost = $_GET['cost'];
@ -121,7 +124,7 @@ if ($_GET['mobkill'] == 1) {
} }
$rand_hp1 = rand(1, 10); $rand_hp1 = rand(1, 10);
$rand_hp = $rand_hp1 * $user['level']; $rand_hp = $rand_hp1 * $user['level'];
$bot = mysql_fetch_array(mysql_query("select * from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1")); $bot = mysql_fetch_array(mysql_query("select * from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1"));
$hels = $bot['bot_hp'] - $rand_hp; $hels = $bot['bot_hp'] - $rand_hp;
if ($hels < 0) { if ($hels < 0) {
echo "<b>Вы убили моба!</b><br>"; echo "<b>Вы убили моба!</b><br>";
@ -132,11 +135,11 @@ if ($_GET['mobkill'] == 1) {
echo "Вы получили 1 записку!<br>"; echo "Вы получили 1 записку!<br>";
Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'"); Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'");
} }
mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1"); mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1");
//если просто убивалка //если просто убивалка
} else { } else {
Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'"); Mysql_query("update `lab_user` set `zad" . $u_res['zadanie'] . "_kol`=`zad" . $u_res['zadanie'] . "_kol`+'1' where `id_user`='" . $user['id'] . "'");
mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . $user->getRoom() . "' LIMIT 1"); mysql_query("delete from `lab_bots` where `id_bot`='" . $id . "' AND `id_user`='" . $user['id'] . "' AND `id_room`='" . User::getInstance()->getRoom() . "' LIMIT 1");
} }
} else { } else {
echo "Вы отняли у моба -<b>" . $rand_hp . "</b> HP!<br>"; echo "Вы отняли у моба -<b>" . $rand_hp . "</b> HP!<br>";
@ -174,7 +177,7 @@ if ($_GET['exit'] && $room['exit'] == 1) {
if ($_GET['get']) { if ($_GET['get']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_inv` WHERE `id` = '" . mysql_real_escape_string($_GET['get']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_inv` WHERE `id` = '" . mysql_real_escape_string($_GET['get']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
switch ($data['type']) { switch ($data['type']) {
case 1: case 1:
@ -238,13 +241,13 @@ if ($_GET['get']) {
if ($_GET['drop']) { if ($_GET['drop']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($_GET['drop']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($_GET['drop']) . "' AND `id_user`='" . $user['id'] . "';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($data['id']) . "' AND `id_user`='" . $user['id'] . "' LIMIT 1;"); mysql_query("DELETE FROM `lab_tmp` WHERE `id` = '" . mysql_real_escape_string($data['id']) . "' AND `id_user`='" . $user['id'] . "' LIMIT 1;");
mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`,`id_user`) values ('" . mysql_real_escape_string($user->getRoom()) . "','" . mysql_real_escape_string($data['type']) . "','" . mysql_real_escape_string($data['value']) . "','" . mysql_real_escape_string($user['id']) . "');"); mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`,`id_user`) values ('" . mysql_real_escape_string(User::getInstance()->getRoom()) . "','" . mysql_real_escape_string($data['type']) . "','" . mysql_real_escape_string($data['value']) . "','" . mysql_real_escape_string($user['id']) . "');");
unset($data); unset($data);
} }
if ($_GET['nal1']) { if ($_GET['nal1']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal1']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal1']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='1';");
mysql_query("UPDATE `users` SET `money` = `money`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `money` = `money`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -256,7 +259,7 @@ if ($_GET['nal1']) {
if ($_GET['nal2']) { if ($_GET['nal2']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal2']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal2']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='3';");
mysql_query("UPDATE `users` SET `patriotizm` = `patriotizm`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `patriotizm` = `patriotizm`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -268,7 +271,7 @@ if ($_GET['nal2']) {
if ($_GET['nal3']) { if ($_GET['nal3']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal3']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal3']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='8';");
mysql_query("UPDATE `bank` SET `ekr` = `ekr`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `bank` SET `ekr` = `ekr`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -280,7 +283,7 @@ if ($_GET['nal3']) {
if ($_GET['nal4']) { if ($_GET['nal4']) {
$data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal4']) . "' AND `id_user`='" . $user['id'] . "';")); $data = mysql_fetch_array(mysql_query("SELECT * FROM `lab_bots` WHERE `id` = '" . mysql_real_escape_string($_GET['nal4']) . "' AND `id_user`='" . $user['id'] . "';"));
if ($data['id_room'] == $user->getRoom()) { if ($data['id_room'] == User::getInstance()->getRoom()) {
$sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';")); $sum = mysql_fetch_array(mysql_query("SELECT SUM(`value`) FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';"));
mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';"); mysql_query("DELETE FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "' AND `type`='9';");
mysql_query("UPDATE `users` SET `exp` = `exp`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `exp` = `exp`+'" . mysql_real_escape_string($sum[0]) . "' WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
@ -296,28 +299,28 @@ if ($_GET['go']) {
switch ($_GET['go']) { switch ($_GET['go']) {
case "p1": case "p1":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p1']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p1']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p1']); User::getInstance()->setRoom($room['p1']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p2": case "p2":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p2']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p2']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p2']); User::getInstance()->setRoom($room['p2']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p3": case "p3":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p3']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p3']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p3']); User::getInstance()->setRoom($room['p3']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
case "p4": case "p4":
mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p4']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';"); mysql_query("UPDATE `users` SET `room` = '" . mysql_real_escape_string($room['p4']) . "', `fullhptime` = " . time() . " WHERE `id` = '" . mysql_real_escape_string($user['id']) . "';");
$user->setRoom($room['p4']); User::getInstance()->setRoom($room['p4']);
$_SESSION['time'] = time(); $_SESSION['time'] = time();
break; break;
} }
} }
$room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string($user->getRoom()) . "';")); $room = mysql_fetch_array(mysql_query("SELECT * FROM `lab_rooms` WHERE `id` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "';"));
if ($user['hp'] <= 0) { if ($user['hp'] <= 0) {
mysql_query("DELETE FROM `lab_trap` WHERE `id_user` = '" . $user['id'] . "'"); mysql_query("DELETE FROM `lab_trap` WHERE `id_user` = '" . $user['id'] . "'");
@ -332,12 +335,12 @@ if ($user['hp'] <= 0) {
} }
$data = mysql_query("SELECT * FROM `lab_inv` WHERE `id_room` = '" . mysql_real_escape_string($user->getRoom()) . "' AND `id_user`='" . $user['id'] . "';"); $data = mysql_query("SELECT * FROM `lab_inv` WHERE `id_room` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "' AND `id_user`='" . $user['id'] . "';");
$data2 = mysql_query("SELECT * FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "';"); $data2 = mysql_query("SELECT * FROM `lab_tmp` WHERE `id_user` = '" . mysql_real_escape_string($user['id']) . "';");
$data3 = mysql_query("SELECT * FROM `users` WHERE `lab` = 1 AND `room` = '" . mysql_real_escape_string($room['id']) . "';"); $data3 = mysql_query("SELECT * FROM `users` WHERE `lab` = 1 AND `room` = '" . mysql_real_escape_string($room['id']) . "';");
$data4 = mysql_query("SELECT * FROM `lab_bots` WHERE `id_room` = '" . mysql_real_escape_string($room['id']) . "' AND `id_user`='" . $user['id'] . "';"); $data4 = mysql_query("SELECT * FROM `lab_bots` WHERE `id_room` = '" . mysql_real_escape_string($room['id']) . "' AND `id_user`='" . $user['id'] . "';");
$roow = mysql_fetch_array(mysql_query("SELECT * FROM `lab_trap` WHERE `id_room` = '" . mysql_real_escape_string($user->getRoom()) . "' AND `id_user`='" . $user['id'] . "';")); $roow = mysql_fetch_array(mysql_query("SELECT * FROM `lab_trap` WHERE `id_room` = '" . mysql_real_escape_string(User::getInstance()->getRoom()) . "' AND `id_user`='" . $user['id'] . "';"));
if ($roow[0]) { if ($roow[0]) {
$msg .= 'В комнате была установлена ловушка...<br>'; $msg .= 'В комнате была установлена ловушка...<br>';
@ -364,19 +367,19 @@ if ((time() - $_SESSION['time']) > 3) {
} else { } else {
$tt = (time() - $_SESSION['time']); $tt = (time() - $_SESSION['time']);
} }
\Battles\Template::header('lab2'); Template::header('lab2');
echo Nick::id($user)->battle(); echo Nick::id($user)->battle();
echo " <a href=\"#\" onclick=\"javascript:if (confirm('Желаете выбраться из лабиринта? Теряете все что здесь нашли.')){ location.href='lab.php?eexit=1';}\">Выйти?</a>"; echo " <a href=\\";
echo "<table border=0 width=100%><tr><td colspan=4><font color=red>" . $msg; echo "<table border=0 width=100%><tr><td colspan=4><font color=red>" . $msg;
echo "</font>"; echo "</font>";
if ($room['exit'] == 1) { if ($room['exit'] == 1) {
echo "<font color=green><b>В комнате есть выход.</b></font> •<a href='?exit=1'>ВЫЙТИ!</a>•<br>"; echo "<font color=green><b>В комнате есть выход.</b></font> •<a href='?exit=1'>ВЫЙТИ!</a>•<br>";
} }
echo " <a href=\"#\" onclick=\"javascript:if (confirm('Использовать свиток возрата?')){ location.href='lab.php?svitexit=1';}\">Св. возрата: <b>" . $u_res['exit_teleport'] . "</b></a> | <a href=\"#\" onclick=\"javascript:if (confirm('Использовать свиток оздоровления?')){ location.href='lab.php?svitheal=1';}\">Св. оздоровления: <b>" . $u_res['svitok_heal'] . "</b></a><br>"; echo " <a href=\\" . $u_res['exit_teleport'] . "</b></a> | <a href=\\" . $u_res['svitok_heal'] . "</b></a><br>";
echo "Игровые атаки: <b>" . $u_res['svitok_kill_user'] . "</b>"; echo "Игровые атаки: <b>" . $u_res['svitok_kill_user'] . "</b>";
echo " <b>+</b> Бот-атаки: <b>" . $u_res['svitok_kill'] . "</b> <small><a href=\"#\" onclick=\"javascript:if (confirm('Купить 1 Бот-атаку за 0.15 кредит?')){ location.href='lab.php?buykill=1';}\">[купить]</a></small>"; echo " <b>+</b> Бот-атаки: <b>" . $u_res['svitok_kill'] . "</b> <small><a href=\\";
echo "<p>"; echo "<p>";
$log = mysql_query("select * from `lab_heal_log` order by `id` desc LIMIT 1"); $log = mysql_query("select * from `lab_heal_log` order by `id` desc LIMIT 1");
@ -387,7 +390,7 @@ for ($i = 0; $i < mysql_num_rows($log); $i++) {
} }
echo "" . $room['name'] . " (" . $user->getRoom() . ")</tr>"; echo "" . $room['name'] . " (" . User::getInstance()->getRoom() . ")</tr>";
echo "<tr><td><td><button style='width:50px; height:50px;' class='INPUT' disabled id=b1 onclick='location.href=\"lab.php?go=p1\";'>СЕВЕР</button><td><td rowspan=3 style='height:100px;'>&nbsp;<td rowspan=4 width=30% valign=top style='height:100px;'>"; echo "<tr><td><td><button style='width:50px; height:50px;' class='INPUT' disabled id=b1 onclick='location.href=\"lab.php?go=p1\";'>СЕВЕР</button><td><td rowspan=3 style='height:100px;'>&nbsp;<td rowspan=4 width=30% valign=top style='height:100px;'>";
$u_lab = mysql_query("select `login` from `users` where `lab`='1' and `bot`!='1'"); $u_lab = mysql_query("select `login` from `users` where `lab`='1' and `bot`!='1'");
$u_lab_kol = mysql_num_rows($u_lab); $u_lab_kol = mysql_num_rows($u_lab);

View File

@ -1,6 +1,7 @@
<?php <?php
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
$errkom = ''; $errkom = '';
@ -306,7 +307,7 @@ Template::header('Вход в Лабиринты');
</div> </div>
<? <?
if (isset($_GET['del_com'])) { if (isset($_GET['del_com'])) {
if ($user->getAdmin()) { if (User::getInstance()->getAdmin()) {
mysql_query('UPDATE `laba_zv` SET `com` = "" WHERE `id` = "' . (int)$_GET['del_com'] . '" LIMIT 1'); mysql_query('UPDATE `laba_zv` SET `com` = "" WHERE `id` = "' . (int)$_GET['del_com'] . '" LIMIT 1');
$re = 'Комментарий удалён'; $re = 'Комментарий удалён';
} else { } else {
@ -398,7 +399,7 @@ while ($pl = mysql_fetch_array($sp)) {
} }
$userszv = ltrim($userszv, ', '); $userszv = ltrim($userszv, ', ');
if ($pl['com'] != '') { if ($pl['com'] != '') {
if ($user->getAdmin()) { if (User::getInstance()->getAdmin()) {
$del = ' <a href=\'lab_enter.php?del_com=' . $pl['id'] . '\'>Удалить комментарий</a>'; $del = ' <a href=\'lab_enter.php?del_com=' . $pl['id'] . '\'>Удалить комментарий</a>';
} else { } else {
$del = ''; $del = '';

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\InventoryItem; use Battles\InventoryItem;
@ -18,7 +18,7 @@ if ($get == 'exit') {
} }
require_once 'functions.php'; require_once 'functions.php';
User::$current->setOnline(); User::getInstance()->setOnline();
$req = (object)[]; $req = (object)[];
$keys = ['ups', 'drop', 'dress', 'destruct', 'use', 'undress', 'edit', 'goto', 'obraz', 'setshadow']; $keys = ['ups', 'drop', 'dress', 'destruct', 'use', 'undress', 'edit', 'goto', 'obraz', 'setshadow'];
@ -29,7 +29,7 @@ foreach ($keys as $key) {
if ($req->edit) { if ($req->edit) {
if ($req->ups) { if ($req->ups) {
try { try {
$up = new UserInfo(User::$current->getId()); $up = new UserInfo(User::getInstance()->getId());
$up->addOnePointToStat($req->ups); $up->addOnePointToStat($req->ups);
unset($up); unset($up);
} catch (GameException $e) { } catch (GameException $e) {
@ -37,22 +37,22 @@ if ($req->edit) {
} }
} }
if ($req->drop) { if ($req->drop) {
$items = new DressedItems(User::$current->getId()); $items = new DressedItems(User::getInstance()->getId());
$items->undressItem($req->drop); $items->undressItem($req->drop);
unset($items); unset($items);
} }
//Пока что одеваем предмет отсюда. //Пока что одеваем предмет отсюда.
if ($req->dress) { if ($req->dress) {
$dressing = new InventoryItem(DBPDO::$db->ofetch('select * from inventory where item_id = ? ', $req->dress)); $dressing = new InventoryItem(Db::getInstance()->ofetch('select * from inventory where item_id = ? ', $req->dress));
$dressing->dressItem(); $dressing->dressItem();
unset($dressing); unset($dressing);
} }
if ($req->destruct) { if ($req->destruct) {
$q = DBPDO::$db->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [User::$current->getId(), $req->destruct]); $q = Db::getInstance()->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [User::getInstance()->getId(), $req->destruct]);
if ($q) { if ($q) {
if (empty($q->dressed_slot)) { if (empty($q->dressed_slot)) {
InventoryItem::destroyItem($req->destruct); InventoryItem::destroyItem($req->destruct);
GameLogs::addUserLog(User::$current->getId(), User::$current->getLogin() . ' выбросил предмет ' . $q->name . ' id:(cap' . $req->destruct . ')'); GameLogs::addUserLog(User::getInstance()->getId(), User::getInstance()->getLogin() . ' выбросил предмет ' . $q->name . ' id:(cap' . $req->destruct . ')');
err('Предмет ' . $q->name . ' выброшен.'); err('Предмет ' . $q->name . ' выброшен.');
} else { } else {
err('Ошибка: нельзя выбросить одетый предмет!'); err('Ошибка: нельзя выбросить одетый предмет!');
@ -65,23 +65,23 @@ if ($req->edit) {
usemagic($req->use, $req->useTarget); usemagic($req->use, $req->useTarget);
} }
if ($req->undress) { if ($req->undress) {
DressedItems::undressAllItems(User::$current->getId()); DressedItems::undressAllItems(User::getInstance()->getId());
} }
} }
// Подготавливаем отображение инфы и предметов. // Подготавливаем отображение инфы и предметов.
$userInfo = new UserInfo(User::$current->getId()); $userInfo = new UserInfo(User::getInstance()->getId());
$userStats = new UserStats(User::$current->getId()); $userStats = new UserStats(User::getInstance()->getId());
$stat = $userStats->getFullStats(); $stat = $userStats->getFullStats();
$data = DBPDO::$db->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', User::$current->getId()); $data = Db::getInstance()->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', User::getInstance()->getId());
$iteminfo = []; $iteminfo = [];
foreach ($data as $row) { foreach ($data as $row) {
$iteminfo = new InventoryItem($row); $iteminfo = new InventoryItem($row);
} }
//Обработчики нажатий на кнопки. //Обработчики нажатий на кнопки.
if ($req->battlefield ?? 0 && User::$current->getRoom() == 1) { if ($req->battlefield ?? 0 && User::getInstance()->getRoom() == 1) {
header('Location: zayavka.php'); header('Location: zayavka.php');
exit(); exit();
} }
@ -89,11 +89,11 @@ if ($req->module_quest ?? 0) {
header('Location: module_quest.php'); header('Location: module_quest.php');
exit(); exit();
} }
if ($req->move_inside ?? 0 && User::$current->getRoom() == 20) { if ($req->move_inside ?? 0 && User::getInstance()->getRoom() == 20) {
header('Location: main.php?goto=arena'); header('Location: main.php?goto=arena');
exit(); exit();
} }
if ($req->move_outside ?? 0 && User::$current->getRoom() == 1) { if ($req->move_outside ?? 0 && User::getInstance()->getRoom() == 1) {
header('Location: main.php?goto=plo'); header('Location: main.php?goto=plo');
exit(); exit();
} }
@ -104,12 +104,12 @@ if ($req->main_page ?? 0) {
if (!$req->edit) { if (!$req->edit) {
/* === проверяем соответствие комнаты и скрипта === */ /* === проверяем соответствие комнаты и скрипта === */
if (in_array(User::$current->getRoom(), [20, 21, 26, 48, 51, 52, 651, 2655, 2601, 2701, 2702, 2111])) { if (in_array(User::getInstance()->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::$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])) { if (in_array(User::getInstance()->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::$current->getRoom()]); header('location: ' . Travel::$roomFileName[User::getInstance()->getRoom()]);
exit(); exit();
} }
} }
@ -129,9 +129,9 @@ function del_efs($id, $type)
// Входим и выходим если можем. // Входим и выходим если можем.
if ($req->goto) { if ($req->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::$current->getId())->fetch_assoc(); $d = db::c()->query('SELECT SUM(weight) AS sum_weight FROM inventory WHERE owner_id = ?i AND on_sale = 0', User::getInstance()->getId())->fetch_assoc();
$eff = db::c()->query('SELECT 1 FROM `users_effects` WHERE `owner_id` = ?i AND (`type` = 14 OR `type` = 13)', User::$current->getId()); $eff = db::c()->query('SELECT 1 FROM `users_effects` WHERE `owner_id` = ?i AND (`type` = 14 OR `type` = 13)', User::getInstance()->getId());
//(масса: <?= $getItemsBonuses->getItemsWeight() . '/' . User::$current->strength * 4 //(масса: <?= $getItemsBonuses->getItemsWeight() . '/' . User::getInstance()->strength * 4
if ($d['sum_weight'] > $userStats->getMaxWeight()) { if ($d['sum_weight'] > $userStats->getMaxWeight()) {
err('У вас переполнен рюкзак, вы не можете передвигаться...'); err('У вас переполнен рюкзак, вы не можете передвигаться...');
@ -141,15 +141,15 @@ if ($req->goto) {
err('У вас тяжелая травма, вы не можете передвигатся...'); err('У вас тяжелая травма, вы не можете передвигатся...');
$imove = false; $imove = false;
} }
if ($req->goto == 'plo' && !User::$current->getZayavka() && $imove && User::$current->getRoom() != 20) { if ($req->goto == 'plo' && !User::getInstance()->getZayavka() && $imove && User::getInstance()->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::$current->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::getInstance()->getId());
header('Location: city.php'); header('Location: city.php');
exit("<i>Топ-топ-топ...</i>"); exit("<i>Топ-топ-топ...</i>");
} else { } else {
err('Подали заявку на бой и убегаете из клуба? Нехорошо...'); err('Подали заявку на бой и убегаете из клуба? Нехорошо...');
} }
if ($req->goto == 'arena' && User::$current->getRoom() == 20 && $imove) { if ($req->goto == 'arena' && User::getInstance()->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::$current->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::getInstance()->getId());
header('Location: main.php'); header('Location: main.php');
exit("<i>Топ-топ-топ...</i>"); exit("<i>Топ-топ-топ...</i>");
} }
@ -160,8 +160,8 @@ if ($req->use) {
} }
if ($req->obraz) { if ($req->obraz) {
User::$current->setShadow($req->obraz); User::getInstance()->setShadow($req->obraz);
User::$current->saveUser(); User::getInstance()->saveUser();
} }
if ($req->setshadow) { if ($req->setshadow) {
@ -272,12 +272,12 @@ Template::header('Игра');
</td> </td>
<td style="vertical-align: top; width: 250px"> <!-- Второй столбец --> <td style="vertical-align: top; width: 250px"> <!-- Второй столбец -->
<div> <div>
<br>Уровень: <strong><?= User::$current->getLevel() ?></strong> <br>Уровень: <strong><?= User::getInstance()->getLevel() ?></strong>
<br>Опыт: <strong><?= User::$current->getExperience() ?></strong> <br>Опыт: <strong><?= User::getInstance()->getExperience() ?></strong>
<br>Побед: <strong>??</strong> <br>Побед: <strong>??</strong>
<br>Поражений: <strong>??</strong> <br>Поражений: <strong>??</strong>
<br>Ничьих: <strong>??</strong> <br>Ничьих: <strong>??</strong>
<br>Деньги: <strong><?= User::$current->getMoney() ?></strong> кр. <br>Деньги: <strong><?= User::getInstance()->getMoney() ?></strong> кр.
<HR> <HR>
</div> </div>
<!--Параметры--> <!--Параметры-->
@ -329,14 +329,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::$current->getShadow() == '0.gif' || User::$current->getAdmin() == 1): ?> <?php if (User::getInstance()->getShadow() == '0.gif' || User::getInstance()->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::$current->getRoom() == 20): ?> <?php if (User::getInstance()->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::$current->getRoom() == 1): ?> <?php elseif (User::getInstance()->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

@ -1,6 +1,7 @@
<?php <?php
use Battles\Template; use Battles\Template;
use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
require_once 'classes/quests_class.php'; require_once 'classes/quests_class.php';
@ -24,11 +25,11 @@ Template::header('module_quest');
?> ?>
<link rel="stylesheet" href="css/hostel.css"/> <link rel="stylesheet" href="css/hostel.css"/>
<?php <?php
$sp = db::c()->query('SELECT `vars` FROM `actions` WHERE `vars` LIKE "?S" AND `vals` = "?s" AND `uid` = ?i LIMIT 100', "%start_quest%", "go", $user->getId()); $sp = db::c()->query('SELECT `vars` FROM `actions` WHERE `vars` LIKE "?S" AND `vals` = "?s" AND `uid` = ?i LIMIT 100', "%start_quest%", "go", User::getInstance()->getId());
while ($pl = $sp->fetch_assoc()) { while ($pl = $sp->fetch_assoc()) {
$questId = str_replace('start_quest', '', $pl['vars']); $questId = str_replace('start_quest', '', $pl['vars']);
$pq = db::c()->query('SELECT `id`,`name`,`info` FROM `quests` WHERE `id` = ?i', $questId)->fetch_assoc(); $pq = db::c()->query('SELECT `id`,`name`,`info` FROM `quests` WHERE `id` = ?i', $questId)->fetch_assoc();
$qsee .= sprintf('<a href="?end_qst_now=%s"><img src="/i/clear.gif" title="Отказаться от задания"></a> <b>%s</b><span style="float: right;"><a href="?end_qst=%s">Выполнить</a></span><div style="padding-left: 15px; padding-bottom: 5px; border-bottom: 1px solid grey;"><small>%s<br>$s</small></div><br>', $pq['id'], $pq['name'], $pq['id'], $pq['info'], $q->info($pq, $user->getId())); $qsee .= sprintf('<a href="?end_qst_now=%s"><img src="/i/clear.gif" title="Отказаться от задания"></a> <b>%s</b><span style="float: right;"><a href="?end_qst=%s">Выполнить</a></span><div style="padding-left: 15px; padding-bottom: 5px; border-bottom: 1px solid grey;"><small>%s<br>$s</small></div><br>', $pq['id'], $pq['name'], $pq['id'], $pq['info'], $q->info($pq, User::getInstance()->getId()));
$qx++; $qx++;
} }

View File

@ -1,14 +1,13 @@
<?php <?php
// Что ты такое? // Что ты такое?
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\User; use Battles\User;
require_once "../config.php"; require_once "../config.php";
$user = User::$current; if (!User::getInstance()->getAdmin()) {
if (!User::$current->getAdmin()) {
exit('Access denied!'); exit('Access denied!');
} }
$nec = DBPDO::$db->fetchAll('select * from podzem2'); $nec = Db::getInstance()->fetchAll('select * from podzem2');
?> ?>
<style> <style>
@ -50,7 +49,7 @@ $nec = DBPDO::$db->fetchAll('select * from podzem2');
<input name="new" type="submit" value="Создать новую"> <input name="new" type="submit" value="Создать новую">
<?php <?php
if (!empty($_GET['news'] && !empty($_GET['name']))) { if (!empty($_GET['news'] && !empty($_GET['name']))) {
$SQL2 = DBPDO::$db->execute('insert into podzem2 (name) value ?', $_GET['name']); $SQL2 = Db::getInstance()->execute('insert into podzem2 (name) value ?', $_GET['name']);
exit("<script>location.href='edit.php'</script>"); exit("<script>location.href='edit.php'</script>");
} ?> } ?>
<?php else: ?> <?php else: ?>

View File

@ -1,18 +1,18 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\User; use Battles\User;
include "../config.php"; include "../config.php";
if (User::$current->getBattle()) { if (User::getInstance()->getBattle()) {
header('location: fbattle.php'); header('location: fbattle.php');
exit(); exit();
} }
if (!User::$current->getAdmin()) { if (!User::getInstance()->getAdmin()) {
exit('Access denied!'); exit('Access denied!');
} }
if (!empty($_GET['name'])) { if (!empty($_GET['name'])) {
$s = DBPDO::$db->fetchAll('select * from podzem2 where name = ?', $_GET['name']); $s = Db::getInstance()->fetchAll('select * from podzem2 where name = ?', $_GET['name']);
} }
?> ?>
<table width="100%" border="1" cellspacing="0" cellpadding="0"> <table width="100%" border="1" cellspacing="0" cellpadding="0">

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Item; use Battles\Item;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
@ -15,12 +15,12 @@ const QUEST_ITEM_NAME = [
'z' => 'Жетон', 'z' => 'Жетон',
'k' => 'Ключиик', 'k' => 'Ключиик',
]; ];
$fd = DBPDO::$db->fetch('select location, name, glava from labirint where user_id = ?', User::$current->getId()); $fd = Db::getInstance()->execute('select location, name, glava from labirint where user_id = ?', User::getInstance()->getId())->fetch();
$vb = DBPDO::$db->fetch('select n18 from podzem3 where glava = ? and name = ?', [$fd['glava'], 'Канализация 1 этаж']); $vb = Db::getInstance()->fetchColumn('select n18 from podzem3 where glava = ? and name = ?', [$fd['glava'], 'Канализация 1 этаж']);
if ($fd['location'] != '28' || $fd['name'] != 'Канализация 1 этаж' || $vb['n18'] != '8') { if ($fd['location'] != '28' || $fd['name'] != 'Канализация 1 этаж' || $vb != '8') {
return; return;
} }
$userInfo = new UserInfo(User::$current->getId()); $userInfo = new UserInfo(User::getInstance()->getId());
Template::header('Подземелье Луки'); Template::header('Подземелье Луки');
?> ?>
<div id=hint3 class=ahint></div> <div id=hint3 class=ahint></div>
@ -34,7 +34,7 @@ Template::header('Подземелье Луки');
<TD> <TD>
<i> <i>
<?php <?php
$gag = DBPDO::$db->fetchAll('select * from qwest where login = ?', User::$current->getLogin()); $gag = Db::getInstance()->fetchAll('select * from qwest where login = ?', User::getInstance()->getLogin());
foreach ($gag as $qw) { foreach ($gag as $qw) {
$name_qwest = $qw['name_items']; $name_qwest = $qw['name_items'];
if ($name_qwest === QUEST_ITEM_NAME['k']) { if ($name_qwest === QUEST_ITEM_NAME['k']) {
@ -43,9 +43,9 @@ Template::header('Подземелье Луки');
} }
} }
$qwus = DBPDO::$db->fetch('select * from qwest where login = ? and name_qwest = ?', [User::$current->getLogin(), $name_qw]); $qwus = Db::getInstance()->fetch('select * from qwest where login = ? and name_qwest = ?', [User::getInstance()->getLogin(), $name_qw]);
$qwest_status = $qwus["status"]; $qwest_status = $qwus["status"];
$qwesta = DBPDO::$db->fetch('select * from inventory where item_type = 200 and name = ? and owner_id = ?', [QUEST_ITEM_NAME['k'], User::$current->getId()]); $qwesta = Db::getInstance()->fetch('select * from inventory where item_type = 200 and name = ? and owner_id = ?', [QUEST_ITEM_NAME['k'], User::getInstance()->getId()]);
if ($qwesta) { if ($qwesta) {
$ok_qwest = "1"; $ok_qwest = "1";
} }
@ -74,11 +74,11 @@ Template::header('Подземелье Луки');
$item_name = 'Гайка ловкости'; $item_name = 'Гайка ловкости';
} }
if ($ok_qwest == 1 && ($_GET['d'] == 1.3 || $_GET['d'] == 1.4)) { if ($ok_qwest == 1 && ($_GET['d'] == 1.3 || $_GET['d'] == 1.4)) {
DBPDO::$db->execute($query, [User::$current->getId(), $item_name, 3, 30, Item::ITEM_TYPE_AMULET, 20]); Db::getInstance()->execute($query, [User::getInstance()->getId(), $item_name, 3, 30, Item::ITEM_TYPE_AMULET, 20]);
$query = 'delete from inventory where owner_id = ? and item_type = 200 and name = ?'; $query = 'delete from inventory where owner_id = ? and item_type = 200 and name = ?';
DBPDO::$db->execute($query, [User::$current->getId(), QUEST_ITEM_NAME['k']]); Db::getInstance()->execute($query, [User::getInstance()->getId(), QUEST_ITEM_NAME['k']]);
$query = 'update qwest set status = ? where name_qwest = ? and login = ?'; $query = 'update qwest set status = ? where name_qwest = ? and login = ?';
DBPDO::$db->execute($query, ['ok', 'kluchiik', User::$current->getLogin()]); Db::getInstance()->execute($query, ['ok', 'kluchiik', User::getInstance()->getLogin()]);
echo sprintf('<span style="font-size: 11px; color: #f00">Вы получили предмет %s.</span><br><br>Лука говорит спасибо...', $item_name); echo sprintf('<span style="font-size: 11px; color: #f00">Вы получили предмет %s.</span><br><br>Лука говорит спасибо...', $item_name);
} }
} }
@ -93,7 +93,7 @@ Template::header('Подземелье Луки');
if ($_GET['d'] == '3') { if ($_GET['d'] == '3') {
$query = 'select item_id, durability, name from inventory where item_type = 200 and name in (?,?,?) and owner_id = ?'; $query = 'select item_id, durability, name from inventory where item_type = 200 and name in (?,?,?) and owner_id = ?';
$a = DBPDO::$db->fetchAll($query, [QUEST_ITEM_NAME['g'], QUEST_ITEM_NAME['v'], QUEST_ITEM_NAME['b'], User::$current->getId()]); $a = Db::getInstance()->fetchAll($query, [QUEST_ITEM_NAME['g'], QUEST_ITEM_NAME['v'], QUEST_ITEM_NAME['b'], User::getInstance()->getId()]);
unset($query); unset($query);
foreach ($a as $row) { foreach ($a as $row) {
@ -111,7 +111,7 @@ Template::header('Подземелье Луки');
} }
} }
if (in_array(User::$current->getLevel(), [4, 5, 6])) { if (in_array(User::getInstance()->getLevel(), [4, 5, 6])) {
$lim = 3; $lim = 3;
$max = 60; $max = 60;
@ -121,7 +121,7 @@ Template::header('Подземелье Луки');
$vsego_b = $total_mass_b; $vsego_b = $total_mass_b;
$ziton_b = $total_mass_b; $ziton_b = $total_mass_b;
} elseif (in_array(User::$current->getLevel(), [7, 8])) { } elseif (in_array(User::getInstance()->getLevel(), [7, 8])) {
$lim = 9; $lim = 9;
$max = 200; $max = 200;
@ -153,21 +153,21 @@ Template::header('Подземелье Луки');
$ostalos_b = intval($total_mass_b - $vsego_b); $ostalos_b = intval($total_mass_b - $vsego_b);
if ($ostalos == 0) { if ($ostalos == 0) {
DBPDO::$db->execute($query1, [QUEST_ITEM_NAME['g'], User::$current->getId()]); Db::getInstance()->execute($query1, [QUEST_ITEM_NAME['g'], User::getInstance()->getId()]);
} else { } else {
DBPDO::$db->execute($query2, [$ostalos, $ostalos * 0.1, $alls_id]); Db::getInstance()->execute($query2, [$ostalos, $ostalos * 0.1, $alls_id]);
} }
if ($ostalos_v == 0) { if ($ostalos_v == 0) {
DBPDO::$db->execute($query1, [QUEST_ITEM_NAME['v'], User::$current->getId()]); Db::getInstance()->execute($query1, [QUEST_ITEM_NAME['v'], User::getInstance()->getId()]);
} else { } else {
DBPDO::$db->execute($query2, [$ostalos_v, $ostalos_v * 0.2, $vls_id]); Db::getInstance()->execute($query2, [$ostalos_v, $ostalos_v * 0.2, $vls_id]);
} }
if ($ostalos_b == 0) { if ($ostalos_b == 0) {
DBPDO::$db->execute($query1, [QUEST_ITEM_NAME['b'], User::$current->getId()]); Db::getInstance()->execute($query1, [QUEST_ITEM_NAME['b'], User::getInstance()->getId()]);
} else { } else {
DBPDO::$db->execute($query2, [$ostalos_b, $ostalos_b * 0.1, $bls_id]); Db::getInstance()->execute($query2, [$ostalos_b, $ostalos_b * 0.1, $bls_id]);
} }
unset($query1, $query2); unset($query1, $query2);
@ -179,11 +179,11 @@ Template::header('Подземелье Луки');
$all_zitons = $ziton + $ziton_v + $ziton_b; $all_zitons = $ziton + $ziton_v + $ziton_b;
if (!empty($all_zitons)) { if (!empty($all_zitons)) {
$check = DBPDO::$db->fetch($query1, [User::$current->getId(), QUEST_ITEM_NAME['z']]); $check = Db::getInstance()->fetch($query1, [User::getInstance()->getId(), QUEST_ITEM_NAME['z']]);
if ($check['durability'] > 0) { if ($check['durability'] > 0) {
DBPDO::$db->execute($query2, [$all_zitons, $all_zitons * 0.1, 'Лука', User::$current->getId(), QUEST_ITEM_NAME['z']]); Db::getInstance()->execute($query2, [$all_zitons, $all_zitons * 0.1, 'Лука', User::getInstance()->getId(), QUEST_ITEM_NAME['z']]);
} else { } else {
DBPDO::$db->execute($query3, [QUEST_ITEM_NAME['z'], $all_zitons, User::$current->getId(), 200, $all_zitons * 0.1 . 'Лука']); Db::getInstance()->execute($query3, [QUEST_ITEM_NAME['z'], $all_zitons, User::getInstance()->getId(), 200, $all_zitons * 0.1 . 'Лука']);
} }
unset($query1, $query2, $query3); unset($query1, $query2, $query3);
} else { } else {
@ -213,7 +213,7 @@ Template::header('Подземелье Луки');
} }
if ($_GET['d'] == '7') { if ($_GET['d'] == '7') {
if ($qwest != '1') { if ($qwest != '1') {
$T1 = DBPDO::$db->execute('insert into qwest (user_id,login,name_qwest,name_items,id_items,dlja,zadanie,kw,status) values (?,?,?,?,?,?,?,?,?)', [User::$current->getId(), User::$current->getLogin(), 'kluchiik', QUEST_ITEM_NAME['k'], '', 'Лука', 'Найти ключиик', 0, 'no']); $T1 = Db::getInstance()->execute('insert into qwest (user_id,login,name_qwest,name_items,id_items,dlja,zadanie,kw,status) values (?,?,?,?,?,?,?,?,?)', [User::getInstance()->getId(), User::getInstance()->getLogin(), 'kluchiik', QUEST_ITEM_NAME['k'], '', 'Лука', 'Найти ключиик', 0, 'no']);
echo sprintf('<span style="font-size:11px; color:red;">Вы приняли задание.(Найти %s).</span><br><br>Хорошо... Лука будет ждать...', QUEST_ITEM_NAME['k']); echo sprintf('<span style="font-size:11px; color:red;">Вы приняли задание.(Найти %s).</span><br><br>Хорошо... Лука будет ждать...', QUEST_ITEM_NAME['k']);
} else { } else {
echo sprintf('<span style="font-size:11px; color:red;">Вы уже приняли задание.(Найти %s).</span><br><br>Ну что? Лука ждёт...', QUEST_ITEM_NAME['k']); echo sprintf('<span style="font-size:11px; color:red;">Вы уже приняли задание.(Найти %s).</span><br><br>Ну что? Лука ждёт...', QUEST_ITEM_NAME['k']);
@ -289,7 +289,7 @@ Template::header('Подземелье Луки');
</TD> </TD>
<TD> <TD>
<?php <?php
$buser = DBPDO::$db->fetch('select * from users where login = ?', 'Лука'); $buser = Db::getInstance()->fetch('select * from users where login = ?', 'Лука');
//Этот класс не умеет работать с ботами! Этот вызов - заглушка! //Этот класс не умеет работать с ботами! Этот вызов - заглушка!
$botInfo = new UserInfo('Лука'); $botInfo = new UserInfo('Лука');
$botInfo->showUserDoll(); $botInfo->showUserDoll();

View File

@ -5,6 +5,7 @@ use Battles\GameLogs;
use Battles\InventoryItem; use Battles\InventoryItem;
use Battles\Nick; use Battles\Nick;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
@ -27,11 +28,11 @@ if ($_SESSION['receiverName']) {
$sendItemId = $_POST['item_id'] ?? 0; $sendItemId = $_POST['item_id'] ?? 0;
$telegraphText = $_POST['message'] ?? 0; $telegraphText = $_POST['message'] ?? 0;
if ($submit == 'sendMessage' && $telegraphText && $user->getMoney()) { if ($submit == 'sendMessage' && $telegraphText && User::getInstance()->getMoney()) {
if ($telegraphText) { if ($telegraphText) {
$user->setMoney($user->getMoney() - 1); User::getInstance()->setMoney(User::getInstance()->getMoney() - 1);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, $telegraphText); db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, $telegraphText);
$statusMessage = 'Сообщение отправлено.'; $statusMessage = 'Сообщение отправлено.';
} else { } else {
@ -39,16 +40,16 @@ if ($_SESSION['receiverName']) {
} }
} }
if ($submit == 'sendItem' && $sendItemId && $user->getMoney()) { if ($submit == 'sendItem' && $sendItemId && User::getInstance()->getMoney()) {
$res = db::c()->query('SELECT name FROM inventory WHERE owner_id = ?i AND item_id = ?i AND dressed_slot = 0 AND on_sale = 0', $user->getId(), $sendItemId)->fetch_assoc(); $res = db::c()->query('SELECT name FROM inventory WHERE owner_id = ?i AND item_id = ?i AND dressed_slot = 0 AND on_sale = 0', User::getInstance()->getId(), $sendItemId)->fetch_assoc();
if (!$res) { if (!$res) {
$statusMessage = "Предмет не найден в рюкзаке."; $statusMessage = "Предмет не найден в рюкзаке.";
} else { } else {
$user->setMoney($user->getMoney() - 1); User::getInstance()->setMoney(User::getInstance()->getMoney() - 1);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
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'] . '" передан персонажу ' . Nick::id($receiverId)->short(1); $statusMessage = 'Предмет "' . $res['name'] . '" передан персонажу ' . User::getInstance($receiverId)->getLogin();
$receiverLogMessage = 'Получен предмет "' . $res['name'] . '" от персонажа ' . Nick::id($_SESSION['uid'])->short(1); $receiverLogMessage = 'Получен предмет "' . $res['name'] . '" от персонажа ' . User::getInstance()->getLogin();
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($_SESSION['uid'], $statusMessage, 'почта');
@ -57,7 +58,7 @@ if ($_SESSION['receiverName']) {
} }
} }
$queryItems = db::c()->query('SELECT * FROM inventory WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ?i', $user->getId()); $queryItems = db::c()->query('SELECT * FROM inventory WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ?i', User::getInstance()->getId());
while ($row = $queryItems->fetch_assoc()) { while ($row = $queryItems->fetch_assoc()) {
$iteminfo[] = new InventoryItem($row); $iteminfo[] = new InventoryItem($row);
} }

View File

@ -13,6 +13,7 @@
* *
*/ */
use Battles\Bank;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
@ -23,7 +24,6 @@ if ($_SESSION['uid'] != 2) {
} }
require_once 'config.php'; require_once 'config.php';
$user = new User($_SESSION['uid']);
$status = ''; $status = '';
$dirname = "i/presents/"; $dirname = "i/presents/";
$images = glob($dirname . "*.png"); $images = glob($dirname . "*.png");
@ -47,21 +47,21 @@ if (!empty($_POST['sendAction'])) {
$_POST['days'] = 1; $_POST['days'] = 1;
} }
$cost = $_POST['days'] * 5; $cost = $_POST['days'] * 5;
if ($user->getMoney() < $cost) { if (User::getInstance()->getMoney() < $cost) {
$status = "Не хватает кредитов на оплату подарка!"; $status = "Не хватает кредитов на оплату подарка!";
return; return;
} }
if ($_POST['sender'] == 1) { if ($_POST['sender'] == 1) {
$sender = "Анонимный подарок"; $sender = "Анонимный подарок";
} elseif ($_POST['sender'] == 2 && $user->getClan()) { } elseif ($_POST['sender'] == 2 && User::getInstance()->getClan()) {
$sender = "Подарок от клана {$user->getClan()}"; $sender = "Подарок от клана " . User::getInstance()->getClan();
} else { } else {
$sender = "Подарок от {$user->getLogin()}"; $sender = "Подарок от " . User::getInstance()->getLogin();
} }
$user->setMoney($user->getMoney() - $cost); User::getInstance()->setMoney(User::getInstance()->getMoney() - $cost);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
db::c()->query('INSERT INTO users_presents (owner, img, text, sender, expiration_date) VALUES (?i,"?s","?s","?s",DATE_ADD(CURDATE(),INTERVAL ?i DAY))', $receiver['id'], $_POST['present'], $_POST['text'], $sender, $_POST['days']); db::c()->query('INSERT INTO users_presents (owner, img, text, sender, expiration_date) VALUES (?i,"?s","?s","?s",DATE_ADD(CURDATE(),INTERVAL ?i DAY))', $receiver['id'], $_POST['present'], $_POST['text'], $sender, $_POST['days']);
$telegraphText = "Вам пришёл подарок от {$sender}!"; $telegraphText = "Вам пришёл подарок от {$sender}!";
@ -105,10 +105,10 @@ Template::header('Дарильня');
rows=6 cols=80 rows=6 cols=80
placeholder="Текст сопроводительной записки (в информации о персонаже не отображается). Заполнять не обязательно."></textarea><br> placeholder="Текст сопроводительной записки (в информации о персонаже не отображается). Заполнять не обязательно."></textarea><br>
<br>Выберите, от чьего имени подарок:<br> <br>Выберите, от чьего имени подарок:<br>
<label><input type=radio name=sender value=0 checked> <?= $user->getLogin() ?></label><br> <label><input type=radio name=sender value=0 checked> <?= User::getInstance()->getLogin() ?></label><br>
<label><input type=radio name=sender value=1> анонимно</label><br> <label><input type=radio name=sender value=1> анонимно</label><br>
<?php if (!empty($user['ClanName'])): ?> <?php if (!empty(User::getInstance()->getClan())): ?>
<label><input type=radio name=sender value=2> от имени клана <b><?= $user->getClan() ?></b></label><br> <label><input type=radio name=sender value=2> от имени клана <b><?= User::getInstance()->getClan() ?></b></label><br>
<?php endif; ?> <?php endif; ?>
<br>Долговечность подарка (5кр в день):<br> <br>Долговечность подарка (5кр в день):<br>
<input name="days" placeholder="Количество дней"><br> <input name="days" placeholder="Количество дней"><br>

View File

@ -1,6 +1,7 @@
<?php <?php
use Battles\Template; use Battles\Template;
use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
include('classes/quests_class.php'); include('classes/quests_class.php');
@ -56,7 +57,7 @@ if (!empty($q->error)) {
Template::header('Памятник'); Template::header('Памятник');
?> ?>
<div style="float: right;"> <div style="float: right;">
<?php if (($user->getLevel() < 5 || $user->getAdmin()) && $user->getHealth() < $user->getMaxHealth()): ?> <?php if ((User::getInstance()->getLevel() < 5 || User::getInstance()->getAdmin()) && User::getInstance()->getHealth() < User::getInstance()->getMaxHealth()): ?>
<button onclick="location.href='?hps'">Восстановить здоровье</button> <button onclick="location.href='?hps'">Восстановить здоровье</button>
<? endif ?> <? endif ?>
<button onclick="location.href='?'">Обновить</button> <button onclick="location.href='?'">Обновить</button>

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Template, Battles\Database\DBPDO; use Battles\Template, Battles\Database\Db;
require_once "config.php"; require_once "config.php";
@ -18,15 +18,14 @@ if ($_COOKIE[GAMEDOMAIN] ?? null) {
$newUser = new class { $newUser = new class {
public static function addUser(string $login, string $password, string $email, string $birthday): bool public static function addUser(string $login, string $password, string $email, string $birthday): bool
{ {
$db = new DBPDO(); if (Db::getInstance()->ofetch('SELECT 1 FROM users WHERE login = ? OR email = ?', [$login, $email])) {
if ($db->ofetch('SELECT 1 FROM users WHERE login = ? OR email = ?', [$login, $email])) {
return false; return false;
} }
$db->execute('INSERT INTO users (login,pass,email,borndate,ip,session_id,shadow) Db::getInstance()->execute('INSERT INTO users (login,pass,email,borndate,ip,session_id,shadow)
VALUES (?,?,?,?,?,?,?)', [$login, $password, $email, $birthday, $_SERVER['REMOTE_ADDR'], session_id(), '0.png']); VALUES (?,?,?,?,?,?,?)', [$login, $password, $email, $birthday, $_SERVER['REMOTE_ADDR'], session_id(), '0.png']);
$userId = $db->lastInsertId(); $userId = Db::getInstance()->lastInsertId();
$db->execute('INSERT INTO online (user_id, login_time, room, real_time) VALUES (?,?,1,?)', [$userId, time(), time()]); Db::getInstance()->execute('INSERT INTO online (user_id, login_time, room, real_time) VALUES (?,?,1,?)', [$userId, time(), time()]);
$db->execute('INSERT INTO bank (user_id) VALUES ?', $userId); Db::getInstance()->execute('INSERT INTO bank (user_id) VALUES ?', $userId);
setcookie(GAMEDOMAIN, $userId, time() + 3600); setcookie(GAMEDOMAIN, $userId, time() + 3600);
setcookie("battle", time()); setcookie("battle", time());
$_SESSION['uid'] = $userId; $_SESSION['uid'] = $userId;

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
require_once("config.php"); require_once("config.php");
@ -37,16 +37,15 @@ $operation = new class {
public function sendRecoveryMail(string $to): string public function sendRecoveryMail(string $to): string
{ {
$db = new DBPDO(); $check = Db::getInstance()->ofetch('SELECT email FROM users WHERE login = ?', $to);
$check = $db->ofetch('SELECT email FROM users WHERE login = ?', $to); if (!empty(Db::getInstance()->fetchColumn('select email from users where login = ?', $to))) {
if (!$check) {
return ERROR_WRONG_LOGIN; return ERROR_WRONG_LOGIN;
} }
if ($db->ofetch('SELECT 1 FROM users_recovery WHERE login = ?', $to)) { if (!empty(Db::getInstance()->ofetch('SELECT 1 FROM users_recovery WHERE login = ?', $to))) {
return ERROR_TOO_MANY_TRIES; return ERROR_TOO_MANY_TRIES;
} }
$hash = bin2hex(random_bytes(8)); $hash = bin2hex(random_bytes(8));
$db->execute('INSERT INTO users_recovery (login, hash, ip, date) VALUES (?,?,?,?)', [$to, $hash, date('Y-m-d', strtotime('+1days')), $_SERVER['REMOTE_ADDR']]); Db::getInstance()->execute('INSERT INTO users_recovery (login, hash, ip, date) VALUES (?,?,?,?)', [$to, $hash, date('Y-m-d', strtotime('+1days')), $_SERVER['REMOTE_ADDR']]);
$message = "Здравствуйте!<br><br> $message = "Здравствуйте!<br><br>
Кто-то запросил восстановление пароля к вашему персонажу " . $to . ".<br><br> Кто-то запросил восстановление пароля к вашему персонажу " . $to . ".<br><br>
Для смены пароля пройдите по Для смены пароля пройдите по
@ -58,19 +57,18 @@ $operation = new class {
public function isAllowed($hash) public function isAllowed($hash)
{ {
return DBPDO::INIT()->fetch('SELECT 1 FROM users_recovery WHERE hash = ? AND date < ?', [$hash, date('Y-m-d')]) ? true : ERROR_OLD_HASH; return Db::getInstance()->execute('SELECT 1 FROM users_recovery WHERE hash = ? AND date < ?', [$hash, date('Y-m-d')])->fetchColumn() ? true : ERROR_OLD_HASH;
} }
public function setNewPassword(string $newPassword, string $hash):string public function setNewPassword(string $newPassword, string $hash):string
{ {
$db = new DBPDO(); $login = Db::getInstance()->execute('select login from users_recovery where hash = ?', $hash)->fetchColumn();
$row = $db->ofetch('SELECT login FROM users_recovery WHERE hash = ?', $hash); if (empty($login)) {
if (!$row) {
return ERROR_WRONG_HASH; return ERROR_WRONG_HASH;
} }
$newPassword = password_hash($newPassword, PASSWORD_DEFAULT); $newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$db->execute('UPDATE users SET pass = ? WHERE login = ?', [$newPassword, $row->login]); Db::getInstance()->execute('UPDATE users SET pass = ? WHERE login = ?', [$newPassword, $login]);
$db->execute('DELETE FROM users_recovery WHERE hash = ?', $hash); Db::getInstance()->execute('DELETE FROM users_recovery WHERE hash = ?', $hash);
return OK_PASSWORD_CHANGED; return OK_PASSWORD_CHANGED;
} }
}; };

View File

@ -1,10 +1,11 @@
<?php <?php
use Battles\Bank; use Battles\Bank;
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\InventoryItem; use Battles\InventoryItem;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once("functions.php"); require_once("functions.php");
const GRAV_LIMIT = 32; const GRAV_LIMIT = 32;
@ -26,11 +27,11 @@ $gravirovka_query = null;
// Гравировка 30 кред. Максимум 32 символа. // Гравировка 30 кред. Максимум 32 символа.
if ($gravirovkaText && $itemId) { if ($gravirovkaText && $itemId) {
if ($user->getMoney() >= GRAV_COST) { if (User::getInstance()->getMoney() >= GRAV_COST) {
if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) { if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) {
DBPDO::$db->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, $user->getId(), $itemId]); Db::getInstance()->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, User::getInstance()->getId(), $itemId]);
$user->setMoney($user->getMoney() - GRAV_COST); User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
$status = REPAIR_STATUS['OK_GRAV_ADDED']; $status = REPAIR_STATUS['OK_GRAV_ADDED'];
} else { } else {
$status = REPAIR_STATUS['ERROR_SIZE_LIMIT']; $status = REPAIR_STATUS['ERROR_SIZE_LIMIT'];
@ -41,10 +42,10 @@ if ($gravirovkaText && $itemId) {
} }
// Снять гравировку. // Снять гравировку.
if ($gravirovkaRemove) { if ($gravirovkaRemove) {
if ($user->getMoney() >= GRAV_COST) { if (User::getInstance()->getMoney() >= GRAV_COST) {
DBPDO::$db->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]); Db::getInstance()->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]);
$user->setMoney($user->getMoney() - GRAV_COST); User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST);
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
$status = REPAIR_STATUS['OK_GRAV_REMOVED']; $status = REPAIR_STATUS['OK_GRAV_REMOVED'];
} else { } else {
$status = REPAIR_STATUS['ERROR_NO_MONEY']; $status = REPAIR_STATUS['ERROR_NO_MONEY'];
@ -53,22 +54,22 @@ if ($gravirovkaRemove) {
// Ремонт 0,5 кред за единицу. // Ремонт 0,5 кред за единицу.
// Пока что лимит ремонта поставлен на 25. Дальше можно обыграть. // Пока что лимит ремонта поставлен на 25. Дальше можно обыграть.
if ($action == 'repair' && $itemId) { if ($action == 'repair' && $itemId) {
$q = DBPDO::$db->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId); $q = Db::getInstance()->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId);
if ($user->getMoney() > ceil($q->duration / 2)) { if (User::getInstance()->getMoney() > ceil($q->duration / 2)) {
DBPDO::$db->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$user->getId(), $itemId]); Db::getInstance()->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]);
$user->setMoney($user->getMoney() - ceil($q->duration / 2)); User::getInstance()->setMoney(User::getInstance()->getMoney() - ceil($q->duration / 2));
Bank::setWalletMoney($user->getMoney(), $user->getId()); Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId());
GameLogs::addUserLog($user->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.'); GameLogs::addUserLog(User::getInstance()->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.');
$status = REPAIR_STATUS['OK_REPAIRED']; $status = REPAIR_STATUS['OK_REPAIRED'];
} else { } else {
$status = REPAIR_STATUS['ERROR_NO_MONEY']; $status = REPAIR_STATUS['ERROR_NO_MONEY'];
} }
} }
if ($goto == 'remont') { if ($goto == 'remont') {
$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()); $remont_query = Db::getInstance()->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::getInstance()->getId());
} }
if ($goto == 'gravirovka') { if ($goto == 'gravirovka') {
$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()]); $gravirovka_query = Db::getInstance()->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::getInstance()->getId(), User::getInstance()->getId()]);
} }
Template::header('Кузня'); Template::header('Кузня');
?> ?>

View File

@ -8,25 +8,25 @@ use Battles\Template;
use Battles\User; use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
Shop::$current = new Shop(Shop::GENERAL_SHOP);
if (!empty($_GET['otdel'])) { if (!empty($_GET['otdel'])) {
if ($_GET['otdel'] === 'sale') { if ($_GET['otdel'] === 'sale') {
Shop::$current->categoryType = Shop::CATEGORY_SALE_ITEMS; Shop::id(Shop::GENERAL_SHOP)->categoryType = Shop::CATEGORY_SALE_ITEMS;
} }
elseif ($_GET['otdel'] === 'market') { elseif ($_GET['otdel'] === 'market') {
Shop::$current->categoryType = Shop::BARTER_SHOP; Shop::id(Shop::GENERAL_SHOP)->categoryType = Shop::BARTER_SHOP;
} }
else { else {
Shop::$current->categoryType = $_GET['otdel']; Shop::id(Shop::GENERAL_SHOP)->categoryType = $_GET['otdel'];
} }
} }
if (!empty($_POST['sellshop'])) { if (!empty($_POST['sellshop'])) {
ShopItem::sellItem($_POST['itemId'], User::$current, 1); ShopItem::sellItem($_POST['itemId'], User::getInstance(), 1);
} }
if (!empty($_POST['buyshop'])) { if (!empty($_POST['buyshop'])) {
ShopItem::buyItem($_POST['itemId'], User::$current); ShopItem::buyItem($_POST['itemId'], User::getInstance());
} }
if (!empty($_POST['buymarket'])) { if (!empty($_POST['buymarket'])) {
@ -42,20 +42,20 @@ Template::header('Магазин');
<div class="status"><?= ShopItem::$status ?></div> <div class="status"><?= ShopItem::$status ?></div>
<div class="row shop"> <div class="row shop">
<div class="left column"> <div class="left column">
<h3><?= Shop::$current->getCategoryName() ?></h3> <h3><?= Shop::id(Shop::GENERAL_SHOP)->getCategoryName() ?></h3>
<div> <div>
<?php if (Shop::$current->categoryType === -1): ?> <?php if (Shop::id(Shop::GENERAL_SHOP)->categoryType === -1): ?>
Вы можете продать ваши предметы за сущие копейки. Вы можете продать ваши предметы за сущие копейки.
<?php endif; ?> <?php endif; ?>
</div> </div>
<!--Магазин--> <!--Магазин-->
<?= Shop::$current->getItemsList() ?> <?= Shop::id(Shop::GENERAL_SHOP)->getItemsList() ?>
</div> </div>
<div class="right column"> <div class="right column">
<div> <div>
<strong> <strong>
Масса всех вещей: <?= InventoryItem::getWeightData() ?> <br> Масса всех вещей: <?= InventoryItem::getWeightData() ?> <br>
Деньги: <?= User::$current->getMoney() ?>. Деньги: <?= User::getInstance()->getMoney() ?>.
</strong> </strong>
</div> </div>
<hr> <hr>

View File

@ -1,6 +1,6 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
@ -33,7 +33,7 @@ if (!empty($_POST)) {
} }
} }
$dateD = DBPDO::$db->fetch('select datetime from turnament where old = 0 limit 1'); $dateD = Db::getInstance()->fetch('select datetime from turnament where old = 0 limit 1');
if (mktime() >= ($dateD['dt'] + 10)) { if (mktime() >= ($dateD['dt'] + 10)) {
$Tournament->UpdateTournir(); $Tournament->UpdateTournir();
@ -46,7 +46,7 @@ if (mktime() >= ($dateD['dt'] + 10)) {
$Tournament->ShowTournirFinaliats(); $Tournament->ShowTournirFinaliats();
?> ?>
<form method="post"> <form method="post">
<?php if (User::$current->getAdmin()) { ?> <?php if (User::getInstance()->getAdmin()) { ?>
<div> <div>
<input type="submit" name="newtournament" value="Добавить новый турнир"> <input type="submit" name="newtournament" value="Добавить новый турнир">
<input type="submit" name="preptournament" value="Приготовить турнир и запустить"> <input type="submit" name="preptournament" value="Приготовить турнир и запустить">

View File

@ -8,7 +8,8 @@ use Battles\Template;
use Battles\User; use Battles\User;
require_once "functions.php"; require_once "functions.php";
if (User::$current->getInTower() != 1) { $user = User::getInstance();
if (User::getInstance()->getInTower() != 1) {
header('Location: main.php'); header('Location: main.php');
exit; exit;
} }
@ -77,6 +78,34 @@ $rhar = [
"560" => [20, 0, 0, 0, 559], "560" => [20, 0, 0, 0, 559],
]; ];
function get_out($u)
{
$pers = db::c()->query('SELECT * FROM users WHERE id = ?i', $u)->fetch_assoc_array();
DressedItems::undressAllItems($pers['id']);
db::c()->query('UPDATE inventory SET owner = ?i WHERE owner = ?i', $pers['id'], $pers['id'] + _BOTSEPARATOR_);
###
$row = db::c()->query('SELECT * FROM `effects` WHERE `owner` = ?i', $pers['id'] + _BOTSEPARATOR_);
$travm = [11, 12, 13, 14];
while ($efs = $row->fetch_assoc()) {
if (in_array($efs['type'], $travm)) {
$pers['sila'] -= $efs['sila'];
$pers['lovk'] -= $efs['lovk'];
$pers['inta'] -= $efs['inta'];
$pers['vinos'] -= $efs['vinos'];
} else {
$pers['sila'] += $efs['sila'];
$pers['lovk'] += $efs['lovk'];
$pers['inta'] += $efs['inta'];
$pers['vinos'] += $efs['vinos'];
$pers['maxhp'] += $efs['hp'];
}
$efs['owner'] = $_SESSION['uid'];
//mysql_query('UPDATE `effects` SET `owner` = "' . $efs['owner'] . '" WHERE `id` = "' . $efs['id'] . '" LIMIT 1');
//mysql_query('UPDATE `users` SET `sila` = "' . $pers['sila'] . '", `lovk` = "' . $pers['lovk'] . '", `inta` = "' . $pers['inta'] . '", `vinos` = "' . $pers['vinos'] . '", `maxhp` = "' . $pers['maxhp'] . '" WHERE `id` = "' . $pers['id'] . '" LIMIT 1');
}
###
}
mysql_query("LOCK TABLES `bots` WRITE, `deztow_stavka` WRITE, `users` WRITE, `deztow_items` WRITE, `inventory` WRITE, `battle` WRITE, `logs` WRITE, `deztow_turnir` WRITE, `effects` WRITE,`shop` WRITE, `online` WRITE, `deztow_gamers_inv` WRITE, `deztow_realchars` WRITE, `deztow_eff` WRITE, `variables` WRITE"); mysql_query("LOCK TABLES `bots` WRITE, `deztow_stavka` WRITE, `users` WRITE, `deztow_items` WRITE, `inventory` WRITE, `battle` WRITE, `logs` WRITE, `deztow_turnir` WRITE, `effects` WRITE,`shop` WRITE, `online` WRITE, `deztow_gamers_inv` WRITE, `deztow_realchars` WRITE, `deztow_eff` WRITE, `variables` WRITE");
$ls = mysql_num_rows(mysql_query("SELECT `id` FROM `users` WHERE `bot` = 1 and `in_tower` = 1")); $ls = mysql_num_rows(mysql_query("SELECT `id` FROM `users` WHERE `bot` = 1 and `in_tower` = 1"));

View File

@ -1,13 +1,18 @@
<?php <?php
use Battles\DressedItems;
use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
$effect = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = '{$user['id']}' LIMIT 1")); $effect = mysql_fetch_array(mysql_query("SELECT * FROM `effects` WHERE `owner` = '{$user['id']}' LIMIT 1"));
if ($user->getRoom() != 31) { if (User::getInstance()->getRoom() != 31) {
exit('Для распределения статов необходимо находиться в прихожей "Башни смерти"'); exit('Для распределения статов необходимо находиться в прихожей "Башни смерти"');
} }
if (isset($effect['id'])) { if (isset($effect['id'])) {
exit('Для распределения статов на Вас не дожно быть никаких эффектов'); exit('Для распределения статов на Вас не дожно быть никаких эффектов');
} }
\Battles\DressedItems::undressAllItems($user['id']); DressedItems::undressAllItems($user['id']);
if ((int)$_GET['delsn'] > 0) { if ((int)$_GET['delsn'] > 0) {
mysql_query("DELETE FROM `deztow_charstams` WHERE `id` = '" . (int)$_GET['delsn'] . "' AND `name` = '" . $_GET['ddname'] . "' AND `owner` = '" . (int)$user['id'] . "' LIMIT 1"); mysql_query("DELETE FROM `deztow_charstams` WHERE `id` = '" . (int)$_GET['delsn'] . "' AND `name` = '" . $_GET['ddname'] . "' AND `owner` = '" . (int)$user['id'] . "' LIMIT 1");
@ -40,7 +45,7 @@ if ($_GET['setdef']) {
echo "<font color=red><b>Сохранено.</b></font>" . mysql_error(); echo "<font color=red><b>Сохранено.</b></font>" . mysql_error();
} }
\Battles\Template::header('towerstamp'); Template::header('towerstamp');
?> ?>
<h3>Профили характеристик</h3> <h3>Профили характеристик</h3>
Статы не позволяют сходить в БС? Раскиньте ваши статы так, как вы хотите, и участвуйте в турнире! Выбранный по умолчанию профиль, загрузится сам. Вы можете создавать неограниченное число профилей, и менять их за секунды до турнира! Статы не позволяют сходить в БС? Раскиньте ваши статы так, как вы хотите, и участвуйте в турнире! Выбранный по умолчанию профиль, загрузится сам. Вы можете создавать неограниченное число профилей, и менять их за секунды до турнира!

View File

@ -1,15 +1,15 @@
<?php <?php
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
require_once "config.php"; require_once "config.php";
if (!empty($_GET['id']) && User::$current->getAdmin()) { if (!empty($_GET['id']) && User::getInstance()->getAdmin()) {
echo "Пробуем перейти на выбранную замковую улицу..."; echo "Пробуем перейти на выбранную замковую улицу...";
$_SESSION["klan"] = $_GET['klan']; $_SESSION["klan"] = $_GET['klan'];
$a = $_GET['klan']; $a = $_GET['klan'];
DBPDO::$db->execute('update users, online set users.room = 651, online.room = 651 where user_id = id and user_id = ?', User::$current->getId()); Db::getInstance()->execute('update users, online set users.room = 651, online.room = 651 where user_id = id and user_id = ?', User::getInstance()->getId());
header("location: city.php"); header("location: city.php");
exit; exit;
} }
@ -19,7 +19,7 @@ Template::header('Клановый перекрёсток');
<h1>Переход к клановым улицам</h1> <h1>Переход к клановым улицам</h1>
На данный момент свои замки имеют такие кланы: На данный момент свои замки имеют такие кланы:
<?php <?php
$rows = DBPDO::$db->fetchAll('select short_name, full_name, owner_id from clans where zamok = 2'); $rows = Db::getInstance()->fetchAll('select short_name, full_name, owner_id from clans where zamok = 2');
foreach ($rows as $row) { foreach ($rows as $row) {
$frm = "<img src='i/clan/%s.png'> %s<br><form><input name='klan' type='hidden' value='%s'><input type='submit' value='Вход'></form>"; $frm = "<img src='i/clan/%s.png'> %s<br><form><input name='klan' type='hidden' value='%s'><input type='submit' value='Вход'></form>";
echo sprintf($frm, $row['short_name'], $row['full_name'], $row['owner_id']); echo sprintf($frm, $row['short_name'], $row['full_name'], $row['owner_id']);

View File

@ -6,59 +6,59 @@
* One file to rule 'em all! * One file to rule 'em all!
*/ */
use Battles\Database\DBPDO; use Battles\Database\Db;
use Battles\Template; use Battles\Template;
use Battles\User; use Battles\User;
require_once 'functions.php'; require_once 'functions.php';
if (!empty($_GET['teleport']) && $user->getAdmin() == 1) { if (!empty($_GET['teleport']) && User::getInstance()->getAdmin() == 1) {
DBPDO::$db->execute('update users, online set users.room = 20, online.room = 20 where user_id = id and user_id = ?', User::$current->getId()); Db::getInstance()->execute('update users, online set users.room = 20, online.room = 20 where user_id = id and user_id = ?', User::getInstance()->getId());
} }
# ORDEN PHP # ORDEN PHP
$_POST['use'] ??= null; $_POST['use'] ??= null;
if ($user->getAdmin()) { if (User::getInstance()->getAdmin()) {
$abil = DBPDO::$db->fetch('SELECT 1 FROM users WHERE id = ?i', $user->getId()); $abil = Db::getInstance()->execute('SELECT 1 FROM users WHERE id = ?i', User::getInstance()->getId())->fetchColumn();
//$abil = unserialize($abil['abil']); //$abil = unserialize($abil['abil']);
switch ($_POST['use']) { switch ($_POST['use']) {
case "healing": case "healing":
include("./magic/Healing.php"); include("./magic/Healing.php");
break; break;
case "ct1": case "ct1":
if ($abil[0] > 0 && $user->getAlign() == 6) { if ($abil[0] > 0 && User::getInstance()->getAlign() == 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct1.php"); //include("./magic/ct1.php");
if ($outok == 1) { if ($outok == 1) {
$abil[0] -= 1; $abil[0] -= 1;
db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), $user->getId()); db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId());
} }
} elseif ($user->getAlign() != 6) { } elseif (User::getInstance()->getAlign() != 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct1.php"); //include("./magic/ct1.php");
} }
break; break;
case "ct2": case "ct2":
if ($abil[1] > 0 && $user->getAlign() == 6) { if ($abil[1] > 0 && User::getInstance()->getAlign() == 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct2.php"); //include("./magic/ct2.php");
if ($outok == 1) { if ($outok == 1) {
$abil[1] -= 1; $abil[1] -= 1;
db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), $user->getId()); db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId());
} }
} elseif ($user->getAlign() != 6) { } elseif (User::getInstance()->getAlign() != 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct2.php"); //include("./magic/ct2.php");
} }
break; break;
case "ct3": case "ct3":
if ($abil[2] > 0 && $user->getAlign() == 6) { if ($abil[2] > 0 && User::getInstance()->getAlign() == 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct3.php"); //include("./magic/ct3.php");
if ($outok == 1) { if ($outok == 1) {
$abil[2] -= 1; $abil[2] -= 1;
db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), $user->getId()); db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId());
} }
} elseif ($user->getAlign() != 6) { } elseif (User::getInstance()->getAlign() != 6) {
//Заменён на CureInjury.php class. Придумать вызов. //Заменён на CureInjury.php class. Придумать вызов.
//include("./magic/ct3.php"); //include("./magic/ct3.php");
} }
@ -82,11 +82,11 @@ if ($user->getAdmin()) {
break; break;
case "attackk_close": case "attackk_close":
if ($abil[1] > 0 && $user->getAlign() == 2) { if ($abil[1] > 0 && User::getInstance()->getAlign() == 2) {
include("./magic/attackk_close.php"); include("./magic/attackk_close.php");
if ($outok == 1) { if ($outok == 1) {
$abil[1] -= 1; $abil[1] -= 1;
db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), $user->getId()); db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId());
header("Location:fbattle.php"); header("Location:fbattle.php");
exit(); exit();
} }
@ -98,11 +98,11 @@ if ($user->getAdmin()) {
break; break;
case "attackk_open": case "attackk_open":
if ($abil[1] > 0 && $user->getAlign() == 2) { if ($abil[1] > 0 && User::getInstance()->getAlign() == 2) {
include("./magic/attackk_open.php"); include("./magic/attackk_open.php");
if ($outok == 1) { if ($outok == 1) {
$abil[2] -= 1; $abil[2] -= 1;
db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), $user->getId()); db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId());
header("Location:fbattle.php"); header("Location:fbattle.php");
exit(); exit();
} }
@ -175,9 +175,9 @@ function show_byu($type)
34 => 'mirror', 34 => 'mirror',
35 => 'antimirror', 35 => 'antimirror',
]; ];
if ($user->getClan()) { if (User::getInstance()->getClan()) {
$clan = db::c()->query('SELECT owner_id FROM clans WHERE short_name = "?s"', $user->getClan())->fetch_assoc(); $clan = db::c()->query('SELECT owner_id FROM clans WHERE short_name = "?s"', User::getInstance()->getClan())->fetch_assoc();
if ($clan['owner_id'] == $user->getId()) { if ($clan['owner_id'] == User::getInstance()->getId()) {
$r = '<div style="text-align: center;"><a href="javascript:void(0);" class="byu_klan" id="' . $type . '">купить 1 шт.</a></div>'; $r = '<div style="text-align: center;"><a href="javascript:void(0);" class="byu_klan" id="' . $type . '">купить 1 шт.</a></div>';
} else { } else {
$r = '<div style="text-align: center;"><a href="javascript:void(0);">Вы не глава</a></div>'; $r = '<div style="text-align: center;"><a href="javascript:void(0);">Вы не глава</a></div>';
@ -216,7 +216,7 @@ echo <<<RELICTS
<button disabled>clone</button> <button disabled>clone</button>
<button disabled>unclone</button> <button disabled>unclone</button>
RELICTS; RELICTS;
if ($user->getAdmin()) { if (User::getInstance()->getAdmin()) {
echo <<<A echo <<<A
<button onclick="location.href='?teleport=1'">Телепорт на ЦП</button> <button onclick="location.href='?teleport=1'">Телепорт на ЦП</button>
A; A;
@ -229,7 +229,7 @@ A;
<div style="text-align: center;" id=hint3></div> <div style="text-align: center;" id=hint3></div>
<div> <div>
<?php <?php
if ($user->getAlign() == 2 || $user->getAdmin()) // Нейтралы if (User::getInstance()->getAlign() == 2 || User::getInstance()->getAdmin()) // Нейтралы
{ {
$abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); $abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc();
@ -245,7 +245,7 @@ A;
echo("<img src='i/magic/attackk_open.gif' title='Кулачное закрытое нападение'> Кулачное закрытое нападение - " . $abil[2] . "<br />"); echo("<img src='i/magic/attackk_open.gif' title='Кулачное закрытое нападение'> Кулачное закрытое нападение - " . $abil[2] . "<br />");
} }
if ($user->getAlign() == 6 || $user->getAdmin()) // Свет if (User::getInstance()->getAlign() == 6 || User::getInstance()->getAdmin()) // Свет
{ {
$abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); $abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc();
@ -449,7 +449,7 @@ A;
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: 'fancy/buy.php', url: 'fancy/buy.php',
data: "type=" + type + "&user=" + <?= $user->getId() ?> + "", data: "type=" + type + "&user=" + <?= User::getInstance()->getId() ?> + "",
success: function (data) { success: function (data) {
if (data === 'success') { if (data === 'success') {
$(".child").html('<b style="color: Red;">' + types_user[type - 1] + ' успешно куплено</b>'); $(".child").html('<b style="color: Red;">' + types_user[type - 1] + ' успешно куплено</b>');
@ -469,7 +469,7 @@ A;
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: 'fancy/buy_klan.php', url: 'fancy/buy_klan.php',
data: "type=" + type + "&user=" + <?= $user->getId() ?> + "", data: "type=" + type + "&user=" + <?= User::getInstance()->getId() ?> + "",
success: function (data) { success: function (data) {
if (data === 'success') { if (data === 'success') {
$(".child").html('<b style="color: Red;">' + types_klan[type - 21] + ' успешно куплено</b>'); $(".child").html('<b style="color: Red;">' + types_klan[type - 21] + ' успешно куплено</b>');

View File

@ -17,18 +17,18 @@ if ($name || $hobbie) {
err('Максимальная длинна поля Хобби: ' . User::INFO_CHAR_LIMIT . ' символов!'); err('Максимальная длинна поля Хобби: ' . User::INFO_CHAR_LIMIT . ' символов!');
} else { } else {
if ($name) { if ($name) {
$user->setRealname($name); User::getInstance()->setRealname($name);
} }
if ($hobbie) { if ($hobbie) {
$user->setInfo($hobbie); User::getInstance()->setInfo($hobbie);
} }
$user->saveUser(); User::getInstance()->saveUser();
} }
} }
if ($oldpsw && $newpsw) { if ($oldpsw && $newpsw) {
if (password_verify($oldpsw, $user->getPass())) { if (password_verify($oldpsw, User::getInstance()->getPass())) {
$user->setPass(password_hash($newpsw, PASSWORD_DEFAULT)); User::getInstance()->setPass(password_hash($newpsw, PASSWORD_DEFAULT));
$user->saveUser(); User::getInstance()->saveUser();
} else { } else {
err('Неверный текущий пароль!'); err('Неверный текущий пароль!');
} }
@ -36,13 +36,13 @@ if ($oldpsw && $newpsw) {
Template::header('Анкета'); Template::header('Анкета');
?> ?>
<a href="main.php"> на главную</a> <a href="main.php"> на главную</a>
<h1>Анкета персонажа <?= $user->getLogin() ?></h1> <h1>Анкета персонажа <?= User::getInstance()->getLogin() ?></h1>
<form method="post"> <form method="post">
<label> <label>
<input name="name" placeholder="Реальное имя" value="<?= $user->getRealname() ?>"> <input name="name" placeholder="Реальное имя" value="<?= User::getInstance()->getRealname() ?>">
Реальное имя Реальное имя
</label><br> </label><br>
<textarea name="hobbie" placeholder="Хобби"><?= $user->getInfo() ?></textarea><br> <textarea name="hobbie" placeholder="Хобби"><?= User::getInstance()->getInfo() ?></textarea><br>
<input name="submit" type="submit"> <input name="submit" type="submit">
</form> </form>
<h1>Безопасность</h1> <h1>Безопасность</h1>

View File

@ -1,14 +1,15 @@
<?php <?php
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
if ($user->getLevel() < 4 && $user->getLevel() > 10) { if (User::getInstance()->getLevel() < 4 && User::getInstance()->getLevel() > 10) {
header('location: main.php?act=none'); header('location: main.php?act=none');
exit; exit;
} }
if ($user->getRoom() == 403) { if (User::getInstance()->getRoom() == 403) {
header('Location: canalizaciya.php'); header('Location: canalizaciya.php');
exit; exit;
} }

View File

@ -5,8 +5,10 @@ use Battles\DressedItems;
use Battles\GameLogs; use Battles\GameLogs;
use Battles\Nick; use Battles\Nick;
use Battles\Template; use Battles\Template;
use Battles\User;
require_once "functions.php"; require_once "functions.php";
$user = User::getInstance();
try { try {
db::c()->query('LOCK TABLES `bots` WRITE, `battle` WRITE, `logs` WRITE, `users` WRITE, `inventory` WRITE, `zayavka` WRITE, `effects` WRITE, `online` WRITE, `clans` WRITE'); db::c()->query('LOCK TABLES `bots` WRITE, `battle` WRITE, `logs` WRITE, `users` WRITE, `inventory` WRITE, `zayavka` WRITE, `effects` WRITE, `online` WRITE, `clans` WRITE');
} catch (Exception $e) { } catch (Exception $e) {