Замена define на const. Отказ от дублирующих инициализаций переменных $user $db и вызовов классов User и DBPDO из-за ошибочно настроенной IDE.

This commit is contained in:
lopar 2021-08-23 21:51:34 +03:00
parent c3cfc4ff22
commit 49c2e7c6d6
24 changed files with 90 additions and 167 deletions

View File

@ -8,7 +8,6 @@ session_start();
require_once '../functions.php';
use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\GameConfigs;
use Battles\Moderation;
use Battles\Nick;
@ -73,10 +72,10 @@ UNREGCLANLIST;
{
$bank = new Bank($id);
$this->db->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id);
$bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN_REGISTER_COST, $id);
$bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id);
}
};
$unregisteredClans->db = new DBPDO();
$unregisteredClans->db = $db;
$unregisteredClans->getList();
if (isset($_GET['regclan'])) {
@ -92,12 +91,12 @@ if (isset($_GET['remclan'])) {
# Телеграф.
if (!empty($_POST['receiver']) && !empty($_POST['tgmsg'])) {
$receiver = DBPDO::INIT()->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']);
$receiver = $db->ofetch('SELECT id FROM users WHERE login= ?', $_POST['receiver']);
telegraph($receiver->id, $_POST['tgmsg']);
echo "Успешно.";
}
# Показывает невидимок.
$row = DBPDO::INIT()->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->ofetchAll('SELECT id,login FROM users LEFT JOIN users_effects ue on users.id = ue.owner_id WHERE type = 1022 ORDER BY `id` DESC');
$i = 0;
$invisList = '';
while ($i < count($row)) {

View File

@ -7,7 +7,6 @@
session_start();
require_once "../functions.php";
$user = $user ?? new User($_SESSION['uid']);
if (!$user->getAdmin()) {
header("HTTP/1.0 404 Not Found");
exit;

View File

@ -3,11 +3,9 @@
use Battles\Bank;
use Battles\GameLogs;
use Battles\Template;
use Battles\User;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
const SMITH = 'оружейник';
const MERCENARY = 'наёмник';
const MEDIC = 'лекарь';

View File

@ -4,13 +4,11 @@ use Battles\Bank;
use Battles\GameConfigs;
use Battles\Rooms;
use Battles\Template;
use Battles\User;
use Exceptions\GameException;
ob_start("ob_gzhandler");
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
const SUCCESS = "Успешная операция!";
$bank = new Bank($user->getId());

View File

@ -1,11 +1,9 @@
<?php
use Battles\Template;
use Battles\User;
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
if ($user->getRoom() == 403) {
include "startpodzemel.php";
if ($_GET['act'] == "cexit") {

1
ch.php
View File

@ -4,7 +4,6 @@ use Battles\Template;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
db::c()->query('UPDATE `online` SET `real_time` = ?i WHERE `id` = ?i', time(), $u->i()['id']);
if (isset($_GET['online']) && $_GET['online'] != null) {

View File

@ -4,7 +4,6 @@
*/
session_start();
require_once "functions.php";
$user = $user ?? new \Battles\User($_SESSION['uid']);
if ($user->getZayavka()) {
exit;

View File

@ -4,11 +4,9 @@ use Battles\Bank;
use Battles\GameConfigs;
use Battles\Rooms;
use Battles\Template;
use Battles\User;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
$userClan = db::c()->query('SELECT short_name, full_name, info FROM clans where owner_id = ?i', $user->getId())->fetch_object();
$clanFullName = $_POST['clan_full_name'] ?? '';
$clanShortName = $_POST['clan_short_name'] ?? '';

View File

@ -12,9 +12,14 @@ class GameConfigs
const DATABASE_PASS = 'bottle-neck-horse';
const DATABASE_PORT = '32101';
const DATABASE_CHARSET = 'utf8';
const CLAN_REGISTER_COST = 10000;
const CLAN_REGISTER_LOCK = true; // Запрет на регистрацию кланов.
const CLAN = [
'add_member_cost' => 100,
'remove_member_cost' => 30,
'create_castle_cost' => 25000,
'create_castle_reputation_cost' => 1000000,
'clan_register_cost' => 10000,
'clan_register_lock' => true, // Запрет на регистрацию кланов.
];
const BANK_COMISSION = 0.05; // 5%
const DB_SQLITE = '/volume2/web/battles/databases/logs.sqlite';

View File

@ -16,50 +16,35 @@ class ShopItem extends Item
'sellshop' => 'Продать',
'buyshop' => 'Купить',
];
private const BUY_QUERY = 'insert into inventory (owner_id, name, item_type, durability,
need_strength, need_dexterity, need_intuition, need_endurance, need_intelligence, need_wisdom,
add_strength, add_dexterity, add_intuition, add_endurance, add_intelligence, add_wisdom,
add_accuracy, add_evasion, add_criticals, add_min_physical_damage, add_max_physical_damage,
image, weight, price)
select
?,
name,
item_type,
durability,
need_strength,
need_dexterity,
need_intuition,
need_endurance,
need_intelligence,
need_wisdom,
add_strength,
add_dexterity,
add_intuition,
add_endurance,
add_intelligence,
add_wisdom,
add_accuracy,
add_evasion,
add_criticals,
add_min_physical_damage,
add_max_physical_damage,
image,
weight,
greatest(
(
(add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) *
(5 + floor((add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) / 10))
) +
(
(add_accuracy + add_criticals + add_evasion) *
(2 + floor((add_accuracy + add_criticals + add_evasion) / 50))
) +
(
(add_min_physical_damage + add_max_physical_damage) *
(1 + floor((add_min_physical_damage + add_max_physical_damage) / 100))
)
,1)
from items where id = ?';
private const BUY_QUERY = <<<SQL
insert into inventory (
owner_id, name, item_type, durability,
need_strength, need_dexterity, need_intuition, need_endurance, need_intelligence, need_wisdom,
add_strength, add_dexterity, add_intuition, add_endurance, add_intelligence, add_wisdom,
add_accuracy, add_evasion, add_criticals, add_min_physical_damage, add_max_physical_damage,
image, weight, price)
select
?, name, item_type, durability,
need_strength, need_dexterity, need_intuition, need_endurance, need_intelligence, need_wisdom,
add_strength, add_dexterity, add_intuition, add_endurance, add_intelligence, add_wisdom,
add_accuracy, add_evasion, add_criticals, add_min_physical_damage, add_max_physical_damage,
image, weight, greatest(
(
(add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) *
(5 + floor((add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) / 10))
) +
(
(add_accuracy + add_criticals + add_evasion) *
(2 + floor((add_accuracy + add_criticals + add_evasion) / 50))
) +
(
(add_min_physical_damage + add_max_physical_damage) *
(1 + floor((add_min_physical_damage + add_max_physical_damage) / 100))
)
,1)
from items where id = ?
SQL;
// Тип операции в магазине. Для отображения разных блоков в разных случаях.
private $optype;
private ?int $shop_item_quantity;

View File

@ -3,11 +3,9 @@
use Battles\GameLogs;
use Battles\ShopItem;
use Battles\Template;
use Battles\User;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
$get = urldecode(filter_input(INPUT_SERVER, 'QUERY_STRING'));
$putItemCost = (int)filter_input(INPUT_POST, 'cost', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$putItemId = (int)filter_input(INPUT_POST, 'putId', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
@ -15,6 +13,8 @@ $returningItemId = (int)filter_input(INPUT_GET, 'back', FILTER_VALIDATE_INT, ['o
$byingItemId = (int)filter_input(INPUT_GET, 'set', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($putItemId) {
$query = 'select name from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?';
\Battles\Database\DBPDO::INIT()->ofetch($query, [$_SESSION['uid'], $putItemId]);
$dress = db::c()->query('SELECT `name`,`duration`,`maxdur`,`cost` FROM `inventory` WHERE `dressed` = 0 AND `id` = ?i AND `owner` = ?i', $putItemId, $_SESSION['uid'])->fetch_assoc();
if (empty($putItemCost)) {
$putItemCost = $dress['cost'];
@ -75,60 +75,30 @@ if ($byingItemId) {
$classPrintControlName = "marketbuy";
if ($get === 'sale') {
$data = db::c()->query('SELECT `inventory`.*,
`magic`.`name` AS `magic_name`,
`magic`.`chanse` AS `magic_chanse`,
`magic`.`time` AS `magic_time`,
`magic`.`file` AS `magic_file`,
`magic`.`targeted` AS `magic_targeted`,
`magic`.`needcharge` AS `magic_needcharge`,
`magic`.`img` AS `magic_img`,
0 AS `maxdur`
FROM `inventory` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `setsale` = 0 AND `dressed` = 0 AND `present` = "?s" AND `owner` = ?i ORDER BY `update` DESC ', '', $_SESSION['uid']);
$search = $_SESSION['uid'];
$query = 'select * from inventory where on_sale = 0 and dressed_slot = 0 and present is null and owner_id = ? order by name';
$classPrintControlName = "marketput";
} elseif ($get === 'unsale') {
$data = db::c()->query('SELECT `inventory`.*,
`magic`.`name` AS `magic_name`,
`magic`.`chanse` AS `magic_chanse`,
`magic`.`time` AS `magic_time`,
`magic`.`file` AS `magic_file`,
`magic`.`targeted` AS `magic_targeted`,
`magic`.`needcharge` AS `magic_needcharge`,
`magic`.`img` AS `magic_img`,
0 AS `maxdur`
FROM `inventory` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `setsale` > 0 AND `dressed` = 0 AND `owner` = ?i ORDER BY `update` DESC', $_SESSION['uid']);
$search = $_SESSION['uid'];
$query = 'select * from inventory where on_sale > 0 and dressed_slot = 0 and owner_id = ? order by name';
$classPrintControlName = "marketgetback";
} else if (!empty($_POST['search'])) {
$data = db::c()->query('SELECT `inventory`.*,
`magic`.`name` AS `magic_name`,
`magic`.`chanse` AS `magic_chanse`,
`magic`.`time` AS `magic_time`,
`magic`.`file` AS `magic_file`,
`magic`.`targeted` AS `magic_targeted`,
`magic`.`needcharge` AS `magic_needcharge`,
`magic`.`img` AS `magic_img`,
0 AS `maxdur`
FROM `inventory` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `dressed` = 0 AND `inventory`.`name` LIKE "%?S%" AND `setsale` > 0 ORDER BY `setsale` ASC', $_POST['search']);
$search = "%{$_POST['search']}%";
$query = 'select * from inventory where on_sale > 0 and dressed_slot = 0 and name like ? order by item_id';
} else {
$data = db::c()->query('SELECT `inventory`.*,
`magic`.`name` AS `magic_name`,
`magic`.`chanse` AS `magic_chanse`,
`magic`.`time` AS `magic_time`,
`magic`.`file` AS `magic_file`,
`magic`.`targeted` AS `magic_targeted`,
`magic`.`needcharge` AS `magic_needcharge`,
`magic`.`img` AS `magic_img`,
0 AS `maxdur`
FROM `inventory` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `dressed` = 0 AND `setsale` > 0 ORDER BY `setsale` ASC');
$query = 'select * from inventory where on_sale > 0 and dressed_slot = 0 order by name';
}
if (isset($search)) {
$data = \Battles\Database\DBPDO::INIT()->ofetchAll($query, $search);
unset($search);
} else {
$data = \Battles\Database\DBPDO::INIT()->ofetchAll($query);
}
$iteminfo = [];
while ($row = $data->fetch_assoc()) {
$iteminfo[] = new ShopItem($row);
foreach ($data as $itemObject) {
$iteminfo[] = new ShopItem($itemObject, 'buymarket');
}
Template::header('Рынок');
@ -137,12 +107,12 @@ Template::header('Рынок');
<h1>Рынок</h1>
<a href=# onclick=hrefToFrame('city.php?cp')> ← выйти на Центральную площадь</a>
<div><?php if (!empty($status)) err($status); ?></div>
<TABLE width=100% cellspacing="0" cellpadding="4">
<TR>
<TD valign=top align=left>
<TABLE class="zebra" width=100%>
<TR>
<TH>
<table width=100% cellspacing="0" cellpadding="4">
<tr>
<td valign=top align=left>
<table class="zebra" width=100%>
<tr>
<th>
<?php if ($get === 'sale'): ?>
Выставить товар на продажу.
<br>Комиссия за услуги магазина составляет 10% от цены, по которой вы предлагаете предмет.
@ -154,9 +124,9 @@ Template::header('Рынок');
<input name="search"> <input type="submit" value="Искать товар">
</form>
<?php endif; ?>
<TR>
<TD><!--Рюкзак-->
<TABLE WIDTH=100%>
<tr>
<td><!--Рюкзак-->
<table width=100%>
<?php
foreach ($iteminfo as $ii) {
echo "<tr><td style='width: 150px; text-align: center;'>";
@ -168,8 +138,8 @@ Template::header('Рынок');
echo "</td></tr>";
}
?>
</TABLE>
</TABLE>
</table>
</table>
<TD valign=top width=280>
<div style="margin-left:15px; margin-top: 10px;">
<b>Масса всех ваших вещей: <?= getItemsMassaInfo() ?>
@ -184,4 +154,4 @@ Template::header('Рынок');
<br>
<button onclick="hrefToFrame('city.php?cp=1')">Вернуться</button>
</div>
</TABLE>
</table>

View File

@ -6,10 +6,10 @@ use Battles\Template;
session_start();
require_once "config.php";
define('ERROR_NO_SUCH_USER', 'Такого пользователя не существует!');
define('ERROR_USER_IS_BLOCKED', 'Пользователь заблокирован!');
define('ERROR_WRONG_PASSWORD', 'Неверный пароль!');
define('ERROR_EMPTY_CREDENTIALS', 'Вы не ввели логин или пароль!');
const ERROR_NO_SUCH_USER = 'Такого пользователя не существует!';
const ERROR_USER_IS_BLOCKED = 'Пользователь заблокирован!';
const ERROR_WRONG_PASSWORD = 'Неверный пароль!';
const ERROR_EMPTY_CREDENTIALS = 'Вы не ввели логин или пароль!';
$db = new DBPDO();
foreach ($_POST as $key => $val) { //Проверка всех значений массива POST одним махом.
$_POST[$key] = iconv(mb_detect_encoding($_POST[$key], 'auto'), 'utf-8', $val);

View File

@ -1,11 +1,9 @@
<?php
use Battles\Template;
use Battles\User;
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
function secs2hrs($s, $short = 0)
{

View File

@ -22,6 +22,7 @@ if ($user->getId() && $user->getBlock()) {
exit('user blocked!');
}
$db = new DBPDO();
/*
* Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам.

View File

@ -1,11 +1,9 @@
<?php
use Battles\Template;
use Battles\User;
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
class hellround
{

View File

@ -1,14 +1,9 @@
<?php
/**
* @var User $user
*/
use Battles\Database\DBPDO;
use Battles\DressedItems;
use Battles\GameLogs;
use Battles\InventoryItem;
use Battles\Template;
use Battles\Travel;
use Battles\User;
use Battles\UserInfo;
use Battles\UserStats;
@ -54,12 +49,12 @@ if ($edit) {
}
//Пока что одеваем предмет отсюда.
if ($dress) {
$dressing = new InventoryItem(DBPDO::INIT()->ofetch('select * from inventory where item_id = ? ', $dress));
$dressing = new InventoryItem($db->ofetch('select * from inventory where item_id = ? ', $dress));
$dressing->dressItem();
unset($dressing);
}
if ($destruct) {
$q = DBPDO::INIT()->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [$user->getId(), $destruct]);
$q = $db->ofetch('select name,dressed_slot from inventory where owner_id = ? and item_id = ?', [$user->getId(), $destruct]);
if ($q) {
if (empty($q->dressed_slot)) {
InventoryItem::destroyItem($destruct);
@ -84,7 +79,7 @@ if ($edit) {
// Подготавливаем отображение инфы и предметов.
$userInfo = new UserInfo($user->getId());
$userStats = new UserStats($user->getId());
$data = DBPDO::INIT()->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', $user->getId());
$data = $db->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', $user->getId());
$iteminfo = [];
foreach ($data as $row) {
$iteminfo = new InventoryItem($row);

View File

@ -5,11 +5,9 @@ use Battles\GameLogs;
use Battles\InventoryItem;
use Battles\Nick;
use Battles\Template;
use Battles\User;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
if ($_GET['change'] ?? 0) {
unset($_SESSION['receiverName']);
}

View File

@ -4,13 +4,13 @@ use Battles\Database\DBPDO;
use Battles\Template;
require_once("config.php");
define('OK_MAIL_SENT', 'Письмо отправлено!');
define('OK_PASSWORD_CHANGED', 'Пароль изменён!');
define('ERROR_MAIL_NOT_SENT', 'Письмо не отправлено!');
define('ERROR_WRONG_LOGIN', 'Такого пользователя не существует!');
define('ERROR_TOO_MANY_TRIES', 'Вы уже отправляли себе письмо сегодня!');
define('ERROR_OLD_HASH', 'Ссылка устарела!');
define('ERROR_WRONG_HASH', 'Неверная ссылка!');
const OK_MAIL_SENT = 'Письмо отправлено!';
const OK_PASSWORD_CHANGED = 'Пароль изменён!';
const ERROR_MAIL_NOT_SENT = 'Письмо не отправлено!';
const ERROR_WRONG_LOGIN = 'Такого пользователя не существует!';
const ERROR_TOO_MANY_TRIES = 'Вы уже отправляли себе письмо сегодня!';
const ERROR_OLD_HASH = 'Ссылка устарела!';
const ERROR_WRONG_HASH = 'Неверная ссылка!';
$login = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_SPECIAL_CHARS);
$password = isset($_POST['psw']) ? password_hash($_POST['psw'], PASSWORD_DEFAULT) : null;
$_GET['change'] = $_GET['change'] ?? null;

View File

@ -1,24 +1,20 @@
<?php
use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\GameLogs;
use Battles\Template;
use Battles\User;
session_start();
require_once("functions.php");
$user = $user ?? new User($_SESSION['uid']);
$db = new DBPDO();
define('GRAV_LIMIT', 32);
define('GRAV_COST', 30);
define('REPAIR_STATUS', [
const GRAV_LIMIT = 32;
const GRAV_COST = 30;
const REPAIR_STATUS = [
'OK_GRAV_ADDED' => 'Гравировка добавлена!',
'OK_GRAV_REMOVED' => 'Гравировка удалена!',
'OK_REPAIRED' => 'Предмет отремонтирован!',
'ERROR_SIZE_LIMIT' => 'Превышен лимит в ' . GRAV_LIMIT . ' символа!',
'ERROR_NO_MONEY' => 'Недостаточно денег!',
]);
];
$gravirovkaText = $_POST['gravirovka_text'] ?? null;
$itemId = $_POST['itemId'] ?? null;
$gravirovkaRemove = $_POST['gravirovka_remove'] ?? null;

View File

@ -1,17 +1,13 @@
<?php
use Battles\Bank;
use Battles\Database\DBPDO;
use Battles\Item;
use Battles\ShopItem;
use Battles\Template;
use Battles\User;
ob_start();
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
$db = new DBPDO();
$saleItems = false;
$shopCategoryType = $_POST['sale'] ?? '';
$shopCategoryTypeNumber = $_GET['otdel'] ?? 0;

View File

@ -1,7 +1,6 @@
<?php
session_start();
require_once "functions.php";
$user = $user ?? new \Battles\User($_SESSION['uid']);
$Tournament = new Tournament();
\Battles\Template::header('Турниры');
?>

View File

@ -7,11 +7,9 @@
*/
use Battles\Template;
use Battles\User;
session_start();
require_once 'functions.php';
$user = $user ?? new User($_SESSION['uid']);
if (!empty($_GET['teleport']) && $user->getAdmin() == 1) {
db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 20,`online`.`room` = 20 WHERE `online`.`id` = `users`.`id` AND `online`.`id` = ?i', $_SESSION['uid']);
}

View File

@ -1,11 +1,9 @@
<?php
use Battles\Template;
use Battles\User;
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
if ($user->getLevel() < 4 && $user->getLevel() > 10) {
header('location: main.php?act=none');
exit;

View File

@ -2,11 +2,9 @@
use Battles\Nick;
use Battles\Template;
use Battles\User;
session_start();
require_once "functions.php";
$user = $user ?? new User($_SESSION['uid']);
try {
db::c()->query('LOCK TABLES `bots` WRITE, `battle` WRITE, `logs` WRITE, `users` WRITE, `inventory` WRITE, `zayavka` WRITE, `effects` WRITE, `online` WRITE, `clans` WRITE');
} catch (Exception $e) {