diff --git a/admin/admin.php b/admin/admin.php index b6b5f7e..23fcc34 100644 --- a/admin/admin.php +++ b/admin/admin.php @@ -7,25 +7,23 @@ require_once '../functions.php'; use Battles\Bank; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\GameConfigs; use Battles\Moderation; use Battles\Nick; use Battles\Template; use Battles\User; -if (!User::$current->getAdmin()) { +if (!User::getInstance()->getAdmin()) { header("HTTP/1.0 404 Not Found"); exit; } 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'])) { - $u = new User($_POST['ldnick']); - Moderation::addToUserLog($u->getId(), $_POST['ldtext'], User::$current->getId()); - unset($u); + Moderation::addToUserLog(User::getInstance($_POST['ldnick'])->getId(), $_POST['ldtext'], User::getInstance()->getId()); } if (isset($_POST['syschatmsg'])) { @@ -37,11 +35,11 @@ $unregisteredClans = new class { 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; while ($i < count($row)) { $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; $shortName = $row[$i]->short_name; $info = nl2br($row[$i]->info); @@ -64,13 +62,13 @@ UNREGCLANLIST; 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) { $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); } }; @@ -89,12 +87,12 @@ if (isset($_GET['remclan'])) { # Телеграф. 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']); 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) { $invisList .= '[id] = ' .$r->id. ', ' .$r->login. '
'; } diff --git a/admin/edit_user.php b/admin/edit_user.php index df84ab0..1d931fb 100644 --- a/admin/edit_user.php +++ b/admin/edit_user.php @@ -5,12 +5,13 @@ * Project name: Battles-Game */ -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\DressedItems; use Battles\Template; +use Battles\User; require_once "../functions.php"; -if (!$user->getAdmin()) { +if (!User::getInstance()->getAdmin()) { header("HTTP/1.0 404 Not Found"); exit; } @@ -21,7 +22,7 @@ $end = $_POST['end'] ?? null; $del = $_POST['del'] ?? null; 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_name'] = $row->login; unset($row); @@ -46,7 +47,7 @@ if ($del) { $item->undressItem(7); } } - DBPDO::$db->execute('delete from inventory where id = ?', $del); + Db::getInstance()->execute('delete from inventory where id = ?', $del); } Template::header('ᐰdminка инвентаря'); ?> diff --git a/akadem.php b/akadem.php index f9d5546..4ed73c6 100644 --- a/akadem.php +++ b/akadem.php @@ -3,6 +3,7 @@ use Battles\Bank; use Battles\GameLogs; use Battles\Template; +use Battles\User; require_once 'functions.php'; const SMITH = 'оружейник'; @@ -42,9 +43,9 @@ function setProfession($name, $type, $needMoney, $needLevel) $profId = 22; } if (!empty($profId)) { - $user->setMoney($user->getMoney() - $needMoney); - Bank::setWalletMoney($user->getMoney(), $user->getId()); - db::c()->query('UPDATE `users` SET ?f = ?i WHERE `id` = ?i', 'prof' . $type, $profId, $user->getId()); + User::getInstance()->setMoney(User::getInstance()->getMoney() - $needMoney); + Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); + db::c()->query('UPDATE `users` SET ?f = ?i WHERE `id` = ?i', 'prof' . $type, $profId, User::getInstance()->getId()); $deloText = "{$user['login']} купил профессию «{$name}» в академии за {$needMoney} кр."; GameLogs::addUserLog($_SESSION['uid'], $deloText); $user['prof' . $type] = true; @@ -66,7 +67,7 @@ if ($get == 'medic') { } 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'); } Template::header('Академия'); @@ -79,8 +80,8 @@ Template::header('Академия');
Информация - КредитыgetMoney() ?> - Уровень персонажаgetLevel() ?> + КредитыgetMoney() ?> + Уровень персонажаgetLevel() ?>
Наёмник diff --git a/bank.php b/bank.php index d0a9dd7..41914fb 100644 --- a/bank.php +++ b/bank.php @@ -5,11 +5,12 @@ use Battles\GameConfigs; use Battles\Rooms; use Battles\Template; use Exceptions\GameException; +use Battles\User; require_once "functions.php"; const SUCCESS = "Успешная операция!"; -$bank = new Bank($user->getId()); +$bank = new Bank(User::getInstance()->getId()); $status = ''; $toid = $_POST['to_id'] ?? 0; @@ -19,20 +20,20 @@ try { // Зачисление кредитов на счёт. if ($submit === 'depositMoney' && $summa) { $operation = $bank->depositMoney($summa); - $user->setMoney($operation['walletMoney']); + User::getInstance()->setMoney($operation['walletMoney']); $bank->setMoney($operation['bankMoney']); $status = SUCCESS; } // Снятие кредитов со счёта. if ($submit === 'withdrawMoney' && $summa) { $operation = $bank->withdrawMoney($summa); - $user->setMoney($operation['walletMoney']); + User::getInstance()->setMoney($operation['walletMoney']); $bank->setMoney($operation['bankMoney']); $status = SUCCESS; } // Перевод кредитов на другой счёт. if ($submit === 'sendMoney' && $summa && $toid) { - $user->setMoney($bank->sendMoney($toid, $summa)); + User::getInstance()->setMoney($bank->sendMoney($toid, $summa)); $status = SUCCESS; } } catch (GameException $e) { @@ -49,7 +50,7 @@ Template::header('Банк');
На счету: getMoney() ?>
- На руках: getMoney() ?> + На руках: getMoney() ?>
Работа со счётом diff --git a/buy.php b/buy.php index b0f05cb..590d251 100644 --- a/buy.php +++ b/buy.php @@ -1,11 +1,11 @@ getBattle()) { +if (User::getInstance()->getBattle()) { exit(); } const PRICES = [ @@ -26,7 +26,7 @@ const PRICES = [ '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) { exit('Запрещено: Вам нельзя покупать бонусы.'); @@ -35,12 +35,12 @@ if (!$check_bonuses) { function buy_bonus($name): bool { global $prices; - $bank = new Bank(User::$current->getId()); + $bank = new Bank(User::getInstance()->getId()); if ($bank->getMoney() <= PRICES[$name]) { return false; } $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]); return true; } diff --git a/buy_klan.php b/buy_klan.php index c0828f2..138f88e 100644 --- a/buy_klan.php +++ b/buy_klan.php @@ -1,11 +1,11 @@ getClan() || User::$current->getBattle()) { +if (!User::getInstance()->getClan() || User::getInstance()->getBattle()) { exit(); } const PRICES = [ @@ -26,10 +26,10 @@ const PRICES = [ 'unclone' => 25, ]; -$check_owner = DBPDO::$db->ofetch('select short_name from clans where owner_id = ?', User::$current->getId()); -$check_bonuses = DBPDO::$db->ofetch('select 1 from clan_bonuses where short_name = ?', User::$current->getClan()); +$check_owner = Db::getInstance()->execute('select short_name from clans where owner_id = ?', User::getInstance()->getId())->fetchColumn(); +$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('Запрещено: Вы не глава клана.'); } if (!$check_bonuses) { @@ -38,14 +38,14 @@ if (!$check_bonuses) { function buy_bonus($name): bool { - global $prices; - $bank = new Bank(User::$current->getId()); + $bank = new Bank(User::getInstance()->getId()); if ($bank->getMoney() <= PRICES[$name]) { return false; } + $query = sprintf('update clan_bonuses set %s = %s + 1 where short_name = ?', $name, $name); - DBPDO::$db->execute($query, User::$current->getClan()); - $bank->setMoney($bank->getMoney() - $prices[$name]); + Db::getInstance()->execute($query, User::getInstance()->getClan()); + $bank->setMoney($bank->getMoney() - PRICES[$name]); return true; } diff --git a/c_forest.php b/c_forest.php index eda874a..1bcd881 100644 --- a/c_forest.php +++ b/c_forest.php @@ -1,9 +1,9 @@ getRoom() == 51) { +if (User::getInstance()->getRoom() == 51) { header('location: city.php'); exit; } @@ -26,8 +26,8 @@ $map_user = loadmap_cell(); if ($_GET['exit_forest'] == 'true') { if ($forest['room']) { - #db::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_bots` 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('DELETE FROM `forest` WHERE `user` = ?i', $user['id']); unset($forest); diff --git a/canalizaciya.php b/canalizaciya.php index a12a23c..90c20ba 100644 --- a/canalizaciya.php +++ b/canalizaciya.php @@ -1,9 +1,9 @@ getRoom() == 403) { +if (User::getInstance()->getRoom() == 403) { include "startpodzemel.php"; if ($_GET['act'] == "cexit") { $das = mysql_query("select glava,glav_id from `labirint` where user_id='" . $user['id'] . "'"); @@ -38,7 +38,7 @@ if ($user->getRoom() == 403) { 'Ключик №9', 'Ключик №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'] . "'"); @@ -51,7 +51,7 @@ if ($user->getRoom() == 403) { { $frt = mysql_query("select user_id from `labirint` where glava='" . $glava . "'"); while ($rbb = mysql_fetch_array($frt)) { - addchp('' . $user->getLogin() . ' поднял предмет "' . $mis . '". ', '{[]}' . Nick::id($rbb["user_id"])->short() . '{[]}'); + addchp('' . User::getInstance()->getLogin() . ' поднял предмет "' . $mis . '". ', '{[]}' . Nick::id($rbb["user_id"])->short() . '{[]}'); } } } diff --git a/canalization_mod.php b/canalization_mod.php index d7d310f..e7c3002 100644 --- a/canalization_mod.php +++ b/canalization_mod.php @@ -1,5 +1,8 @@ getRoom() == 403) { + +use Battles\User; + +if (User::getInstance()->getRoom() == 403) { $s = db::c()->query('SELECT * FROM podzem2 WHERE name= "?s"', $mir['name'])->fetch_assoc(); $rooms[0] = ""; diff --git a/cave.php b/cave.php index 867b039..aef740f 100644 --- a/cave.php +++ b/cave.php @@ -9,191 +9,85 @@ use Battles\User; require_once 'functions.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']; -function cancarry($m, $u) +function cancarry($m, $uid) { - global $user; - if (!$u) { - $u = $user['id']; + if (!$uid) { + $uid = User::getInstance()->getId(); } - $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")); - $mw = 40 * $user['level'] + $user['vinos'] + $bp['gmeshok']; - if ($bp['massa'] + $m > $mw) { - return false; - } - return true; + $weight = \Battles\Database\Db::getInstance()->execute('select sum(weight) from inventory where owner_id = ? and on_sale = 0', $uid)->fetchColumn(); + $maxWeight = \Battles\Database\Db::getInstance()->execute('select strength * 4 from users where id = ?', $uid)->fetchColumn(); + return $weight + $m > $maxWeight ? false : true; } -function placeinbackpack($qty, $userid = 0) +function placeinbackpack($qty, $userid = null) { - global $user; - if (!$userid) { - $userid = $user['id']; + if (is_null($userid)) { + $userid = User::getInstance()->getId(); } - if ($userid == $user['id']) { - $user1 = $user; - } else { - $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']); + $user1 = $userid === User::getInstance()->getId() ? User::getInstance() : User::getInstance($userid); + $count = \Battles\Database\Db::getInstance()->execute('select count(*) from inventory where owner_id = ? and on_sale = 0', $user1->getId())->fetchColumn(); + return $count + $qty <= $user1->getLevel() * 10 + 5; } -function backpacksize($u = 0) -{ // $l * 10 +5 - $l = 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) +// x, $btl +// x, 0, $otherbots +function battlewithbot($b, $otherbots = [], $noredir = 0) { - global $user; - 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")); - } + $user1 = User::getInstance(); $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']; - } + mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$name', '$b', '', '" . $bot['maxhp'] . "')"); + $hps[$b] = $bot['maxhp']; + $botid1 = mysql_insert_id(); + $cond = " `id` = '$botid1' "; - if (@$battleid > 0) { - $bd = mysql_fetch_array(mysql_query("SELECT * FROM `battle` WHERE `id` = '$battleid' LIMIT 1")); - $battle = unserialize($bd['teams']); + $teams = []; + $teams[$user1['id']][$botid1] = [0, 0, time()]; + $teams[$botid1][$user1['id']] = [0, 0, time()]; + $t2 = "$botid1"; - $t1 = explode(";", $bd['t1']); - $t2 = explode(";", $bd['t2']); + $others = ""; + $hps = []; - $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; + foreach ($otherbots as $k => $v) { + if (CaveBots::$botnames[$v['name']]) { + $i = 1; + while (CaveBots::$botnames["$v[name] ($i)"]) $i++; + $botname = "$v[name] ($i)"; } else { - $ttt = 1; + $botname = $v['name']; } - - if ($user1['invis'] == 1) { - GameLogs::addBattleLog($battleid, '' . date("H:i") . ' невидимка вмешался в поединок!
'); - } else { - GameLogs::addBattleLog($battleid, '' . date("H:i") . ' ' . Nick::id($user['id'])->short() . ' вмешался в поединок!
'); + CaveBots::$botnames[$botname] = 1; + if (!@$hps[$v['id']]) { + $hps[$v['id']] = mysql_fetch_array(mysql_query("SELECT `maxhp` FROM `users` WHERE `id` = '$v[id]' LIMIT 1")); } + mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$botname', '$v[id]', '', '" . $hps[$v['id']]['maxhp'] . "')"); + $botid = mysql_insert_id(); + $cond .= " OR `id` = '$botid' "; + $teams[$user1['id']][$botid] = [0, 0, time()]; + $teams[$botid][$user1['id']] = [0, 0, time()]; + $others .= "" . date("H:i") . " $botname вмешался в поединок.
"; + $t2 .= ";$botid"; + } + 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") . "')"); - 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"); + $battleid = mysql_insert_id(); + mysql_query("UPDATE `bots` SET `battle` = {$battleid} WHERE $cond"); + mysql_query("UPDATE `users` SET `battle` = {$battleid} WHERE `id` = {$user1['id']} LIMIT 1"); - if (!$noredir) { - header("Location: fbattle.php"); - } + if ($user1['invis'] == 1) { + $rr = "невидимка и " . Nick::id($botid1)->full(1) . ""; } else { - - mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$name', '$b', '', '" . $bot['maxhp'] . "')"); - $hps[$b] = $bot['maxhp']; - $botid1 = mysql_insert_id(); - $cond = " `id` = '$botid1' "; - - $teams = []; - $teams[$user1['id']][$botid1] = [0, 0, time()]; - $teams[$botid1][$user1['id']] = [0, 0, time()]; - $t2 = "$botid1"; - - $others = ""; - $hps = []; - - foreach ($otherbots as $k => $v) { - if (CaveBots::$botnames[$v['name']]) { - $i = 1; - while (CaveBots::$botnames["$v[name] ($i)"]) $i++; - $botname = "$v[name] ($i)"; - } else { - $botname = $v['name']; - } - CaveBots::$botnames[$botname] = 1; - if (!@$hps[$v['id']]) { - $hps[$v['id']] = mysql_fetch_array(mysql_query("SELECT `maxhp` FROM `users` WHERE `id` = '$v[id]' LIMIT 1")); - } - mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$botname', '$v[id]', '', '" . $hps[$v['id']]['maxhp'] . "')"); - $botid = mysql_insert_id(); - $cond .= " OR `id` = '$botid' "; - $teams[$user1['id']][$botid] = [0, 0, time()]; - $teams[$botid][$user1['id']] = [0, 0, time()]; - $others .= "" . date("H:i") . " $botname вмешался в поединок.
"; - $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") . "')"); - - $battleid = mysql_insert_id(); - mysql_query("UPDATE `bots` SET `battle` = {$battleid} WHERE $cond"); - mysql_query("UPDATE `users` SET `battle` = {$battleid} WHERE `id` = {$user1['id']} LIMIT 1"); - - if ($user1['invis'] == 1) { - $rr = "невидимка и " . Nick::id($botid1)->full(1) . ""; - } else { - $rr = "" . Nick::id($user1['id'])->full(1) . " и " . Nick::id($botid1)->full(1) . ""; - } - GameLogs::addBattleLog($battleid, "Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
" . ($others ? "$others
" : "")); - if (!$noredir) { - header("Location: fbattle.php"); - } + $rr = "" . Nick::id($user1['id'])->full(1) . " и " . Nick::id($botid1)->full(1) . ""; } + GameLogs::addBattleLog($battleid, "Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
" . ($others ? "$others
" : "")); + if (!$noredir) { + header("Location: fbattle.php"); + } + return $battleid; } @@ -290,15 +184,15 @@ function makedeath() { global $user, $floor, $loses, $x, $y, $dir; $cavedata = CAVE_DATA ?? []; - if (!isset($cavedata[$user->getRoom()]['x' . $floor])) { + if (!isset($cavedata[User::getInstance()->getRoom()]['x' . $floor])) { $floor = 1; 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'); - $x = $cavedata[$user->getRoom()]['x' . $floor]; - $y = $cavedata[$user->getRoom()]['y' . $floor]; - $dir = $cavedata[$user->getRoom()]['dir' . $floor]; + $x = $cavedata[User::getInstance()->getRoom()]['x' . $floor]; + $y = $cavedata[User::getInstance()->getRoom()]['y' . $floor]; + $dir = $cavedata[User::getInstance()->getRoom()]['dir' . $floor]; updparties(); $loses++; } @@ -444,7 +338,7 @@ while ($rec = mysql_fetch_assoc($r)) { $party[] = $rec; } -if ($user->getRoom() == 621) { +if (User::getInstance()->getRoom() == 621) { $base = "/underdesigns/alchcave"; } @@ -525,18 +419,14 @@ if ($_GET['useitem']) { $tx = $x; $ty = $y + 1; } - if (@$_GET['useitem']) { - if (file_exists("underground/objects/$user->getRoom().php")) { - include "underground/objects/$user->getRoom().php"; - } + if ($_GET['useitem'] && file_exists("underground/objects/" . User::getInstance()->getRoom() . ".php")) { + include "underground/objects/" . User::getInstance()->getRoom() . ".php"; } [$t, $obj] = explode("/", $map[$ty * 2][$tx * 2]); - if ($t == "o") { - if ($obj == 500) { - $report = "В этот сундук уже кто-то заглядывал"; - } + if ($t == "o" && $obj == 500) { + $report = "В этот сундук уже кто-то заглядывал"; } mysql_query("UNLOCK TABLES"); } @@ -623,7 +513,7 @@ if ($wander && !isset($_GET['attack'])) { $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]) { break; } @@ -691,8 +581,8 @@ if ($moved && (substr($map[$y * 2][$x * 2], 0, 1) === "e" || substr($map[$y * 2] $tx = $x; $ty = $y; $tmp = explode("/", $map[$y * 2][$x * 2]); - if (file_exists("underground/events/$user->getRoom().php")) { - include("underground/events/$user->getRoom().php"); + if (file_exists("underground/events/" . User::getInstance()->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) { $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) { $dir1 = 0; } elseif ($ax > $x) { @@ -759,7 +649,7 @@ if ($_GET['takeitem']) { $report = "Ваш рюкзак перегружен."; } else { $destiny = 0; - $taken = ShopItem::giveNewItem($it['item'], User::$current->getId()); + $taken = ShopItem::giveNewItem($it['item'], User::getInstance()->getId()); if (@$taken['error']) { $report = $taken['error']; } else { @@ -826,7 +716,7 @@ if (@$_GET['attack']) { } elseif (isset($rec['bot'])) { $btl = $rec['battle']; if ($btl > 0) { - battlewithbot(CaveBots::$bots[$rec['bot']], "", "", 10, 0, 0, $btl); + battlewithbot(CaveBots::$bots[$rec['bot']], $btl); } else { $firstbot = CaveBots::$bots[$rec['bot']]; $otherbots = []; @@ -843,7 +733,7 @@ if (@$_GET['attack']) { $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'"); } } @@ -882,7 +772,7 @@ if (@$_GET['exit']) { } } 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]; @@ -891,414 +781,414 @@ foreach ($party as $k => $v) { } Template::header('cave'); ?> - + -
- - + el2.innerHTML = ''; + el2.style.left = posx + "px"; + el2.style.top = posy + 33 + "px"; + el2.style.visibility = "visible"; + } + +
+ + 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 .= " 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 { $ret .= " 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]; $top = $imgdata[$x][$y]["y"] + $ht; } - $rrm = $user->getRoom(); + $rrm = User::getInstance()->getRoom(); if (!isset($imgmap[$obj])) { $ret .= " @@ -1587,7 +1477,7 @@ function drawmap($map1, $players, $x, $y, $direction) $left = $imgdata[$x][$y]["x"][1]; $top = $imgdata[$x][$y]["y"] + $ht; } - $rrm = $user->getRoom(); + $rrm = User::getInstance()->getRoom(); if (!isset($imgmap[$obj])) { $ret .= " " . ($y == 1 && $x == 3 ? "" : "") . " @@ -1748,7 +1638,7 @@ function drawmap($map1, $players, $x, $y, $direction) } $objInWall = explode('/', $map[3][$wall]); 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); } } @@ -1914,86 +1804,87 @@ progress_update(); } ?> - - - + + +
-
- - $v) { - if ($v["user"] == $user["id"]) { - $usr = $user; - } else { - $usr = mysql_fetch_array(mysql_query("SELECT `level`, `hp`, `maxhp` FROM `users` WHERE `id` = '$v[user]'")); - } - $wd = floor($usr["hp"] / $usr["maxhp"] * 120); - echo " - - -
+ + +
+
+ + $v) { + if ($v["user"] == $user["id"]) { + $usr = $user; + } else { + $usr = mysql_fetch_array(mysql_query("SELECT `level`, `hp`, `maxhp` FROM `users` WHERE `id` = '$v[user]'")); + } + $wd = floor($usr["hp"] / $usr["maxhp"] * 120); + echo " + if ($v["user"] == $user["id"] && $user["id"] == $user["caveleader"]) echo "\"Выгнать \"Новый"; + echo ""; - } - ?> -
$v[login] [$usr[level]]
" . ($v["user"] == $user["id"] ? "" : "") . "$usr[hp]" . ($v["user"] == $user["id"] ? "" : "") . "/$usr[maxhp]\"Уровень\"Уровень
"; - if ($v["user"] == $user["id"] && $user["id"] == $user["caveleader"]) echo "\"Выгнать \"Новый"; - echo "
-
-
- +
+
+
+ -  
-
-

-
+ ?> +   +
+

+
+ 0) echo "В комнате разбросаны вещи:
 
"; + while ($rec = mysql_fetch_assoc($r)) { + echo " "; + } + ?>
+
0) echo "В комнате разбросаны вещи:
 
"; - while ($rec = mysql_fetch_assoc($r)) { - echo " "; - } - ?>
-
- = 3) echo "
Вас убили 3 раза, и вы покидете подземелье

+ if ($loses >= 3) echo "
Вас убили 3 раза, и вы покидете подземелье

Вернуться

"; - if ($loses) echo "
Количество смертей: $loses
"; + if ($loses) echo "
Количество смертей: $loses
"; - ?> -
-
- getRoom() - 1)), 0, 0)); - $cPlace = $dMap[$y * 2][$x * 2]; - $tmp = explode("/", $cPlace); - if ($user->getRoom() == 621) { - if ($floor == 1) { - echo 'Проклятый Рудник, 1 этаж'; - } elseif ($floor == 2) { - echo 'Проклятый Рудник, 2 этаж'; - } - } elseif (@$roomnames[$tmp[1]]) echo $roomnames[$tmp[1]]; - else echo $rooms[$user["room"]]; - ?>     -      Выйти -
- -
+ ?> +
+
+ getRoom() - 1)), 0, 0)); + $cPlace = $dMap[$y * 2][$x * 2]; + $tmp = explode("/", $cPlace); + if (User::getInstance()->getRoom() == 621) { + if ($floor == 1) { + echo 'Проклятый Рудник, 1 этаж'; + } elseif ($floor == 2) { + echo 'Проклятый Рудник, 2 этаж'; + } + } elseif (@$roomnames[$tmp[1]]) echo $roomnames[$tmp[1]]; + else echo $rooms[$user["room"]]; + ?>     +      Выйти +
+ +
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 ($_GET['room'] && (int)$_GET['room'] < 500) { - $user->setRoom($_GET['room']); + User::getInstance()->setRoom($_GET['room']); } if ($u->i()['caveleader'] > 0) { $data = db::c()->query(' @@ -35,13 +35,13 @@ if (isset($_GET['online']) && $_GET['online'] != null) { ORDER BY `u`.`login` '); - $ttl = "" . $rooms[$user->getRoom()] . " (" . mysql_num_rows($data) . ")"; + $ttl = "" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")"; $ch1 = '_active'; $ch2 = '_passive'; $ch3 = '_passive'; $ch4 = '_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(); $sp = db::c()->query('SELECT `id`, `room`, `user` FROM `forest` WHERE `room` = "' . $forest['room'] . '"'); while ($pl = $sp->fetch_assoc()) { @@ -100,18 +100,18 @@ if (isset($_GET['online']) && $_GET['online'] != null) { WHERE `o`.`id` = `u`.`id` AND (`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND - `o`.`room` = "' . $user->getRoom() . '" + `o`.`room` = "' . User::getInstance()->getRoom() . '" ORDER BY `u`.`login` '); - $ttl = "" . $rooms[$user->getRoom()] . " (" . mysql_num_rows($data) . ")"; + $ttl = "" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")"; $ch1 = '_active'; $ch2 = '_passive'; $ch3 = '_passive'; $ch4 = '_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))); ?> "); -} -if ($_POST['admin_start1']) { - $tm = time() - 900; - mysql_query("UPDATE `variables` SET `value`='{$tm}' WHERE `var`='cc_time';"); - exit(""); -} - -if ($_POST['add_zay']) { - mysql_query("INSERT INTO `clan_castle` VALUES ('{$user['id']}','{$user['klan']}');"); - exit(""); -} -Template::header('Замок Мэра'); -?> - - - - - - - - - - - - '; - } - - } 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 'Внимание!' . $tmp_k['name'] . ' собираются штурмовать замок'; - } - if ($tmp_k && $own['value'] > 0) { - echo '' . $tmp_o['name'] . '!'; - } - 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 "Смелых так и не нашлось...
"; - } elseif (empty($ow_t) && ($own['value'] > 0)) { - echo "Хозяева слили замок без боя...
"; - $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('Клан ' . $cc_a['name'] . ' без боя забрал у клана ' . $cc_k['name'] . ' Замок Мэра'); - - - $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 = ""; - - foreach ($at_t as $k => $v) { - if ($k != 0) { - $rr .= ", "; - $rrc .= ", "; - } - $rr .= Nick::id($v)->full(1); - $rrc .= Nick::id($v)->short(); - addchp('Внимание! Ваш бой начался!
\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}'); - } - $rr .= "
и "; - $rrc .= " и "; - foreach ($bots as $k => $v) { - if ($k != 0) { - $rr .= ", "; - $rrc .= ", "; - } - $rr .= Nick::id($v)->full(1); - $rrc .= Nick::id($v)->short(); - } - $rr .= ""; - addch("Поединок между " . $rrc . " начался. ", $user->getRoom()); - mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
');"); - - GameLogs::addBattleLog($id, "Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
"); - $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 = ""; - - foreach ($at_t as $k => $v) { - if ($k != 0) { - $rr .= ", "; - $rrc .= ", "; - } - $rr .= Nick::id($v)->full(1); - $rrc .= Nick::id($v)->short(); - addchp('Внимание! Ваш бой начался!
\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}'); - } - $rr .= "
и "; - $rrc .= " и "; - foreach ($ow_t as $k => $v) { - if ($k != 0) { - $rr .= ", "; - $rrc .= ", "; - } - $rr .= Nick::id($v)->full(1); - $rrc .= Nick::id($v)->short(); - addchp('Внимание! Ваш бой начался!
\'; top.frames[\'main\'].location=\'fbattle.php\'; var z = \' ', '{[]}' . Nick::id($v)->short() . '{[]}'); - } - $rr .= "
"; - addch("Поединок между " . $rrc . " начался. ", $user->getRoom()); - mysql_query("INSERT INTO `logs` (`id`,`log`) VALUES('{$id}','Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
');"); - - GameLogs::addBattleLog($id, "Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " бросили вызов друг другу.
"); - $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`"); - } - ?> - - -

Замок Мэра

-
-
Добро пожаловать в Замок доброго и справедливого Мэра! - Если Вы заинтерисованы в обладании правами на Замок, либо считаете что обладаете достаточными способностями - для исполнения - обязанностей Мэра, приглашаем Вас и Ваших единомышлеников поселиться в Замке!

- Внимание! Администрация не несет ответственности за возможные конфликты на основе спора о правах обладания - Замком, - целость и сохранность Ваших личных вещей, здоровье и жизни посетителей!
- 0) { - $tmp_k = mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$own['value']}'")); - } - echo '
Над Замком развевается флаг '; - if ($tmp_k['name']) { - echo 'клана ' . $tmp_k['name'] . '
'; - } else { - echo 'сил Хаоса
'; - } - - if ($user->getAdmin()) { - echo '

'; - echo '

'; - } - if ($ccd >= time()) { - echo "Следующая битва: " . (date("j.m", $ccd)) . " в " . (date("H:i", $ccd)); - } elseif ($ccd < time() && ($ccd + 900) >= time()) { - $zays = []; - echo "Заявили права на Замок Мэра:"; - echo ''; - $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 ''; - } - if (empty($zays)) { - echo ''; - } - echo '
Клан ' . $tmp_k['name'] . '
Ждем смелых ...
'; - echo "
Прием заявок до: " . (date("H:i", $ccd + 900)) . ""; - - $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 "
Прием заявок от глав кланов:"; - echo '
-
\ No newline at end of file diff --git a/clan_create.php b/clan_create.php index 9dac13a..8b44c3c 100644 --- a/clan_create.php +++ b/clan_create.php @@ -1,28 +1,30 @@ 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'] ?? ''; $clanShortName = $_POST['clan_short_name'] ?? ''; $clanInfo = $_POST['clan_info'] ?? ''; -$userBank = new Bank($user->getId()); +$userBank = new Bank(User::getInstance()->getId()); if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { - $eff = db::c()->query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $user->getId()); - $name_check = db::c()->query('SELECT owner_id FROM clans WHERE full_name = "?s" OR short_name = "?s"', $clanFullName, $clanShortName); + $eff = Db::getInstance()->execute('select count(*) from users_effects where type = 20 and owner_id = ?', User::getInstance()->getId())->fetchColumn(); + $name_check = Db::getInstance()->execute('select count(*) from clans where full_name = ? or short_name = ?', [$clanFullName, $clanShortName])->fetchColumn(); $errorMessage = []; if (GameConfigs::CLAN['clan_register_lock']) { $errorMessage[10] = 'Регистрация кланов закрыта!
'; } - if ($user->getAlign()) { + if (User::getInstance()->getAlign()) { $errorMessage[0] = 'Вы уже имеете направленность!.
'; } - if ($user->getClan()) { + if (User::getInstance()->getClan()) { $errorMessage[1] = 'Вы уже состоите в клане!.
'; } if (GameConfigs::CLAN['clan_register_cost'] >= $userBank->getMoney()) { @@ -34,11 +36,11 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { if (!$name_check) { $errorMessage[4] = 'Клан с такими данными уже существует.
'; } - if (!$errorMessage || $user->getAdmin()) { + if (!$errorMessage || User::getInstance()->getAdmin()) { 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']); - Battles\Bank::setBankMoney($userBank->getMoney(), $user->getId(), 'clanRegister'); + Battles\Bank::setBankMoney($userBank->getMoney(), User::getInstance()->getId(), 'clanRegister'); // Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит. $userClan = new stdClass(); $userClan->full_name = $clanFullName; @@ -61,10 +63,16 @@ if ($userClan): ?>
Заявка на регистрацию - -
+ +

-
+
@@ -73,12 +81,18 @@ if ($userClan): ?>
Заявка на регистрацию - -
+ +

-
+
diff --git a/clans.php b/clans.php index 63dc050..b9498fe 100644 --- a/clans.php +++ b/clans.php @@ -1,22 +1,25 @@ * Project name: Battles-Game */ -\Battles\Template::header('Список кланов'); + +use Battles\Template; + +Template::header('Список кланов'); include_once "config.php"; $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 "

{$query['name']}

{$query['descr']}

"; - $clanlist = db::c()->query('SELECT `login`,`status` FROM `users` WHERE `klan` = ?i',$query['id']); - while ($member = $clanlist->fetch_assoc()) { + $clanlist = \Battles\Database\Db::getInstance()->execute('select login from users where clan = ?', $claninf); + while ($member = $clanlist->fetch()) { echo " ",$member['login']," - ",$member['status'],"
"; } } else { echo "

Список кланов

"; - $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()) { $frm = " %s
"; echo sprintf($frm,$clanrow['align'],$clanrow['short'],$clanrow['name'],$clanrow['name']); diff --git a/classes/Battles/Bank.php b/classes/Battles/Bank.php index bad8055..99a534b 100644 --- a/classes/Battles/Bank.php +++ b/classes/Battles/Bank.php @@ -8,7 +8,7 @@ namespace Battles; use Exceptions\GameException; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Throwable; class Bank @@ -16,7 +16,6 @@ class Bank public int $user_id = 0; private int $money = 0; private $user; - private static DBPDO $db; const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; @@ -33,9 +32,8 @@ class Bank public function __construct(int $user_id) { - self::$db = DBPDO::INIT(); - $bank_row = self::$db->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id); - $this->user = self::$db->fetch('SELECT money FROM users WHERE id = ?', $user_id); + $bank_row = Db::getInstance()->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); foreach ($this as $key => $value) { if (isset($bank_row[$key])) { $this->$key = $bank_row[$key]; @@ -70,9 +68,9 @@ class Bank * * @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; } $text = self::LOG[$operationType]; @@ -98,7 +96,7 @@ class Bank */ 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) { throw new GameException(self::ERROR_WRONG_AMOUNT); } @@ -134,8 +132,8 @@ class Bank if ($amount <= 0) { throw new GameException(self::ERROR_WRONG_AMOUNT); } - $wallet = self::$db->fetch('SELECT money FROM users WHERE id = ?', $this->user_id); - if ($wallet->money < $amount) { + $walletMoney = Db::getInstance()->fetchColumn('SELECT money FROM users WHERE id = ?', $this->user_id); + if ($walletMoney < $amount) { 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 { 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) { 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 { - $u = new User($user_id); - $u->setMoney($amount); - $u->saveMoney(); + User::getInstance($user_id)->setMoney($amount); + User::getInstance($user_id)->saveMoney(); } public function getMoney(): int diff --git a/classes/Battles/Chat.php b/classes/Battles/Chat.php index 45b2713..aabd8a6 100644 --- a/classes/Battles/Chat.php +++ b/classes/Battles/Chat.php @@ -2,16 +2,16 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; use DateTime; use Exception; class Chat { private DateTime $d; - private DBPDO $db; + private Db $db; - public function __construct(DBPDO $db) + public function __construct(Db $db) { $this->db = $db; } @@ -34,7 +34,7 @@ class Chat or r.id is null or s.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; foreach ($chatrows as $row) { try { @@ -45,7 +45,7 @@ class Chat $m = htmlspecialchars($row->msg); if ($row->type === 'sys' && empty($row->rid)) { $wrappedMessage .= sprintf('%s %s
', $this->d->format('H:i'), $m); - } elseif ($row->rid === User::$current->getId()) { + } elseif ($row->rid === User::getInstance()->getId()) { if ($row->type === 'sys') { $wrappedMessage .= sprintf('%s [Система] → %s
', $this->d->format('H:i'), $m); } elseif ($row->type == 'sms') { @@ -64,12 +64,12 @@ class Chat 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) { - 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']); } } \ No newline at end of file diff --git a/classes/Battles/Check.php b/classes/Battles/Check.php index 5424706..d7d812b 100644 --- a/classes/Battles/Check.php +++ b/classes/Battles/Check.php @@ -3,19 +3,19 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Check { private User $user; - private DBPDO $db; + private Db $db; /** * Check constructor. * * @param User $user */ - public function __construct(User $user, DBPDO $db) + public function __construct(User $user, Db $db) { $this->user = $user; $this->db = $db; diff --git a/classes/Battles/Clan.php b/classes/Battles/Clan.php index f3484f3..9c89bad 100644 --- a/classes/Battles/Clan.php +++ b/classes/Battles/Clan.php @@ -2,104 +2,105 @@ # Date: 23.08.2021 (23:05) namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Clan { - private DBPDO $db; - private User $user; + private static ?self $_instance = null; private $clan; - public static Clan $current; - public function __construct() + private function __construct() { - $this->db = DBPDO::$db; - $this->user = User::$current; - $this->clan = $this->db->ofetch('select * from clans where owner_id = ?', $this->user->getId()); + $this->clan = Db::getInstance()->ofetch('select * from clans where owner_id = ?', User::getInstance()->getId()); + } + + public static function getInstance(): self + { + if (is_null(self::$_instance)) { + self::$_instance = new self(); + } + return self::$_instance; } public function addMember(string $login): string { - $target = new User($login); $error = null; - if (!$this->getProverka($target->getId())) { + if (!$this->getProverka(User::getInstance($login)->getId())) { $error .= '
Нет проверки!'; } - if ($target->getClan()) { + if (User::getInstance($login)->getClan()) { $error .= '
Персонаж уже состоит в клане!'; } - if ($target->getLevel() < 1) { + if (User::getInstance($login)->getLevel() < 1) { $error .= '
Персонаж 0 уровня не может быть принят!'; } - if ($this->user->getMoney() < GameConfigs::CLAN['add_member_cost']) { + if (User::getInstance()->getMoney() < GameConfigs::CLAN['add_member_cost']) { $error .= '
Недостаточно денег!'; } if ($error) { return $error; } - $this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['add_member_cost']); - $this->user->saveMoney(); - $target->setClan($this->user->getClan()); + User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['add_member_cost']); + User::getInstance()->saveMoney(); + User::getInstance($login)->setClan(User::getInstance()->getClan()); return "Персонаж «{$login}» успешно принят в клан."; } public function removeMember(string $login): string { - $target = new User($login); $error = null; - if ($this->user->getMoney() < GameConfigs::CLAN['remove_member_cost']) { + if (User::getInstance()->getMoney() < GameConfigs::CLAN['remove_member_cost']) { $error .= '
Недостаточно денег!'; } - if ($target->getId() === $this->user->getId()) { + if (User::getInstance($login)->getId() === User::getInstance()->getId()) { $error .= '
Себя выгонять нельзя!'; } - if ($target->getClan() !== $this->user->getClan()) { + if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) { $error .= '
Персонаж не состоит в этом клане!'; } if ($error) { return $error; } - $this->user->setMoney($this->user->getMoney() - GameConfigs::CLAN['remove_member_cost']); - $this->user->saveMoney(); - $target->setClan(null); + User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['remove_member_cost']); + User::getInstance()->saveMoney(); + User::getInstance($login)->setClan(null); return "Персонаж «{$login}» покинул клан."; } public function changeOwner(string $login): string { - $target = new User($login); $error = null; - if ($target->getId() === $this->user->getId()) { + if (User::getInstance($login)->getId() === User::getInstance()->getId()) { $error .= '
Самоудовлетворяетесь? ;)'; } - if ($target->getClan() !== $this->user->getClan()) { + if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) { $error .= '
Персонаж не состоит в этом клане!'; } if ($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 . '».'; } 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()); - if ($check->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 ($checkId !== User::getInstance()->getId()) { 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 'Описание клана изменено!'; } 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) { - 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 diff --git a/classes/Battles/Database/DBPDO.php b/classes/Battles/Database/DBPDO.php deleted file mode 100644 index 0038989..0000000 --- a/classes/Battles/Database/DBPDO.php +++ /dev/null @@ -1,154 +0,0 @@ -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(); - } -} \ No newline at end of file diff --git a/classes/Battles/Database/Db.php b/classes/Battles/Database/Db.php new file mode 100644 index 0000000..a6c6a4d --- /dev/null +++ b/classes/Battles/Database/Db.php @@ -0,0 +1,134 @@ +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(); + } +} \ No newline at end of file diff --git a/classes/Battles/DressedItems.php b/classes/Battles/DressedItems.php index 34dd8f3..c1ce5b8 100644 --- a/classes/Battles/DressedItems.php +++ b/classes/Battles/DressedItems.php @@ -7,7 +7,7 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; use stdClass; class DressedItems @@ -22,13 +22,13 @@ class DressedItems */ public function __construct(int $user_id) { - self::$db = DBPDO::INIT(); + self::$db = Db::getInstance(); $this->USERID = $user_id; } 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 diff --git a/classes/Battles/GameLogs.php b/classes/Battles/GameLogs.php index ad712d0..5d10425 100644 --- a/classes/Battles/GameLogs.php +++ b/classes/Battles/GameLogs.php @@ -81,7 +81,7 @@ class GameLogs 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->bindParam(1, $battle_id, SQLITE3_INTEGER); $row->bindParam(2, $text, SQLITE3_TEXT); diff --git a/classes/Battles/InventoryItem.php b/classes/Battles/InventoryItem.php index f7f6df0..873209b 100644 --- a/classes/Battles/InventoryItem.php +++ b/classes/Battles/InventoryItem.php @@ -1,13 +1,12 @@ owner_id = $row->owner_id; $this->present = $row->present; - $this->db = DBPDO::INIT(); } public function printInfo() @@ -37,13 +35,13 @@ class InventoryItem extends Item { if (in_array($this->item_type, range(1, 12))) { echo <<item_id} title='Надеть'> - +item_id title='Надеть'> + HTML; } else { echo << + IMG; } } @@ -79,8 +77,8 @@ IMG; // считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами // Count добавленный в первый запрос возвращает одну строку в любом случае. // 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]); - $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]); + $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 = 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) { foreach ($weared as $item) { @@ -95,11 +93,11 @@ IMG; //работаем с нормальными слотами if ($wearedCount->c == 1) { //если слот занят, снимаем старый предмет и одеваем новый предмет - $this->db->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 = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $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) { //если слот пуст, одеваем новый предмет - $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 { /* проверка на переполнение слотов */ $error = self::TOO_MANY_ITEMS_IN_SLOTS; @@ -113,11 +111,11 @@ IMG; // Сортируем массив свободных слотов по возрастанию. 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) { // Cнимаем предмет из последнего слота 11 и одеваем новый предмет - $this->db->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 = 0 WHERE dressed_slot = 11'); + Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id); } else { /* проверка на переполнение слотов */ $error = self::TOO_MANY_ITEMS_IN_SLOTS; @@ -132,7 +130,7 @@ IMG; 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() и другую выдачу одной строкой. @@ -141,7 +139,7 @@ IMG; 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 = ?'; - $weight = DBPDO::$db->ofetch($query, User::$current->getId()); + $weight = Db::getInstance()->ofetch($query, User::getInstance()->getId()); $css = $weight->all > $weight->max ? ' style="color:maroon;"' : ''; return "$weight->all / $weight->max"; } diff --git a/classes/Battles/Item.php b/classes/Battles/Item.php index 255835e..d6472c3 100644 --- a/classes/Battles/Item.php +++ b/classes/Battles/Item.php @@ -1,7 +1,7 @@ ofetch('select * from items where id = ?', $item_id)); + return new Item(Db::getInstance()->ofetch('select * from items where id = ?', $item_id)); } } \ No newline at end of file diff --git a/classes/Battles/Magic/CureInjury.php b/classes/Battles/Magic/CureInjury.php index a1677b7..9ef433f 100644 --- a/classes/Battles/Magic/CureInjury.php +++ b/classes/Battles/Magic/CureInjury.php @@ -3,7 +3,7 @@ // Магия лечения травм namespace Battles\Magic; -use Battles\UserEffects, Battles\Database\DBPDO, Battles\User; +use Battles\UserEffects, Battles\Database\Db, Battles\User; class CureInjury extends Magic { @@ -18,7 +18,7 @@ class CureInjury extends Magic */ public function __construct(int $target, int $injuryType) { - $db = DBPDO::INIT(); + $db = Db::getInstance(); $this->target = $target; if (!$this->isUsable()) { return $this->status; @@ -46,13 +46,13 @@ class CureInjury extends Magic */ private function isUsable(): bool { - $caster = new User($_SESSION['uid']); - if ($this->target == $_SESSION['uid']) { - $this->target = $caster; - } else { - $this->target = new User($this->target); - } + $this->target = $this->target == $_SESSION['uid'] ? User::getInstance() : User::getInstance($this->target); $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); } } \ No newline at end of file diff --git a/classes/Battles/Magic/Healing.php b/classes/Battles/Magic/Healing.php index 91e534e..f19de7c 100644 --- a/classes/Battles/Magic/Healing.php +++ b/classes/Battles/Magic/Healing.php @@ -2,7 +2,7 @@ // Магия восстановления здоровья use Battles\Magic\Magic; use Battles\User; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Healing extends Magic { @@ -30,7 +30,7 @@ class Healing extends Magic if ($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; return "Вы восстановили ${healHealthAmount} здоровья персонажу ${targetName}."; } @@ -41,12 +41,7 @@ class Healing extends Magic */ private function isUsable(): bool { - $caster = new User($_SESSION['uid']); - if ($this->target == $_SESSION['uid']) { - $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); + $this->target = $this->target == $_SESSION['uid'] ? User::getInstance() : User::getInstance($this->target); + return $this->isVisible(User::getInstance(), $this->target) && $this->isNotDead(User::getInstance()) && $this->enoughMana(User::getInstance()) && $this->isSuccess(User::getInstance()); } } diff --git a/classes/Battles/Magic/Sharpen.php b/classes/Battles/Magic/Sharpen.php index 461b853..dd7b71b 100644 --- a/classes/Battles/Magic/Sharpen.php +++ b/classes/Battles/Magic/Sharpen.php @@ -3,7 +3,7 @@ namespace Battles\Magic; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\DressedItems; use Battles\Item; use Battles\User; @@ -27,20 +27,19 @@ class Sharpen extends Magic } $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 'Этот предмет точить нельзя!'; } - $newMinPhysicalDamage = $item['add_min_physical_damage'] + $sharpenStrength; - $newMaxPhysicalDamage = $item['add_max_physical_damage'] + $sharpenStrength; - $newItemName = $item['name'] . " [+$sharpenStrength]"; + $newMinPhysicalDamage = $item->add_min_physical_damage + $sharpenStrength; + $newMaxPhysicalDamage = $item->add_max_physical_damage + $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!"; } private function isUsable(): bool { - $caster = new User($_SESSION['uid']); - return $this->isNotInBattle($caster) && $this->isSuccess($caster, $this->magicDifficulty); + return $this->isNotInBattle(User::getInstance()) && $this->isSuccess(User::getInstance(), $this->magicDifficulty); } } \ No newline at end of file diff --git a/classes/Battles/Models/EffectsModel.php b/classes/Battles/Models/EffectsModel.php index d08b346..c3281b4 100644 --- a/classes/Battles/Models/EffectsModel.php +++ b/classes/Battles/Models/EffectsModel.php @@ -7,7 +7,7 @@ namespace Battles\Models; -use Battles\Database\DBPDO; +use Battles\Database\Db; class EffectsModel { @@ -16,7 +16,7 @@ class EffectsModel 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); } /** diff --git a/classes/Battles/Models/PresentsModel.php b/classes/Battles/Models/PresentsModel.php index d7045b9..38836b1 100644 --- a/classes/Battles/Models/PresentsModel.php +++ b/classes/Battles/Models/PresentsModel.php @@ -6,7 +6,7 @@ */ namespace Battles\Models; -use Battles\Database\DBPDO; +use Battles\Database\Db; class PresentsModel { @@ -15,7 +15,7 @@ class PresentsModel public function __construct(int $user_id) { 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); } } diff --git a/classes/Battles/Moderation.php b/classes/Battles/Moderation.php index 4358111..a8cf52e 100644 --- a/classes/Battles/Moderation.php +++ b/classes/Battles/Moderation.php @@ -3,7 +3,7 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Moderation { @@ -54,13 +54,13 @@ class Moderation public static function blockUser(int $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) { 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) @@ -70,12 +70,12 @@ class Moderation 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) { - 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) diff --git a/classes/Battles/Nick.php b/classes/Battles/Nick.php index 89bcf7f..52a2e2c 100644 --- a/classes/Battles/Nick.php +++ b/classes/Battles/Nick.php @@ -1,40 +1,41 @@ невидимка'; -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 */ - private function getAlignToNickname():?string + private function getAlignImage(): ?string { - if ($this->align) { - return sprintf('', $this->align); - } else { - return null; - } + return $this->align ? "Склонность" : null; } /** * Отображение иконки клана. * @return string */ - private function getClanToNickname():?string + private function getClanImage(): ?string { - if ($this->clan) { - return sprintf('', $this->clan); - } else { - return null; - } + return $this->clan ? "Клан" : null; + } + + private function getInfolinkImage(): string + { + return "Ссылка на профиль"; } /** @@ -43,7 +44,7 @@ class Nick extends User * * @return Nick */ - public static function id($playerId): Nick + public static function id($playerId): self { return new self($playerId); } @@ -55,50 +56,27 @@ class Nick extends User * * @return string */ - public function full($showInvisibility = 0):string + public function full(int $showInvisibility = 0): string { - if (!$showInvisibility && $this->getInvisibilityStatus()) { - return INVIS; - } - return $this->getAlignToNickname().$this->getClanToNickname().sprintf('%s [%s] ', $this->login, $this->level, $this->login); + return !$showInvisibility && $this->isInvisible() ? INVIS : $this->getAlignImage() . $this->getClanImage() . " $this->login [$this->level] " . $this->getInfolinkImage(); } /** - * Возвращает строку с логином или невидимым статусом. - * @param int $showInvisibility отображать логин даже если персонаж невидимка. + * Возвращает строку с логином. + * Избавиться от этого! Оставлено для совместимости. * @return string */ - public function short($showInvisibility = 0):string + public function short(): string { - if (!$showInvisibility && $this->getInvisibilityStatus()) { - return INVIS; - } else { - return htmlspecialchars($this->login); - } + return $this->login; } /** * Возвращает строку со склонностью, кланом, логином, уровнем, ссылкой на профиль, здоровьем. * @return string */ - public function battle():string + public function battle(): string { - return $this->getAlign().$this->getClan().sprintf('%s [%s] HP _hp_/_maxhp_', $this->login, $this->level, $this->login); - } - - /** - * Возвращает строку с логином и здоровьем, выделяя строку определённым стилем. - * @param $textstyle - Название стиля отображения логина персонажа (main.css) для цветового разделения команд. - * - * @return string - */ - public function battleShort($textstyle):string - { - if ($this->getInvisibilityStatus()) { - return INVIS; - } - else { - return sprintf('%s [_hp_/_maxhp_]', $textstyle, $this->login); - } + return $this->full() . "HP [$this->health/$this->maxHealth]"; } } \ No newline at end of file diff --git a/classes/Battles/Register.php b/classes/Battles/Register.php new file mode 100644 index 0000000..4dd5e17 --- /dev/null +++ b/classes/Battles/Register.php @@ -0,0 +1,21 @@ +execute('select count(*) from users where login = ? or email = ?', [$login, $email])->fetchColumn()) { + return 0; + } + 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']); + $userId = Db::getInstance()->lastInsertId(); + Db::getInstance()->execute('insert into online (user_id, login_time, room, real_time) values (?,?,1,?)', [$userId, time(), time()]); + Db::getInstance()->execute('insert into bank (user_id) values ?', $userId); + return $userId; + } +} \ No newline at end of file diff --git a/classes/Battles/RememberPassword.php b/classes/Battles/RememberPassword.php new file mode 100644 index 0000000..caa92ef --- /dev/null +++ b/classes/Battles/RememberPassword.php @@ -0,0 +1,68 @@ +"; + $subject = "=?UTF-8?B?" . base64_encode('Восстановление забытого пароля') . "?="; + $headers = [ + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-type' => 'text/html; charset=UTF-8', + ]; + + if (extension_loaded('tidy')) { + $cleaner = new tidy(); + $message = $cleaner->repairString($message, ['show-errors' => 0, 'show-warnings' => false], 'utf8'); + } + return mail($to, $subject, $message, $headers); + } + + public function sendRecoveryMail(string $to): string + { + $check = Db::getInstance()->ofetch('SELECT email FROM users WHERE login = ?', $to); + if (!empty(Db::getInstance()->fetchColumn('select email from users where login = ?', $to))) { + return self::ERROR_WRONG_LOGIN; + } + if (!empty(Db::getInstance()->ofetch('SELECT 1 FROM users_recovery WHERE login = ?', $to))) { + return self::ERROR_TOO_MANY_TRIES; + } + + $hash = uniqid(); + $tomorrow = date('d-M-Y', strtotime('+1 days')); + Db::getInstance()->execute('INSERT INTO users_recovery (login, hash, ip, date) VALUES (?,?,?,?)', [$to, $hash, $tomorrow, $_SERVER['REMOTE_ADDR']]); + $message = sprintf('Здравствуйте!

Кто-то запросил восстановление пароля к вашему персонажу %s

+ Для смены пароля пройдите по данной ссылке.

+ Ссылка будет действовать до %s',$to, GAMEDOMAIN, $hash, $tomorrow); + return self::mailSend($check->email, $message) ? self::OK_MAIL_SENT : self::ERROR_MAIL_NOT_SENT; + } + public function isAllowed($hash) + { + return Db::getInstance()->execute('SELECT count(*) FROM users_recovery WHERE hash = ? AND date < ?', [$hash, date('d-M-Y')])->fetchColumn() ? true : self::ERROR_OLD_HASH; + } + + public function setNewPassword(string $newPassword, string $hash):string + { + $login = Db::getInstance()->execute('select login from users_recovery where hash = ?', $hash)->fetchColumn(); + if (empty($login)) { + return self::ERROR_WRONG_HASH; + } + $newPassword = password_hash($newPassword, PASSWORD_DEFAULT); + Db::getInstance()->execute('UPDATE users SET pass = ? WHERE login = ?', [$newPassword, $login]); + Db::getInstance()->execute('DELETE FROM users_recovery WHERE hash = ?', $hash); + return self::OK_PASSWORD_CHANGED; + } +} \ No newline at end of file diff --git a/classes/Battles/Shop.php b/classes/Battles/Shop.php index ebe8b74..e2d1d3b 100644 --- a/classes/Battles/Shop.php +++ b/classes/Battles/Shop.php @@ -2,29 +2,34 @@ # Date: 29.08.2021 (21:34) namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Shop { public const GENERAL_SHOP = 1; public const BARTER_SHOP = 2; public const CATEGORY_SALE_ITEMS = -1; - public static Shop $current; public int $categoryType = 0; private int $shopId; - public function __construct($shop_id) { + private function __construct($shop_id) + { $this->shopId = $shop_id; } + public static function id($shopid): self + { + return new self($shopid); + } + private function showGoods(): string { 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]); - $stmt2 = DBPDO::$db->ofetchAll('select * from inventory where on_sale != 0 and present is null and item_type = ?', $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 = Db::getInstance()->ofetchAll('select * from inventory where on_sale != 0 and present is null and item_type = ?', $this->categoryType); } 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); - $stmt2 = DBPDO::$db->ofetchAll('select * from inventory where on_sale != 0 and present is null'); + $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 = Db::getInstance()->ofetchAll('select * from inventory where on_sale != 0 and present is null'); } $iteminfo = []; @@ -39,7 +44,7 @@ class Shop 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 = []; $operationType = 'sellshop'; diff --git a/classes/Battles/ShopItem.php b/classes/Battles/ShopItem.php index 84ceefb..1c4ecc6 100644 --- a/classes/Battles/ShopItem.php +++ b/classes/Battles/ShopItem.php @@ -2,7 +2,7 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\Models\PresentsModel; use Exceptions\GameException; @@ -137,8 +137,8 @@ SQL; public static function buyItem($id, User $buyer) { - $check = DBPDO::$db->ofetch("select * from trade_offers where offer_id = ?", $id); - $item = new Item(DBPDO::$db->fetch('select * from items where id = ?', $check->shop_item_id)); + $check = Db::getInstance()->ofetch("select * from trade_offers where offer_id = ?", $id); + $item = new Item(Db::getInstance()->fetch('select * from items where id = ?', $check->shop_item_id)); $price = $item->calculateItemCost(); if ( @@ -149,7 +149,7 @@ SQL; 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 . "."; GameLogs::addUserLog($buyer->getId(), $deloText); self::$status = "Предмет " . $item->name . " куплен за " . $price . "."; @@ -162,7 +162,7 @@ SQL; } $allowItemRemove = true; 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) { $allowItemRemove = false; } @@ -174,20 +174,20 @@ SQL; foreach (json_decode($json_list) as $item) { $query = 'delete from inventory where name = ? and owner_id = ? limit ' . (int)$item->quantity; // У-у-у, сука! 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; } private static function checkAndPayTheBills(int $price, User $user): bool { - if ($user->getMoney() > $price) { - $user->setMoney($user->getMoney() - $price); - $user->saveMoney(); + if (User::getInstance()->getMoney() > $price) { + User::getInstance()->setMoney(User::getInstance()->getMoney() - $price); + User::getInstance()->saveMoney(); return true; } try { - $bank = new Bank($user->getId()); + $bank = new Bank(User::getInstance()->getId()); $bank->withdrawMoney($price); return true; } catch (GameException $e) { @@ -205,24 +205,23 @@ SQL; if ($current_quantity === -1) { 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; } public static function sellItem($id, User $seller, $bankTrade = 0) { - $db = new DBPDO(); - $item = $db->ofetch('select * from inventory where item_id = ?', $id); + $item = Db::getInstance()->ofetch('select * from inventory where item_id = ?', $id); $sellingItemName = $item->name; // Продажа за цену от нуля до половины стоимости. $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) { $bank = new Bank($seller->getId()); $bank->setMoney($bank->getMoney() + $sellingPrice); Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'sellShop'); } 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 кр."; GameLogs::addUserLog($seller->getId(), $deloText); @@ -280,12 +279,12 @@ FORM; */ 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) { return []; } - DBPDO::$db->execute(self::BUY_QUERY, [$to, $item_id]); - $return = DBPDO::$db->ofetch('select image, name from inventory where item_id = ?', DBPDO::$db->lastInsertId()); + Db::getInstance()->execute(self::BUY_QUERY, [$to, $item_id]); + $return = Db::getInstance()->ofetch('select image, name from inventory where item_id = ?', Db::getInstance()->lastInsertId()); return [ 'img' => $return->image, 'name' => $return->name, diff --git a/classes/Battles/Travel.php b/classes/Battles/Travel.php index a741633..ae88e2a 100644 --- a/classes/Battles/Travel.php +++ b/classes/Battles/Travel.php @@ -2,7 +2,7 @@ # Date: 26.10.2020 (16:08) namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class Travel { @@ -55,24 +55,60 @@ class Travel 2702 => 'city.php' ]; + private static array $fbattleCheckFiles = [ + 'c_haos_in.php', + 'c_haos.php', + 'c_park.php', + 'city.php', + 'clan_castle.php', + 'enter_cave.php', + 'library.php', + 'atk.php', + 'podzem_dialog.php', + 'post.php', + 'shop.php', + 'tournament.php', + 'vxod.php', + 'bank.php', + 'canalizaciya,php', + 'forest.php', + 'main.php', + 'repair.php', + 'towerstamp.php', + 'hell.php', + 'ul_clans.php', + 'labirint.php', + 'akadem.php', + 'towerin.php', + 'user_anketa.php', + 'zayavka.php', + ]; + private static array $towerinCheckFiles = [ + 'main.php', + 'city.php', + 'tower.php' + ]; + private static array $roomsCheck = [22, 23, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401, 402, 600, 601, 602, 621, 650, 1051, 1052]; + /** * Перемещение по комнатам. - * @param int $roomId ID куда идём. + * + * @param int $roomId ID куда идём. * @param int $roomIdCurrent ID откуда идём. */ public static function toRoom(int $roomId, int $roomIdCurrent): void { - $db = DBPDO::INIT(); - $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']]); - $eff = $db->fetch('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']); + UserStats::getInstance()-> + $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::getInstance()->fetchColumn('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']); $errors = []; - if ($itemsWeight['weight_overflow'] > 0) { + if ($itemsWeightOverflow > 0) { $errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...'; } - if ($eff['type'] == 10) { + if ($eff == 10) { $errors[1] = 'Вы парализованы и не можете передвигаться...'; } - if ($eff['type'] == 13 || $eff['type'] == 14) { + if ($eff == 13 || $eff == 14) { $errors[2] = 'У вас тяжелая травма, вы не можете передвигаться...'; } if ($errors) { @@ -80,7 +116,7 @@ class Travel echo sprintf('%s', $error); } } 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]); exit; } @@ -88,7 +124,9 @@ class Travel /** * Проверка можно ли перейти из комнаты в комнату. + * * @param int $roomId ID комнаты + * * @return array|int[] */ private static function allowedRoomMoves(int $roomId): array @@ -141,4 +179,32 @@ class Travel } return $room[$roomId]; } + + /** Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам. + * @param int $inRoom + * @param int $inBattle + * @param int $inTower + * + * @return void + */ + public static function roomRedirects(int $inRoom, int $inBattle, int $inTower) + { + if ($inBattle && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], self::$fbattleCheckFiles)) { + header('location: fbattle.php'); + exit; + } + if ($inTower && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], self::$towerinCheckFiles)) { + header('location: towerin.php'); + exit; + } + // Если я в одной из этих комнат, + // [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь + // [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых + if (in_array($inRoom, self::$roomsCheck) + && pathinfo(debug_backtrace()[0]['file'])['basename'] != self::$roomFileName[$inRoom] + && in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], self::$roomFileName), self::$roomsCheck)) { + header('location: main.php'); + exit; + } + } } \ No newline at end of file diff --git a/classes/Battles/User.php b/classes/Battles/User.php index 041d98d..5440af0 100644 --- a/classes/Battles/User.php +++ b/classes/Battles/User.php @@ -2,10 +2,12 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; class User { + private static ?self $_instance = null; + protected int $id = 0; protected string $login = ''; protected ?string $pass = null; @@ -29,26 +31,20 @@ class User protected int $battle = 0; protected int $in_tower = 0; // Скорее башню похороним чем запустим... protected int $zayavka = 0; - protected static DBPDO $db; public const INFO_CHAR_LIMIT = 1500; - /** - * @var User Переменная инициализируемая при запуске, хранящая объект текущего пользователя. - */ - public static User $current; - /** - * @param int|string $user - */ - public function __construct($user) + protected function __construct($user = null) { - self::$db = DBPDO::INIT(); + if (is_null($user)) { + $user = $_SESSION['uid']; + } $query = 'select * from users where login = ?'; if (is_numeric($user)) { $query = 'select * from users where id = ?'; $user = (int)$user; } - $user_query = self::$db->fetch($query, $user); + $user_query = Db::getInstance()->fetch($query, $user); foreach ($this as $key => $value) { if (isset($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 $type @@ -66,13 +70,13 @@ class User public static function addUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null) { $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 { - if (self::$db->fetch('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]); + if (Db::getInstance()->fetchColumn('SELECT 1 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; } @@ -157,12 +161,12 @@ class User public function setMoney(int $money) { - $this->money = $money < 0 ? 0 : $money; + $this->money = max($money, 0); } 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 @@ -229,7 +233,7 @@ class User 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 @@ -285,6 +289,6 @@ class User $this->admin, $this->id //where ]; - DBPDO::$db->execute($query, $vals); + Db::getInstance()->execute($query, $vals); } } \ No newline at end of file diff --git a/classes/Battles/UserInfo.php b/classes/Battles/UserInfo.php index 925b031..87f3b7b 100644 --- a/classes/Battles/UserInfo.php +++ b/classes/Battles/UserInfo.php @@ -2,7 +2,7 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\Models\EffectsModel; class UserInfo extends UserStats @@ -10,8 +10,6 @@ class UserInfo extends UserStats use Rooms; private int $bankMoney; - //Тот, кто смотрит на информацию. - private User $watcher; public function __construct($user) { @@ -172,7 +170,7 @@ HTML; while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) { $log .= sprintf('%s
', 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 << E-Mail: $this->email
@@ -216,7 +214,7 @@ INFO; echo $this->realname ? "Имя: $this->realname" : ""; echo $this->info ? "
" . nl2br($this->info) : ""; echo '
'; - if ($this->watcher->getAdmin() || $this->watcher->getAlign() == 1) { + if (User::getInstance()->getAdmin() || User::getInstance()->getAlign() == 1) { echo $this->showPrivateData(); } } @@ -225,9 +223,9 @@ INFO; { $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 "Персонаж $this->login заблокирован!"; - } elseif ($effects->getHideUserInfoStatus() && (!$this->watcher->getAdmin() || !$this->watcher->getAlign() == 1)) { + } elseif ($effects->getHideUserInfoStatus() && (!User::getInstance()->getAdmin() || !User::getInstance()->getAlign() == 1)) { if ($effects->getHideUserInfoStatus() == -1) { $date = 'навсегда'; } else { @@ -256,7 +254,7 @@ INFO; 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; $r = ''; foreach ($effs as $effect) { @@ -271,14 +269,4 @@ INFO; } return $r; } - - /** - * @param mixed $watcher_id - */ - public function setWatcher(int $watcher_id): void - { - $this->watcher = new User($watcher_id); - } - - } \ No newline at end of file diff --git a/classes/Battles/UserStats.php b/classes/Battles/UserStats.php index d6a66e3..676bfb0 100644 --- a/classes/Battles/UserStats.php +++ b/classes/Battles/UserStats.php @@ -3,7 +3,7 @@ namespace Battles; -use Battles\Database\DBPDO; +use Battles\Database\Db; use Exceptions\GameException; class UserStats extends User @@ -86,7 +86,7 @@ class UserStats extends User throw new GameException(self::ERROR_STAT_IS_MAXIMUM); } else { $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 { - $stats = self::$db->ofetch(" + $stats = Db::getInstance()->ofetch(" select strength, dexterity, @@ -170,7 +170,7 @@ class UserStats extends User intelligence, wisdom from users where id = $this->id"); - $itemBonuses = self::$db->ofetch(" + $itemBonuses = Db::getInstance()->ofetch(" select sum(add_strength) as item_strength, 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_max_physical_damage) as item_max_physical_damage from inventory where dressed_slot != 0 and owner_id = $this->id"); - $effectBonuses = self::$db->ofetch(" + $effectBonuses = Db::getInstance()->ofetch(" select sum(mod_strength) as effect_strength, sum(mod_dexterity) as effect_dexterity, @@ -238,6 +238,6 @@ class UserStats extends User $this->level, $this->id //where ]; - DBPDO::$db->execute($query, $vals); + Db::getInstance()->execute($query, $vals); } } \ No newline at end of file diff --git a/classes/Database/Mysql.php b/classes/Database/Mysql.php index 2731340..df0ef11 100644 --- a/classes/Database/Mysql.php +++ b/classes/Database/Mysql.php @@ -12,7 +12,7 @@ * маркеры - т.н. "заполнители", а сами данные передаются "позже", в качестве последующих аргументов основного метода, * выполняющего 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 данного класса, экранируются специальными функциями * экранирования, в зависимости от типа заполнителей. Т.е. вам теперь нет необходимости заключать переменные в функции @@ -45,8 +45,8 @@ * Например, попытка передать в качестве аргумента значение 55.5 или '55.5' для заполнителя целочисленного типа ?i * приведет к выбросу исключения: * - * $db->setTypeMode(Mysql::MODE_STRICT); // устанавливаем строгий режим работы - * $db->query('SELECT ?i', 55.5); // Попытка указать для заполнителя типа int значение типа double в шаблоне запроса SELECT ?i + * $getInstance->setTypeMode(Mysql::MODE_STRICT); // устанавливаем строгий режим работы + * $getInstance->query('SELECT ?i', 55.5); // Попытка указать для заполнителя типа int значение типа double в шаблоне запроса SELECT ?i * * Это утверждение не относится к числам (целым и с плавающей точкой), заключенным в строки. * С точки зрения библиотеки, строка '123' и значение 123 являются типом int. @@ -140,7 +140,7 @@ * заполнителей скалярного типа, таких как ?i, ?d и ?s. Это сделано по идеологическим соображениям, * автоподстановка кавычек может стать ограничением для возможностей SQL. * Например, выражение - * $db->query('SELECT "Total: ?s"', '200'); + * $getInstance->query('SELECT "Total: ?s"', '200'); * вернёт строку * 'Total: 200' * Если бы кавычки, ограничивающие строковой литерал, ставились бы автоматически, @@ -151,20 +151,23 @@ * Тем не менее, для перечислений ?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` = "Москва" * - * $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") * * Также исключения составляют заполнители типа ?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` */ namespace Krugozor\Database\Mysql; +use mysqli; +use mysqli_result; + 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 - число или числовая строка, * а в качестве аргумента передаётся строка '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 - число или числовая строка, * а в качестве аргумента передаётся строка '2+мусор' не являющаяся ни числом, ни числовой строкой. @@ -397,7 +400,7 @@ class Mysql 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); } @@ -425,7 +428,7 @@ class Mysql * Применяется для случаев, когда 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) * @@ -548,7 +551,7 @@ class Mysql private function connect() { 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) { throw new Exception(__METHOD__ . ': ' . $this->mysqli->connect_error); diff --git a/classes/Tournament.php b/classes/Tournament.php index f4aeef2..0554000 100644 --- a/classes/Tournament.php +++ b/classes/Tournament.php @@ -2,6 +2,7 @@ use Battles\GameLogs; use Battles\Nick; +use Battles\User; class Tournament { @@ -160,8 +161,8 @@ class Tournament // кидаем в бой mysql_query("UPDATE `users` SET `battle` = {$id} WHERE `id` = " . $user1 . " OR `id` = " . $user2); // создаем лог - $rr = "" . Nick::id($user['id'])->full(1) . " и " . Nick::id($jert['id'])->full(1) . ""; - addch("Бой между " . Nick::id($user['id'])->short() . " и " . Nick::id($jert['id'])->short() . " начался. ", $user->getRoom()); + $rr = "" . Nick::id(User::getInstance()->getId())->full(1) . " и " . Nick::id($jert['id'])->full(1) . ""; + addch("Бой между " . Nick::id(User::getInstance()->getId())->short() . " и " . Nick::id($jert['id'])->short() . " начался. ", User::getInstance()->getRoom()); GameLogs::addBattleLog($id, "Часы показывали " . date("Y.m.d H.i") . ", когда " . $rr . " решили выяснить кто из них сильнее. (турнир)
"); return $id; } diff --git a/classes/quests_class.php b/classes/quests_class.php index a246ce4..82c3f28 100644 --- a/classes/quests_class.php +++ b/classes/quests_class.php @@ -1,5 +1,7 @@ error = 'Вы успешно сдали задание!'; $text = 'Внимание! За успешно выполненное задание Вы получили : ' . $c; - $this->msg($text, '{[]}' . $user['login'] . '{[]}', $user->getRoom()); + $this->msg($text, '{[]}' . $user['login'] . '{[]}', User::getInstance()->getRoom()); } else { $this->error = 'Не все условия задания были выполнены ...'; } diff --git a/config.php b/config.php index e818988..b8acd9b 100644 --- a/config.php +++ b/config.php @@ -6,7 +6,7 @@ * Project name: Battles-Game */ -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\User; 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 = [ 'rooms' => [620, 621, 1051, 1052], diff --git a/cronjobs/cron_tower.php b/cronjobs/cron_tower.php index 86d145d..a2dbbbf 100644 --- a/cronjobs/cron_tower.php +++ b/cronjobs/cron_tower.php @@ -187,11 +187,32 @@ 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"); } - if ($u['id'] != 233 && $u['id'] != 234 && $u['id'] != 235) { - settravma($u['id'], 100, 86400, 1); - } - get_out($u['id']); - mysql_query("UPDATE `users` SET `in_tower` = 0, `room` = '31' WHERE `id` = '" . $u['id'] . "' LIMIT 1"); + $pers = db::c()->query('SELECT * FROM users WHERE id = ?i', $u['id'])->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("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"); } } diff --git a/enter.php b/enter.php index 37d96d1..e2c0221 100644 --- a/enter.php +++ b/enter.php @@ -1,6 +1,6 @@ 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) { $error = ERROR_NO_SUCH_USER; @@ -43,14 +43,14 @@ if ($username && $password) { setcookie("uid", $user_query->id, 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) { - 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 { - 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(); diff --git a/enter_cave.php b/enter_cave.php index 68a2a49..d837788 100644 --- a/enter_cave.php +++ b/enter_cave.php @@ -1,6 +1,7 @@ getRoom(), CANAL_ENTERS)) { - $podzemroom = $user->getRoom() + 1; +if (in_array(User::getInstance()->getRoom(), CANAL_ENTERS)) { + $podzemroom = User::getInstance()->getRoom() + 1; $cavedata = [620 => ['x1' => 3, 'y1' => 2, 'dir1' => 2]]; $podzemdata = [621 => ['name1' => 'Проклятый Рудник', 'name2' => 'Проклятого Рудника']]; $warning = $_GET["warning"] ?? ''; @@ -89,7 +90,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { if (($user['align'] == '2.99') && $wait_sec > $new_t) { $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']) { @@ -199,7 +200,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { 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)) { $cr = $DATA['glav_id']; $z_login[$i] = $DATA['login']; @@ -275,7 +276,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { exit(); } $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')"); if ($SQL2) { echo ""; @@ -305,7 +306,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { } $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 ""; exit(); } @@ -353,7 +354,7 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { } if ($_GET['start']) { - if (in_array($user->getRoom() + 1, CAVE_ROOMS)) { + if (in_array(User::getInstance()->getRoom() + 1, CAVE_ROOMS)) { $nc = 1; $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"); $user['money'] += $nana['fee']; $esth['money'] -= $nana['fee']; - adddelo($user['id'], "Персонаж $user[login] получил $nana[fee] кр. за поход по локации \"" . $rooms[$user->getRoom() + 1] . "\" от персонажа $esth[login] ($user[money]).", 1); - adddelo($esth['id'], "Персонаж $esth[login] заплатил $nana[fee] кр. за поход по локации \"" . $rooms[$user->getRoom() + 1] . "\" персонажу $user[login] ($esth[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::getInstance()->getRoom() + 1] . "\" персонажу $user[login] ($esth[money]).", 1); } if ($esth['level'] > $level) { $level = $esth['level']; @@ -389,12 +390,12 @@ if (in_array($user->getRoom(), CANAL_ENTERS)) { $vrem = 30 * 60 + time(); $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("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("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::getInstance()->getRoom() + 1) . "', `online`.`room` = '" . (User::getInstance()->getRoom() + 1) . "' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '" . $esth['id'] . "'"); } 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)) { $map = unserialize($rec['map']); foreach ($map as $k => $v) { diff --git a/fight.php b/fight.php index c7f3a93..2c8318c 100644 --- a/fight.php +++ b/fight.php @@ -1,12 +1,12 @@ 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)) { - 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('Окно игры'); diff --git a/forest.php b/forest.php index 6bc9f0c..77e0661 100644 --- a/forest.php +++ b/forest.php @@ -3,9 +3,10 @@ use Battles\GameLogs; use Battles\Nick; use Battles\Template; +use Battles\User require_once "functions.php"; -if ($user->getRoom() == 51) { +if (User::getInstance()->getRoom() == 51) { header('location: city.php'); exit; } diff --git a/forum.php b/forum.php index 632350d..77b9fbe 100644 --- a/forum.php +++ b/forum.php @@ -1,7 +1,11 @@ query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', $user['id'], time())->fetch_assoc(); +$sleep = db::c()->query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', User::getInstance()->getId(), time())->fetch_assoc(); $ps = $_GET['page'] ?? 0; $isModerator = false; $isAdmin = false; @@ -72,7 +76,7 @@ function close_dangling_tags($html) return $html; } -if (isset($_POST['add']) && isset($user['id'])) { +if (isset($_POST['add']) && User::getInstance()->getId()) { $icon = htmlentities($_POST['icon'], ENT_NOQUOTES, 'utf8'); $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8'); @@ -86,12 +90,8 @@ if (isset($_POST['add']) && isset($user['id'])) { rtrim($_POST['text']); if (empty($_POST['text']) || empty($_POST['title'])) { $error = "Заголовок или текст не могут быть пустыми!"; - } elseif (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || ($user['align'] >= $minmax['min_align'] && $user['align'] <= $minmax['max_align']) || $isAdmin) { - if ($user['invis'] == 1) { - $userPost = 'Невидимка'; - } else { - $userPost = Nick::id($user['id'])->full(1); - } + } elseif (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || (User::getInstance()->getAlign() >= $minmax['min_align'] && User::getInstance()->getAlign() <= $minmax['max_align']) || $isAdmin) { + $userPost = Nick::id(User::getInstance()->getId())->full(); if ($isModerator == false) $text1 = strip_tags($text1, '
'); 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']); } -if (isset($_POST['add2']) && isset($user['id'])) { +if (isset($_POST['add2']) && User::getInstance()->getId()) { $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8'); $text1 = parse_bb_code(preg_replace("/\n/", "
", $_POST['text'])); @@ -120,12 +120,8 @@ if (isset($_POST['add2']) && isset($user['id'])) { $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 ($user['invis'] == 1) { - $userPost = 'Невидимка'; - } else { - $userPost = Nick::id($user['id'])->full(1); - } + 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) { + $userPost = Nick::id(User::getInstance()->getId())->full(); if ($isModerator == false) { $text1 = strip_tags($text1, '

'); @@ -165,11 +161,7 @@ if (isset($_GET['dt']) && $isModerator == true) { } if (isset($_GET['com']) && isset($_GET['cpr']) && $isModerator == true) { - if ($user['invis'] == 1) { - $addText = "
Невидимка: " . $_GET['cpr']; - } else { - $addText = Nick::id($user['id'])->full(1) . ": " . $_GET['cpr']; - } + $addText = Nick::id(User::getInstance()->getId())->full() . ": " . $_GET['cpr']; db::c()->query('UPDATE `forum` SET `text` = CONCAT(`text`,"?s") WHERE `id` = ?i', $addText, $_GET['com']); echo ""; exit(); @@ -183,7 +175,7 @@ if (isset($_GET['do']) && $isModerator == true) { } if ($_GET['do'] == "close") { - $closeComment = "Обсуждение закрыл " . ($isAdmin) ? "Администратор" : Nick::id($user['id'])->full(1); + $closeComment = "Обсуждение закрыл " . ($isAdmin) ? "Администратор" : Nick::id(User::getInstance()->getId())->full(1); db::c()->query('UPDATE `forum` SET `close` = 1, `closepal` = "?s" WHERE `id` = "?s"', $closeComment, $_GET['topic']); echo ""; exit(); @@ -201,7 +193,7 @@ if (isset($_GET['do']) && $isModerator == true) { exit(); } } -\Battles\Template::header('Форум'); +Template::header('Форум'); ?> @@ -209,17 +201,17 @@ if (isset($_GET['do']) && $isModerator == true) {
- full(1) . "
"; ?> + getId()) { echo "Игрок : " . Nick::id(User::getInstance()->getId())->full(1) . "
"; } ?>

Конференции

query('SELECT * FROM `forum` WHERE `parent` = 0 AND `type` = 1 ORDER BY `id` ASC'); 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; $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 '  📕'; } else { echo '  📖 '; @@ -234,7 +226,7 @@ if (isset($_GET['do']) && $isModerator == true) { 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']; $parentCat = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $top)->fetch_assoc(); $icons = $row['icon']; @@ -371,9 +363,9 @@ if (isset($_GET['do']) && $isModerator == true) { if ($closed == 1) { echo "
" . $closepal . "


"; } else { - if (!empty($user['block'])) { + if (User::getInstance()->getBlock()) { $error = "Вы заблокированы!"; - } elseif ($user['level'] < 2) { + } elseif (User::getInstance()->getLevel() < 2) { $error = "Персонажам до 2-го уровня запрещено писать на форуме!"; } elseif (isset($sleep['id'])) { $error = "Вы молчите!"; @@ -423,7 +415,7 @@ if (isset($_GET['do']) && $isModerator == true) { } } else { 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'] . '»'; $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; @@ -506,9 +498,9 @@ if (isset($_GET['do']) && $isModerator == true) { echo $pages_str . "

"; - if (!empty($user['block'])) { + if (User::getInstance()->getBlock()) { $error = "Вы заблокированы!"; - } elseif ($user['level'] < 2) { + } elseif (User::getInstance()->getLevel() < 2) { $error = "Персонажам до 2-го уровня запрещено писать на форуме!"; } elseif (isset($sleep['id'])) { $error = "Вы молчите!"; diff --git a/functions.php b/functions.php index 2ec6cd4..7057804 100644 --- a/functions.php +++ b/functions.php @@ -5,7 +5,7 @@ * Project name: Battles-Game */ -use Battles\Database\DBPDO; +use Battles\Database\Db; use Battles\DressedItems; use Battles\InventoryItem; use Battles\Travel; @@ -17,70 +17,71 @@ require_once 'config.php'; if (empty($_SESSION['uid'])) { header("Location: index.php"); exit; -} elseif (empty($user)) { - $user = new User($_SESSION['uid']); } -if (User::$current->getBlock()) { +if (User::getInstance()->getBlock()) { exit('user blocked!'); } -/* - * Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам. - */ -$fbattleCheckFiles = [ - 'c_haos_in.php', - 'c_haos.php', - 'c_park.php', - 'city.php', - 'clan_castle.php', - 'enter_cave.php', - 'library.php', - 'atk.php', - 'podzem_dialog.php', - 'post.php', - 'shop.php', - 'tournament.php', - 'vxod.php', - 'bank.php', - 'canalizaciya,php', - 'forest.php', - 'main.php', - 'repair.php', - 'towerstamp.php', - 'hell.php', - 'ul_clans.php', - 'labirint.php', - 'akadem.php', - 'towerin.php', - 'user_anketa.php', - 'zayavka.php', -]; -//Может просто отовсюду? О_о -if (User::$current->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) { - header('location: fbattle.php'); - exit; -} -$towerinCheckFiles = ['main.php', 'city.php', 'tower.php']; -if (User::$current->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) { - header('location: towerin.php'); - exit; -} -$roomsCheck = [22, 23, 25, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401, 402, 600, 601, 602, 621, 650, 1051, 1052]; -// Если я в одной из этих комнат, -// [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь -// [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых -if (in_array(User::$current->getRoom(), $roomsCheck) - && pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::$current->getRoom()] - && in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], Travel::$roomFileName), $roomsCheck)) { - header('location: main.php'); - exit; -} +//Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам. +Travel::roomRedirects(User::$current->getRoom(), User::$current->getBattle(), User::$current->getInTower()); + +///* +// * Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам. +// */ +//$fbattleCheckFiles = [ +// 'c_haos_in.php', +// 'c_haos.php', +// 'c_park.php', +// 'city.php', +// 'clan_castle.php', +// 'enter_cave.php', +// 'library.php', +// 'atk.php', +// 'podzem_dialog.php', +// 'post.php', +// 'shop.php', +// 'tournament.php', +// 'vxod.php', +// 'bank.php', +// 'canalizaciya,php', +// 'forest.php', +// 'main.php', +// 'repair.php', +// 'towerstamp.php', +// 'hell.php', +// 'ul_clans.php', +// 'labirint.php', +// 'akadem.php', +// 'towerin.php', +// 'user_anketa.php', +// 'zayavka.php', +//]; +////Может просто отовсюду? О_о +//if (User::$current->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) { +// header('location: fbattle.php'); +// exit; +//} +//$towerinCheckFiles = ['main.php', 'city.php', 'tower.php']; +//if (User::$current->getInTower() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $towerinCheckFiles)) { +// header('location: towerin.php'); +// exit; +//} +//$roomsCheck = [22, 23, 25, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401, 402, 600, 601, 602, 621, 650, 1051, 1052]; +//// Если я в одной из этих комнат, +//// [И] Имя файла который инклюдит файл с проверкой не совпадает с именем файла локации в которой я нахожусь +//// [И] Номер комнаты который я пытаюсь открыть есть в списке проверяемых +//if (in_array(User::$current->getRoom(), $roomsCheck) +// && pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::$current->getRoom()] +// && in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], Travel::$roomFileName), $roomsCheck)) { +// header('location: main.php'); +// exit; +//} 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 = ?'; - DBPDO::$db->execute($query, [$_GET['goto'], $_GET['goto'], User::$current->getId()]); - User::$current->setRoom(intval($_GET['goto'])); + Db::getInstance()->execute($query, [$_GET['goto'], $_GET['goto'], User::getInstance()->getId()]); + User::getInstance()->setRoom(intval($_GET['goto'])); } function createbot($bot, $login = "") @@ -109,34 +110,6 @@ $var_map = [ '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; function savecavedata($cavedata, $caveleader, $floor) @@ -185,19 +158,19 @@ HTML; function echoscroll($slot) { $all_magic = 0; - if (User::$current->getBattle()) { + if (User::getInstance()->getBattle()) { $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']); } else { $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(); - if ((User::$current->$slot > 0) && ($all_magic[User::$current->getId()] < 1 || empty($need_charge['needcharge']))) { - $row['id'] = User::$current->$slot; + if ((User::getInstance()->$slot > 0) && ($all_magic[User::getInstance()->getId()] < 1 || empty($need_charge['needcharge']))) { + $row['id'] = User::getInstance()->$slot; if ($dress['magic']) { $magic = db::c()->query('SELECT targeted FROM `magic` WHERE `id` = ?i', $dress['magic'])->fetch_assoc(); echo "
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; @@ -367,8 +340,9 @@ function ref_drop() // использовать магию function usemagic($id, $target) { - $row = db::c()->query('SELECT * FROM `inventory` WHERE `owner` = ?i AND id = ?i', User::$current->getId(), $id)->fetch_assoc_array(); - $bat = db::c()->query('SELECT * FROM `battle` WHERE `id` = ?i', User::$current->getBattle())->fetch_assoc_array(); + $user = Db::getInstance()->fetch('select * from users where id = ?', $_SESSION['uid']); + $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']); $charge = 0; $magic = db::c()->query('SELECT * FROM `magic` WHERE `id` = ?i', $row['magic'])->fetch_assoc_array(); @@ -382,7 +356,7 @@ function usemagic($id, $target) $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['lovk'] >= $row['nlovk'] && $user['inta'] >= $row['ninta'] && @@ -430,22 +404,22 @@ function usemagic($id, $target) } else { $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) { $charge = 0; } //ограничение по кол-ву за ход - if (User::$current->getBattle()) { - $bat = DBPDO::$db->fetch('select * from battle where battle_id = ?', User::$current->getBattle()); + if (User::getInstance()->getBattle()) { + $batMagic = Db::getInstance()->fetchColumn('select magic from battle where battle_id = ?', User::getInstance()->getBattle()); } - if ($bat['magic'] == '') { + if (empty($batMagic)) { $all_magic = []; } else { - $all_magic = unserialize($bat['magic']); + $all_magic = unserialize($batMagic); } - $all_magic[User::$current->getId()] += $charge; - DBPDO::$db->execute('update battle set magic = ? where battle_id = ?', [serialize($all_magic), User::$current->getBattle()]); + $all_magic[User::getInstance()->getId()] += $charge; + Db::getInstance()->execute('update battle set magic = ? where battle_id = ?', [serialize($all_magic), User::getInstance()->getBattle()]); } } return false; @@ -462,11 +436,11 @@ function usemagic($id, $target) function addch($text, $room = 0) { if ($room == 0) { - $room = User::$current->getRoom(); + $room = User::getInstance()->getRoom(); } if ($fp = @fopen("tmp/chat.txt", "a")) { //открытие flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА - fputs($fp, ":[" . time() . "]:[!sys!!]:[" . ($text) . "]:[" . $room . "]\r\n"); //работа с файлом + fwrite($fp, ":[" . time() . "]:[!sys!!]:[" . ($text) . "]:[" . $room . "]\r\n"); //работа с файлом fflush($fp); //ОЧИЩЕНИЕ ФАЙЛОВОГО БУФЕРА И ЗАПИСЬ В ФАЙЛ flock($fp, LOCK_UN); //СНЯТИЕ БЛОКИРОВКИ fclose($fp); //закрытие @@ -477,11 +451,11 @@ function addch($text, $room = 0) function addchp($text, $who, $room = 0) { if ($room == 0) { - $room = User::$current->getRoom(); + $room = User::getInstance()->getRoom(); } $fp = fopen("tmp/chat.txt", "a"); //открытие flock($fp, LOCK_EX); //БЛОКИРОВКА ФАЙЛА - fputs($fp, ":[" . time() . "]:[{$who}]:[" . ($text) . "]:[" . $room . "]\r\n"); //работа с файлом + fwrite($fp, ":[" . time() . "]:[{$who}]:[" . ($text) . "]:[" . $room . "]\r\n"); //работа с файлом fflush($fp); //ОЧИЩЕНИЕ ФАЙЛОВОГО БУФЕРА И ЗАПИСЬ В ФАЙЛ flock($fp, LOCK_UN); //СНЯТИЕ БЛОКИРОВКИ fclose($fp); //закрытие @@ -500,8 +474,8 @@ function err($t) */ function telegraph(int $userId, string $text) { - if (DBPDO::$db->ofetch('SELECT 1 FROM users WHERE id = ?', $userId)) { - DBPDO::$db->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']); + if (Db::getInstance()->ofetch('SELECT 1 FROM users WHERE id = ?', $userId)) { + Db::getInstance()->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']); } } @@ -542,33 +516,31 @@ function SolveExp($at_id, $def_id, $damage): float $bot_def = false; if ($at_id > _BOTSEPARATOR_) { - $bots = DBPDO::$db->fetch('select * from bots where bot_id = ?', $at_id); - $at_id = $bots['prototype']; + $at_id = Db::getInstance()->fetchColumn('select prototype from bots where bot_id = ?', $at_id); $bot_active = true; } $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); - $def = DBPDO::$db->fetch($query, $def_id); + $atAllPrice = Db::getInstance()->fetchColumn($query, $at_id); + $defAllPrice = Db::getInstance()->fetchColumn($query, $def_id); $atInfo = new UserStats($at_id); $defInfo = new UserStats($def_id); $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_) { - $bots = DBPDO::$db->fetch('select * from bots where bot_id = ?', $def_id); - $def_id = $bots['prototype']; + $def_id = Db::getInstance()->fetchColumn('select prototype from bots where bot_id = ?', $def_id); $bot_def = true; } - if ($bt['blood']) { + if ($bt->blood) { $expmf = $mods['bloodb']; } $filebtl = '/tmp/' . $at_id . '.btl'; - if ($bt['type'] == 1 && file_exists($filebtl)) { + if ($bt->type == 1 && file_exists($filebtl)) { $btfl = fopen($filebtl, 'r'); $contents = fread($btfl, filesize($filebtl)); fclose($btfl); @@ -614,7 +586,7 @@ function SolveExp($at_id, $def_id, $damage): float "25" => 919 ]; - $mfit = ($at['allprice'] / ($standart[$atInfo->getLevel()] / 3)); + $mfit = ($atAllPrice / ($standart[$atInfo->getLevel()] / 3)); if ($mfit < 0.8) { $mfit = 0.8; } @@ -622,7 +594,7 @@ function SolveExp($at_id, $def_id, $damage): float $mfit = 1.5; } - $pls = count(explode(";", $bt['t1'])) + count(explode(";", $bt['t2'])); + $pls = count(explode(";", $bt->t1)) + count(explode(";", $bt->t2)); if ($pls > 2) { $mfbot = $bot_active ? 0.3 : 1; $mfbot2 = $bot_def ? 0.7 : 1; @@ -634,5 +606,5 @@ function SolveExp($at_id, $def_id, $damage): float $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); } \ No newline at end of file diff --git a/gotzamok.php b/gotzamok.php index ff9de94..626dd76 100644 --- a/gotzamok.php +++ b/gotzamok.php @@ -1,5 +1,9 @@ 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 ($_GET['goto'] == 'arsenal') { - $user->setRoom(38); + User::getInstance()->setRoom(38); } if ($_GET['goto'] == 'home') { - $user->setRoom(37); + User::getInstance()->setRoom(37); } if ($_GET['goto'] == 'dvor') { - $user->setRoom(39); + User::getInstance()->setRoom(39); } if ($_GET['goto'] == 'master') { - $user->setRoom(40); + User::getInstance()->setRoom(40); } if ($_GET['goto'] == 'rest') { - $user->setRoom(41); + User::getInstance()->setRoom(41); } 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'); } else { $status = 'В этом замке нет такого места!'; } } -switch ($user->getRoom()) { - case '37' : - $backgroundImage = '689_small_550.jpg'; - break; - case '41' : - $backgroundImage = 'ko.jpg'; - break; +$i = User::getInstance()->getRoom(); +if ($i == '37') { + $backgroundImage = '689_small_550.jpg'; +} elseif ($i == '41') { + $backgroundImage = 'ko.jpg'; } -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(); // возврат шмотки 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(); $def = db::c()->query('SELECT * FROM `variables` WHERE `var` = "?s"', 'gotzam_def')->fetch_assoc(); 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']) { 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'); $at += 1; - } else $status = 'Не хватает денег!'; + } else { + $status = 'Не хватает денег!'; + } } 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']) { 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'); $def += 1; - } else $status = 'Не хватает денег!'; + } else { + $status = 'Не хватает денег!'; + } } } -\Battles\Template::header('Клановый замок'); +Template::header('Клановый замок'); ?>