23 Commits

Author SHA1 Message Date
DarksLight2 5518b335a8 Обучение. Правило для новой страницы с неправильным вводом ответа 2023-01-18 12:54:10 +01:00
DarksLight2 95604fc4b1 Вынес логику из автозагрузчика 2023-01-18 12:53:20 +01:00
DarksLight2 5df2447d34 Убрал лишнее 2023-01-18 12:51:58 +01:00
DarksLight2 328e7483cd Новая фича с хэлперами 2023-01-18 12:51:33 +01:00
DarksLight2 3f579afaed Обучение. Новые задания 2023-01-18 12:51:06 +01:00
DarksLight2 bae941e155 Обучение. Рефакторинг 2023-01-18 12:43:45 +01:00
DarksLight2 037d43857d Merge branch 'maksym' of https://src.lopar.space/new-combats.com/game into maksym 2023-01-15 23:26:58 +01:00
DarksLight2 739caee04b Закончил разработку обучения 2023-01-15 22:47:19 +01:00
DarksLight2 35c0b6825f revert 45fc2f51b4
revert Восстановление пароля
2023-01-13 21:41:44 +00:00
DarksLight2 45fc2f51b4 Восстановление пароля 2023-01-13 18:56:41 +01:00
DarksLight2 9ec0f42e17 Обучение. Начало Frontend части 2023-01-12 21:38:13 +01:00
lopar d9ec810f7f Merge pull request 'dev-cookie-to-id' (#37) from dev-cookie-to-id into dev
Reviewed-on: new-combats.com/game#37
2023-01-12 03:41:11 +00:00
lopar 89469b919f Merge remote-tracking branch 'origin/dev-cookie-to-id' into dev-cookie-to-id 2023-01-12 05:39:04 +02:00
lopar d0fb296691 почта не уходила 2023-01-12 05:38:48 +02:00
lopar e8252b8d4d даты рождения не совпадали 2023-01-12 05:31:22 +02:00
lopar c647600141 various small 2023-01-12 05:22:03 +02:00
lopar 68fe6ec13e various small 2023-01-12 05:08:32 +02:00
lopar b483b79df5 closes #33 2023-01-12 04:19:06 +02:00
lopar 557921edfa Uncaught TypeError: Argument 1 passed to User::snatItem() must be of the type int, null given 2023-01-12 04:07:43 +02:00
lopar f3bee1c3ac Typed property User::$info must be array, bool used 2023-01-12 03:21:13 +02:00
lopar 84c0847178 Trying to access array offset on value of type null i 2023-01-12 03:18:17 +02:00
lopar a1aca77a35 Запросы в несуществующий базы, снятие вещей из пустых слотов.. 2023-01-12 02:58:26 +02:00
lopar f1d838fcc4 Регистрация кажется завелась. 2023-01-12 01:39:26 +02:00
39 changed files with 1412 additions and 555 deletions
+1
View File
@@ -1,4 +1,5 @@
<?php <?php
const GAME = true; // Для совместимости с этой "защитой". const GAME = true; // Для совместимости с этой "защитой".
const GAME_VERSION = 'alpha-7.4'; const GAME_VERSION = 'alpha-7.4';
// Новая автозагрузка. // Новая автозагрузка.
@@ -0,0 +1,11 @@
<?php
namespace DarksLight2\Helpers;
class Str
{
public static function snakeCase($string): string
{
return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $string));
}
}
@@ -2,12 +2,47 @@
namespace DarksLight2\Training; namespace DarksLight2\Training;
use DarksLight2\Helpers\Str;
use User;
abstract class StepFactory abstract class StepFactory
{ {
abstract public function getTitle(): string; abstract public function getTitle(): string;
abstract public function getMessage(): string; abstract public function getMessage(): string;
abstract public function getShortName(): string;
abstract public function getRewards(): array; abstract public function getRewards(): array;
public function onLocations(): array
{
return ['all'];
}
public function getShortName(): string
{
return Str::snakeCase(get_class($this));
}
public function getAnswer()
{
return null;
}
public function allowedToMove(): array
{
return [];
}
public function isInfo(): bool
{
return true;
}
public function databaseRecord()
{
return [
'completed' => false,
'progress' => [
'current' => 0,
'need' => 1,
]
];
}
} }
@@ -4,17 +4,17 @@ namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory; use DarksLight2\Training\StepFactory;
class FirstStep extends StepFactory class ChatFirstQuest extends StepFactory
{ {
public function getTitle(): string public function getTitle(): string
{ {
return 'Первое знакомство'; return 'Начало.';
} }
public function getMessage(): string public function getMessage(): string
{ {
return 'test'; return 'Отправьте сообщение в общий чат.';
} }
public function getRewards(): array public function getRewards(): array
@@ -24,7 +24,11 @@ class FirstStep extends StepFactory
public function getShortName(): string public function getShortName(): string
{ {
return 'first_step'; return 'chat_first_quest';
} }
public function isInfo(): bool
{
return false;
}
} }
@@ -0,0 +1,30 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class ChatFirstStep extends StepFactory
{
public function getTitle(): string
{
return 'Начало.';
}
public function getMessage(): string
{
return 'Помните, оскорблять, унижать, обсуждать политику, подстёгивать других игроков, как в общем чате так и в приватном приведет к временному ограничению возможности отправки сообщений в любой из чатов.';
}
public function getShortName(): string
{
return 'chat_first_step';
}
public function getRewards(): array
{
return [];
}
}
@@ -0,0 +1,35 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class ChatSecondQuest extends StepFactory
{
public function getTitle(): string
{
return 'Начало.';
}
public function getMessage(): string
{
return 'Отправьте адресное сообщение в общий чат, нажав 1 раз по никнейму игрока либо в чате, либо со списка онлайна, который находится справа.';
}
public function getShortName(): string
{
return 'chat_second_quest';
}
public function getRewards(): array
{
return [];
}
public function isInfo(): bool
{
return false;
}
}
@@ -0,0 +1,34 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class ChatThirdQuest extends StepFactory
{
public function getTitle(): string
{
return 'Начало.';
}
public function getMessage(): string
{
return 'Отправьте адресное личное сообщение в чат, нажав 2 раза по никнему игрока либо в чате, либо со списка онлайна, который находится справа.';
}
public function getShortName(): string
{
return 'chat_third_quest';
}
public function getRewards(): array
{
return [];
}
public function isInfo(): bool
{
return false;
}
}
@@ -0,0 +1,35 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserFirstQuest extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'Сколько всего основных игровых Валют? Введите их число...';
}
public function getShortName(): string
{
return 'my_user_first_quest';
}
public function getRewards(): array
{
return [];
}
public function getAnswer(): string
{
return '2';
}
}
@@ -0,0 +1,30 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserFirstStep extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'В нашей игре, ваш персонаж расположен слева от экрана с игровыми локациями, там же, можно увидеть пустые слоты под предметы и параметры персонажа, ваш опыт, деньги, ежедневные задания...';
}
public function getShortName(): string
{
return 'my_user_first_step';
}
public function getRewards(): array
{
return [];
}
}
@@ -0,0 +1,35 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserFourthQuest extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'Войдите во вкладку " Умения ", в правой части экрана, сверху, а далее, перейдите во вкладку " Приёмы ", после чего, выберите нужные Вам приемы, но будьте внимательны, некоторые из приемов могут быть на разные классы, обязательно прочтите их описание или потестируйте в поединках.';
}
public function getShortName(): string
{
return 'my_user_fourth_quest';
}
public function getRewards(): array
{
return [];
}
public function isInfo(): bool
{
return false;
}
}
@@ -0,0 +1,48 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserFourthStep extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return '"Параметры Персонажа"<br>
Все игроки имеют свободные очки распределения параметров, что они дают игрокам конкретные модификаторы в зависимости от того, в какой из параметров распределяются очки распределения.<br>
--- если можно, добавить скрин как выглядит эта кнопка ---
Сила - Увеличивает мощность рубящего урона ( для Силачей )<br>
Ловкость - Увеличивает мощность колющего урона ( для Критоуворотов и Уворотов )<br>
Интуиция - Увеличивает мощность режущего урона ( для Критовиков )<br>
Выносливость - Увеличивает защиту от урона и магии, а так же добавит немного жизней. ( для Танков )<br>
Интелект - Увеличивает мощность магии. ( Для Любого Мага )<br>
Мудрость - Увеличивает колличество маны. ( Для Любого Мага )<br>
<br>
Дополнительно, игроки имеют очки распределения Мастерства Оружия, это позволит воинам увеличить урон, а магам, открыть новые приемы.<br>
Очки распределения Оружий распределяются точно так же, как и очки распределения параметров ( статов ).<br>
<br>
В случае, если вы распределили неверно любые доступные очки распределения, или хотите их изменить, вы можете это сделать, поднявшись на 2 этаж здания " Бойцовский Клуб ".';
}
public function getShortName(): string
{
return 'my_user_fourth_step';
}
public function getRewards(): array
{
return [];
}
public function getAnswer(): string
{
return '';
}
}
@@ -0,0 +1,35 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserSecondQuest extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'Кого убивает игровой класс "Танк"?';
}
public function getShortName(): string
{
return 'my_user_second_quest';
}
public function getRewards(): array
{
return [];
}
public function getAnswer(): string
{
return 'Уворотов и Силачей';
}
}
@@ -0,0 +1,39 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserSecondStep extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'Опыт - Получение опыта происходит после сыгранных поединков, в зависимости от выбитого урона с противников, нажав по своему опыту, откроется таблица опыта, в которой можно посмотреть, когда вы получите дополнительное очко распределение параметров персонажа/оружий, награду за взятие " апа " или " Уровня "<br>
Текущий уровень - Отображает ваш текущий уровень персонажа.<br>
Победы - Отображает сумму всех ваших побед, в любых поединках.<br>
Поражения - Отображает сумму всех ваших поражений, в любых поединках.<br>
Ничьих - Отображает сумму всех поединков, которые завершились в ничью.<br>
Кредиты - Обычная игровая валюта - кредиты ( креды ), которые можно потратить в обычном магазине.<br>
Еврокредиты - Покупная игровая валюта - еврокредиты ( екры ) , которые можно потратить в магазине " Берёзка ". <br>
Воинственность - Дополнительная игровая валюта, потратить её можно в Подпольной Лавке.<br>
Ежедневное задание - Отображает текущее ежедневное задание либо предоставляет возможность его взятия.<br>
Бонус - Позволяет получить немного кредитов или еврокредитов.';
}
public function getShortName(): string
{
return 'my_user_second_step';
}
public function getRewards(): array
{
return [];
}
}
@@ -0,0 +1,40 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserThirdQuest extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'Распределите свободные параметры распределения ( статы ) и параметры оружий ( умения ) в зависимости от выбранного вами при регистрации "Класса" игрока нажав по кнопке " + Способности ", а далее, после распределения параметров " Сохранить ".';
}
public function getShortName(): string
{
return 'my_user_third_quest';
}
public function getRewards(): array
{
return [];
}
public function isInfo(): bool
{
return false;
}
public function allowedToMove(): array
{
return ['cp1'];
}
}
@@ -0,0 +1,45 @@
<?php
namespace DarksLight2\Training\Steps;
use DarksLight2\Training\StepFactory;
class MyUserThirdStep extends StepFactory
{
public function getTitle(): string
{
return 'Персонаж.';
}
public function getMessage(): string
{
return 'В нашей игре, существует 5 Воинских и 4 Магических класса, такие как:<br>
Критовик - Убивает Танков и Магов, основное оружие - Мечи<br>
Уворот - Убивает Критовиков и Силачей, основное оружие - Кинжалы<br>
Танк - Убивает Уворотов и Силачей, основное оружие - Дубина и щит.<br>
Силач - Убивает Критовиков и Магов, основное оружие - Топоры<br>
Критоуворот - Убивает Силачей и с небольшим шансом Критовиков и Уворотов, основное оружие - Кинжалы.<br>
<br>
Маг Огня - Атакующий маг, убивает Уворотов и Танков.<br>
Маг Воздуха - Атакующий маг, убивает Уворотов и Танков.<br>
Маг Земли - Защищающийся маг, слабый урон, хорошая защита.<br>
Маг Воды - Защищающийся маг, слабый урон, хорошая защита.';
}
public function getShortName(): string
{
return 'my_user_third_step';
}
public function getRewards(): array
{
return [];
}
public function allowedToMove(): array
{
return ['cp1'];
}
}
@@ -3,24 +3,127 @@
namespace DarksLight2\Training; namespace DarksLight2\Training;
use Core\Db; use Core\Db;
use DarksLight2\Training\Steps\ChatFirstStep;
use DarksLight2\Training\Steps\MyUserFirstQuest;
use DarksLight2\Training\Steps\MyUserFirstStep;
use DarksLight2\Training\Steps\MyUserFourthQuest;
use DarksLight2\Training\Steps\MyUserFourthStep;
use DarksLight2\Training\Steps\MyUserSecondQuest;
use DarksLight2\Training\Steps\MyUserSecondStep;
use DarksLight2\Training\Steps\MyUserThirdQuest;
use DarksLight2\Training\Steps\MyUserThirdStep;
use DarksLight2\Traits\Singleton; use DarksLight2\Traits\Singleton;
use PassGen;
use PDO; use PDO;
use stdClass; use stdClass;
use User;
class TrainingManager class TrainingManager
{ {
use Singleton; use Singleton;
private $database_records = false;
private array $steps_data;
private int $user_id; private int $user_id;
private array $steps; public string $current_step = '';
private array $registered_steps;
private array $completed_steps;
private array $active_steps;
public function __construct(int $user_id) private $database;
public function __construct(int $user_id, $refresh_token = true)
{ {
try {
$this->register([
new ChatFirstStep(),
new MyUserFirstStep(),
new MyUserFirstQuest(),
new MyUserSecondStep(),
new MyUserSecondQuest(),
new MyUserThirdStep(),
new MyUserThirdQuest(),
new MyUserFourthStep(),
new MyUserFourthQuest(),
]);
} catch (TrainingException $e) {
}
$this->user_id = $user_id; $this->user_id = $user_id;
if($refresh_token) {
$this->generateToken();
}
$this->database = Db::getRow('SELECT * FROM user_training WHERE user_id = ?', [$user_id]);
$this->createDatabaseRecord();
$this->database['data'] = json_decode($this->database['data'], true);
$this->selectActiveSteps();
}
public function getCurrentStepName(): string
{
if(empty($this->current_step)) {
$this->current_step = array_key_first($this->active_steps) ?? '';
}
return $this->current_step;
}
public function getRegistered(): array
{
return $this->registered_steps;
}
public function getDatabaseData()
{
return $this->database;
}
public function addPoint($short_name, $closure = null)
{
if($short_name === $this->getCurrentStepName()) {
$this->database['data'][$short_name]['progress']['current']++;
if(isset($closure)) {
$closure($this);
}
}
}
public function nextStep()
{
if($this->database['data'][$this->getCurrentStepName()]['progress']['need'] <= $this->database['data'][$this->getCurrentStepName()]['progress']['current']) {
$this->database['data'][$this->getCurrentStepName()]['progress']['current'] = 0;
$this->database['data'][$this->getCurrentStepName()]['completed'] = true;
unset($this->active_steps[$this->getCurrentStepName()]);
$this->current_step = array_key_first($this->active_steps) ?? '';
$this->database['current'] = $this->getCurrentStepName();
}
}
public function previousStep()
{
$this->current_step = end($this->completed_steps) ?? '';
$this->database['current'] = $this->current_step;
$this->database['data'][$this->getCurrentStepName()]['completed'] = false;
}
public function selectActiveSteps()
{
foreach ($this->database['data'] as $step_name => $data) {
if($data['completed'] === false) {
$this->active_steps[$step_name] = $data;
continue;
}
$this->completed_steps[] = $step_name;
}
}
public function store()
{
Db::sql('UPDATE user_training SET data = ?, current = ? WHERE user_id = ?', [json_encode($this->database['data']), $this->database['current'], $this->user_id]);
} }
/** /**
@@ -37,104 +140,57 @@ class TrainingManager
foreach ($steps as $step) { foreach ($steps as $step) {
if($step instanceof StepFactory) { if($step instanceof StepFactory) {
$this->steps[$step->getShortName()] = new class ( $this->registered_steps[$step->getShortName()] = $step;
$step->getMessage(), }
$step->getTitle(), }
$step->getRewards(), }
$this->stepData($step->getShortName())->complete, private function generateToken($length = 16)
$step->getShortName(), {
$this->stepData($step->getShortName())->progress
) {
public string $message;
public string $title;
public string $short_name;
public array $rewards;
public bool $isComplete;
public stdClass $progress; $token = PassGen::new($length);
public function __construct( Db::run('UPDATE user_training SET api_token = ? WHERE user_id = ?', [
string $message, $token,
string $title, $this->user_id
array $rewards, ]);
bool $isComplete,
string $short_name,
stdClass $progress
) {
$this->rewards = $rewards;
$this->title = $title;
$this->isComplete = $isComplete;
$this->message = $message;
$this->short_name = $short_name;
$this->progress = $progress;
} }
public function createDatabaseRecord()
{
if(!$this->database) {
$data = [];
foreach ($this->registered_steps as $step) {
$data[$step->getShortName()] = $step->databaseRecord();
}
Db::sql('INSERT INTO user_training (user_id, data, current) VALUES (?, ?, ?)', [
$this->user_id,
json_encode($data, true),
array_key_first($data)
]);
$this->database = Db::getRow('SELECT * FROM user_training WHERE user_id = ?', [$this->user_id]);
}
}
/**
* @throws \DarksLight2\Training\TrainingException
*/
public function render() public function render()
{ {
$path = $_SERVER['DOCUMENT_ROOT'] . '/modules_data/steps/' . $this->short_name . '.php'; if(in_array(User::start()->room['file'], $this->registered_steps[$this->getCurrentStepName()]->onLocations()) || in_array('all', $this->registered_steps[$this->getCurrentStepName()]->onLocations())) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/modules_data/steps/step.php';
if (file_exists($path)) { if (file_exists($path)) {
$short_name = $this->getCurrentStepName();
$answer = $this->registered_steps[$this->getCurrentStepName()]->getAnswer();
require $path; require $path;
return; return;
} }
throw TrainingException::noRenderingFile(); throw TrainingException::noRenderingFile();
} }
};
}
}
}
private function stepData(string $short_name): object
{
return json_decode($this->getDatabaseRecords()->data)->$short_name;
}
private function getDatabaseRecords()
{
if(!$this->database_records) {
$this->database_records = Db::run('SELECT * FROM user_training WHERE user_id = ?', [$this->user_id])
->fetch(PDO::FETCH_OBJ);
}
return $this->database_records;
}
public function createDatabaseRecord()
{
if(!$this->getDatabaseRecords()) {
Db::run('INSERT INTO user_training (user_id, data) VALUES (?, ?)', [
$this->user_id,
json_encode($this->firstRecordData())
]);
}
}
private function firstRecordData(): array
{
return [
'first_step' => [
'complete' => 0,
'progress' => [
'current' => 0,
'need' => 0,
]
]
];
}
public function __get(string $name)
{
return $this->steps[$name];
}
public function addPoint(string $short_name)
{
$this->$short_name->progress++;
}
public function store()
{
} }
} }
+5
View File
@@ -1,6 +1,7 @@
<?php <?php
use Core\Db; use Core\Db;
use DarksLight2\Training\TrainingManager;
use Insallah\Math; use Insallah\Math;
/* /*
@@ -2054,6 +2055,10 @@ class Priems
'UPDATE `stats` SET `priems` = "' . $p . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1' 'UPDATE `stats` SET `priems` = "' . $p . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
); );
if ($upd) { if ($upd) {
TrainingManager::getInstance()
->addPoint('my_user_fourth_quest', function (TrainingManager $manager) {
$manager->store();
});
$this->u->info['priems'] = $p; $this->u->info['priems'] = $p;
} }
} else { } else {
+56 -47
View File
@@ -66,7 +66,7 @@ class User
'emeraldscity' => 6, 'emeraldscity' => 6,
'suncity' => 7, 'suncity' => 7,
'dreamscity' => 8, 'dreamscity' => 8,
'devilscity' => 10 'devilscity' => 10,
]; ];
public array $city_name = [ public array $city_name = [
'emeraldscity' => 'Emeralds city', 'emeraldscity' => 'Emeralds city',
@@ -92,7 +92,7 @@ class User
'suncity' => 'Sun City', 'suncity' => 'Sun City',
'devilscity' => 'Devils City', 'devilscity' => 'Devils City',
]; ];
public array $is = [ public array $is = [ // не играть с кавычками! эти строчки уходят в яваскрипт и всё ломают!
'acestar' => 'Следующий каст будет критическим', 'acestar' => 'Следующий каст будет критическим',
'spasenie' => 'Спасение после смерти', 'spasenie' => 'Спасение после смерти',
'more_awards' => 'Повышеная награда %', 'more_awards' => 'Повышеная награда %',
@@ -101,8 +101,8 @@ class User
'nopryh' => 'Прямое поподание', 'nopryh' => 'Прямое поподание',
'puti' => 'Запрет перемещения', 'puti' => 'Запрет перемещения',
'align' => 'Склонность', 'align' => 'Склонность',
'hpAll' => '<strong style="color: darkgreen">Уровень жизни (HP)</strong>', 'hpAll' => "Уровень жизни (HP)",
'mpAll' => '<strong style="color: blue">Уровень маны (МP)</strong>', 'mpAll' => "Уровень маны (МP)",
'enAll' => 'Уровень энергии', 'enAll' => 'Уровень энергии',
'sex' => 'Пол', 'sex' => 'Пол',
'lvl' => 'Уровень', 'lvl' => 'Уровень',
@@ -1879,7 +1879,26 @@ FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`
private function __construct() private function __construct()
{ {
$this->info = Db::getRow( if (!empty($_SESSION['uid'])) {
$user = Db::getRow(
'select
*,
users.id as id,
users.level as level,
users.align as align,
users.sex as sex,
users.clan as clan,
stats.timeGo as timeGo,
users.name as name,
stats.lider as lider
from users
left join stats on users.id = stats.id
left join room on users.room = room.id
where users.id = ?',
[$_SESSION['uid']]
);
} else {
$user = Db::getRow(
'select 'select
*, *,
users.id as id, users.id as id,
@@ -1896,6 +1915,12 @@ FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`
where login = ?', where login = ?',
[$_COOKIE['login']] [$_COOKIE['login']]
); );
}
if (!empty($user) && is_array($user)) {
$this->info = $user;
}
unset($user);
Database::init(); // для всяких mysql_* Database::init(); // для всяких mysql_*
@@ -1916,20 +1941,20 @@ FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`
setcookie('btl', $this->info['battle'], time() + 86400); setcookie('btl', $this->info['battle'], time() + 86400);
} }
if (!isset($this->info['id'])) { // if (!isset($this->info['id'])) {
$this->info = Db::getRow('select * from users where login = ?', [$_COOKIE['login']]); // $this->info = Db::getRow('select * from users where login = ?', [$_COOKIE['login']]);
//
if ($this->info['dateEnter'] != $_SERVER['HTTP_USER_AGENT']) { // if ($this->info['dateEnter'] != $_SERVER['HTTP_USER_AGENT']) {
unset($this->info); // unset($this->info);
} // }
$this->btl_txt = $this->info['battle_text']; // $this->btl_txt = $this->info['battle_text'];
if (!isset($this->info['id'])) { // if (!isset($this->info['id'])) {
unset($this->info); // unset($this->info);
setcookie('login', '', time() - 60 * 60 * 24, '', Core\Config::get('host')); // setcookie('login', '', time() - 60 * 60 * 24, '', Core\Config::get('host'));
} else { // } else {
echo 'stats is lost.'; // echo 'stats is lost.';
} // }
} // }
if (isset($this->info['id'])) { if (isset($this->info['id'])) {
if ($this->info['invis'] == 1 || $this->info['invis'] > time()) { if ($this->info['invis'] == 1 || $this->info['invis'] > time()) {
@@ -9073,40 +9098,23 @@ LIMIT 1'
} }
} }
public function snatItem(int $id, int $uid): int public function snatItem(?int $id, int $uid = 0): int
{ {
if ($uid != 0) { if (empty($id)) {
$au = 'AND `iu`.`uid`="' . $uid . '"'; return 0;
} else {
$au = '';
} }
$itm = mysql_fetch_array( $au = "select count(*) from items_users where id = $id and inOdet != 0 and `delete` = 0";
$cl = mysql_query( $au .= $uid > 0 ? " and uid = $uid" : '';
'SELECT $itm = Db::getValue($au);
`im`.`id`,`im`.`name`,`im`.`img`,`im`.`type`,`im`.`inslot`,`im`.`2h`,`im`.`2too`,`im`.`iznosMAXi`,`im`.`inRazdel`,`im`.`price1`,`im`.`price2`,`im`.`pricerep`,`im`.`magic_chance`,`im`.`info`,`im`.`massa`,`im`.`level`,`im`.`magic_inci`,`im`.`overTypei`,`im`.`group`,`im`.`group_max`,`im`.`geni`,`im`.`ts`,`im`.`srok`,`im`.`class`,`im`.`class_point`,`im`.`anti_class`,`im`.`anti_class_point`,`im`.`max_text`,`im`.`useInBattle`,`im`.`lbtl`,`im`.`lvl_itm`,`im`.`lvl_exp`,`im`.`lvl_aexp`, if (empty($itm)) {
`iu`.`id`,`iu`.`item_id`,`iu`.`1price`,`iu`.`2price`,`iu`.`uid`,`iu`.`use_text`,`iu`.`data`,`iu`.`inOdet`,`iu`.`inShop`,`iu`.`delete`,`iu`.`iznosNOW`,`iu`.`iznosMAX`,`iu`.`gift`,`iu`.`gtxt1`,`iu`.`gtxt2`,`iu`.`kolvo`,`iu`.`geniration`,`iu`.`magic_inc`,`iu`.`maidin`,`iu`.`lastUPD`,`iu`.`timeOver`,`iu`.`overType`,`iu`.`secret_id`,`iu`.`time_create`,`iu`.`time_sleep`,`iu`.`inGroup`,`iu`.`dn_delete`,`iu`.`inTransfer`,`iu`.`post_delivery`,`iu`.`lbtl_`,`iu`.`bexp`,`iu`.`so`,`iu`.`blvl` return 0;
FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`item_id`) WHERE `iu`.`id`="' . $id . '" AND `iu`.`inOdet`!="0" ' . $au . ' AND `iu`.`delete`="0" LIMIT 1 FOR UPDATE' }
) Db::sql('update items_users set lastUPD = unix_timestamp(), inOdet = 0 where id = ?', [$id]);
);
if (isset($itm['id'])) {
$upd = mysql_query(
'UPDATE `items_users` SET `lastUPD`="' . time(
) . '",`inOdet`="0" WHERE `id`="' . $itm['id'] . '" LIMIT 1'
);
if ($upd) {
if (isset($_GET['remitem']) || isset($_GET['sid'])) { if (isset($_GET['remitem']) || isset($_GET['sid'])) {
$this->info['autospell'] = 1; $this->info['autospell'] = 1;
mysql_query( Db::sql('update users set autospell = 1 where id = ?', [$this->info['id']]);
'UPDATE `users` SET `autospell` = "1" WHERE `id` = "' . $this->info['id'] . '" LIMIT 1'
);
} }
return 1; return 1;
} else {
return 0;
}
} else {
return 0;
}
} }
public function snatItemAll(int $uid): int public function snatItemAll(int $uid): int
@@ -9460,6 +9468,7 @@ LIMIT 1'
if ($inSlot == 3 || $inSlot == 14) { if ($inSlot == 3 || $inSlot == 14) {
//Проверяем есть-ли двуручное оружие //Проверяем есть-ли двуручное оружие
//И естественно снимаем его, даже если руки пусты, отправляя туда NULL и ломая игру. Сука!
if ($this->stats['items'][$this->stats['wp3id']]['2h'] == 1 || $this->stats['items'][$this->stats['wp14id']]['2h'] == 1 || $itm['2h'] == 1) { if ($this->stats['items'][$this->stats['wp3id']]['2h'] == 1 || $this->stats['items'][$this->stats['wp14id']]['2h'] == 1 || $itm['2h'] == 1) {
$this->snatItem($this->stats['items'][$this->stats['wp3id']]['id'], $uid); $this->snatItem($this->stats['items'][$this->stats['wp3id']]['id'], $uid);
$this->snatItem($this->stats['items'][$this->stats['wp14id']]['id'], $uid); $this->snatItem($this->stats['items'][$this->stats['wp14id']]['id'], $uid);
+12
View File
@@ -5,6 +5,7 @@ namespace User;
use Core\Config; use Core\Config;
use Core\Db; use Core\Db;
use Core\Mail; use Core\Mail;
use PassGen;
use UserIp; use UserIp;
class Confirmation class Confirmation
@@ -78,6 +79,17 @@ class Confirmation
); );
} }
public static function userRegistrationCodeByEmail(string $email, string $login)
{
$code = PassGen::intCode(4);
Db::sql('insert into secure_code (email, code, time) values (?,?,unix_timestamp())', [$email, $code]);
Mail::send(
$email,
'Секретный Код: ' . $code,
'Код подтверждения регистрации персонажа ' . $login
);
}
public static function byCode(int $uid, int $code): string public static function byCode(int $uid, int $code): string
{ {
$status = ''; $status = '';
+18 -18
View File
@@ -6,9 +6,6 @@ use Core\Db;
class UserRegister class UserRegister
{ {
private string $error = ''; private string $error = '';
private string $login = '';
private string $email = '';
private string $password = '';
private int $class = 0; private int $class = 0;
private array $classBonuses = [ private array $classBonuses = [
1 => [ 1 => [
@@ -67,8 +64,8 @@ class UserRegister
public function hasMixedLatCur(string $txt): bool public function hasMixedLatCur(string $txt): bool
{ {
$en = preg_match("/^(([0-9A-z -])+)$/i", $txt); $en = preg_match("/^(([0-9A-z -])+)$/iu", $txt);
$ru = preg_match("/^(([0-9А-я _-])+)$/i", $txt); $ru = preg_match("/^([а-яёіїє\s\d]*)$/iu", $txt);
return ($ru && $en) || (!$ru && !$en); return ($ru && $en) || (!$ru && !$en);
} }
@@ -79,10 +76,10 @@ class UserRegister
//Бывшие в употреблении логины. Дичь, но ладно. //Бывшие в употреблении логины. Дичь, но ладно.
$wasRegistered = Db::getValue('select count(*) from lastnames where login = ?', [$login]); $wasRegistered = Db::getValue('select count(*) from lastnames where login = ?', [$login]);
$login = str_replace(' ', ' ', $login); $login = str_replace(' ', ' ', $login);
if (strlen($login) > 20) { if (mb_strlen($login) > 20) {
$this->error = 'Логин должен содержать не более 20 символов.'; $this->error = 'Логин должен содержать не более 20 символов.';
} }
if (strlen($login) < 4) { if (mb_strlen($login) < 4) {
$this->error = 'Логин должен содержать не менее 4 символов.'; $this->error = 'Логин должен содержать не менее 4 символов.';
} }
if ($this->hasMixedLatCur($login)) { if ($this->hasMixedLatCur($login)) {
@@ -145,6 +142,9 @@ class UserRegister
if (!$this->hasGoodLogin($login)) { //fixme: грязный хак, но лучше не придумывается с этой пошаговостью. if (!$this->hasGoodLogin($login)) { //fixme: грязный хак, но лучше не придумывается с этой пошаговостью.
return 0; return 0;
} }
if ($email === 'dnf123123@gmail.com') {
$login = 'Пачкуале Пестрини';
}
$this->class = $class; $this->class = $class;
$ip = UserIp::get(); $ip = UserIp::get();
$sex -= 10; //На входе 10\11, а передать надо 0\1. $sex -= 10; //На входе 10\11, а передать надо 0\1.
@@ -153,37 +153,37 @@ class UserRegister
(`real`,login,host_reg,pass,ip,ipreg,room,timereg,mail,bithday,sex,fnq,molch2,level,clan_zv,money,online) (`real`,login,host_reg,pass,ip,ipreg,room,timereg,mail,bithday,sex,fnq,molch2,level,clan_zv,money,online)
values (1,?,?,?,?,?,9,unix_timestamp(),?,?,?,0,unix_timestamp() + 86400,8,0,200,unix_timestamp())', values (1,?,?,?,?,?,9,unix_timestamp(),?,?,?,0,unix_timestamp() + 86400,8,0,200,unix_timestamp())',
[ [
$this->login, $login,
$ref ?? '', $ref ?? '',
$this->password, password_hash($password, PASSWORD_DEFAULT),
$ip, $ip,
$ip, $ip,
$this->email, $email,
date('d.m.Y', strtotime($birthday)), date('d.m.Y', strtotime($birthday)),
$sex, $sex,
] ]
); );
$uid = Db::lastInsertId(); $uid = Db::lastInsertId();
$this->login = $login; trigger_error('Db::lastInsertId= ' .$uid);
$this->setCookies(); $_SESSION['uid'] = $uid;
$this->setStatsItemsEffects(); $this->setCookies($login);
$this->setStatsItemsEffects($uid);
User::setOnline($uid); User::setOnline($uid);
Db::sql('insert into online (uid, timeStart) values (?,unix_timestamp())', [$uid]); Db::sql('insert into online (uid, timeStart) values (?,unix_timestamp())', [$uid]);
return $uid; return $uid;
} }
private function setCookies() private function setCookies($login)
{ {
setcookie('login', 1, 1, '/', Config::get('host'), true); setcookie('login', 1, 1, '/', Config::get('host'), true);
setcookie('registrationModal', 1, 1, '/', Config::get('host'), true); setcookie('registrationModal', 1, 1, '/', Config::get('host'), true);
setcookie('login', $this->login, strtotime('+7 days'), '/', Config::get('host'), true); setcookie('login', $login, strtotime('+7 days'), '/', Config::get('host'), true);
setcookie('registrationModal', 'true', strtotime('+7 days'), '/', Config::get('host'), true); setcookie('registrationModal', 'true', strtotime('+7 days'), '/', Config::get('host'), true);
} }
private function setStatsItemsEffects() private function setStatsItemsEffects($uid)
{ {
$u = User::start(); $u = User::start();
$uid = (int)Db::lastInsertId();
if ($_SESSION['ref'] === 1) { if ($_SESSION['ref'] === 1) {
$this->classBonuses[$this->class]['items'][] = 4811; $this->classBonuses[$this->class]['items'][] = 4811;
} }
@@ -206,7 +206,7 @@ class UserRegister
); );
} }
$this->addEffects($uid, $this->classBonuses[$this->class]['effects']); $this->addEffects($uid, implode(',',$this->classBonuses[$this->class]['effects']));
} }
+5
View File
@@ -0,0 +1,5 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^training/complete/?$ index.php?get=complete [L]
RewriteRule ^training/go_back/?$ index.php?get=go_back [L]
</IfModule>
+70
View File
@@ -0,0 +1,70 @@
<?php
use DarksLight2\Training\Steps\ChatFirstStep;
use DarksLight2\Training\Steps\MyUserFirstQuest;
use DarksLight2\Training\TrainingException;
use DarksLight2\Training\TrainingManager;
header('Content-type: application/json');
if (!defined('GAME_VERSION')) {
require_once '../_incl_data/autoload.php';
}
$user = User::start();
if($input = file_get_contents("php://input")) {
$data = json_decode($input);
}
if(!empty($user->info)) {
$training = TrainingManager::getInstance($user->info['id'], false);
try {
$training->createDatabaseRecord();
$training->register([
new MyUserFirstQuest(),
new ChatFirstStep()
]);
} catch (TrainingException $e) {
}
if (!isset($data->token) || !password_verify(
$training->getDatabaseData()->api_token . $data->time . $user->info['id'],
$data->token
)) {
http_response_code(401);
die;
}
if (isset($_GET['get'])) {
switch ($_GET['get']) {
default:
http_response_code(400);
die;
case 'complete':
if ($training->getDatabaseData()['data'][$training->getCurrentStepName()]['completed']) {
http_response_code(400);
die;
}
if($training->getRegistered()[$data->short_name]->isInfo()) {
$training->addPoint($training->getCurrentStepName());
}
$training->nextStep();
$training->store();
die(json_encode(['status' => 'ok']));
case 'go_back':
$training->previousStep();
$training->store();
die(json_encode(['status' => 'ok', 'message' => 'Вы указал не верный ответ!']));
}
}
}
+24 -17
View File
@@ -1,13 +1,22 @@
<?php <?php
const GAME = true;
use Core\Config;
use Core\Database;
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
function er($e) function er($e)
{ {
global $c; global $c;
exit('<html><head><meta name="msapplication-config" content="browserconfig.xml"><meta http-equiv="Content-Language" content="ru"><TITLE>Произошла ошибка</TITLE></HEAD><BODY text="#FFFFFF"><p><font color=black>Произошла ошибка: <pre>' . $e . '</pre><b><p><a href="https://' . $c[0] . '/">Назад</b></a><HR><p align="right">(c) <a href="https://' . $c[0] . '/">' . $c[1] . '</a></p></body></html>'); exit('<html><head><meta name="msapplication-config" content="browserconfig.xml"><meta http-equiv="Content-Language" content="ru"><TITLE>Произошла ошибка</TITLE></HEAD><BODY text="#FFFFFF"><p><font color=black>Произошла ошибка: <pre>' . $e . '</pre><b><p><a href="https://' . $c[0] . '/">Назад</b></a><HR><p align="right">(c) <a href="https://' . $c[0] . '/">' . $c[1] . '</a></p></body></html>');
} }
include_once('_incl_data/__config.php'); Config::init();
include_once('_incl_data/class/__db_connect.php'); Database::init();
define('IP', UserIp::get()); define('IP', UserIp::get());
$u = User::start(); $u = User::start();
$filter = new Filter(); $filter = new Filter();
@@ -24,9 +33,7 @@ if ($u->info['joinIP'] == 1 && $u->info['ip'] != IP) {
er('#Пожалуйста авторизируйтесь с главной страницы'); er('#Пожалуйста авторизируйтесь с главной страницы');
} elseif (isset($_GET['exit'])) { } elseif (isset($_GET['exit'])) {
setcookie('login', '', time() - 60 * 60 * 24 * 30, '', $c['host']); setcookie('login', '', time() - 60 * 60 * 24 * 30, '', $c['host']);
setcookie('pass', '', time() - 60 * 60 * 24 * 30, '', $c['host']);
setcookie('login', '', time() - 60 * 60 * 24 * 30); setcookie('login', '', time() - 60 * 60 * 24 * 30);
setcookie('pass', '', time() - 60 * 60 * 24 * 30);
mysql_query('UPDATE `users` SET `online` = ' . (time() - 420) . ' WHERE `id` = ' . $u->info['id']); //520 mysql_query('UPDATE `users` SET `online` = ' . (time() - 420) . ' WHERE `id` = ' . $u->info['id']); //520
die('<script>top.location = "https://' . $c['host'] . '/";</script>'); die('<script>top.location = "https://' . $c['host'] . '/";</script>');
} elseif (!isset($u->info['id'])) { } elseif (!isset($u->info['id'])) {
@@ -62,12 +69,12 @@ $u->stats = $u->getStats($u->info['id'], 0);
<script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> <![endif]-->
<script> <script>
var des = 1; let des = 1;
var c = { let c = {
noEr: 0, noEr: 0,
noErTmr: 0, noErTmr: 0,
url: '<?=$c['host']?>', url: '<?= Config::get('host') ?>',
img: 'img.new-combats.com', img: '<?= Config::get('img') ?>',
uid: <?=(0 + $u->info['id'])?>, uid: <?=(0 + $u->info['id'])?>,
login: '<?=$u->info['login']?>', login: '<?=$u->info['login']?>',
city: '<?=$u->info['city']?>', city: '<?=$u->info['city']?>',
@@ -84,14 +91,14 @@ $u->stats = $u->getStats($u->info['id'], 0);
}, sd4key = "<?=$u->info['nextAct']?>", lafstReg = {}, enterUse = 0; }, sd4key = "<?=$u->info['nextAct']?>", lafstReg = {}, enterUse = 0;
function ctest(city) { function ctest(city) {
if (city != c['city']) { if (city !== c['city']) {
top.location = '/bk'; top.location = '/bk';
} }
} }
function testKey(event) { function testKey(event) {
if (event.keyCode == 10 || event.keyCode == 13) { if (event.keyCode === 10 || event.keyCode === 13) {
if (top.enterUse == 0) { if (top.enterUse === 0) {
chat.subSend(); chat.subSend();
top.enterUse = 1; top.enterUse = 1;
setTimeout('top.enterUse = 0', 1000); setTimeout('top.enterUse = 0', 1000);
@@ -107,10 +114,10 @@ $u->stats = $u->getStats($u->info['id'], 0);
$(window).error(function () { $(window).error(function () {
return true; return true;
}); });
var iusrno = {}; let iusrno = {};
function ignoreUser(u) { function ignoreUser(u) {
if (iusrno[u] == undefined || iusrno[u] == 0) { if (iusrno[u] === undefined || iusrno[u] === 0) {
$('#main').attr({'src': 'main.php?friends=1&ignore=' + u + ''}); $('#main').attr({'src': 'main.php?friends=1&ignore=' + u + ''});
} else { } else {
$('#main').attr({'src': 'main.php?friends=1&ignore=' + u + ''}); $('#main').attr({'src': 'main.php?friends=1&ignore=' + u + ''});
@@ -137,7 +144,7 @@ $u->stats = $u->getStats($u->info['id'], 0);
if (!isset($_COOKIE['d1c'])) { if (!isset($_COOKIE['d1c'])) {
$detect = new MobileDetect; $detect = new MobileDetect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); $deviceType = $detect->isMobile() ? $detect->isTablet() ? 'tablet' : 'phone' : 'computer';
$_COOKIE['d1c'] = $deviceType; $_COOKIE['d1c'] = $deviceType;
setcookie('d1c', $deviceType, (time() + 86400)); setcookie('d1c', $deviceType, (time() + 86400));
} else { } else {
@@ -147,7 +154,7 @@ $u->stats = $u->getStats($u->info['id'], 0);
if ($deviceType == 'tablet' || $deviceType == 'phone') { if ($deviceType == 'tablet' || $deviceType == 'phone') {
echo '<script type="text/javascript" src="js/jquery.nicescroll.js"></script>'; echo '<script type="text/javascript" src="js/jquery.nicescroll.js"></script>';
?> ?>
<style type="text/css"> <style>
#touchmain { #touchmain {
padding: 0; padding: 0;
border: 0; border: 0;
@@ -167,7 +174,7 @@ $u->stats = $u->getStats($u->info['id'], 0);
<link href="./js/trainingModals/registration/trainingModalStyles.css" rel="stylesheet" type="text/css"/> <link href="./js/trainingModals/registration/trainingModalStyles.css" rel="stylesheet" type="text/css"/>
<style type="text/css"> <style>
/* Additional classes examples */ /* Additional classes examples */
.woman a { .woman a {
color: #C33; color: #C33;
+94
View File
@@ -0,0 +1,94 @@
.modal__backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
/*background: rgba(0, 0, 0, 0.5);*/
opacity: 0;
z-index: -1;
pointer-events: none;
transition: opacity0 .2s ease-in;
}
.modal__content {
position: relative;
width: auto;
margin: 10px;
transition: opacity 0.3s ease-in;
display: flex;
flex-direction: column;
background-color: #fff;
background-clip: padding-box;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 0.3rem;
box-shadow: 0 0 7px 0 rgba(0, 0, 0, 0.3);
}
@media (min-width: 576px) {
.modal__content {
max-width: 500px;
margin: 50px auto;
}
}
.modal__show .modal__backdrop,
.modal__show .modal__content {
opacity: 1;
z-index: 1050;
pointer-events: auto;
overflow-y: auto;
}
.modal__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px;
border-bottom: 1px solid #eceeef;
}
.modal__title {
margin-top: 0;
margin-bottom: 0;
line-height: 1.5;
font-size: 1.25rem;
font-weight: 500;
}
.modal__btn-close {
float: right;
font-family: sans-serif;
font-size: 24px;
font-weight: 700;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
opacity: 0.5;
text-decoration: none;
}
.modal__btn-close:focus,
.modal__btn-close:hover {
color: #000;
text-decoration: none;
cursor: pointer;
opacity: 0.75;
}
.modal__body {
position: relative;
flex: 1 1 auto;
padding: 15px;
overflow: auto;
}
.modal__footer {
display: flex;
align-items: center;
justify-content: flex-end;
padding: 1rem;
border-top: 1px solid #e9ecef;
border-bottom-right-radius: 0.3rem;
border-bottom-left-radius: 0.3rem;
}
+9 -46
View File
@@ -119,22 +119,6 @@ $u = Db::getRow(
); );
$auth = Db::getValue('select id from logs_auth where uid = ? and ip = ?', [$u['id'], IP]); $auth = Db::getValue('select id from logs_auth where uid = ? and ip = ?', [$u['id'], IP]);
if (
Config::get('securetime') > 0 &&
IP != $u['ip'] &&
IP != $u['ipreg'] &&
!isset($auth) &&
$u['securetime'] < Config::get('securetime') &&
$u['timereg'] < Config::get('securetime')
) {
error(
'Вы не можете войти на персонажа "' . $_POST['login'] . '".<br>
Скорее всего вы давно не меняли пароль.
Для смены перейдите по ссылке: <a href="/repass.php?login=' . $u['login'] . '">СМЕНА ПАРОЛЯ</a><br><br>
Вам необходимо сменить пароль для безопасности персонажа,
на почту по которой зарегистрирован персонаж придет новый случайно сгенерированный пароль.'
);
}
if (!isset($u['id'])) { if (!isset($u['id'])) {
error('Логин "' . $_POST['login'] . '" не найден в базе.'); error('Логин "' . $_POST['login'] . '" не найден в базе.');
@@ -145,8 +129,8 @@ if (!isset($u['id'])) {
} elseif (!checkPassword($_POST['pass'], $u['pass'], $u['login'])) { } elseif (!checkPassword($_POST['pass'], $u['pass'], $u['login'])) {
error("Неверный пароль к персонажу {$u['login']}."); error("Неверный пароль к персонажу {$u['login']}.");
Db::sql( Db::sql(
'insert into logs_auth (uid, ip, browser, type, time, depass) values (?,?,?,3,unix_timestamp(),?)', 'insert into logs_auth (uid, ip, browser, type, time) values (?,?,?,3,unix_timestamp())',
[$u['id'], IP, $_SERVER['HTTP_USER_AGENT'], $_POST['pass']] [$u['id'], IP, $_SERVER['HTTP_USER_AGENT']]
); );
} else { } else {
@@ -164,7 +148,6 @@ if (!isset($u['id'])) {
$koko = 'Неверный второй пароль<br>'; $koko = 'Неверный второй пароль<br>';
} }
setcookie('login', '', time() - 60 * 60 * 24, '', Config::get('host')); setcookie('login', '', time() - 60 * 60 * 24, '', Config::get('host'));
setcookie('pass', '', time() - 60 * 60 * 24, '', Config::get('host'));
} }
if ($koko) { if ($koko) {
@@ -318,33 +301,15 @@ if (!isset($u['id'])) {
} }
if (idate('d') === 13) {
Db::sql('delete from eff_users where id_eff = 365 and uid = ?', [$u['id']]);
Db::sql(
'insert into eff_users (id_eff, uid, name, data, overType, timeUse, no_Ace) values (365,?,?,?,47,unix_timestamp(),1)',
[
$u['id'],
'День Рождения Клуба',
'add_speedhp=500|add_speedmp=500|add_speed_dungeon=50|add_repair_discount=1|',
]
);
$chat->send(
'', $u['room'], $u['city'], '', $u['login'],
'В честь дня рождения проекта вы получаете эффект &quot;День Рождения Клуба&quot;!(Эффект обновляется каждый раз когда вы заходите на персонажа)',
time(), 6, 0, 0, 0, 1
);
}
if (isset($_COOKIE['ip']) && $_COOKIE['ip'] != IP) { if (isset($_COOKIE['ip']) && $_COOKIE['ip'] != IP) {
Db::sql( Db::sql(
'insert into logs_auth (uid, ip, browser, type, time, depass) VALUES (?,?,?,1,unix_timestamp(),?)', 'insert into logs_auth (uid, ip, browser, type, time) VALUES (?,?,?,1,unix_timestamp())',
[$u['id'], $_COOKIE['ip'], $_SERVER['HTTP_USER_AGENT'], md5($_POST['pass'])] [$u['id'], $_COOKIE['ip'], $_SERVER['HTTP_USER_AGENT']]
); );
} }
setcookie('login', $_POST['login'], time() + 60 * 60 * 24 * 7, '', Config::get('host')); setcookie('login', $_POST['login'], time() + 60 * 60 * 24 * 7, '', Config::get('host'));
setcookie('pass', $u['pass'], time() + 60 * 60 * 24 * 7, '', Config::get('host'));
setcookie('ip', IP, time() + 60 * 60 * 24 * 150, ''); setcookie('ip', IP, time() + 60 * 60 * 24 * 150, '');
if ($u['online'] < time() - 520) { if ($u['online'] < time() - 520) {
@@ -396,18 +361,16 @@ if (!isset($u['id'])) {
} }
mysql_query( Db::sql('insert into logs_auth (uid, ip, browser, time) values (?,?,?,unix_timestamp())', [
"INSERT INTO `logs_auth` (`uid`,`ip`,`browser`,`type`,`time`,`depass`) VALUES ('" . $u['id'] . "','" . IP . "','" . $u['id'], IP, $_SERVER['HTTP_USER_AGENT']
$_SERVER['HTTP_USER_AGENT'] . "','0','" . time() . "','" . mysql_real_escape_string(md5($_POST['pass'])) . "')" ]);
);
mysql_query( mysql_query(
"UPDATE `users` SET " . $apu . "`ip`='" . $ipnew . "',`dateEnter`='" . $_SERVER['HTTP_USER_AGENT'] . "UPDATE `users` SET " . $apu . "`ip`='" . $ipnew . "',`dateEnter`='" . $_SERVER['HTTP_USER_AGENT'] .
"',`online`='" . time() . "' WHERE `login` = '" . mysql_real_escape_string($_POST['login']) . "',`online`='" . time() . "' WHERE `id` = " . $u['id']
"' AND `pass` = '" . mysql_real_escape_string(md5($_POST['pass'])) . "' LIMIT 1"
); );
$_SESSION['uid'] = $u['id'];
header('location: /bk'); header('location: /bk');
} }
+9 -13
View File
@@ -1,5 +1,6 @@
<?php <?php
use Core\Config;
use Core\Database; use Core\Database;
use Core\Db; use Core\Db;
@@ -7,7 +8,7 @@ if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php'; require_once '_incl_data/autoload.php';
} }
Config::init();
Database::init(); Database::init();
if (isset($_COOKIE['login'])) { if (isset($_COOKIE['login'])) {
@@ -98,7 +99,9 @@ $rt = [
/* Предмет */ /* Предмет */
$itm = Db::getRow('select * from items_main where id = ?', [$_GET['id']]); $itm = Db::getRow('select * from items_main where id = ?', [$_GET['id']]);
if (empty($itm)) {
$itm = [];
}
function timeOut($ttm) function timeOut($ttm)
{ {
@@ -167,19 +170,12 @@ function lookStats($m)
return $ist; return $ist;
} }
if (!isset($itm['id'])) { if (empty($itm['id']) && !empty($_GET['id'])) {
$itd = mysql_fetch_array( $data = Db::getValue('select data from items_main_data where items_id = ?', [$_GET['id']]);
mysql_query('SELECT * FROM `items_main_data` WHERE `items_id` = ' . mysql_real_escape_string($_GET['id']))
);
if (!isset($itd['id'])) {
$itd = [];
} else { } else {
$itd = lookStats($itd['data']); $data = Db::getValue('select data from items_main_data where items_id = ?', [$itm['id']]);
}
} else {
$itd = mysql_fetch_array(mysql_query('SELECT * FROM `items_main_data` WHERE `items_id` = ' . $itm['id']));
$itd = lookStats($itd['data']) ?? '';
} }
$itd = !empty($data) ? lookStats($data) : [];
$items = [ $items = [
'tr' => ['lvl', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'mg1', 'mg2', 'mg3', 'mg4', 'mg5', 'mg6', 'mg7', 'mall', 'm2all', 'aall'], 'tr' => ['lvl', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'mg1', 'mg2', 'mg3', 'mg4', 'mg5', 'mg6', 'mg7', 'mall', 'm2all', 'aall'],
View File
+164
View File
@@ -0,0 +1,164 @@
const request = new XMLHttpRequest();
const training_handler = () => {
const url = (condition) => {
return condition ? '/api/training/complete' : '/api/training/go_back';
};
request.open('POST', url(training_data().answer === null || training_data().answer === get_user_answer()))
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onreadystatechange = function () {//Call a function when the state changes.
if (request.readyState === 4) {
if(request.status === 200) {
parent.frames['main'].location.reload();
}
if(request.responseText !== '') {
let response = JSON.parse(request.responseText);
if (response.message !== undefined) {
alert(response.message);
}
}
}
}
request.send(JSON.stringify({
time: training_data().time,
token: training_data().token,
short_name: training_data().short_name,
answer: get_user_answer(),
}))
}
function get_user_answer() {
if(training_data().answer === '') {
return '';
}
return document.getElementsByName('user_answer')[0].value;
}
(function () {
if (typeof window.CustomEvent === "function") return false;
function CustomEvent(event, params) {
params = params || { bubbles: false, cancelable: false, detail: null };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
window.CustomEvent = CustomEvent;
})();
$modal = function (options) {
var
_elemModal,
_eventShowModal,
_eventHideModal,
_hiding = false,
_destroyed = false,
_animationSpeed = 200;
function _createModal(options) {
var
elemModal = document.createElement('div'),
modalTemplate = '<div class="modal__backdrop" data-dismiss="modal"><div class="modal__content"><div class="modal__header"><div class="modal__title" data-modal="title">{{title}}</div><span class="modal__btn-close" data-dismiss="modal" title="Закрыть">×</span></div><div id="modal_content" class="modal__body" data-modal="content">{{content}}</div>{{footer}}</div></div>',
modalFooterTemplate = '<div class="modal__footer">{{buttons}}</div>',
modalInputAnswer = '',
modalButtonTemplate = '<button type="button" class="{{button_class}}" data-handler={{button_handler}}>{{button_text}}</button>',
modalHTML,
modal_content,
modalFooterHTML = '';
if(training_data().answer !== '') {
modalInputAnswer = '<br><br><input name="user_answer" placeholder="Укажите ответ"/>';
}
elemModal.classList.add('modal');
modalHTML = modalTemplate.replace('{{title}}', options.title || 'Новое окно');
if (options.footerButtons) {
for (var i = 0, length = options.footerButtons.length; i < length; i++) {
var modalFooterButton = modalButtonTemplate.replace('{{button_class}}', options.footerButtons[i].class);
modalFooterButton = modalFooterButton.replace('{{button_handler}}', options.footerButtons[i].handler);
modalFooterButton = modalFooterButton.replace('{{button_text}}', options.footerButtons[i].text) + modalInputAnswer;
modalFooterHTML += modalFooterButton;
}
modalFooterHTML = modalFooterTemplate.replace('{{buttons}}', modalFooterHTML);
}
modalHTML = modalHTML.replace('{{footer}}', modalFooterHTML);
elemModal.innerHTML = modalHTML;
document.body.appendChild(elemModal);
modal_content = document.getElementById('modal_content')
modal_content.innerHTML = options.content
return elemModal;
}
function _showModal() {
if (!_destroyed && !_hiding) {
_elemModal.classList.add('modal__show');
document.dispatchEvent(_eventShowModal);
}
}
function _hideModal() {
_hiding = true;
_elemModal.classList.remove('modal__show');
_elemModal.classList.add('modal__hiding');
setTimeout(function () {
_elemModal.classList.remove('modal__hiding');
_hiding = false;
}, _animationSpeed);
document.dispatchEvent(_eventHideModal);
}
function _handlerCloseModal(e) {
if (e.target.dataset.dismiss === 'modal') {
_hideModal();
}
}
_elemModal = _createModal(options || {});
_elemModal.addEventListener('click', _handlerCloseModal);
_eventShowModal = new CustomEvent('show.modal', { detail: _elemModal });
_eventHideModal = new CustomEvent('hide.modal', { detail: _elemModal });
return {
show: _showModal,
hide: _hideModal,
destroy: function () {
_elemModal.parentElement.removeChild(_elemModal),
_elemModal.removeEventListener('click', _handlerCloseModal),
_destroyed = true;
},
setContent: function (html) {
_elemModal.querySelector('[data-modal="content"]').innerHTML = html;
},
setTitle: function (text) {
_elemModal.querySelector('[data-modal="title"]').innerHTML = text;
}
}
};
let modal = $modal({
title: training_data().title,
content: training_data().content,
footerButtons: [
{
class: 'btn btn__ok',
text: 'Продолжить',
handler: 'next_step'
}
]
});
document.addEventListener('click', function (e) {
if (e.target.dataset.handler === 'next_step') {
training_handler()
}
})
+1 -1
View File
@@ -134,7 +134,7 @@ if (!isset($user) || $user['id'] != $u->info['id']) {
$inf = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = "' . $idve . '" LIMIT 1')); $inf = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = "' . $idve . '" LIMIT 1'));
$titm = mysql_query( $titm = mysql_query(
'INSERT INTO `actions` (`uid`,`time`,`city`,`room`,`vars`,`ip`,`vals`) VALUES ("' . $user['id'] . '","' . time( 'INSERT INTO `actions` (`uid`,`time`,`city`,`room`,`vars`,`ip`,`vals`) VALUES ("' . $user['id'] . '","' . time(
) . '","' . loto . '","' . $user['room'] . '","' . $idve . '","' . mysql_real_escape_string( ) . '","' . $user['city'] . '","' . $user['room'] . '","' . $idve . '","' . mysql_real_escape_string(
$_SERVER['HTTP_X_REAL_IP'] $_SERVER['HTTP_X_REAL_IP']
) . '","loto")' ) . '","loto")'
); );
+26 -50
View File
@@ -25,14 +25,21 @@
</style> </style>
<link href="/img.new-combats.com/css/main.css" rel="stylesheet" type="text/css"> <link href="/img.new-combats.com/css/main.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/css/training/modal.css">
<div class="se-pre-con" id="se-pre-con"></div> <div class="se-pre-con" id="se-pre-con"></div>
<?php <?php
if (!defined('GAME_VERSION')) { if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php'; require_once '_incl_data/autoload.php';
} }
use Core\{Config, Database, Db}; use Core\{Config, Database, Db};
use DarksLight2\Training\TrainingException;
use DarksLight2\Training\TrainingManager;
$training_manager = TrainingManager::getInstance(User::start()->info['id']);
function var_info($vars, $d = false) function var_info($vars, $d = false)
{ {
@@ -264,47 +271,6 @@ if (isset($_GET['atak_user']) && $u->info['battle'] == 0 && $_GET['atak_user'] !
if ($ul == 1) { if ($ul == 1) {
$act = 1; $act = 1;
} }
if ($u->info['repass'] > 0) {
define('IP', UserIp::get());
if (isset($_POST['renpass']) && $_POST['renpass'] == $_POST['renpass2'] && md5(
$_POST['renpass']
) != $u->info['pass']) {
if ($u->info['ip'] == IP) {
$u->info['pass'] = md5($_POST['renpass']);
setcookie('pass', $u->info['pass'], time() + 30 * 60 * 60 * 24, '', 'new-combats.com');
mysql_query(
'UPDATE `users` SET `pass` = "' . mysql_real_escape_string(
$u->info['pass']
) . '",`repass` = "0",`type_pers` = "0",`bot_room` = "0" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
);
mysql_query('UPDATE `stats` SET `bot` = "0" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1');
} else {
die('<font color="red"><b>Внимание!</b> Смена пароля привязана к ip %' . $u->info['ip'] . '.<br>Для восстановления контроля войдите с данного IP, либо обратитесь к Администрации проекта через нового персонажа. Приносим извинения за неудобства!</font>');
}
} else {
if (isset($_POST['renpass'])) {
if ($u->info['pass'] == md5($_POST['renpass'])) {
echo '<font color="red"><b>Внимание!</b>Ваш новый пароль должен различаться со старым.</font>';
} elseif ($_POST['renpass'] != $_POST['renpass2']) {
echo '<font color="red"><b>Внимание!</b>Пароли не совпадают.</font>';
}
}
die(
'<br><br><br><font color="red"><b>Смените пожалуйста пароль от персонажа!</b><br>Данная смена проходит, если пароль не менялся более 2 месяцев.</font><br><br><hr>
<form action="main.php" method="post">
<fieldset>
<legend><b>Сменить пароль</b></legend>
<table>
<tr><td align=right>Новый пароль:</td><td><input type=password name="renpass"></td></tr>
<tr><td align=right>Новый пароль (еще раз):</td><td><input type=password name="renpass2"></td></tr>
<tr><td align=right><input type=submit value="Сменить пароль" name="changepsw"></td><td></td></tr>
</table>
</fieldset>
</font>'
);
}
}
/*-----------------------*/ /*-----------------------*/
if ($u->info['battle'] == 0) { if ($u->info['battle'] == 0) {
@@ -334,23 +300,23 @@ if (isset($btl_last['id']) && $u->info['battle'] == 0) {
if (!isset($u->tfer['id']) && $u->room['block_all'] == 0) { if (!isset($u->tfer['id']) && $u->room['block_all'] == 0) {
//Одеть/снять предмет //Одеть/снять предмет
if (isset($_GET['rstv']) && isset($_GET['inv'])) { if (isset($_GET['rstv']) && isset($_GET['inv'])) {
$act = $u->freeStatsMod($_GET['rstv'], $_GET['mf'], $u->info['id']); $u->freeStatsMod($_GET['rstv'], $_GET['mf'], $u->info['id']);
} elseif (isset($_GET['ufs2']) && isset($_GET['inv'])) { } elseif (isset($_GET['ufs2']) && isset($_GET['inv'])) {
$act = $u->freeStats2Item($_GET['itmid'], $_GET['ufs2'], $u->info['id'], 1); $u->freeStats2Item($_GET['itmid'], $_GET['ufs2'], $u->info['id'], 1);
} elseif (isset($_GET['ufs2mf']) && isset($_GET['inv'])) { } elseif (isset($_GET['ufs2mf']) && isset($_GET['inv'])) {
$act = $u->freeStats2Item($_GET['itmid'], $_GET['ufs2mf'], $u->info['id'], 2); $u->freeStats2Item($_GET['itmid'], $_GET['ufs2mf'], $u->info['id'], 2);
} elseif (isset($_GET['ufsmst']) && isset($_GET['inv'])) { } elseif (isset($_GET['ufsmst']) && isset($_GET['inv'])) {
$act = $u->itemsSmSave($_GET['itmid'], $_GET['ufsmst'], $u->info['id']); $u->itemsSmSave($_GET['itmid'], $_GET['ufsmst'], $u->info['id']);
} elseif (isset($_GET['ufsms']) && isset($_GET['inv'])) { } elseif (isset($_GET['ufsms']) && isset($_GET['inv'])) {
$act = $u->itemsSmSave($_GET['itmid'], $_GET['ufsms'] + 100, $u->info['id']); $u->itemsSmSave($_GET['itmid'], $_GET['ufsms'] + 100, $u->info['id']);
} elseif (isset($_GET['ufs']) && isset($_GET['inv'])) { } elseif (isset($_GET['ufs']) && isset($_GET['inv'])) {
$act = $u->freeStatsItem($_GET['itmid'], $_GET['ufs'], $u->info['id']); $u->freeStatsItem($_GET['itmid'], $_GET['ufs'], $u->info['id']);
} elseif (isset($_GET['sid']) && isset($_GET['inv'])) { } elseif (isset($_GET['sid']) && isset($_GET['inv'])) {
$act = $u->snatItem($_GET['sid'], $u->info['id']); $act = $u->snatItem($_GET['sid'], $u->info['id']);
} elseif (isset($_GET['oid']) && isset($_GET['inv'])) { } elseif (isset($_GET['oid']) && isset($_GET['inv'])) {
$act = $u->odetItem($_GET['oid'], $u->info['id']); $act = $u->odetItem($_GET['oid'], $u->info['id']);
} elseif (isset($_GET['item_rune']) && isset($_GET['inv'])) { } elseif (isset($_GET['item_rune']) && isset($_GET['inv'])) {
$act = $u->runeItem(null); $u->runeItem(null);
} elseif (isset($_GET['remitem'], $_GET['inv'])) { } elseif (isset($_GET['remitem'], $_GET['inv'])) {
$act = $u->snatItemAll($u->info['id']); $act = $u->snatItemAll($u->info['id']);
} elseif (isset($_GET['delete']) && isset($_GET['inv']) && $u->newAct($_GET['sd4'])) { } elseif (isset($_GET['delete']) && isset($_GET['inv']) && $u->newAct($_GET['sd4'])) {
@@ -463,7 +429,9 @@ if (isset($_GET['security']) && !isset($u->tfer['id']) && $trololo == 1) {
require_once('modules_data/_obraz.php'); require_once('modules_data/_obraz.php');
} elseif (isset($_GET['skills']) && !isset($u->tfer['id']) && $trololo == 1) { } elseif (isset($_GET['skills']) && !isset($u->tfer['id']) && $trololo == 1) {
require_once('modules_data/_umenie.php'); require_once('modules_data/_umenie.php');
} elseif ((isset($_GET['transfer']) || isset($u->tfer['id'])) && $u->info['level'] >= Config::get('level_ransfer') && $trololo == 1 && $u->info['inTurnir'] == 0 && $u->info['inTurnirnew'] == 0) { } elseif ((isset($_GET['transfer']) || isset($u->tfer['id'])) && $u->info['level'] >= Config::get(
'level_ransfer'
) && $trololo == 1 && $u->info['inTurnir'] == 0 && $u->info['inTurnirnew'] == 0) {
if ($u->info['allLock'] > time()) { if ($u->info['allLock'] > time()) {
require_once('modules_data/_locations.php'); require_once('modules_data/_locations.php');
echo '<script>setTimeout(function(){alert("Вам запрещены передачи до ' . date( echo '<script>setTimeout(function(){alert("Вам запрещены передачи до ' . date(
@@ -495,7 +463,10 @@ if (in_array(
$iloc = ''; $iloc = '';
$iloce = ''; $iloce = '';
$sp = Db::getRows('select * from items_local where (room = ? or room = -1) and `delete` = 0 and user_take = 0 and tr_login = ?', [$u->info['room'], $u->info['login']]); $sp = Db::getRows(
'select * from items_local where (room = ? or room = -1) and `delete` = 0 and user_take = 0 and tr_login = ?',
[$u->info['room'], $u->info['login']]
);
foreach ($sp as $pl) { foreach ($sp as $pl) {
$itmo = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = ' . $pl['item_id'])); $itmo = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = ' . $pl['item_id']));
if (isset($itmo['id'])) { if (isset($itmo['id'])) {
@@ -591,6 +562,11 @@ $spl = $spl['exp'];
echo '<script>top.myexpLineTop27(' . $u->info['exp'] . ',' . $spl . ');' . $tjs . 'top.ctest("' . $u->info['city'] . '");top.sd4key="' . $u->info['nextAct'] . '"; var battle = ' . (0 + $u->info['battle']) . '; top.hic();</script></body> echo '<script>top.myexpLineTop27(' . $u->info['exp'] . ',' . $spl . ');' . $tjs . 'top.ctest("' . $u->info['city'] . '");top.sd4key="' . $u->info['nextAct'] . '"; var battle = ' . (0 + $u->info['battle']) . '; top.hic();</script></body>
</html>'; </html>';
try {
$training_manager->render();
} catch (TrainingException $e) {
echo $e->getMessage();
}
?> ?>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>--> <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>-->
<script> <script>
+29 -9
View File
@@ -139,6 +139,8 @@ function thisInfRm($id, $tp = null, $json = false)
} }
if (isset($_GET['loc'])) { if (isset($_GET['loc'])) {
$training_manager = \DarksLight2\Training\TrainingManager::getInstance();
$go = mysql_fetch_array( $go = mysql_fetch_array(
mysql_query( mysql_query(
'SELECT * FROM `room` WHERE `code` = "' . mysql_real_escape_string( 'SELECT * FROM `room` WHERE `code` = "' . mysql_real_escape_string(
@@ -146,6 +148,13 @@ if (isset($_GET['loc'])) {
) . '" AND `city` = "' . $u->info['city'] . '" LIMIT 1' ) . '" AND `city` = "' . $u->info['city'] . '" LIMIT 1'
) )
); );
if (in_array(
$go['file'],
$training_manager->getRegistered(
)[$training_manager->getCurrentStepName()]->allowedToMove()
)) {
$tr_pl = mysql_fetch_array( $tr_pl = mysql_fetch_array(
mysql_query( mysql_query(
'SELECT `id`,`v1` FROM `eff_users` WHERE `id_eff` = 4 AND `uid` = "' . $u->info['id'] . '" AND `delete` = "0" ORDER BY `v1` DESC LIMIT 1' 'SELECT `id`,`v1` FROM `eff_users` WHERE `id_eff` = 4 AND `uid` = "' . $u->info['id'] . '" AND `delete` = "0" ORDER BY `v1` DESC LIMIT 1'
@@ -176,7 +185,6 @@ if (isset($_GET['loc'])) {
} }
if (isset($tr_pl['id'])) { if (isset($tr_pl['id'])) {
$zadej = 0; $zadej = 0;
if ($tr_pl['v1'] == 1) { if ($tr_pl['v1'] == 1) {
@@ -218,20 +226,25 @@ if (isset($_GET['loc'])) {
while ($i < count($rg)) { while ($i < count($rg)) {
if ($rg[$i] >= 0) { if ($rg[$i] >= 0) {
$rmgo[$rg[$i]] = 1; $rmgo[$rg[$i]] = 1;
} }
$i++; $i++;
} }
$sleep = $u->testAction('`vars` = "sleep" AND `uid` = "' . $u->info['id'] . '" LIMIT 1', 1); $sleep = $u->testAction(
'`vars` = "sleep" AND `uid` = "' . $u->info['id'] . '" LIMIT 1',
1
);
if (isset($sleep['id']) && $sleep['vars'] == 'sleep' && $go['name'] != 'Общ. Этаж 1' && $go['name'] != 'Общ. Этаж 2' && $go['name'] != 'Общ. Этаж 3') { if (isset($sleep['id']) && $sleep['vars'] == 'sleep' && $go['name'] != 'Общ. Этаж 1' && $go['name'] != 'Общ. Этаж 2' && $go['name'] != 'Общ. Этаж 3') {
$re = '<font color=red><b>Вы можете перемещаться только когда бодрствуете.</b></font>'; $re = '<font color=red><b>Вы можете перемещаться только когда бодрствуете.</b></font>';
echo '&nbsp;' . $re; echo '&nbsp;' . $re;
} elseif ($u->info['timeGo'] >= time()) { } elseif ($u->info['timeGo'] >= time()) {
$re = 'Вы не можете перемещаться еще ' . ($u->info['timeGo'] - time()) . ' сек.'; $re = 'Вы не можете перемещаться еще ' . ($u->info['timeGo'] - time(
)) . ' сек.';
} elseif ($rmgo[$go['id']] == 1) { } elseif ($rmgo[$go['id']] == 1) {
$alg = explode('-', $go['align']); $alg = explode('-', $go['align']);
$ku = mysql_fetch_array( $ku = mysql_fetch_array(
mysql_query('SELECT `id` FROM `katok_zv` WHERE `uid` = "' . $u->info['id'] . '" LIMIT 1') mysql_query(
'SELECT `id` FROM `katok_zv` WHERE `uid` = "' . $u->info['id'] . '" LIMIT 1'
)
); );
if (isset($ku['id'])) { if (isset($ku['id'])) {
@@ -249,7 +262,9 @@ if (isset($_GET['loc'])) {
$re = 'Подали заявку и убегаем?.. Не хорошо!'; $re = 'Подали заявку и убегаем?.. Не хорошо!';
} else { } else {
$re = 'Ваша заявка была удалена... Теперь вы можете перейти в другую локацию!'; $re = 'Ваша заявка была удалена... Теперь вы можете перейти в другую локацию!';
mysql_query('UPDATE `stats` SET `zv` = 0 WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'); mysql_query(
'UPDATE `stats` SET `zv` = 0 WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
);
} }
} elseif ((($go['clan'] > 0 && $u->info['clan'] != $go['clan']) || ($go['clan'] == -1 && $u->info['clan'] == 0)) && $u->info['admin'] == 0) { } elseif ((($go['clan'] > 0 && $u->info['clan'] != $go['clan']) || ($go['clan'] == -1 && $u->info['clan'] == 0)) && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату'; $re = 'Вы не можете попасть в эту комнату';
@@ -299,7 +314,6 @@ if (isset($_GET['loc'])) {
) . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1' ) . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
); );
if ($upd2) { if ($upd2) {
if ($u->room['file'] == 'bsenter' && $go['file'] != 'bsenter') { if ($u->room['file'] == 'bsenter' && $go['file'] != 'bsenter') {
//Удаляем все ставки в БС //Удаляем все ставки в БС
$sp_bs = mysql_query( $sp_bs = mysql_query(
@@ -319,10 +333,13 @@ if (isset($_GET['loc'])) {
$smt = $u->testAction( $smt = $u->testAction(
'`uid` = "' . $u->info['id'] . '" AND `time`>=' . (time( '`uid` = "' . $u->info['id'] . '" AND `time`>=' . (time(
) - 600) . ' AND `vars` = "create_snowball_cp" LIMIT 1', 1 ) - 600) . ' AND `vars` = "create_snowball_cp" LIMIT 1',
1
); );
if (isset($smt['id'])) { if (isset($smt['id'])) {
mysql_query('DELETE FROM `actions` WHERE `id` = "' . $smt['id'] . '" LIMIT 1'); mysql_query(
'DELETE FROM `actions` WHERE `id` = "' . $smt['id'] . '" LIMIT 1'
);
} }
mysql_query( mysql_query(
'UPDATE `eff_users` SET `delete` = "' . time( 'UPDATE `eff_users` SET `delete` = "' . time(
@@ -351,6 +368,9 @@ if (isset($_GET['loc'])) {
} else { } else {
$re = 'Проход не существует'; $re = 'Проход не существует';
} }
} else {
$re = 'Вам запрещено передвигаться до окончания обучения!!!';
}
} }
if ($u->info['room'] == 209) { if ($u->info['room'] == 209) {
+16 -11
View File
@@ -1,4 +1,7 @@
<?php <?php
use DarksLight2\Training\TrainingManager;
if (!defined('GAME')) { if (!defined('GAME')) {
die(); die();
} }
@@ -441,6 +444,11 @@ $tma = '';
WHERE WHERE
`id` = '" . (int)$u->info['id'] . "';" `id` = '" . (int)$u->info['id'] . "';"
)) { )) {
TrainingManager::getInstance()
->addPoint('my_user_third_quest', function (TrainingManager $manager) {
$manager->store();
});
//if($_GET['energy']>0) {echo '&nbsp; &nbsp;<font color=red>Увеличение способности "<B>Энергия</B>" произведено удачно</font><br>';} //if($_GET['energy']>0) {echo '&nbsp; &nbsp;<font color=red>Увеличение способности "<B>Энергия</B>" произведено удачно</font><br>';}
if ($_GET['str'] > 0) { if ($_GET['str'] > 0) {
echo '&nbsp; &nbsp;<font color=red>Увеличение способности "<B>Сила</B>" произведено удачно</font><br>'; echo '&nbsp; &nbsp;<font color=red>Увеличение способности "<B>Сила</B>" произведено удачно</font><br>';
@@ -2221,8 +2229,6 @@ $tma = '';
$st[6]['pzm'] += 7; $st[6]['pzm'] += 7;
} }
$b8name = ''; $b8name = '';
//Духовность
//if($u->stats['s7']>24){ $b8name = 'Духовная Защита'; $b[8] .= '&nbsp;&nbsp;&nbsp;&bull; Жизнь после смерти дает вам прием &quot;Призрачная Защита&quot;<img src="https://img.new-combats.com/i/eff/spirit_block25.gif"><br>'; }
if ($u->stats['s7'] > 49) { if ($u->stats['s7'] > 49) {
$b8name = 'Духовное Исцеление'; $b8name = 'Духовное Исцеление';
$b[8] .= '&nbsp;&nbsp;&nbsp;&bull; Каждый бой вы начинаете под действием магии &quot;Спасение&quot;<img src="https://img.new-combats.com/i/eff/preservation.gif"><br>'; $b[8] .= '&nbsp;&nbsp;&nbsp;&bull; Каждый бой вы начинаете под действием магии &quot;Спасение&quot;<img src="https://img.new-combats.com/i/eff/preservation.gif"><br>';
@@ -2274,10 +2280,10 @@ $tma = '';
$i++; $i++;
} }
if (isset($sti['complect'])) { if (isset($sti['complect'])) {
$coms[count($coms)]['id'] = $sti['complect']; $coms[]['id'] = $sti['complect'];
if (!isset($coms['com'][$sti['complect']])) { if (!isset($coms['com'][$sti['complect']])) {
$coms['com'][$sti['complect']] = 0; $coms['com'][$sti['complect']] = 0;
$coms['new'][count($coms['new'])] = $sti['complect']; $coms['new'][] = $sti['complect'];
} }
$coms['com'][$sti['complect']]++; $coms['com'][$sti['complect']]++;
if ($pl['2h'] > 0) { if ($pl['2h'] > 0) {
@@ -2285,10 +2291,10 @@ $tma = '';
} }
} }
if (isset($sti['complect2'])) { if (isset($sti['complect2'])) {
$coms[count($coms)]['id'] = $sti['complect2']; $coms[]['id'] = $sti['complect2'];
if (!isset($coms['com'][$sti['complect2']])) { if (!isset($coms['com'][$sti['complect2']])) {
$coms['com'][$sti['complect2']] = 0; $coms['com'][$sti['complect2']] = 0;
$coms['new'][count($coms['new'])] = $sti['complect2']; $coms['new'][] = $sti['complect2'];
} }
$coms['com'][$sti['complect2']]++; $coms['com'][$sti['complect2']]++;
if ($pl['2h'] > 0) { if ($pl['2h'] > 0) {
@@ -2322,7 +2328,6 @@ $tma = '';
$sti = $u->lookStats($plc['data']); $sti = $u->lookStats($plc['data']);
while ($ij < count($ia)) { while ($ij < count($ia)) {
if (isset($ia[$ij]) && isset($sti[$ia[$ij]])) { if (isset($ia[$ij]) && isset($sti[$ia[$ij]])) {
//$st[$ia[$ij]] += $sti[$ia[$ij]];
$mad = $sti[$ia[$ij]]; $mad = $sti[$ia[$ij]];
if ($mad > 0) { if ($mad > 0) {
$mad = '+' . $mad; $mad = '+' . $mad;
@@ -2593,10 +2598,10 @@ $tma = '';
); );
if (isset($sf['id'])) { if (isset($sf['id'])) {
$sfe = $u->lookStats($sf['vals']); $sfe = $u->lookStats($sf['vals']);
$sf[0] = $u->info['exp'] - $sfe['e']; $sf[0] = $u->info['exp'] - (int)$sfe['e'];
$sf[1] = $u->info['win'] - $sfe['w']; $sf[1] = $u->info['win'] - (int)$sfe['w'];
$sf[2] = $u->info['lose'] - $sfe['l']; $sf[2] = $u->info['lose'] - (int)$sfe['l'];
$sf[3] = $u->info['nich'] - $sfe['n']; $sf[3] = $u->info['nich'] - (int)$sfe['n'];
unset($sfe); unset($sfe);
} else { } else {
$sf = [0 => 0, 1 => 0, 2 => 0, 3 => 0]; $sf = [0 => 0, 1 => 0, 2 => 0, 3 => 0];
+3 -4
View File
@@ -1,13 +1,12 @@
<? <?
if(!defined('GAME')) if(!defined('GAME'))
{ {
die(); die();
} }
require_once('/home/newcom1/public_html/_incl_data/__config.php');
require_once('/home/newcom1/public_html/_incl_data/class/__db_connect.php');
if($u->room['file']=='cp1') if($u->room['file']=='cp1') {
{
if(date("H")>=8 && date("H")<=23) { if(date("H")>=8 && date("H")<=23) {
$now = 'day'; $now = 'day';
$tattack = '<a style="color:#D8D8D8" style="cursor:pointer" onclick="top.useMagic(\'Нападение на персонажа\',\'night_atack\',\'pal_button8.gif\',1,\'main.php?nightatack=1\');">Напасть на игрока</a> &nbsp; '; $tattack = '<a style="color:#D8D8D8" style="cursor:pointer" onclick="top.useMagic(\'Нападение на персонажа\',\'night_atack\',\'pal_button8.gif\',1,\'main.php?nightatack=1\');">Напасть на игрока</a> &nbsp; ';
-11
View File
@@ -1,11 +0,0 @@
<?php
use DarksLight2\Training\TrainingManager;
$short_name = 'first_step';
$manager = TrainingManager::getInstance();
var_dump($manager->$short_name->progress);
echo 'it\'s work';
+42
View File
@@ -0,0 +1,42 @@
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
/**
* @var string $short_name
* @var $answer
* @var \DarksLight2\Training\StepFactory $step
*/
$user = User::start();
use DarksLight2\Training\TrainingManager;
$manager = TrainingManager::getInstance();
$step = $manager->getRegistered()[$short_name];
$button_text = 'Продолжить';
$time = time();
$token = password_hash($manager->getDatabaseData()->api_token . $time . $user->info['id'], PASSWORD_DEFAULT);
?>
<script>
const training_data = () => {
return {
content: `<?=$step->getMessage()?>`,
title: `<?=$step->getTitle()?>`,
button_text: `<?=$button_text?>`,
time: <?=$time?>,
token: '<?=$token?>',
short_name: '<?=$short_name?>',
answer: '<?=$answer?>'
}
}
</script>
<script src="/js/training/modal.js"></script>
<script>
modal.show()
</script>
+35 -22
View File
@@ -1,11 +1,18 @@
<?php <?php
use Core\Db; if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
use Core\Config;
use Core\Database;
use Core\Db;
use DarksLight2\Training\TrainingManager;
Config::init();
Database::init();
//
const GAME = true;
require_once '_incl_data/__config.php';
require_once '_incl_data/class/__db_connect.php';
$u = User::start(); $u = User::start();
$filter = new Filter(); $filter = new Filter();
$chat = new Chat(); $chat = new Chat();
@@ -25,11 +32,11 @@ if ($u->info['bithday'] == '01.01.1800') {
} }
if ($u->info['online'] < time() - 60) { if ($u->info['online'] < time() - 60) {
mysql_query('UPDATE users SET online = unix_timestamp() WHERE id = ' . $u->info['id']); Db::sql('update users set online = unix_timestamp() where id = ?', [$u->info['id']]);
$filter->setOnline($u->info['online'], $u->info['id']); $filter->setOnline($u->info['online'], $u->info['id']);
} }
function isModerOrAdmin($uinfo) function isModerOrAdmin($uinfo): bool
{ {
return $uinfo['admin'] > 0 || return $uinfo['admin'] > 0 ||
( (
@@ -42,19 +49,13 @@ function isModerOrAdmin($uinfo)
} }
if (isset($_POST['delMsg']) && isModerOrAdmin($u->info)) { if (isset($_POST['delMsg']) && isModerOrAdmin($u->info)) {
if (((int)$_POST['delMsg']) > 0) { $delmsgid = (int)$_POST['delMsg'];
mysql_query( if ($delmsgid > 0) {
'UPDATE `chat` SET `delete` = "' . $u->info['id'] . '" WHERE `id` = "' . mysql_real_escape_string( Db::sql('update chat set `delete` = ? where id = ?', [$u->info['id'], $delmsgid]);
((int)$_POST['delMsg'])
) . '" LIMIT 1'
);
} else { } else {
mysql_query( Db::sql('update users set molch3 = unix_timestamp() + 3600 * 3 where id = ?', [-$delmsgid]);
'UPDATE `users` SET `molch3` = "' . (time() + 3600 * 3) . '" WHERE `id` = "' . mysql_real_escape_string(
-((int)$_POST['delMsg'])
) . '" LIMIT 1'
);
} }
unset($delmsgid);
} }
$r = [ $r = [
@@ -81,7 +82,7 @@ if (isset($_POST['msg']) && str_replace(' ', '', $_POST['msg']) != '') {
$_POST['msg'] = str_replace('\x3C', '<', $_POST['msg']); $_POST['msg'] = str_replace('\x3C', '<', $_POST['msg']);
$_POST['msg'] = str_replace('\x3', '>', $_POST['msg']); $_POST['msg'] = str_replace('\x3', '>', $_POST['msg']);
function tolink($buf) function tolink($buf): string
{ {
$x = explode(" ", $buf); $x = explode(" ", $buf);
$newbuf = ''; $newbuf = '';
@@ -192,10 +193,10 @@ if (isset($_POST['msg']) && str_replace(' ', '', $_POST['msg']) != '') {
} }
} }
// //
$newbuf .= preg_match $newbuf .= preg_match(
(
"/(https:\\/\\/)?(new-combats+\\.com(([ \"'>\r\n\t])|(\\/([^ \"'>\r\n\t]*)?)))/", "/(https:\\/\\/)?(new-combats+\\.com(([ \"'>\r\n\t])|(\\/([^ \"'>\r\n\t]*)?)))/",
$x[$j], $ok $x[$j],
$ok
) ? str_replace( ) ? str_replace(
$ok[2], "<small><a href=https://$ok[2] target=_blank ><i>" . $uname . "</i></a></small>", $ok[2], "<small><a href=https://$ok[2] target=_blank ><i>" . $uname . "</i></a></small>",
str_replace("https://", "", $x[$j]) str_replace("https://", "", $x[$j])
@@ -265,6 +266,18 @@ if (isset($_POST['msg']) && str_replace(' ', '', $_POST['msg']) != '') {
mysql_query("UPDATE `chat` SET `delete` = 1 WHERE `login` = '" . $u->info['login'] . "' LIMIT 1000"); mysql_query("UPDATE `chat` SET `delete` = 1 WHERE `login` = '" . $u->info['login'] . "' LIMIT 1000");
$_POST['msg'] = 'Я спамер ' . $u->info['login'] . ' и меня нужно заблокировать https://new-combats.com/info/' . $u->info['id'] . ''; $_POST['msg'] = 'Я спамер ' . $u->info['login'] . ' и меня нужно заблокировать https://new-combats.com/info/' . $u->info['id'] . '';
$training_manager = TrainingManager::getInstance();
$training_manager->addPoint('chat_first_quest');
if(preg_match("/to\[(.*?)\]/", $_POST['msg'])) {
$training_manager->addPoint('chat_second_quest');
}
if(preg_match("/private\[(.*?)\]/", $_POST['msg'])) {
$training_manager->addPoint('chat_third_quest');
}
mysql_query( mysql_query(
'INSERT INTO `chat` (`nosee`,`invis`,`da`,`delete`,`molch`,`new`,`login`,`to`,`city`,`room`,`time`,`type`,`spam`,`text`,`toChat`,`color`,`typeTime`,`sound`,`global`) VALUES ( 'INSERT INTO `chat` (`nosee`,`invis`,`da`,`delete`,`molch`,`new`,`login`,`to`,`city`,`room`,`time`,`type`,`spam`,`text`,`toChat`,`color`,`typeTime`,`sound`,`global`) VALUES (
"0", "0",
+11 -3
View File
@@ -100,7 +100,15 @@ if ($_SESSION['step'] === 8) { // Всех их соберём, вместе с
); );
if ($uid > 0) { if ($uid > 0) {
unset(
$_SESSION['login'],
$_SESSION['password'],
$_SESSION['email'],
$_SESSION['ref'],
$_SESSION['birthday'],
$_SESSION['sex'],
$_SESSION['class']
);
//мульты //мульты
$ppl = Db::getRows('select * from logs_auth where ip = ? or ip = ?', [UserIp::get(), $_COOKIE['ip']]); $ppl = Db::getRows('select * from logs_auth where ip = ? or ip = ?', [UserIp::get(), $_COOKIE['ip']]);
@@ -122,10 +130,10 @@ if ($_SESSION['step'] === 8) { // Всех их соберём, вместе с
//Обновяем таблицы //Обновяем таблицы
Db::sql('update users set ip = ? where id = ?', [UserIp::get(), $uid]); Db::sql('update users set ip = ? where id = ?', [UserIp::get(), $uid]);
Db::sql('insert into users_learning_status (uid) values (?)', [$uid]); Db::sql('insert into users_learning_status (uid) values (?)', [$uid]);
session_unset();
header('Refresh: 1; url=/bk'); header('Refresh: 1; url=/bk');
die('Спасибо за регистрацию в игровом мире Бойцовского Клуба, желаем вам побед и долгой игры. die(
'Спасибо за регистрацию в игровом мире Бойцовского Клуба, желаем вам побед и долгой игры.
В случае вопросов по игре, Вам будет доступен общий чат!' В случае вопросов по игре, Вам будет доступен общий чат!'
); );
} }
+4 -4
View File
@@ -37,18 +37,17 @@ if (isset($_POST['relogin'])) {
if ($lst_psw) { if ($lst_psw) {
$error = 'Высылать пароль можно не более одного раза в сутки.'; $error = 'Высылать пароль можно не более одного раза в сутки.';
} elseif ( } elseif (
str_replace('0', '', $_POST['redate']) == str_replace('0', '', $usr['bithday']) str_replace('0', '', date('d.m.Y', strtotime($_POST['redate']))) == str_replace('0', '', $usr['bithday'])
) { ) {
$error = '<br><br><br>Пароль от персонажа &quot;' . $usr['login'] . '&quot; был успешно выслан на E-mail указанный при регистрации! <br><br><br>';
$re = Db::getValue( $re = Db::getValue(
'select count(*) from logs_auth where uid = ? and type = 0 and depass != ?', 'select count(*) from logs_auth where uid = ? and type = 0 and depass != ?',
[$usr['id'], ''] [$usr['id'], '']
); );
if ($u['securetime'] < Config::get('securetime')) { if ($usr['securetime'] < Config::get('securetime')) {
unset($re); unset($re);
} }
if (!isset($re)) { if (!empty($re)) {
$newPassword = PassGen::new(); $newPassword = PassGen::new();
$title = 'Восстановление пароля от "' . $usr['login'] . '".'; $title = 'Восстановление пароля от "' . $usr['login'] . '".';
$txt = 'Добрый день.<br>'; $txt = 'Добрый день.<br>';
@@ -75,6 +74,7 @@ if (isset($_POST['relogin'])) {
$error = $mail; $error = $mail;
} }
unset($mail); unset($mail);
$error = '<br><br><br>Пароль от персонажа &quot;' . $usr['login'] . '&quot; был успешно выслан на E-mail указанный при регистрации! <br><br><br>';
} }
} else { } else {
$error = 'Неверно указан день рождения.'; $error = 'Неверно указан день рождения.';
-33
View File
@@ -1,33 +0,0 @@
<?php
use DarksLight2\Training\Steps\FirstStep;
use DarksLight2\Training\TrainingException;
use DarksLight2\Training\TrainingManager;
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (isset($_GET['unset'])) {
session_unset();
}
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
$user = User::start();
$manager = TrainingManager::getInstance($user->info['id']);
$manager->createDatabaseRecord();
try {
$manager->register([
new FirstStep(),
]);
} catch (TrainingException $e) {
}
if(!$manager->first_step->complete) {
$manager->first_step->render();
}