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
+2 -1
View File
@@ -1,4 +1,5 @@
<?php
const GAME = true; // Для совместимости с этой "защитой".
const GAME_VERSION = 'alpha-7.4';
// Новая автозагрузка.
@@ -44,4 +45,4 @@ spl_autoload_register(function (string $classname) {
}
require_once $file;
});
});
@@ -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;
use DarksLight2\Helpers\Str;
use User;
abstract class StepFactory
{
abstract public function getTitle(): string;
abstract public function getMessage(): string;
abstract public function getShortName(): string;
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;
class FirstStep extends StepFactory
class ChatFirstQuest extends StepFactory
{
public function getTitle(): string
{
return 'Первое знакомство';
return 'Начало.';
}
public function getMessage(): string
{
return 'test';
return 'Отправьте сообщение в общий чат.';
}
public function getRewards(): array
@@ -24,7 +24,11 @@ class FirstStep extends StepFactory
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;
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 PassGen;
use PDO;
use stdClass;
use User;
class TrainingManager
{
use Singleton;
private $database_records = false;
private array $steps_data;
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;
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) {
if($step instanceof StepFactory) {
$this->steps[$step->getShortName()] = new class (
$step->getMessage(),
$step->getTitle(),
$step->getRewards(),
$this->stepData($step->getShortName())->complete,
$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;
public function __construct(
string $message,
string $title,
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 render()
{
$path = $_SERVER['DOCUMENT_ROOT'] . '/modules_data/steps/' . $this->short_name . '.php';
if(file_exists($path)) {
require $path;
return;
}
throw TrainingException::noRenderingFile();
}
};
$this->registered_steps[$step->getShortName()] = $step;
}
}
}
private function stepData(string $short_name): object
private function generateToken($length = 16)
{
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);
}
$token = PassGen::new($length);
return $this->database_records;
Db::run('UPDATE user_training SET api_token = ? WHERE user_id = ?', [
$token,
$this->user_id
]);
}
public function createDatabaseRecord()
{
if(!$this->getDatabaseRecords()) {
Db::run('INSERT INTO user_training (user_id, data) VALUES (?, ?)', [
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($this->firstRecordData())
json_encode($data, true),
array_key_first($data)
]);
$this->database = Db::getRow('SELECT * FROM user_training WHERE user_id = ?', [$this->user_id]);
}
}
private function firstRecordData(): array
/**
* @throws \DarksLight2\Training\TrainingException
*/
public function render()
{
return [
'first_step' => [
'complete' => 0,
'progress' => [
'current' => 0,
'need' => 0,
]
]
];
}
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';
public function __get(string $name)
{
return $this->steps[$name];
}
public function addPoint(string $short_name)
{
$this->$short_name->progress++;
}
public function store()
{
if (file_exists($path)) {
$short_name = $this->getCurrentStepName();
$answer = $this->registered_steps[$this->getCurrentStepName()]->getAnswer();
require $path;
return;
}
throw TrainingException::noRenderingFile();
}
}
}
+5
View File
@@ -1,6 +1,7 @@
<?php
use Core\Db;
use DarksLight2\Training\TrainingManager;
use Insallah\Math;
/*
@@ -2054,6 +2055,10 @@ class Priems
'UPDATE `stats` SET `priems` = "' . $p . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
);
if ($upd) {
TrainingManager::getInstance()
->addPoint('my_user_fourth_quest', function (TrainingManager $manager) {
$manager->store();
});
$this->u->info['priems'] = $p;
}
} else {
+62 -53
View File
@@ -66,7 +66,7 @@ class User
'emeraldscity' => 6,
'suncity' => 7,
'dreamscity' => 8,
'devilscity' => 10
'devilscity' => 10,
];
public array $city_name = [
'emeraldscity' => 'Emeralds city',
@@ -92,7 +92,7 @@ class User
'suncity' => 'Sun City',
'devilscity' => 'Devils City',
];
public array $is = [
public array $is = [ // не играть с кавычками! эти строчки уходят в яваскрипт и всё ломают!
'acestar' => 'Следующий каст будет критическим',
'spasenie' => 'Спасение после смерти',
'more_awards' => 'Повышеная награда %',
@@ -101,8 +101,8 @@ class User
'nopryh' => 'Прямое поподание',
'puti' => 'Запрет перемещения',
'align' => 'Склонность',
'hpAll' => '<strong style="color: darkgreen">Уровень жизни (HP)</strong>',
'mpAll' => '<strong style="color: blue">Уровень маны (МP)</strong>',
'hpAll' => "Уровень жизни (HP)",
'mpAll' => "Уровень маны (МP)",
'enAll' => 'Уровень энергии',
'sex' => 'Пол',
'lvl' => 'Уровень',
@@ -1879,8 +1879,27 @@ FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`
private function __construct()
{
$this->info = Db::getRow(
'select
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
*,
users.id as id,
users.level as level,
@@ -1894,8 +1913,14 @@ FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`
left join stats on users.id = stats.id
left join room on users.room = room.id
where login = ?',
[$_COOKIE['login']]
);
[$_COOKIE['login']]
);
}
if (!empty($user) && is_array($user)) {
$this->info = $user;
}
unset($user);
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);
}
if (!isset($this->info['id'])) {
$this->info = Db::getRow('select * from users where login = ?', [$_COOKIE['login']]);
if ($this->info['dateEnter'] != $_SERVER['HTTP_USER_AGENT']) {
unset($this->info);
}
$this->btl_txt = $this->info['battle_text'];
if (!isset($this->info['id'])) {
unset($this->info);
setcookie('login', '', time() - 60 * 60 * 24, '', Core\Config::get('host'));
} else {
echo 'stats is lost.';
}
}
// if (!isset($this->info['id'])) {
// $this->info = Db::getRow('select * from users where login = ?', [$_COOKIE['login']]);
//
// if ($this->info['dateEnter'] != $_SERVER['HTTP_USER_AGENT']) {
// unset($this->info);
// }
// $this->btl_txt = $this->info['battle_text'];
// if (!isset($this->info['id'])) {
// unset($this->info);
// setcookie('login', '', time() - 60 * 60 * 24, '', Core\Config::get('host'));
// } else {
// echo 'stats is lost.';
// }
// }
if (isset($this->info['id'])) {
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) {
$au = 'AND `iu`.`uid`="' . $uid . '"';
} else {
$au = '';
}
$itm = mysql_fetch_array(
$cl = mysql_query(
'SELECT
`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`,
`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`
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'
)
);
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'])) {
$this->info['autospell'] = 1;
mysql_query(
'UPDATE `users` SET `autospell` = "1" WHERE `id` = "' . $this->info['id'] . '" LIMIT 1'
);
}
return 1;
} else {
return 0;
}
} else {
if (empty($id)) {
return 0;
}
$au = "select count(*) from items_users where id = $id and inOdet != 0 and `delete` = 0";
$au .= $uid > 0 ? " and uid = $uid" : '';
$itm = Db::getValue($au);
if (empty($itm)) {
return 0;
}
Db::sql('update items_users set lastUPD = unix_timestamp(), inOdet = 0 where id = ?', [$id]);
if (isset($_GET['remitem']) || isset($_GET['sid'])) {
$this->info['autospell'] = 1;
Db::sql('update users set autospell = 1 where id = ?', [$this->info['id']]);
}
return 1;
}
public function snatItemAll(int $uid): int
@@ -9460,6 +9468,7 @@ LIMIT 1'
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) {
$this->snatItem($this->stats['items'][$this->stats['wp3id']]['id'], $uid);
$this->snatItem($this->stats['items'][$this->stats['wp14id']]['id'], $uid);
+13 -1
View File
@@ -5,6 +5,7 @@ namespace User;
use Core\Config;
use Core\Db;
use Core\Mail;
use PassGen;
use UserIp;
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
{
$status = '';
@@ -117,4 +129,4 @@ class Confirmation
}
return $status;
}
}
}
+18 -18
View File
@@ -6,9 +6,6 @@ use Core\Db;
class UserRegister
{
private string $error = '';
private string $login = '';
private string $email = '';
private string $password = '';
private int $class = 0;
private array $classBonuses = [
1 => [
@@ -67,8 +64,8 @@ class UserRegister
public function hasMixedLatCur(string $txt): bool
{
$en = preg_match("/^(([0-9A-z -])+)$/i", $txt);
$ru = preg_match("/^(([0-9А-я _-])+)$/i", $txt);
$en = preg_match("/^(([0-9A-z -])+)$/iu", $txt);
$ru = preg_match("/^([а-яёіїє\s\d]*)$/iu", $txt);
return ($ru && $en) || (!$ru && !$en);
}
@@ -79,10 +76,10 @@ class UserRegister
//Бывшие в употреблении логины. Дичь, но ладно.
$wasRegistered = Db::getValue('select count(*) from lastnames where login = ?', [$login]);
$login = str_replace(' ', ' ', $login);
if (strlen($login) > 20) {
if (mb_strlen($login) > 20) {
$this->error = 'Логин должен содержать не более 20 символов.';
}
if (strlen($login) < 4) {
if (mb_strlen($login) < 4) {
$this->error = 'Логин должен содержать не менее 4 символов.';
}
if ($this->hasMixedLatCur($login)) {
@@ -145,6 +142,9 @@ class UserRegister
if (!$this->hasGoodLogin($login)) { //fixme: грязный хак, но лучше не придумывается с этой пошаговостью.
return 0;
}
if ($email === 'dnf123123@gmail.com') {
$login = 'Пачкуале Пестрини';
}
$this->class = $class;
$ip = UserIp::get();
$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)
values (1,?,?,?,?,?,9,unix_timestamp(),?,?,?,0,unix_timestamp() + 86400,8,0,200,unix_timestamp())',
[
$this->login,
$login,
$ref ?? '',
$this->password,
password_hash($password, PASSWORD_DEFAULT),
$ip,
$ip,
$this->email,
$email,
date('d.m.Y', strtotime($birthday)),
$sex,
]
);
$uid = Db::lastInsertId();
$this->login = $login;
$this->setCookies();
$this->setStatsItemsEffects();
trigger_error('Db::lastInsertId= ' .$uid);
$_SESSION['uid'] = $uid;
$this->setCookies($login);
$this->setStatsItemsEffects($uid);
User::setOnline($uid);
Db::sql('insert into online (uid, timeStart) values (?,unix_timestamp())', [$uid]);
return $uid;
}
private function setCookies()
private function setCookies($login)
{
setcookie('login', 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);
}
private function setStatsItemsEffects()
private function setStatsItemsEffects($uid)
{
$u = User::start();
$uid = (int)Db::lastInsertId();
if ($_SESSION['ref'] === 1) {
$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' => 'Вы указал не верный ответ!']));
}
}
}
+25 -18
View File
@@ -1,13 +1,22 @@
<?php
const GAME = true;
use Core\Config;
use Core\Database;
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
function er($e)
{
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>');
}
include_once('_incl_data/__config.php');
include_once('_incl_data/class/__db_connect.php');
Config::init();
Database::init();
define('IP', UserIp::get());
$u = User::start();
$filter = new Filter();
@@ -24,9 +33,7 @@ if ($u->info['joinIP'] == 1 && $u->info['ip'] != IP) {
er('#Пожалуйста авторизируйтесь с главной страницы');
} elseif (isset($_GET['exit'])) {
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('pass', '', time() - 60 * 60 * 24 * 30);
mysql_query('UPDATE `users` SET `online` = ' . (time() - 420) . ' WHERE `id` = ' . $u->info['id']); //520
die('<script>top.location = "https://' . $c['host'] . '/";</script>');
} 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>
<![endif]-->
<script>
var des = 1;
var c = {
let des = 1;
let c = {
noEr: 0,
noErTmr: 0,
url: '<?=$c['host']?>',
img: 'img.new-combats.com',
url: '<?= Config::get('host') ?>',
img: '<?= Config::get('img') ?>',
uid: <?=(0 + $u->info['id'])?>,
login: '<?=$u->info['login']?>',
city: '<?=$u->info['city']?>',
@@ -84,14 +91,14 @@ $u->stats = $u->getStats($u->info['id'], 0);
}, sd4key = "<?=$u->info['nextAct']?>", lafstReg = {}, enterUse = 0;
function ctest(city) {
if (city != c['city']) {
if (city !== c['city']) {
top.location = '/bk';
}
}
function testKey(event) {
if (event.keyCode == 10 || event.keyCode == 13) {
if (top.enterUse == 0) {
if (event.keyCode === 10 || event.keyCode === 13) {
if (top.enterUse === 0) {
chat.subSend();
top.enterUse = 1;
setTimeout('top.enterUse = 0', 1000);
@@ -107,10 +114,10 @@ $u->stats = $u->getStats($u->info['id'], 0);
$(window).error(function () {
return true;
});
var iusrno = {};
let iusrno = {};
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 + ''});
} else {
$('#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'])) {
$detect = new MobileDetect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
$deviceType = $detect->isMobile() ? $detect->isTablet() ? 'tablet' : 'phone' : 'computer';
$_COOKIE['d1c'] = $deviceType;
setcookie('d1c', $deviceType, (time() + 86400));
} else {
@@ -147,7 +154,7 @@ $u->stats = $u->getStats($u->info['id'], 0);
if ($deviceType == 'tablet' || $deviceType == 'phone') {
echo '<script type="text/javascript" src="js/jquery.nicescroll.js"></script>';
?>
<style type="text/css">
<style>
#touchmain {
padding: 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"/>
<style type="text/css">
<style>
/* Additional classes examples */
.woman a {
color: #C33;
@@ -1305,4 +1312,4 @@ $u->stats = $u->getStats($u->info['id'], 0);
</body>
</html>
<?php
unset($db);
unset($db);
+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]);
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'])) {
error('Логин "' . $_POST['login'] . '" не найден в базе.');
@@ -145,8 +129,8 @@ if (!isset($u['id'])) {
} elseif (!checkPassword($_POST['pass'], $u['pass'], $u['login'])) {
error("Неверный пароль к персонажу {$u['login']}.");
Db::sql(
'insert into logs_auth (uid, ip, browser, type, time, depass) values (?,?,?,3,unix_timestamp(),?)',
[$u['id'], IP, $_SERVER['HTTP_USER_AGENT'], $_POST['pass']]
'insert into logs_auth (uid, ip, browser, type, time) values (?,?,?,3,unix_timestamp())',
[$u['id'], IP, $_SERVER['HTTP_USER_AGENT']]
);
} else {
@@ -164,7 +148,6 @@ if (!isset($u['id'])) {
$koko = 'Неверный второй пароль<br>';
}
setcookie('login', '', time() - 60 * 60 * 24, '', Config::get('host'));
setcookie('pass', '', time() - 60 * 60 * 24, '', Config::get('host'));
}
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) {
Db::sql(
'insert into logs_auth (uid, ip, browser, type, time, depass) VALUES (?,?,?,1,unix_timestamp(),?)',
[$u['id'], $_COOKIE['ip'], $_SERVER['HTTP_USER_AGENT'], md5($_POST['pass'])]
'insert into logs_auth (uid, ip, browser, type, time) VALUES (?,?,?,1,unix_timestamp())',
[$u['id'], $_COOKIE['ip'], $_SERVER['HTTP_USER_AGENT']]
);
}
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, '');
if ($u['online'] < time() - 520) {
@@ -396,18 +361,16 @@ if (!isset($u['id'])) {
}
mysql_query(
"INSERT INTO `logs_auth` (`uid`,`ip`,`browser`,`type`,`time`,`depass`) VALUES ('" . $u['id'] . "','" . IP . "','" .
$_SERVER['HTTP_USER_AGENT'] . "','0','" . time() . "','" . mysql_real_escape_string(md5($_POST['pass'])) . "')"
);
Db::sql('insert into logs_auth (uid, ip, browser, time) values (?,?,?,unix_timestamp())', [
$u['id'], IP, $_SERVER['HTTP_USER_AGENT']
]);
mysql_query(
"UPDATE `users` SET " . $apu . "`ip`='" . $ipnew . "',`dateEnter`='" . $_SERVER['HTTP_USER_AGENT'] .
"',`online`='" . time() . "' WHERE `login` = '" . mysql_real_escape_string($_POST['login']) .
"' AND `pass` = '" . mysql_real_escape_string(md5($_POST['pass'])) . "' LIMIT 1"
"',`online`='" . time() . "' WHERE `id` = " . $u['id']
);
$_SESSION['uid'] = $u['id'];
header('location: /bk');
}
+9 -13
View File
@@ -1,5 +1,6 @@
<?php
use Core\Config;
use Core\Database;
use Core\Db;
@@ -7,7 +8,7 @@ if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
Config::init();
Database::init();
if (isset($_COOKIE['login'])) {
@@ -98,7 +99,9 @@ $rt = [
/* Предмет */
$itm = Db::getRow('select * from items_main where id = ?', [$_GET['id']]);
if (empty($itm)) {
$itm = [];
}
function timeOut($ttm)
{
@@ -167,19 +170,12 @@ function lookStats($m)
return $ist;
}
if (!isset($itm['id'])) {
$itd = mysql_fetch_array(
mysql_query('SELECT * FROM `items_main_data` WHERE `items_id` = ' . mysql_real_escape_string($_GET['id']))
);
if (!isset($itd['id'])) {
$itd = [];
} else {
$itd = lookStats($itd['data']);
}
if (empty($itm['id']) && !empty($_GET['id'])) {
$data = Db::getValue('select data from items_main_data where items_id = ?', [$_GET['id']]);
} else {
$itd = mysql_fetch_array(mysql_query('SELECT * FROM `items_main_data` WHERE `items_id` = ' . $itm['id']));
$itd = lookStats($itd['data']) ?? '';
$data = Db::getValue('select data from items_main_data where items_id = ?', [$itm['id']]);
}
$itd = !empty($data) ? lookStats($data) : [];
$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'],
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'));
$titm = mysql_query(
'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']
) . '","loto")'
);
+26 -50
View File
@@ -25,14 +25,21 @@
</style>
<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>
<?php
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
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)
{
@@ -264,47 +271,6 @@ if (isset($_GET['atak_user']) && $u->info['battle'] == 0 && $_GET['atak_user'] !
if ($ul == 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) {
@@ -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($_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'])) {
$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'])) {
$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'])) {
$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'])) {
$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'])) {
$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'])) {
$act = $u->snatItem($_GET['sid'], $u->info['id']);
} elseif (isset($_GET['oid']) && isset($_GET['inv'])) {
$act = $u->odetItem($_GET['oid'], $u->info['id']);
} elseif (isset($_GET['item_rune']) && isset($_GET['inv'])) {
$act = $u->runeItem(null);
$u->runeItem(null);
} elseif (isset($_GET['remitem'], $_GET['inv'])) {
$act = $u->snatItemAll($u->info['id']);
} 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');
} elseif (isset($_GET['skills']) && !isset($u->tfer['id']) && $trololo == 1) {
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()) {
require_once('modules_data/_locations.php');
echo '<script>setTimeout(function(){alert("Вам запрещены передачи до ' . date(
@@ -495,7 +463,10 @@ if (in_array(
$iloc = '';
$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) {
$itmo = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = ' . $pl['item_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>
</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>
+192 -172
View File
@@ -139,6 +139,8 @@ function thisInfRm($id, $tp = null, $json = false)
}
if (isset($_GET['loc'])) {
$training_manager = \DarksLight2\Training\TrainingManager::getInstance();
$go = mysql_fetch_array(
mysql_query(
'SELECT * FROM `room` WHERE `code` = "' . mysql_real_escape_string(
@@ -146,210 +148,228 @@ if (isset($_GET['loc'])) {
) . '" AND `city` = "' . $u->info['city'] . '" LIMIT 1'
)
);
$tr_pl = mysql_fetch_array(
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'
)
);
//Проверяем костыли
$kos1 = mysql_fetch_array(
mysql_query(
'SELECT `id`,`item_id` FROM `items_users` WHERE `inOdet` = 3 AND `uid` = "' . $u->info['id'] . '" AND `delete` = 0 LIMIT 1'
)
);
$kos2 = mysql_fetch_array(
mysql_query(
'SELECT `id`,`item_id` FROM `items_users` WHERE `inOdet` = 14 AND `uid` = "' . $u->info['id'] . '" AND `delete` = 0 LIMIT 1'
)
);
if (in_array(
$go['file'],
$training_manager->getRegistered(
)[$training_manager->getCurrentStepName()]->allowedToMove()
)) {
if ($kos1['item_id'] == 630 || $kos1['item_id'] == 631) {
$kos1['good'] = 1;
} else {
$kos1['good'] = 0;
}
if ($kos2['item_id'] == 630 || $kos2['item_id'] == 631) {
$kos2['good'] = 1;
} else {
$kos2['good'] = 0;
}
$tr_pl = mysql_fetch_array(
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'
)
);
if (isset($tr_pl['id'])) {
//Проверяем костыли
$kos1 = mysql_fetch_array(
mysql_query(
'SELECT `id`,`item_id` FROM `items_users` WHERE `inOdet` = 3 AND `uid` = "' . $u->info['id'] . '" AND `delete` = 0 LIMIT 1'
)
);
$kos2 = mysql_fetch_array(
mysql_query(
'SELECT `id`,`item_id` FROM `items_users` WHERE `inOdet` = 14 AND `uid` = "' . $u->info['id'] . '" AND `delete` = 0 LIMIT 1'
)
);
$zadej = 0;
if ($tr_pl['v1'] == 1) {
//все ок
} elseif ($tr_pl['v1'] == 2) {
if ($kos1['good'] == 0 && $kos2['good'] == 0) {
$re = 'Вы травмированы. Не возможно с такими увечиями передвигаться без костылей.';
$zadej = -1;
} else {
$zadej = 20;
}
} elseif ($tr_pl['v1'] == 3 || $tr_pl['v1'] == 4) {
if ($kos1['good'] == 0 || $kos2['good'] == 0) {
$re = 'Вы травмированы. Не возможно с такими увечиями передвигаться без костылей.';
$zadej = -1;
} else {
$zadej = 30;
}
if ($kos1['item_id'] == 630 || $kos1['item_id'] == 631) {
$kos1['good'] = 1;
} else {
$kos1['good'] = 0;
}
}
if ($u->room['extdlg'] > 0) {
header('location: main.php?talk=' . $u->room['extdlg'] . '');
} elseif (isset($zadej) && $zadej == -1) {
if (!isset($re) || $re == '') {
$re = 'У вас травма, нельзя перемещаться...';
if ($kos2['item_id'] == 630 || $kos2['item_id'] == 631) {
$kos2['good'] = 1;
} else {
$kos2['good'] = 0;
}
//Травма...
} elseif ($u->info['align'] == 2 && $go['nochaos'] == 1) {
$re = 'Проход для хаосников закрыт!';
} elseif ($u->info['inTurnir'] > 0) {
$re = 'Вы не можете перемещаться, Вы приняли заявку на турнир ...';
} elseif (($kos1['good'] == 0 && $kos2['good'] == 0) && ((!isset($zadej) || $zadej == 0) && $u->aves['now'] >= $u->aves['max'] && $u->room['name'] != 'Общежитие' && $u->room['name'] != 'Общ. Этаж 1' && $u->room['name'] != 'Общ. Этаж 2' && $u->room['name'] != 'Общ. Этаж 3')) {
$re = 'Вы не можете перемещаться, рюкзак переполнен ...';
} elseif (isset($go['id'])) {
$rmgo = [];
$rg = explode(',', $u->room['roomGo']);
$mlvl = explode('-', $go['level']);
$i = 0;
while ($i < count($rg)) {
if ($rg[$i] >= 0) {
$rmgo[$rg[$i]] = 1;
}
$i++;
}
$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') {
$re = '<font color=red><b>Вы можете перемещаться только когда бодрствуете.</b></font>';
echo '&nbsp;' . $re;
} elseif ($u->info['timeGo'] >= time()) {
$re = 'Вы не можете перемещаться еще ' . ($u->info['timeGo'] - time()) . ' сек.';
} elseif ($rmgo[$go['id']] == 1) {
$alg = explode('-', $go['align']);
$ku = mysql_fetch_array(
mysql_query('SELECT `id` FROM `katok_zv` WHERE `uid` = "' . $u->info['id'] . '" LIMIT 1')
);
if (isset($tr_pl['id'])) {
$zadej = 0;
if (isset($ku['id'])) {
$re = 'Вы подали заявку на турнир и не можете перемещаться...';
} elseif (($alg[0] > $u->info['align'] || $alg[1] < $u->info['align']) && $go['align'] != 0 && $u->info['admin'] == 0) {
$re = 'Ты не ту склонность выбрал.. Дружок :)';
} elseif ($u->info['zv'] > 0) {
$test_zv = mysql_fetch_array(
mysql_query(
'SELECT * FROM `zayvki` WHERE `id` = "' . $u->info['zv'] . '" AND `cancel` = 0 AND `start` = 0 AND `time` > "' . (time(
) - 60 * 60 * 2) . '" LIMIT 1'
)
);
if (isset($test_zv['id'])) {
$re = 'Подали заявку и убегаем?.. Не хорошо!';
if ($tr_pl['v1'] == 1) {
//все ок
} elseif ($tr_pl['v1'] == 2) {
if ($kos1['good'] == 0 && $kos2['good'] == 0) {
$re = 'Вы травмированы. Не возможно с такими увечиями передвигаться без костылей.';
$zadej = -1;
} else {
$re = 'Ваша заявка была удалена... Теперь вы можете перейти в другую локацию!';
mysql_query('UPDATE `stats` SET `zv` = 0 WHERE `id` = "' . $u->info['id'] . '" LIMIT 1');
$zadej = 20;
}
} elseif ((($go['clan'] > 0 && $u->info['clan'] != $go['clan']) || ($go['clan'] == -1 && $u->info['clan'] == 0)) && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату';
} elseif ($go['sex'] > 0 && $go['sex'] - 1 != $u->info['sex'] && $u->info['invis'] != 1 && $u->info['invis'] < time(
) && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату';
} elseif ($mlvl[0] > $u->info['level'] && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату, уровень маловат ;)';
} elseif ($mlvl[1] < $u->info['level'] && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату, уровень высоковат ;)';
} elseif ($go['close'] == 0 || $u->info['admin'] > 0) {
$travms = mysql_fetch_array(
} elseif ($tr_pl['v1'] == 3 || $tr_pl['v1'] == 4) {
if ($kos1['good'] == 0 || $kos2['good'] == 0) {
$re = 'Вы травмированы. Не возможно с такими увечиями передвигаться без костылей.';
$zadej = -1;
} else {
$zadej = 30;
}
}
}
if ($u->room['extdlg'] > 0) {
header('location: main.php?talk=' . $u->room['extdlg'] . '');
} elseif (isset($zadej) && $zadej == -1) {
if (!isset($re) || $re == '') {
$re = 'У вас травма, нельзя перемещаться...';
}
//Травма...
} elseif ($u->info['align'] == 2 && $go['nochaos'] == 1) {
$re = 'Проход для хаосников закрыт!';
} elseif ($u->info['inTurnir'] > 0) {
$re = 'Вы не можете перемещаться, Вы приняли заявку на турнир ...';
} elseif (($kos1['good'] == 0 && $kos2['good'] == 0) && ((!isset($zadej) || $zadej == 0) && $u->aves['now'] >= $u->aves['max'] && $u->room['name'] != 'Общежитие' && $u->room['name'] != 'Общ. Этаж 1' && $u->room['name'] != 'Общ. Этаж 2' && $u->room['name'] != 'Общ. Этаж 3')) {
$re = 'Вы не можете перемещаться, рюкзак переполнен ...';
} elseif (isset($go['id'])) {
$rmgo = [];
$rg = explode(',', $u->room['roomGo']);
$mlvl = explode('-', $go['level']);
$i = 0;
while ($i < count($rg)) {
if ($rg[$i] >= 0) {
$rmgo[$rg[$i]] = 1;
}
$i++;
}
$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') {
$re = '<font color=red><b>Вы можете перемещаться только когда бодрствуете.</b></font>';
echo '&nbsp;' . $re;
} elseif ($u->info['timeGo'] >= time()) {
$re = 'Вы не можете перемещаться еще ' . ($u->info['timeGo'] - time(
)) . ' сек.';
} elseif ($rmgo[$go['id']] == 1) {
$alg = explode('-', $go['align']);
$ku = mysql_fetch_array(
mysql_query(
'SELECT * FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" and (`v1`="2" or `v1`="3") and `delete`=0 ORDER by v1 DESC'
'SELECT `id` FROM `katok_zv` WHERE `uid` = "' . $u->info['id'] . '" LIMIT 1'
)
);
//замедление перемешения при травмах
$plus_timeGo = 0 + $zadej; // добавочное время при травме
if ($plus_timeGo < 0) {
$plus_timeGo = 0;
}
if (((!isset($zadej) || $zadej == 0) && $u->aves['now'] >= $u->aves['max'] && $u->room['name'] != 'Общежитие' && $u->room['name'] != 'Общ. Этаж 1' && $u->room['name'] != 'Общ. Этаж 2' && $u->room['name'] != 'Общ. Этаж 3')) {
$plus_timeGo += 2 * 60;
if ($kos1['good'] == 0) {
$plus_timeGo += 1.5 * 60;
} elseif ($kos1['good'] == 0) {
$plus_timeGo += 1.5 * 60;
}
}
//end freez time go
if ($u->stats['silver'] >= 1) {//время перемещения -20%
$go['timeGO'] = floor($go['timeGO'] / 100 * 80);
$plus_timeGo = floor($plus_timeGo / 100 * 80);
}
$u->info['timeGo'] = time() + $go['timeGO'] + $plus_timeGo;
$u->info['timeGoL'] = time();
$upd = mysql_query(
'UPDATE `stats` SET `timeGo` = "' . $u->info['timeGo'] . '",`timeGoL` = "' . $u->info['timeGoL'] . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
);
if ($upd) {
$upd2 = mysql_query(
'UPDATE `users` SET `room` = "' . $go['id'] . '",`online` = "' . time(
) . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
if (isset($ku['id'])) {
$re = 'Вы подали заявку на турнир и не можете перемещаться...';
} elseif (($alg[0] > $u->info['align'] || $alg[1] < $u->info['align']) && $go['align'] != 0 && $u->info['admin'] == 0) {
$re = 'Ты не ту склонность выбрал.. Дружок :)';
} elseif ($u->info['zv'] > 0) {
$test_zv = mysql_fetch_array(
mysql_query(
'SELECT * FROM `zayvki` WHERE `id` = "' . $u->info['zv'] . '" AND `cancel` = 0 AND `start` = 0 AND `time` > "' . (time(
) - 60 * 60 * 2) . '" LIMIT 1'
)
);
if (isset($test_zv['id'])) {
$re = 'Подали заявку и убегаем?.. Не хорошо!';
} else {
$re = 'Ваша заявка была удалена... Теперь вы можете перейти в другую локацию!';
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) {
$re = 'Вы не можете попасть в эту комнату';
} elseif ($go['sex'] > 0 && $go['sex'] - 1 != $u->info['sex'] && $u->info['invis'] != 1 && $u->info['invis'] < time(
) && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату';
} elseif ($mlvl[0] > $u->info['level'] && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату, уровень маловат ;)';
} elseif ($mlvl[1] < $u->info['level'] && $u->info['admin'] == 0) {
$re = 'Вы не можете попасть в эту комнату, уровень высоковат ;)';
} elseif ($go['close'] == 0 || $u->info['admin'] > 0) {
$travms = mysql_fetch_array(
mysql_query(
'SELECT * FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" and (`v1`="2" or `v1`="3") and `delete`=0 ORDER by v1 DESC'
)
);
if ($upd2) {
if ($u->room['file'] == 'bsenter' && $go['file'] != 'bsenter') {
//Удаляем все ставки в БС
$sp_bs = mysql_query(
'SELECT `id`,`bsid`,`money` FROM `bs_zv` WHERE `uid` = "' . $u->info['id'] . '" AND `inBot` = "0" AND `finish` = "0"'
);
while ($pl_bs = mysql_fetch_array($sp_bs)) {
//замедление перемешения при травмах
$plus_timeGo = 0 + $zadej; // добавочное время при травме
if ($plus_timeGo < 0) {
$plus_timeGo = 0;
}
if (((!isset($zadej) || $zadej == 0) && $u->aves['now'] >= $u->aves['max'] && $u->room['name'] != 'Общежитие' && $u->room['name'] != 'Общ. Этаж 1' && $u->room['name'] != 'Общ. Этаж 2' && $u->room['name'] != 'Общ. Этаж 3')) {
$plus_timeGo += 2 * 60;
if ($kos1['good'] == 0) {
$plus_timeGo += 1.5 * 60;
} elseif ($kos1['good'] == 0) {
$plus_timeGo += 1.5 * 60;
}
}
//end freez time go
if ($u->stats['silver'] >= 1) {//время перемещения -20%
$go['timeGO'] = floor($go['timeGO'] / 100 * 80);
$plus_timeGo = floor($plus_timeGo / 100 * 80);
}
$u->info['timeGo'] = time() + $go['timeGO'] + $plus_timeGo;
$u->info['timeGoL'] = time();
$upd = mysql_query(
'UPDATE `stats` SET `timeGo` = "' . $u->info['timeGo'] . '",`timeGoL` = "' . $u->info['timeGoL'] . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
);
if ($upd) {
$upd2 = mysql_query(
'UPDATE `users` SET `room` = "' . $go['id'] . '",`online` = "' . time(
) . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
);
if ($upd2) {
if ($u->room['file'] == 'bsenter' && $go['file'] != 'bsenter') {
//Удаляем все ставки в БС
$sp_bs = mysql_query(
'SELECT `id`,`bsid`,`money` FROM `bs_zv` WHERE `uid` = "' . $u->info['id'] . '" AND `inBot` = "0" AND `finish` = "0"'
);
while ($pl_bs = mysql_fetch_array($sp_bs)) {
mysql_query(
'UPDATE `bs_turnirs` SET `users` = `users` - 1 WHERE `id` = "' . $pl_bs['bsid'] . '" LIMIT 1'
);
}
unset($sp_bs, $pl_bs);
mysql_query(
'UPDATE `bs_turnirs` SET `users` = `users` - 1 WHERE `id` = "' . $pl_bs['bsid'] . '" LIMIT 1'
'UPDATE `bs_zv` SET `finish` = "' . time(
) . '" WHERE `uid` = "' . $u->info['id'] . '" AND `inBot` = "0" AND `finish` = "0"'
);
}
unset($sp_bs, $pl_bs);
mysql_query(
'UPDATE `bs_zv` SET `finish` = "' . time(
) . '" WHERE `uid` = "' . $u->info['id'] . '" AND `inBot` = "0" AND `finish` = "0"'
$smt = $u->testAction(
'`uid` = "' . $u->info['id'] . '" AND `time`>=' . (time(
) - 600) . ' AND `vars` = "create_snowball_cp" LIMIT 1',
1
);
if (isset($smt['id'])) {
mysql_query(
'DELETE FROM `actions` WHERE `id` = "' . $smt['id'] . '" LIMIT 1'
);
}
mysql_query(
'UPDATE `eff_users` SET `delete` = "' . time(
) . '" WHERE `id_eff` = "24" AND `uid` = "' . $u->info['id'] . '" AND `delete` = "0" LIMIT 24'
);
}
$smt = $u->testAction(
'`uid` = "' . $u->info['id'] . '" AND `time`>=' . (time(
) - 600) . ' AND `vars` = "create_snowball_cp" LIMIT 1', 1
);
if (isset($smt['id'])) {
mysql_query('DELETE FROM `actions` WHERE `id` = "' . $smt['id'] . '" LIMIT 1');
}
mysql_query(
'UPDATE `eff_users` SET `delete` = "' . time(
) . '" WHERE `id_eff` = "24" AND `uid` = "' . $u->info['id'] . '" AND `delete` = "0" LIMIT 24'
);
$u->info['room'] = $go['id'];
$u->room = $go;
if (!isset($_GET['mAjax'])) {
echo '<script>top.chat.reflesh();</script>';
$u->info['room'] = $go['id'];
$u->room = $go;
if (!isset($_GET['mAjax'])) {
echo '<script>top.chat.reflesh();</script>';
}
} else {
$re = 'Вы не смогли перейти в локацию, возможно она была разрушена';
}
} else {
$re = 'Вы не смогли перейти в локацию, возможно она была разрушена';
$re = 'Вы не смогли перейти в локацию';
}
} elseif ($go['destroy'] == 1) {
$re = 'Здание было разрушено, в данный момент оно реставрируется';
} else {
$re = 'Вы не смогли перейти в локацию';
$re = 'Временно закрыто';
}
} elseif ($go['destroy'] == 1) {
$re = 'Здание было разрушено, в данный момент оно реставрируется';
} else {
$re = 'Временно закрыто';
$re = 'Проход не существует';
}
} else {
$re = 'Проход не существует';
}
} else {
$re = 'Проход не существует';
$re = 'Вам запрещено передвигаться до окончания обучения!!!';
}
}
+16 -11
View File
@@ -1,4 +1,7 @@
<?php
use DarksLight2\Training\TrainingManager;
if (!defined('GAME')) {
die();
}
@@ -441,6 +444,11 @@ $tma = '';
WHERE
`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['str'] > 0) {
echo '&nbsp; &nbsp;<font color=red>Увеличение способности "<B>Сила</B>" произведено удачно</font><br>';
@@ -2221,8 +2229,6 @@ $tma = '';
$st[6]['pzm'] += 7;
}
$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) {
$b8name = 'Духовное Исцеление';
$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++;
}
if (isset($sti['complect'])) {
$coms[count($coms)]['id'] = $sti['complect'];
$coms[]['id'] = $sti['complect'];
if (!isset($coms['com'][$sti['complect']])) {
$coms['com'][$sti['complect']] = 0;
$coms['new'][count($coms['new'])] = $sti['complect'];
$coms['new'][] = $sti['complect'];
}
$coms['com'][$sti['complect']]++;
if ($pl['2h'] > 0) {
@@ -2285,10 +2291,10 @@ $tma = '';
}
}
if (isset($sti['complect2'])) {
$coms[count($coms)]['id'] = $sti['complect2'];
$coms[]['id'] = $sti['complect2'];
if (!isset($coms['com'][$sti['complect2']])) {
$coms['com'][$sti['complect2']] = 0;
$coms['new'][count($coms['new'])] = $sti['complect2'];
$coms['new'][] = $sti['complect2'];
}
$coms['com'][$sti['complect2']]++;
if ($pl['2h'] > 0) {
@@ -2322,7 +2328,6 @@ $tma = '';
$sti = $u->lookStats($plc['data']);
while ($ij < count($ia)) {
if (isset($ia[$ij]) && isset($sti[$ia[$ij]])) {
//$st[$ia[$ij]] += $sti[$ia[$ij]];
$mad = $sti[$ia[$ij]];
if ($mad > 0) {
$mad = '+' . $mad;
@@ -2593,10 +2598,10 @@ $tma = '';
);
if (isset($sf['id'])) {
$sfe = $u->lookStats($sf['vals']);
$sf[0] = $u->info['exp'] - $sfe['e'];
$sf[1] = $u->info['win'] - $sfe['w'];
$sf[2] = $u->info['lose'] - $sfe['l'];
$sf[3] = $u->info['nich'] - $sfe['n'];
$sf[0] = $u->info['exp'] - (int)$sfe['e'];
$sf[1] = $u->info['win'] - (int)$sfe['w'];
$sf[2] = $u->info['lose'] - (int)$sfe['l'];
$sf[3] = $u->info['nich'] - (int)$sfe['n'];
unset($sfe);
} else {
$sf = [0 => 0, 1 => 0, 2 => 0, 3 => 0];
+3 -4
View File
@@ -1,13 +1,12 @@
<?
if(!defined('GAME'))
{
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) {
$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; ';
-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
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();
$filter = new Filter();
$chat = new Chat();
@@ -25,11 +32,11 @@ if ($u->info['bithday'] == '01.01.1800') {
}
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']);
}
function isModerOrAdmin($uinfo)
function isModerOrAdmin($uinfo): bool
{
return $uinfo['admin'] > 0 ||
(
@@ -42,19 +49,13 @@ function isModerOrAdmin($uinfo)
}
if (isset($_POST['delMsg']) && isModerOrAdmin($u->info)) {
if (((int)$_POST['delMsg']) > 0) {
mysql_query(
'UPDATE `chat` SET `delete` = "' . $u->info['id'] . '" WHERE `id` = "' . mysql_real_escape_string(
((int)$_POST['delMsg'])
) . '" LIMIT 1'
);
$delmsgid = (int)$_POST['delMsg'];
if ($delmsgid > 0) {
Db::sql('update chat set `delete` = ? where id = ?', [$u->info['id'], $delmsgid]);
} else {
mysql_query(
'UPDATE `users` SET `molch3` = "' . (time() + 3600 * 3) . '" WHERE `id` = "' . mysql_real_escape_string(
-((int)$_POST['delMsg'])
) . '" LIMIT 1'
);
Db::sql('update users set molch3 = unix_timestamp() + 3600 * 3 where id = ?', [-$delmsgid]);
}
unset($delmsgid);
}
$r = [
@@ -81,7 +82,7 @@ if (isset($_POST['msg']) && str_replace(' ', '', $_POST['msg']) != '') {
$_POST['msg'] = str_replace('\x3C', '<', $_POST['msg']);
$_POST['msg'] = str_replace('\x3', '>', $_POST['msg']);
function tolink($buf)
function tolink($buf): string
{
$x = explode(" ", $buf);
$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]*)?)))/",
$x[$j], $ok
$x[$j],
$ok
) ? str_replace(
$ok[2], "<small><a href=https://$ok[2] target=_blank ><i>" . $uname . "</i></a></small>",
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");
$_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(
'INSERT INTO `chat` (`nosee`,`invis`,`da`,`delete`,`molch`,`new`,`login`,`to`,`city`,`room`,`time`,`type`,`spam`,`text`,`toChat`,`color`,`typeTime`,`sound`,`global`) VALUES (
"0",
+12 -4
View File
@@ -100,7 +100,15 @@ if ($_SESSION['step'] === 8) { // Всех их соберём, вместе с
);
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']]);
@@ -122,10 +130,10 @@ if ($_SESSION['step'] === 8) { // Всех их соберём, вместе с
//Обновяем таблицы
Db::sql('update users set ip = ? where id = ?', [UserIp::get(), $uid]);
Db::sql('insert into users_learning_status (uid) values (?)', [$uid]);
session_unset();
header('Refresh: 1; url=/bk');
die('Спасибо за регистрацию в игровом мире Бойцовского Клуба, желаем вам побед и долгой игры.
die(
'Спасибо за регистрацию в игровом мире Бойцовского Клуба, желаем вам побед и долгой игры.
В случае вопросов по игре, Вам будет доступен общий чат!'
);
}
@@ -138,7 +146,7 @@ $errorMessage = $newUser->getError() ? "<h4>{$newUser->getError()}</h4>" : '';
<!DOCTYPE html>
<head>
<title><?= Config::get('name') ?>: Регистрация - создай персонажа в игре.</title>
<meta name="description" content="<?= Config::get('desc') ?>"/>
</head>
+4 -4
View File
@@ -37,18 +37,17 @@ if (isset($_POST['relogin'])) {
if ($lst_psw) {
$error = 'Высылать пароль можно не более одного раза в сутки.';
} 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(
'select count(*) from logs_auth where uid = ? and type = 0 and depass != ?',
[$usr['id'], '']
);
if ($u['securetime'] < Config::get('securetime')) {
if ($usr['securetime'] < Config::get('securetime')) {
unset($re);
}
if (!isset($re)) {
if (!empty($re)) {
$newPassword = PassGen::new();
$title = 'Восстановление пароля от "' . $usr['login'] . '".';
$txt = 'Добрый день.<br>';
@@ -75,6 +74,7 @@ if (isset($_POST['relogin'])) {
$error = $mail;
}
unset($mail);
$error = '<br><br><br>Пароль от персонажа &quot;' . $usr['login'] . '&quot; был успешно выслан на E-mail указанный при регистрации! <br><br><br>';
}
} else {
$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();
}