Compare commits

..

5 Commits

Author SHA1 Message Date
lopar
fdaadf69e6 Заявки на поединки. Начало. 2022-02-13 01:46:59 +02:00
lopar
1bf7a40fe9 Merge remote-tracking branch 'origin/dev-arena' into dev-arena 2022-02-12 20:17:51 +02:00
lopar
b652c242c4 Merge branch 'master' into dev-arena 2022-02-12 14:41:36 +02:00
lopar
0f62ee20e7 немного логики 2022-02-12 14:25:43 +02:00
Igor Barkov (iwork)
f12e7c8cd7 Отделение классов от кода. 2022-01-27 18:28:32 +02:00
9 changed files with 266 additions and 157 deletions

View File

@ -6,7 +6,46 @@
use Battles\Arena;
use Battles\Template;
if (isset($_POST['startTime']) && isset($_POST['teamMembersQuantity'])) {
Arena::fight()->addNew((int)$_POST['teamMembersQuantity'], 2, (int)$_POST['startTime']);
}
if (isset($_POST['fight_id']) && isset($_POST['team_id'])) {
Arena::fight()->join((int)$_POST['fight_id'], (int)$_POST['team_id']);
}
Template::header('Арена');
?>
$dbname = new SQLite3('name.db');
Arena::$current = new Arena($dbname);
<?php if(Arena::fight()->hasNoPendingFights()): ?>
<form method='post' id='newbattle'></form>
<H3>Подать заявку на поединок</H3>
<label for='startTime'>Начало боя</label>
<select name='startTime' id='startTime' form='newbattle'>
<option value=1 selected>через 1 минуту</option>
<option value=3>через 3 минуты</option>
<option value=5>через 5 минут</option>
<option value=10>через 10 минут</option>
</select>
<br><br>
<label>Размер команды (1-20)
<input type='number' min='1' max='20' name='teamMembersQuantity' form='newbattle' value='5'>
</label>
<br><br>
<input type='submit' value='Подать заявку' form='newbattle'>
<?php endif; ?>
<?= Arena::fight()->getPendingList() ?>
<?php foreach (Arena::fight()->getPendingList() as $row): ?>
<!-- !!PLACEHOLDER!! -->
<div>
User1, User2, User3
<form method='post' style='display:inline'>
<input type='hidden' name='teamId' value='1'>
<input type='submit' value='Я за этих'>
</form>
<em>против</em>
User4, User5, User6
<form method='post' style='display:inline'>
<input type='hidden' name='teamId' value='2'>
<input type='submit' value='Я за этих'>
</form>
<? endforeach; ?>
</div>

View File

@ -74,7 +74,7 @@ class Db
// 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();
$keyed_results = [];
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
}
@ -94,7 +94,7 @@ class Db
return $stmt->fetch(PDO::FETCH_OBJ);
}
public function ofetchAll($query, $values = null, $key = null): object
public function ofetchAll($query, $values = null)
{
if (is_null($values)) {
$values = [];
@ -102,18 +102,7 @@ class Db
$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;
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
public function lastInsertId()

View File

@ -0,0 +1,21 @@
<?php
namespace Battles;
use Battles\Database\Db;
class Register
{
public static function addUser(string $login, string $password, string $email, string $birthday): int
{
if (Db::getInstance()->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;
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Battles;
use tidy, Battles\Database\Db;
class RememberPassword
{
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 = 'Неверная ссылка!';
private function mailSend(string $to, string $message): bool
{
$from = "=?UTF-8?B?" . base64_encode('Noreply') . "?= <noreply@" . GAMEDOMAIN . ">";
$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('Здравствуйте!<br><br>Кто-то запросил восстановление пароля к вашему персонажу %s <br><br>
Для смены пароля пройдите по <a href="//%s/rememberpassword.php?change=%s">данной ссылке</a>.<br><br>
Ссылка будет действовать до <em>%s</em>',$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;
}
}

View File

@ -55,9 +55,45 @@ 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
@ -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;
}
}
}

View File

@ -28,7 +28,6 @@ class User
// Пока несуществующие, для совместимости.
protected int $experience = 0;
protected int $battle = 0;
protected int $in_tower = 0; // Скорее башню похороним чем запустим...
protected int $zayavka = 0;
@ -77,6 +76,7 @@ class User
{
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 true;
}
return false;
}
@ -218,7 +218,7 @@ class User
public function getBattle(): int
{
return $this->battle;
return Arena::fight()->hasNoActiveFights();
}
public function getInTower(): int

View File

@ -23,56 +23,60 @@ if (User::getInstance()->getBlock()) {
exit('user blocked!');
}
/*
* Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам.
*/
$fbattleCheckFiles = [
'c_haos_in.php',
'c_haos.php',
'c_park.php',
'city.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::getInstance()->getBattle() && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], $fbattleCheckFiles)) {
header('location: fbattle.php');
exit;
}
$towerinCheckFiles = ['main.php', 'city.php', 'tower.php'];
if (User::getInstance()->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::getInstance()->getRoom(), $roomsCheck)
&& pathinfo(debug_backtrace()[0]['file'])['basename'] != Travel::$roomFileName[User::getInstance()->getRoom()]
&& in_array(array_search(pathinfo(debug_backtrace()[0]['file'])['basename'], Travel::$roomFileName), $roomsCheck)) {
header('location: main.php');
exit;
}
//Проверки на соответствие скрипта и комнаты, которые были натыканы по всем файлам.
Travel::roomRedirects(User::getInstance()->getRoom(), User::getInstance()->getBattle(), User::getInstance()->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 = ?';
@ -436,7 +440,7 @@ function addch($text, $room = 0)
}
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); //закрытие
@ -451,7 +455,7 @@ function addchp($text, $who, $room = 0)
}
$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); //закрытие

View File

@ -1,6 +1,6 @@
<?php
use Battles\Template, Battles\Database\Db;
use Battles\Template, Battles\Register;
require_once "config.php";
@ -15,26 +15,11 @@ if ($_COOKIE[GAMEDOMAIN] ?? null) {
$law2 = filter_input(INPUT_POST, 'law2', FILTER_VALIDATE_BOOLEAN);
if ($login && $password && $email && $birthday && $law && $law2) {
$newUser = new class {
public static function addUser(string $login, string $password, string $email, string $birthday): bool
{
if (Db::getInstance()->ofetch('SELECT 1 FROM users WHERE login = ? OR email = ?', [$login, $email])) {
return false;
}
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);
setcookie(GAMEDOMAIN, $userId, time() + 3600);
setcookie("battle", time());
$_SESSION['uid'] = $userId;
$_SESSION['sid'] = session_id();
return true;
}
};
$newUser::addUser($login, $password, $email, $birthday);
$uid = Register::addUser($login, $password, $email, $birthday);
setcookie(GAMEDOMAIN, $uid, time() + 3600);
setcookie("battle", time());
$_SESSION['uid'] = $uid;
$_SESSION['sid'] = session_id();
header('Location: fight.php');
exit;
}

View File

@ -1,77 +1,14 @@
<?php
use Battles\Database\Db;
use Battles\Template;
use Battles\Template, Battles\RememberPassword;
require_once("config.php");
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;
$newPassword = $_POST['newpasswd'] ?? 0;
$hashCheck = $_POST['hashcheck'] ?? 0;
$operation = new class {
private function mailSend(string $to, string $message): bool
{
$from = "=?UTF-8?B?" . base64_encode('Noreply') . "?= <noreply@" . GAMEDOMAIN . ">";
$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 ERROR_WRONG_LOGIN;
}
if (!empty(Db::getInstance()->ofetch('SELECT 1 FROM users_recovery WHERE login = ?', $to))) {
return ERROR_TOO_MANY_TRIES;
}
$hash = bin2hex(random_bytes(8));
Db::getInstance()->execute('INSERT INTO users_recovery (login, hash, ip, date) VALUES (?,?,?,?)', [$to, $hash, date('Y-m-d', strtotime('+1days')), $_SERVER['REMOTE_ADDR']]);
$message = "Здравствуйте!<br><br>
Кто-то запросил восстановление пароля к вашему персонажу " . $to . ".<br><br>
Для смены пароля пройдите по
<a href='" . GAMEDOMAIN . "/rememberpassword.php?change=" . $hash . "'> данной ссылке</a>.<br><br>
Ссылка будет действовать до <em>" . date('d-M-Y', strtotime(date('Y-m-d', strtotime('+1days')))) . "</em>.
";
return self::mailSend($check->email, $message) ? OK_MAIL_SENT : ERROR_MAIL_NOT_SENT;
}
public function isAllowed($hash)
{
return Db::getInstance()->execute('SELECT 1 FROM users_recovery WHERE hash = ? AND date < ?', [$hash, date('Y-m-d')])->fetchColumn() ? true : ERROR_OLD_HASH;
}
public function setNewPassword(string $newPassword, string $hash):string
{
$login = Db::getInstance()->execute('select login from users_recovery where hash = ?', $hash)->fetchColumn();
if (empty($login)) {
return 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 OK_PASSWORD_CHANGED;
}
};
$operation = new RememberPassword();
if ($login) {
$statusMessage = $operation->sendRecoveryMail($login);