diff --git a/.htaccess b/.htaccess
index 91a71035..be89ef87 100644
--- a/.htaccess
+++ b/.htaccess
@@ -41,9 +41,6 @@ DefaultLanguage ru
RewriteRule ^clan/(.*)/?$ /clans_inf.php?$1 [L]
RewriteRule ^clan/?$ /clans_inf.php [L]
- RewriteRule ^ruins/(.*)/?$ /ruins.php?$1 [L]
- RewriteRule ^ruins/?$ /ruins.php [L]
-
RewriteRule ^news/(.*)/?$ /n/$1 [R=301,L]
RewriteRule ^news/?$ /n [R=301,L]
diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml
new file mode 100644
index 00000000..f4a650a3
--- /dev/null
+++ b/.idea/dataSources.xml
@@ -0,0 +1,12 @@
+
+
';
@@ -1050,9 +1039,8 @@ class Dungeon
);
if (isset($it['id'])) {
$r .= 'Вы обнаружили предмет "' . $it['name'] . '".
';
- ItemsModel::addItem(
- ['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]
- );
+ ItemsModel::addItem($it['id'], $this->userinfo['id']);
+ //ItemsModel::addItem(['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]);
}
} else {
//неудачная попытка
@@ -1067,98 +1055,84 @@ class Dungeon
}
} elseif ($s[0] == 'itm1') {
//Добавляем предмет , только 1 предмет из всех и все юзеры могут тоже
- $nj = 0;
$t = explode(',', $s[1]);
$j = rand(0, count($t));
- if ($nj == 0) {
- $itm = explode('=', $t[$j]);
- $ch = $u->testAction(
- '`uid` = "' . $this->userinfo['id'] . '" AND `vars` = "takeit_' . $this->info['id'] . '_' . $obj['id'] . '" LIMIT ' . (1 + (int)$itm[2]) . '',
- 2
- ); //кол-во прошлых попыток
- $ch = $ch[0];
- if ($ch >= $itm[2]) {
- //закончились попытки
- $r .= 'Странно, но ничего не произошло...
';
- } else {
- if ($itm[1] * 1000 >= rand(1, 100000)) {
+ $itm = explode('=', $t[$j]);
+ $ch = ActionModel::testCount(["uid = {$this->userinfo['id']}", "vars = takeit_{$this->info['id']}_{$obj['id']}"], 1 + (int)$itm[2]); //кол-во прошлых попыток
- //Случайный предмет (Башня смерти)
- if ($itm[0] == 'random1') {
- $itm[0] = $this->itbs[rand(0, count($this->itbs))];
- }
+ if ($ch >= $itm[2]) {
+ //закончились попытки
+ $r .= 'Странно, но ничего не произошло...
';
+ } else {
+ if ($itm[1] * 1000 >= rand(1, 100000)) {
- //удачная попытка
- $it = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `items_main` WHERE `id`="' . ((int)$itm[0]) . '" LIMIT 1'
- )
- );
- if (isset($it['id'])) {
- $r .= 'Вы обнаружили предмет "' . $it['name'] . '".
';
- $u->addAction(
- time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
- );
- ItemsModel::addItem(
- ['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]
- );
- $nj++;
- }
- } else {
- //неудачная попытка
+ //Случайный предмет (Башня смерти)
+ if ($itm[0] == 'random1') {
+ $itm[0] = $this->itbs[rand(0, count($this->itbs))];
+ }
+
+ //удачная попытка
+ $it = mysql_fetch_assoc(
+ mysql_query(
+ 'SELECT * FROM `items_main` WHERE `id`="' . ((int)$itm[0]) . '" LIMIT 1'
+ )
+ );
+ if (isset($it['id'])) {
+ $r .= 'Вы обнаружили предмет "' . $it['name'] . '".
';
$u->addAction(
time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
);
- $r .= 'Вы ничего не нашли ...
';
+ ItemsModel::addItem($it['id'], $this->userinfo['id']);
+ //ItemsModel::addItem(['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]);
}
+ } else {
+ //неудачная попытка
+ $u->addAction(
+ time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
+ );
+ $r .= 'Вы ничего не нашли ...
';
}
}
+
} elseif ($s[0] == 'itm2') {
//Добавляем предмет , только 1 предмет из всех и только 1 юзер может поднять
- $nj = 0;
+
$t = explode(',', $s[1]);
$j = rand(0, count($t) - 1);
- if ($nj == 0) {
- $itm = explode('=', $t[$j]);
- $ch = $u->testAction(
- '`vars` = "takeit_' . $this->info['id'] . '_' . $obj['id'] . '" LIMIT ' . (1 + (int)$itm[2]) . '',
- 2
- ); //кол-во прошлых попыток
- $ch = $ch[0];
- if ($ch >= $itm[2]) {
- //закончились попытки
- $r .= 'Ничего не произошло...
';
- } else {
- if ($itm[1] * 1000 >= rand(1, 100000)) {
+ $itm = explode('=', $t[$j]);
+ $ch = ActionModel::testCount(["vars = takeit_{$this->info['id']}_{$obj['id']}"], 1 + (int)$itm[2]); //кол-во прошлых попыток
- //Случайный предмет (Башня смерти)
- if ($itm[0] == 'random1') {
- $itm[0] = $this->itbs[rand(0, count($this->itbs))];
- }
+ if ($ch >= $itm[2]) {
+ //закончились попытки
+ $r .= 'Ничего не произошло...
';
+ } else {
+ if ($itm[1] * 1000 >= rand(1, 100000)) {
- //удачная попытка
- $it = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `items_main` WHERE `id`="' . ((int)$itm[0]) . '" LIMIT 1'
- )
- );
- if (isset($it['id'])) {
- $r .= 'Вы обнаружили предмет "' . $it['name'] . '".
';
- $u->addAction(
- time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
- );
- ItemsModel::addItem(
- ['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]
- );
- $nj++;
- }
- } else {
- //неудачная попытка
+ //Случайный предмет (Башня смерти)
+ if ($itm[0] == 'random1') {
+ $itm[0] = $this->itbs[rand(0, count($this->itbs))];
+ }
+
+ //удачная попытка
+ $it = mysql_fetch_assoc(
+ mysql_query(
+ 'SELECT * FROM `items_main` WHERE `id`="' . ((int)$itm[0]) . '" LIMIT 1'
+ )
+ );
+ if (isset($it['id'])) {
+ $r .= 'Вы обнаружили предмет "' . $it['name'] . '".
';
$u->addAction(
time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
);
- $r .= 'Вы ничего не нашли ...
';
+ ItemsModel::addItem($it['id'], $this->userinfo['id']);
+ //ItemsModel::addItem(['uid' => $this->userinfo['id'], 'iid' => $it['id'], 'x' => $this->userinfo['x'], 'y' => $this->userinfo['y'], 'del' => (int)$itm[4]]);
}
+ } else {
+ //неудачная попытка
+ $u->addAction(
+ time(), 'takeit_' . $this->info['id'] . '_' . $obj['id'], $this->userinfo['city']
+ );
+ $r .= 'Вы ничего не нашли ...
';
}
}
} elseif ($s[0] == 'fileact') {
@@ -1166,7 +1140,7 @@ class Dungeon
}
$i++;
}
- $r = rtrim($r, '\
');
+ $r = rtrim($r, '\
');
if ($r == '') {
$r = 'В этот раз не удалось найти что-либо еще';
}
@@ -1690,7 +1664,7 @@ class Dungeon
}
- $sp = mysql_query('SELECT * FROM `dungeon_now` WHERE `time_finish` = "0" LIMIT 50');
+ $sp = mysql_query('select * from dungeon_now where time_finish = 0 limit 50');
while ($pl = mysql_fetch_assoc($sp)) {
$cn = mysql_fetch_assoc(
mysql_query('SELECT `id` FROM `stats` WHERE `dnow` = "' . $pl['id'] . '" LIMIT 1')
diff --git a/_incl_data/class/Helper/QueryBuilder.php b/_incl_data/class/Helper/QueryBuilder.php
new file mode 100644
index 00000000..a27facd2
--- /dev/null
+++ b/_incl_data/class/Helper/QueryBuilder.php
@@ -0,0 +1,68 @@
+columns = $columns;
+ }
+
+ /**
+ * @throws Exception
+ */
+ public function select(array $filters = [], int $limit = 0): array
+ {
+ if (empty($filters)) {
+ return ['sql' => "select $this->columns from $this->tableName"];
+ }
+ $where = [];
+ $params = [];
+ foreach ($filters as $filter) {
+ [$name, $operation, $value] = explode(' ', $filter, 3);
+ $placeholder = ":$name";
+ $value = explode(' ', $value, 3); //todo: а ведь может прилететь значение из нескольких слов с пробелом...
+ if (count($value) === 1) {
+ $value = $value[0];
+ if (is_numeric($value)) {
+ $value = (int)$value;
+ }
+ } else {
+ array_walk_recursive($value, function (&$var) {
+ if (is_numeric($var)) {
+ $var = (int)$var;
+ }
+ });
+ if (is_numeric($value[0]) && is_numeric($value[2])) {
+ $value = match ($value[1]) {
+ '+' => $value[0] + $value[2],
+ '-' => $value[0] - $value[2],
+ '*' => $value[0] * $value[2],
+ '/' => ($value[2] != 0) ? $value[0] / $value[2] : throw new Exception('Деление на ноль недопустимо.'),
+ default => throw new Exception('Недопустимый оператор. Допустимы: +, -, *, /.'),
+ };
+ } elseif (is_string($value[0])) {
+ $placeholder = "$value[0] $value[1] :$name";
+ $value = $value[2];
+ } elseif (is_string($value[2])) {
+ $placeholder = "$value[2] $value[1] :$name";
+ $value = $value[0];
+ }
+ }
+ //todo: но есть ещё форменное скотство, когда в запрос кидают сложные формулы...
+
+ $where[] = "$name $operation $placeholder";
+ $params[$name] = $value;
+ }
+
+ return [
+ 'sql' => "select $this->columns from $this->tableName where " . implode(" and ", $where) . ($limit > 0 ? " limit $limit" : ""),
+ 'binds' => $params,
+ ];
+ }
+}
\ No newline at end of file
diff --git a/_incl_data/class/Magic.php b/_incl_data/class/Magic.php
index ec88e856..dce02ff9 100644
--- a/_incl_data/class/Magic.php
+++ b/_incl_data/class/Magic.php
@@ -1491,9 +1491,6 @@ class Magic
} else {
$u->error = 'Персонаж "' . $jl . '" не найден в этом городе (' . $u->info['city'] . ')';
}
- } elseif (isset($st['useOnItem']) && $st['useOnItem'] == 1) {
- //используем на предмет
-
} else {
//на себя
$goodUse = 1;
@@ -1502,170 +1499,7 @@ class Magic
$u->error = 'Хаосники не могут использовать данное заклятие';
}
- if ($itm['magic_inci'] == 'sanich2') {
- if ($u->info['battle'] == 0) {
- $sz = $u->testAction(
- '`uid` = "' . $u->info['id'] . '" AND `vars` = "sanich2" AND `time` > ' . (time() - 4 * 60 * 60) . ' LIMIT 1', 1
- );
- if (!isset($sz['id'])) {
- $slech = rand(0, 4);
- $goodUse = 0;
- if ($slech == 1) {
- //3083 Настойка на жучьей требухе
- //$this->add_eff($u->info['id'],3083);
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 290 AND `delete` =0'
- );
- $this->addEffect($u->info['id'], 290);
- $echotext = 'Настойка на жучьей требухе!';
- $u->error = 'Вы получили эфект от ' . $echotext . '';
- } elseif ($slech == 2) {
- //5239 Амброзия подмастерья Владык
- //$this->add_eff($u->info['id'],5239);
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 472 AND `delete` =0'
- );
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 470 AND `delete` =0'
- );
- $this->addEffect($u->info['id'], 472);
- $echotext = 'Амброзия подмастерья Владык!';
- $u->error = 'Вы получили эфект от ' . $echotext . '';
- } elseif ($slech == 3) {
- //5069 Амброзия Скучающих Владык
- //$this->add_eff($u->info['id'],470);
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 472 AND `delete` =0'
- );
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 470 AND `delete` =0'
- );
- $this->addEffect($u->info['id'], 470);
- $echotext = 'Амброзия Скучающих Владык!';
- $u->error = 'Вы получили эфект от ' . $echotext . '';
- } elseif ($slech == 4) {
- //1463 Звездное Сияние
- //$this->add_eff($u->info['id'],1463);
- mysql_query(
- 'DELETE FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = 35 AND `delete` =0'
- );
- $this->addEffect($u->info['id'], 35);
- $echotext = 'Звездное Сияние!';
- $u->error = 'Вы получили эфект от ' . $echotext . '';
- } else {
- $slech = 1;
-
- $echotext = 'Не удалось прочитать страницу!';
- $u->error = ' ' . $echotext . ' ';
- }
-
- $itm['iznosNOW'] += $slech;
- mysql_query(
- 'UPDATE `items_users` SET `iznosNOW` = "' . $itm['iznosNOW'] . '" WHERE `id` = "' . $itm['id'] . '" AND `uid` = "' . $u->info['id'] . '" LIMIT 1'
- );
- $u->addAction(time(), 'sanich2', $slech);
-
- if ($u->info['sex'] == 1) {
- $rtxt = '[img[items/' . $itm['img'] . ']] "' . $u->info['login'] . '" использовала "' . $itm['name'] . ' Саныча" и получила эффект ' . $echotext . ' травмы.';
- } else {
- $rtxt = '[img[items/' . $itm['img'] . ']] "' . $u->info['login'] . '" использовал "' . $itm['name'] . ' Саныча" и получил эффект ' . $echotext . ' травмы.';
- }
-
- } else {
- $u->error = 'Задержка использования ' . Conversion::secondsToTimeout(
- ($sz['time'] + 4 * 60 * 60) - time()
- ) . '.';
- }
- } else {
- $u->error = 'Невозможно использовать в бою';
- }
-
- } elseif ($itm['magic_inci'] == 'sanich1' && $u->info['battle'] > 0) {
-
- $sz = $u->testAction(
- '`uid` = "' . $u->info['id'] . '" AND `vars` = "sanich1" AND `time` > ' . (time() - 6 * 60) . ' LIMIT 1', 1
- );
- if (!isset($sz['id'])) {
- $goodUse = 0;
- $u->error = 'Вы успешно использовали "' . $itm['name'] . '"';
- $z = 1;
- while ($z <= 5) {
- $u->info['tactic' . $z]++;
- if ($u->info['tactic' . $z] > 25) {
- $u->info['tactic' . $z] = 25;
- } elseif ($u->info['tactic' . $z] < 0) {
- $u->info['tactic' . $z] = 0;
- }
- $z++;
- }
- if ($u->info['sex'] == 1) {
- $this->inBattleLog('{u1} использовала "' . $itm['name'] . ' Саныча".');
- } else {
- $this->inBattleLog('{u1} использовал "' . $itm['name'] . ' Саныча".');
- }
- mysql_query(
- 'UPDATE `stats` SET `tactic1` = "' . $u->info['tactic1'] . '",`tactic2` = "' . $u->info['tactic2'] . '",`tactic3` = "' . $u->info['tactic3'] . '",`tactic4` = "' . $u->info['tactic4'] . '",`tactic5` = "' . $u->info['tactic5'] . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
- );
- $itm['iznosNOW']++;
- mysql_query(
- 'UPDATE `items_users` SET `iznosNOW` = "' . $itm['iznosNOW'] . '" WHERE `id` = "' . $itm['id'] . '" AND `uid` = "' . $u->info['id'] . '" LIMIT 1'
- );
- $u->addAction(time(), 'sanich1', $u->info['battle']);
- } else {
- $u->error = 'Задержка использования ' . Conversion::secondsToTimeout(($sz['time'] + 6 * 60) - time()) . '.';
- }
-
- } elseif ($itm['magic_inci'] == 'sanich3' && $u->info['battle'] > 0) {
-
- $sz = $u->testAction(
- '`uid` = "' . $u->info['id'] . '" AND `vars` = "sanich3" AND `time` > ' . (time() - 3 * 60 * 60) . ' LIMIT 1', 1
- );
- if (!isset($sz['id'])) {
-
- $usr = mysql_fetch_array(
- mysql_query(
- 'SELECT `u`.`id`,`u`.`level`,`s`.`hpNow`,`s`.`team`,`u`.`login`,`u`.`sex` FROM `users` AS `u` LEFT JOIN `stats` AS `s` ON `s`.`id` = `u`.`id` WHERE `u`.`id` = "' . $u->info['enemy'] . '" AND `u`.`battle` = "' . $u->info['battle'] . '" LIMIT 1'
- )
- );
- if (isset($usr['id']) && $usr['hpNow'] >= 1) {
- $iznslvl = $usr['level'];
-
- $goodUse = 0;
- $u->error = 'Вы успешно использовали "' . $itm['name'] . '" на ' . $usr['login'] . '';
-
- if ($u->info['sex'] == 1) {
- $this->inBattleLog(
- '{u1} использовала "' . $itm['name'] . ' Саныча" на {u2}.',
- $usr
- );
- } else {
- $this->inBattleLog(
- '{u1} использовал "' . $itm['name'] . ' Саныча" на {u2}.', $usr
- );
- }
-
- mysql_query(
- 'UPDATE `stats` SET `hpNow` = "' . $usr['hpNow'] . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
- );
- mysql_query(
- 'UPDATE `stats` SET `hpNow` = "' . $u->stats['hpNow'] . '" WHERE `id` = "' . $usr['id'] . '" LIMIT 1'
- );
- $itm['iznosNOW'] += $iznslvl;
- mysql_query(
- 'UPDATE `items_users` SET `iznosNOW` = "' . $itm['iznosNOW'] . '" WHERE `id` = "' . $itm['id'] . '" AND `uid` = "' . $u->info['id'] . '" LIMIT 1'
- );
- $u->addAction(time(), 'sanich3', $u->info['battle']);
- } else {
- $u->error = 'Нет подходящего противника';
- }
-
- } else {
- $u->error = 'Задержка использования ' . Conversion::secondsToTimeout(
- ($sz['time'] + 3 * 60 * 60) - time()
- ) . '.';
- }
-
- } elseif ($itm['magic_inci'] == 'lech') {
+ if ($itm['magic_inci'] == 'lech') {
$goodUse = 0;
if ($u->info['level'] >= 2 and $u->info['level'] <= 13) {
$travm = mysql_fetch_array(
@@ -1698,7 +1532,6 @@ class Magic
if ($goodUse == 1) {
-
$upd1 = 1;
$upd2 = 1;
//добавляем эффект персонажу
diff --git a/_incl_data/class/Magic/podvig.php b/_incl_data/class/Magic/podvig.php
index 00e1eb30..9b69f509 100644
--- a/_incl_data/class/Magic/podvig.php
+++ b/_incl_data/class/Magic/podvig.php
@@ -1,38 +1,39 @@
info['id'] . '" AND `vars` = "podvig" AND `time` > "' . (time()) . '" LIMIT 1'));
- if ($u->info['align'] != 2) {
- if (isset($test['id'])) {
- $u->error = 'Задержка не прошла, еще ' . Conversion::secondsToTimeout($test['time'] - time());
- } else {
- //
- $dngcity = [
- 5035 => ['angelscity', 'Бездна'],
- 5036 => ['capitalcity', 'Пещера Тысячи Проклятий'],
- 5037 => ['demonscity', 'Катакомбы'],
- 5038 => ['abandonedplain', 'Гора Легиона'], //mooncity
- 5039 => ['suncity', 'Грибница'],
- 5040 => ['sandcity', 'Пещера Мглы'],
- ];
- $dngcity = $dngcity[$itm['item_id']];
- $hgo1 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > "' . (time() - 86400) . '" AND `vars` = "psh_qt_' . $dngcity[0] . '" LIMIT 1', 1);
- if (!isset($hgo1['id'])) {
- $u->error = 'Нет задержки для подземелья ' . $dngcity[1] . '.';
- } else {
- $u->addAction(time(), 'podvig', '');
- $u->error = 'Успешно использован свиток Право на Подвиг (' . $dngcity[1] . ')';
- mysql_query('UPDATE `actions` SET `time` = "' . (time() - 86401) . '" WHERE `id` = "' . ($hgo1['id']) . '" LIMIT 1');
- mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = "' . $itm['id'] . '" LIMIT 1');
- }
- }
+ $test = Db::getRow("select id, time from actions where uid = ? and vars = 'podvig' and time > unix_timestamp() limit 1", [$u->info['id']]);
+ if (isset($test['id'])) {
+ $u->error = 'Задержка не прошла, еще ' . Conversion::secondsToTimeout($test['time'] - time());
} else {
- $u->error = 'Хаосники не могут пользоваться этим свитком!';
+ //
+ $dngcity = [
+ 5035 => ['angelscity', 'Бездна'],
+ 5036 => ['capitalcity', 'Пещера Тысячи Проклятий'],
+ 5037 => ['demonscity', 'Катакомбы'],
+ 5038 => ['abandonedplain', 'Гора Легиона'], //mooncity
+ 5039 => ['suncity', 'Грибница'],
+ 5040 => ['sandcity', 'Пещера Мглы'],
+ ];
+ $dngcity = $dngcity[$itm['item_id']];
+ $hgo1 = ActionModel::getOne(["uid = {$u->info['id']}", "time > unix_timestamp() - 86400", "vars = psh_qt_$dngcity[0]"], 'id');
+
+ if (!isset($hgo1)) {
+ $u->error = 'Нет задержки для подземелья ' . $dngcity[1] . '.';
+ } else {
+ $u->addAction(time(), 'podvig', '');
+ $u->error = "Успешно использован свиток Право на Подвиг ($dngcity[1])";
+ Db::sql('update actions set time = unix_timestamp() - 86401 where id = ?', [$hgo1]);
+ ItemsModel::addIznos($itm['id']);
+ }
}
+
}
diff --git a/_incl_data/class/Magic/tznanie.php b/_incl_data/class/Magic/tznanie.php
index b4f7a607..e08beb0c 100644
--- a/_incl_data/class/Magic/tznanie.php
+++ b/_incl_data/class/Magic/tznanie.php
@@ -1,4 +1,8 @@
error = 'Так не пойдет, вы уже что-то изучаете';
} else {
- $tst = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `vars` = "read" AND `vals` = "' . $itm['item_id'] . '" LIMIT 1', 1);
- if (isset($tst['id'])) {
+ $tst = (bool)ActionModel::testCount(["uid = $u->info['id']", 'vars = read', "vals = {$itm['item_id']}"]);
+
+ if ($tst) {
$u->error = 'Вы уже изучили данное знание';
} else {
$fn = '';
$tom_iz = 0;
if (($itm['item_id'] >= 1045 && $itm['item_id'] <= 1047) || ($itm['item_id'] >= 4812 && $itm['item_id'] <= 4813)) {
- $tst2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `vars` = "read" AND `vals` = "' . ($itm['item_id'] - 1) . '" LIMIT 1', 1);
- if (!isset($tst2['id'])) {
+ $tst2 = (bool)ActionModel::testCount(["uid = $u->info['id']", 'vars = read', "vals = {$itm['item_id']} - 1"]);
+ if (!$tst2) {
$tom_iz = 1;
}
unset($tst2);
@@ -41,7 +46,7 @@ if (isset($po['finish_file']) && $po['finish_file'] == 'tznanie') {
$u->error = 'Вы изучили "' . $itm['name'] . '".';
$u->addAction(time() + $st['timeRead'], 'read', $itm['item_id']);
- mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
+ ItemsModel::addIznos($itm['id']);
} else {
$u->error = 'Требует изучения предыдущего тома';
diff --git a/_incl_data/class/Model/ActionModel.php b/_incl_data/class/Model/ActionModel.php
index e84a8fbc..704b53a6 100644
--- a/_incl_data/class/Model/ActionModel.php
+++ b/_incl_data/class/Model/ActionModel.php
@@ -3,10 +3,13 @@
namespace Model;
use Core\Db;
+use Exception;
+use Helper\QueryBuilder;
use User\UserIp;
class ActionModel
{
+ private const TABLE_NAME = 'actions';
private int $uid;
public function __construct(int $uid)
@@ -34,9 +37,51 @@ class ActionModel
);
}
- public static function getAll(string $filter = ''): array
+ public static function get(array $filters, string $columns = '*'): array
{
- return Db::getRows('select * from actions');
+ $query = new QueryBuilder(self::TABLE_NAME, $columns);
+ try {
+ $stmt = $query->select($filters, 1);
+ return Db::getRow($stmt['sql'], $stmt['binds']);
+ } catch (Exception $e) {
+ echo $e->getMessage();
+ trigger_error(__METHOD__ . ': ' . $e->getMessage(), E_USER_ERROR);
+ }
+ }
+
+ public static function getOne(array $filters, string $column): mixed
+ {
+ $result = self::get($filters, $column);
+ if (!empty($result)) {
+ return array_shift($result);
+ }
+ return '';
+ }
+
+ public static function deleteById(int $id): void
+ {
+ Db::sql('delete from actions where id = ?', [$id]);
+ }
+
+ public static function testCount(array $filters, int $limit = 0): int
+ {
+ $query = new QueryBuilder(self::TABLE_NAME, 'count(id)');
+ try {
+ $stmt = $query->select($filters, $limit);
+ return Db::getValue($stmt['sql'], $stmt['binds']);
+ } catch (Exception $e) {
+ echo $e->getMessage();
+ trigger_error(__METHOD__ . ': ' . $e->getMessage(), E_USER_ERROR);
+ }
+ }
+
+ public static function testCountCustom(string $filter, array $binds, int $limit = 0): int
+ {
+ $sql = "select count(id) from actions where $filter";
+ if ($limit > 0) {
+ $sql .= ' limit ' . $limit;
+ }
+ return (int)Db::getValue($sql, $binds);
}
public function getByVals(string $vals)
@@ -54,6 +99,11 @@ class ActionModel
public function getLastByValsAndTime(string $vals, int $time)
{
+ $filter = [
+ "uid = $this->uid",
+ "vals = '$vals'",
+ "time > unix_timestamp() - $time",
+ ];
return Db::getRow(
'select * from actions where uid = ? and vals = ? and time > unix_timestamp() - ? order by time desc limit 1',
[$this->uid, $vals, $time]
@@ -65,28 +115,14 @@ class ActionModel
Db::sql('delete from actions where uid = ? and vals = ?', [$this->uid, $vals]);
}
- public static function deleteById(int $id): void
+ public function getDailyQuest(): array
{
- Db::sql('delete from actions where id = ?', [$id]);
- }
+ $filter = [
+ "uid = $this->uid",
+ "vars = 'day_quest'",
+ ];
- /*protected function testAction($filter, $tp): array
- {
- if ($tp == 1) {
- $query = 'select * from actions where ' . $filter;
- } elseif ($tp == 2) {
- $query = 'select count(*) from actions where ' . $filter;
- } else {
- return [];
- }
- $arr = mysql_fetch_array(mysql_query($query));
-
- return !empty($arr) ? $arr : [];
- }*/
-
- public function getDailyQuest(): array|false
- {
- return Db::getRow("select * from actions where uid = ? and vars = 'day_quest' limit 1", [$this->uid]);
+ return self::get($filter);
}
public function getFinishedDailyQuestTasks(int $timeout): array
diff --git a/_incl_data/class/Priems.php b/_incl_data/class/Priems.php
index 700d7230..6d4b1a2d 100644
--- a/_incl_data/class/Priems.php
+++ b/_incl_data/class/Priems.php
@@ -5,6 +5,7 @@ use Core\Db;
use DarksLight2\Training\TrainingManager;
use Helper\Conversion;
use Helper\Math;
+use Model\ActionModel;
use Model\Constant\Stat;
use User\Effects;
@@ -108,7 +109,7 @@ class Priems
/** используем прием каждый ход
* @param Battle $btl
- * @param array $eff
+ * @param array $eff
* @return bool
*/
public function hodUsePriem(Battle $btl, array $eff): bool
@@ -466,11 +467,11 @@ class Priems
/**
* Новая функция магического заклинания с приёма.
* Работает с числовыми приёмами в папке [priem].
- * @param int $attackerId кто использует приём
- * @param int $defenderId на кого использует приём
- * @param float $damage базовый урон приёма
- * @param string $damageType тип урона (стихия?) приходит строкой, и конвертируется функцией.
- * @param bool $hasCritical флаг, что приём МОЖЕТ критовать
+ * @param int $attackerId кто использует приём
+ * @param int $defenderId на кого использует приём
+ * @param float $damage базовый урон приёма
+ * @param string $damageType тип урона (стихия?) приходит строкой, и конвертируется функцией.
+ * @param bool $hasCritical флаг, что приём МОЖЕТ критовать
* @return array [0|damage] int урон, [1|crit] bool был ли крит, [2|miss] bool был ли промах, [3|miss_type] int тип промаха (всегда = 2).
* @author Insallah
*/
@@ -786,7 +787,8 @@ class Priems
$krituet = true,
$heal = 0,
$namenew = null
- ) {
+ )
+ {
$trawm_off = false;
global $btl;
if ($namenew != null) {
@@ -965,8 +967,7 @@ class Priems
);
//заносим в лог боя
- $vLog = 'time1=' . time(
- ) . '||s1=' . $btl->users[$btl->uids[$usu]]['sex'] . '||t1=' . $btl->users[$btl->uids[$usu]]['team'] . '||login1=' . $btl->users[$btl->uids[$usu]]['login'] . '||s2=' . $btl->users[$btl->uids[$uen]]['sex'] . '||t2=' . $btl->users[$btl->uids[$uen]]['team'] . '||login2=' . $btl->users[$btl->uids[$uen]]['login'] . '';
+ $vLog = 'time1=' . time() . '||s1=' . $btl->users[$btl->uids[$usu]]['sex'] . '||t1=' . $btl->users[$btl->uids[$usu]]['team'] . '||login1=' . $btl->users[$btl->uids[$usu]]['login'] . '||s2=' . $btl->users[$btl->uids[$uen]]['sex'] . '||t2=' . $btl->users[$btl->uids[$uen]]['team'] . '||login2=' . $btl->users[$btl->uids[$uen]]['login'] . '';
$mas1 = [
'time' => time(),
'battle' => $btl->i->id,
@@ -1088,276 +1089,245 @@ class Priems
return $rr;
}
- public function pruse($id)
+ public function pruse($id): void
{
global $btl;
- $u = $this->u; // Для присоедиянемых файлов.
if ($id == 100500 && $this->u->info['animal'] > 0) {
- $use_lst = $this->u->testAction(
- '`uid` = "' . $this->u->info['id'] . '" AND `vars` = "animal_use' . $btl->i->id . '" LIMIT 1',
- 1
- );
- if (!isset($use_lst['id'])) {
- $a = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `users_animal` WHERE `uid` = "' . $this->u->info['id'] . '" AND `id` = "' . $this->u->info['animal'] . '" AND `pet_in_cage` = "0" AND `delete` = "0" LIMIT 1'
- )
- );
- if ($this->u->stats['hpNow'] < 1) {
- echo 'Вы не можете выпустить зверя, вы потеряли все НР';
- } elseif (isset($a['id']) && $a['eda'] < 1) {
- echo 'Вы не накормили зверя...';
- } elseif (isset($a['id'])) {
- //Добавляем зверя в бой
- $tp = [
- 1 => 'Кот',
- 2 => 'Сова',
- 3 => 'Светляк',
- 4 => 'Чертяка',
- 5 => 'Пес',
- 6 => 'Свин',
- 7 => 'Дракон',
- ];
- $id = mysql_fetch_assoc(
- mysql_query(
- 'SELECT `id` FROM `test_bot` WHERE `login` = "' . $tp[$a['type']] . ' [' . $a['level'] . ']" LIMIT 1'
- )
- );
- if (isset($id['id']) && $btl->i->type != 500) {
- $b = $this->u->addNewbot($id['id'], null, null);
- if ($b > 0 && $b) {
- $a['eda'] -= 4;
- if ($a['eda'] < 0) {
- $a['eda'] = 0;
- }
-
- $vLog = 'time1=' . time() . '||s1=' . $this->u->info['sex'] . '||t1=' . $this->u->info['team'] . '||login1=' . $this->u->info['login'] . '';
- $mas1 = [
- 'time' => time(),
- 'battle' => $btl->i->id,
- 'id_hod' => $btl->hodID,
- 'vars' => $vLog,
- 'zona1' => '',
- 'zonb1' => '',
- 'zona2' => '',
- 'zonb2' => '',
- 'type' => '1',
- ];
-
- $sex = $this->u->info['sex'] === 1 ? 'a' : '';
- $mas1['text'] = "{tm1} {u1} выпустил$sex зверя "" . $a['name'] . '"';
- Log::add($mas1);
-
- mysql_query(
- 'UPDATE `users` SET `login` = "' . $a['name'] . ' (зверь ' . $this->u->info['login'] . ')",`obraz` = "' . $a['obraz'] . '.gif",`battle` = "' . $btl->i->id . '" WHERE `id` = "' . $b['id'] . '" LIMIT 1'
- );
- mysql_query(
- 'UPDATE `stats` SET `team` = "' . $this->u->info['team'] . '" WHERE `id` = "' . $b['id'] . '" LIMIT 1'
- );
- mysql_query(
- 'UPDATE `users_animal` SET `eda` = "' . $a['eda'] . '" WHERE `id` = "' . $a['id'] . '" LIMIT 1'
- );
- $this->u->addAction(time(), 'animal_use' . $btl->i->id, $a['level']);
- } else {
- echo 'Не удалось выпустить зверя...';
- }
- } else {
- //Бот не найден
- echo '
Не удалось выпустить зверя - он боится...';
- }
- } else {
- //зверь не найден
- echo 'У Вас нет зверя ...';
- }
- } else {
- //зверь уже выпущен
- echo 'Вы уже выпускали зверя в этом бою ...';
- }
+ $this->processAnimal($btl);
} else {
- $p = explode('|', $this->u->info['priems']);
- $pz = explode('|', $this->u->info['priems_z']);
- if ($p[(int)$id] > 0 && $pz[(int)$id] <= 0 && $this->u->info['hpNow'] >= 1) {
- $pl = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `priems` WHERE `level`<=' . $this->u->info['level'] . ' AND `id` = ' . $p[(int)$id]
- )
- );
- if (isset($pl['id']) && $pl['activ'] != 1) {
- if ($pl['activ'] == 0) {
- unset($pl);
- } elseif ($pl['activ'] > 1) {
- //Книжный прием
- if ($this->testActiv($pl['activ']) == 0) {
- unset($pl);
- }
- }
- }
- if (isset($pl['id'])) {
- $notr = 0;
- $pl['useon_user'] = $this->u->info['enemy'];
- if (isset($_POST['useon']) && $_POST['useon'] != '' && $_POST['useon'] != 'none') {
- $this->ue = mysql_fetch_assoc(
- mysql_query(
- 'SELECT
-
- `u`.`id`,`u`.`login`,`u`.`login2`,`u`.`online`,`u`.`admin`,`u`.`city`,`u`.`cityreg`,`u`.`align`,`u`.`clan`,
- `u`.`level`,`u`.`money`,`u`.`money3`,`u`.`money4`,`u`.`battle`,`u`.`sex`,`u`.`obraz`,`u`.`win`,`u`.`win_t`,
- `u`.`lose`,`u`.`lose_t`,`u`.`nich`,`u`.`timeMain`,`u`.`invis`,`u`.`bot_id`,`u`.`animal`,`u`.`type_pers`,
- `u`.`notrhod`,`u`.`bot_room`,`u`.`inUser`,`u`.`inTurnir`,`u`.`inTurnirnew`,`u`.`stopexp`,`u`.`real`,
-
- `st`.*
-
- FROM `users` AS `u`
- LEFT JOIN `stats` AS `st` ON (`u`.`id`=`st`.`id`)
- WHERE (
- `u`.`login`="' . mysql_real_escape_string($_POST['useon']) . '" OR
- (
- `u`.`login2` = "' . mysql_real_escape_string($_POST['useon']) . '" AND
- `u`.`login2` != "")
- ) AND
- (
- `u`.`inUser` > 0 OR
- (
- `u`.`battle`="' . $btl->i->id . '" AND
- `st`.`hpNow` > 0
- )
- ) ORDER BY `u`.`id` DESC LIMIT 1'
- )
- );
- if (isset($this->ue['id']) && $this->ue['inUser'] > 0) {
- $this->ue = mysql_fetch_assoc(
- mysql_query(
- 'SELECT
-
- `u`.`id`,`u`.`login`,`u`.`login2`,`u`.`online`,`u`.`admin`,`u`.`city`,`u`.`cityreg`,`u`.`align`,`u`.`clan`,
- `u`.`level`,`u`.`money`,`u`.`money3`,`u`.`money4`,`u`.`battle`,`u`.`sex`,`u`.`obraz`,`u`.`win`,`u`.`win_t`,
- `u`.`lose`,`u`.`lose_t`,`u`.`nich`,`u`.`timeMain`,`u`.`invis`,`u`.`bot_id`,`u`.`animal`,`u`.`type_pers`,
- `u`.`notrhod`,`u`.`bot_room`,`u`.`inUser`,`u`.`inTurnir`,`u`.`inTurnirnew`,`u`.`stopexp`,`u`.`real`,
-
- `st`.*
-
- FROM `users` AS `u`
- LEFT JOIN `stats` AS `st` ON (`u`.`id`=`st`.`id`)
- WHERE
- `u`.`battle`="' . $btl->i->id . '" AND
- `st`.`hpNow` > 0) AND
- `u`.`id` = "' . $this->ue['inUser'] . '" ORDER BY `u`.`id` ASC LIMIT 1'
- )
- );
- }
- if (!isset($this->ue['id']) && $pl['trUser'] > 0) {
- $notr++;
- }
- if ($pl['team'] == 1) {
- //свои
- if ($this->u->info['team'] != $this->ue['team']) {
- $notr++;
- }
- } elseif ($pl['team'] == 2) {
- //противники
- if ($this->u->info['team'] == $this->ue['team']) {
- $notr++;
- }
- }
- } else {
- $ga = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `battle_act` WHERE `battle` = "' . $btl->i->id . '" AND `uid1` = "' . $this->u->info['id'] . '" AND `uid2` = "' . $this->u->info['enemy'] . '" LIMIT 1'
- )
- );
- if (($this->u->info['enemy'] == 0 || isset($ga['id'])) && ($pl['tr_hod'] > 0 || $pl['trUser'] > 0)) {
- $notr++;
- }
- }
-
- $notr += $this->testpriem($pl, 1, $this->ue['id']);
-
- if ($this->ue['id'] > 0) {
- $notr += $this->testRazmenOldUser($this->ue['id'], $this->u->info['enemy'], $pl['id']);
- }
-
- if ($notr == 0) {
- mysql_query(
- 'UPDATE `stats` SET `last_pr` = "' . $pl['id'] . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
- );
-
- //Приемы на персонажах
- if ($this->ue['id'] > 0) {
- $btl->priemsRazmen([$this->u->info['id'], $this->ue['id']], 'fast');
- mysql_query(
- 'UPDATE `eff_users` SET `mark` = 1 WHERE `uid` = "' . $this->ue['id'] . '" AND `delete` = 0'
- );
- } else {
- $btl->priemsRazmen([$this->u->info['id'], $this->u->info['enemy']], 'fast');
- mysql_query(
- 'UPDATE `eff_users` SET `mark` = 1 WHERE `uid` = "' . $this->u->info['enemy'] . '" AND `delete` = 0'
- );
- }
- mysql_query(
- 'UPDATE `eff_users` SET `mark` = 1 WHERE `uid` = "' . $this->u->info['id'] . '" AND `delete` = 0'
- );
-
- if (file_exists('../../_incl_data/class/Priem/' . $pl['id'] . '.php')) {
- require('../../_incl_data/class/Priem/' . $pl['id'] . '.php');
- $this->testDie($this->ue['id']);
- } else {
- echo 'useSkill' . $pl['id'];
- }
-
- if (!isset($cup)) {
- $this->uppz($pl, $id);
- //Отнимаем тактики
- //$this->mintr($pl);
- if ($pl['tr_hod'] > 0) {
- $this->trhod($pl);
- }
- if ($pl['id'] != 258) {
- if ($pl['cancel_eff'] == '') {
- $pl['cancel_eff'] = '258';
- } else {
- $pl['cancel_eff'] .= ',258';
- }
- }
- if ($pl['cancel_eff'] != '') {
- $i = 0;
- $e = explode(',', $pl['cancel_eff']);
- while ($i < count($e)) {
- if ($e[$i] > 0) {
- if ($e[$i] == 258) {
- $nem = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `eff_users` WHERE `uid` = "' . $this->u->info['id'] . '" AND `v1` = "priem" AND `v2` = "' . $e[$i] . '" AND `delete` = "0" AND `mark` = 1 LIMIT 1'
- )
- );
- } else {
- $nem = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `eff_users` WHERE `uid` = "' . $this->ue['id'] . '" AND `v1` = "priem" AND `v2` = "' . $e[$i] . '" AND `delete` = "0" AND `mark` = 1 LIMIT 1'
- )
- );
- }
- if (isset($nem['id'])) {
- $nem['priem'] = mysql_fetch_assoc(
- mysql_query(
- 'SELECT * FROM `priems` WHERE `id` = "' . $e[$i] . '" LIMIT 1'
- )
- );
- if (isset($nem['id'])) {
- $btl->delPriem($nem, $btl->users[$btl->uids[$this->ue['id']]], 500);
- }
- }
- }
- $i++;
- }
- }
- }
- }
- }
- }
+ $this->processPriem($id, $btl);
}
}
- //для папки priems
+ private function processAnimal(Battle $btl): void
+ {
+ if ($this->u->stats['hpNow'] < 1) {
+ echo 'Вы не можете выпустить зверя, вы потеряли все НР';
+ return;
+ }
+
+ $alreadyReleased = ActionModel::testCount(["uid = {$this->u->info['id']}", "vars = animal_use{$btl->i->id}"]);
+
+ if (!empty($alreadyReleased)) {
+ echo 'Вы уже выпускали зверя в этом бою ...';
+ return;
+ }
+
+ $animal = Db::getRow('select * from users_animal where uid = ? and id = ? and pet_in_cage = 0', [$this->u->info['id'], $this->u->info['animal']]);
+
+ if (!isset($animal['id'])) {
+ echo 'У вас нет зверя.';
+ return;
+ }
+
+ if ($animal['eda'] < 1) {
+ echo 'Вы не накормили зверя.';
+ return;
+ }
+
+ $animalTypes = [
+ 1 => 'Кот',
+ 2 => 'Сова',
+ 3 => 'Светляк',
+ 4 => 'Чертяка',
+ 5 => 'Пес',
+ 6 => 'Свин',
+ 7 => 'Дракон',
+ ];
+
+ $botLogin = $animalTypes[$animal['type']] . ' [' . $animal['level'] . ']';
+ $botId = Db::getValue('select id from test_bot where login = ?', [$botLogin]);
+
+ if (!$botId) {
+ echo 'Системная ошибка: Неизвестный зверь!';
+ return;
+ }
+
+ $b = $this->u->addNewbot($botId);
+
+ if (!$b) {
+ echo 'Не удалось призвать зверя.';
+ return;
+ }
+
+ if ($b > 0) {
+ $animal['eda'] -= 4;
+ if ($animal['eda'] < 0) {
+ $animal['eda'] = 0;
+ }
+
+ $logData = [
+ 'time' => time(),
+ 'battle' => $btl->i->id,
+ 'id_hod' => $btl->hodID,
+ 'vars' => 'time1=' . time() . '||s1=' . $this->u->info['sex'] . '||t1=' . $this->u->info['team'] . '||login1=' . $this->u->info['login'],
+ 'zona1' => '',
+ 'zonb1' => '',
+ 'zona2' => '',
+ 'zonb2' => '',
+ 'type' => '1',
+ 'text' => '{tm1} {u1} выпустил' . ($this->u->info['sex'] === 1 ? 'a' : '') . " зверя «{$animal['name']}».",
+ ];
+ Log::add($logData);
+
+ Db::sql('update users set login = ?, obraz = ?, battle = ? where id = ?', [$animal['name'], $animal['obraz'] . '.gif', $btl->i->id, $b['id']]);
+ Db::sql('update stats set team = ? where id = ?', [$this->u->info['team'], $b['id']]);
+ Db::sql('update users_animal set eda = ? where id = ?', [$animal['eda'], $animal['id']]);
+ $this->u->addAction(time(), 'animal_use' . $btl->i->id, $animal['level']);
+ }
+ }
+
+ private function processPriem(int $id, Battle $btl): void
+ {
+ $target = '';
+ $targetNotEmpty = false;
+ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ $target = (string)filter_input(INPUT_POST, 'useon');
+ $targetNotEmpty = $target && $target !== 'none';
+ }
+ $cup = false;
+ $priemsOnPlayer = explode('|', $this->u->info['priems']);
+ $pz = explode('|', $this->u->info['priems_z']);
+ if ($priemsOnPlayer[$id] <= 0 || $pz[$id] > 0 || $this->u->info['hpNow'] < 1) {
+ return;
+ }
+
+ $priem = Db::getRow('select * from priems where level <= ? and id = ?', [$this->u->info['level'], $priemsOnPlayer['id']]);
+
+ if (isset($priem['id']) && $priem['activ'] != 1) {
+ if ($priem['activ'] == 0) {
+ unset($priem);
+ } elseif ($priem['activ'] > 1) {
+ //Книжный прием
+ if ($this->testActiv($priem['activ']) == 0) {
+ unset($priem);
+ }
+ }
+ }
+
+ if (!isset($priem['id'])) {
+ return;
+ }
+
+ $notr = 0;
+ $priem['useon_user'] = $this->u->info['enemy'];
+ if ($targetNotEmpty) {
+ $this->ue = Db::getRow('select
+ users.id, login, login2, online, admin, city, cityreg, align, clan, level, money, money3, money4, battle, sex, obraz, win, win_t, lose, lose_t, nich,
+ timeMain, invis, bot_id, animal, type_pers, notrhod, bot_room, inUser, inTurnir, inTurnirnew, stopexp, `real`, stats.*
+ from users inner join stats on users.id = stats.id where (login = ? or login2 = ?) and (inUser > 0 or (battle = ? and hpNow > 0))
+ order by users.id desc limit 1', [$target, $target, $btl->i->id]);
+
+ if (isset($this->ue['id']) && $this->ue['inUser'] > 0) {
+ $this->ue = Db::getRow('select
+ users.id, login, login2, online, admin, city, cityreg, align, clan, level, money, money3, money4, battle, sex, obraz, win, win_t, lose, lose_t, nich,
+ timeMain, invis, bot_id, animal, type_pers, notrhod, bot_room, inUser, inTurnir, inTurnirnew, stopexp, `real`, stats.*
+ from users inner join stats on users.id = stats.id where battle = ? and hpNow > 0 and users.id = ?
+ order by users.id limit 1', [$btl->i->id, $this->ue['inUser']]);
+ }
+
+ if (!isset($this->ue['id']) && $priem['trUser'] > 0) {
+ $notr++;
+ }
+ if ($priem['team'] == 1) {
+ //свои
+ if ($this->u->info['team'] != $this->ue['team']) {
+ $notr++;
+ }
+ } elseif ($priem['team'] == 2) {
+ //противники
+ if ($this->u->info['team'] == $this->ue['team']) {
+ $notr++;
+ }
+ }
+ } else {
+ $check = Db::getValue('select count(id) from battle_act where battle = ? and uid1 = ? and uid2 = ?', [$btl->i->id, $this->u->info['id'], $this->u->info['enemy']]) > 0;
+
+ if (($this->u->info['enemy'] == 0 || $check) && ($priem['tr_hod'] > 0 || $priem['trUser'] > 0)) {
+ $notr++;
+ }
+ }
+
+ $notr += $this->testpriem($priem, 1, $this->ue['id']);
+
+ if ($this->ue['id'] > 0) {
+ $notr += $this->testRazmenOldUser($this->ue['id'], $this->u->info['enemy'], $priem['id']);
+ }
+
+ if ($notr != 0) {
+ return;
+ }
+
+ Db::sql('update stats set last_pr = ? where id = ?', [$priem['id'], $this->u->info['id']]);
+
+ //Приемы на персонажах
+ $markuids = [];
+ if ($this->ue['id'] > 0) {
+ $btl->priemsRazmen([$this->u->info['id'], $this->ue['id']], 'fast');
+ $markuids[] = $this->ue['id'];
+ } else {
+ $btl->priemsRazmen([$this->u->info['id'], $this->u->info['enemy']], 'fast');
+ $markuids[] = $this->u->info['enemy'];
+ }
+ $markuids[] = $this->u->info['id'];
+
+ Db::sql('update eff_users set mark = 1 where uid in (?)', [implode(',', $markuids)]);
+
+ if (file_exists('../../_incl_data/class/Priem/' . $priem['id'] . '.php')) {
+ $u = $this->u; // Для присоедиянемых файлов.
+ require_once '../../_incl_data/class/Priem/' . $priem['id'] . '.php';
+ $this->testDie($this->ue['id']);
+ } else {
+ echo 'useSkill' . $priem['id'];
+ }
+
+ if ($cup) { // Из подключаемых файлов.
+ return;
+ }
+
+ $this->uppz($priem, $id);
+ //Отнимаем тактики
+ //$this->mintr($pl);
+ if ($priem['tr_hod'] > 0) {
+ $this->trhod($priem);
+ }
+
+ if ($priem['id'] != 258) {
+ if ($priem['cancel_eff'] == '') {
+ $priem['cancel_eff'] = '258';
+ } else {
+ $priem['cancel_eff'] .= ',258';
+ }
+ }
+
+ if ($priem['cancel_eff'] == '') {
+ return;
+ }
+
+ $i = 0;
+ $e = explode(',', $priem['cancel_eff']);
+ while ($i < count($e)) {
+ if ($e[$i] <= 0) {
+ $i++;
+ continue;
+ }
+
+ if ($e[$i] == 258) {
+ $uid = $this->u->info['id'];
+ } else {
+ $uid = $this->ue['id'];
+ }
+
+ $nem = Db::getRow('select * from eff_users where uid = ? and v1 = \'priem\' and v2 = ? and mark = 1 limit 1', [$uid, $e[$i]]);
+
+ if (isset($nem['id'])) {
+ $nem['priem'] = Db::getRow('select * from priems where id = ?', [$e['id']]);
+ $btl->delPriem($nem, $btl->users[$btl->uids[$this->ue['id']]], 500);
+ }
+
+ $i++;
+ }
+ }
private function testActiv($id)
{
@@ -1368,11 +1338,8 @@ class Priems
$this->u->info['id'] > 0) {
$r = 1;
} else {
- $tst = $this->u->testAction(
- '`uid` = "' . $this->u->info['id'] . '" AND `time` < ' . time() . ' AND `vars` = "read" AND `vals` = "' . $id . '" LIMIT 1',
- 1
- );
- if (isset($tst['id'])) {
+ $test = (bool)Db::getValue("select count(id) from actions where uid = ? and time < unix_timestamp() and vars = 'read' and vals = ?", [$this->u->info['id'], $id]);
+ if ($test) {
$r = 1;
}
}
@@ -1428,11 +1395,8 @@ class Priems
if ($pl['xuse'] > 0) {
- $xu = $this->u->testAction(
- '`vars` = "use_priem_' . $btl->i->id . '_' . $this->u->info['id'] . '" AND `vals` = "' . $pl['id'] . '" LIMIT ' . $pl['xuse'],
- 2
- );
- if ($xu[0] >= $pl['xuse']) {
+ $xu = ActionModel::testCount(["vars = use_priem_{$btl->i->id}_{$this->u->info['id']}", "vals = {$pl['id']}"], $pl['xuse']);
+ if ($xu >= $pl['xuse']) {
$notr++;
}
}
@@ -1579,13 +1543,13 @@ class Priems
}
/**
- * @param int $uid на кого кастуем
- * @param int $pr id приема
+ * @param int $uid на кого кастуем
+ * @param int $pr id приема
* @param int|string $data дата, если -1, то добавляем дату3
- * @param int $d2
+ * @param int $d2
* @param $tm
- * @param int $h ход
- * @param int $uu id юзера который использовал
+ * @param int $h ход
+ * @param int $uu id юзера который использовал
* @param $max
* @param $bj
* @param $tp
@@ -1614,7 +1578,8 @@ class Priems
$noupdatebtl = 0,
$noplus = 0,
$pname = null
- ) {
+ )
+ {
global $btl;
//$pl = mysql_fetch_assoc(mysql_query('SELECT * FROM `priems` WHERE `id` = ' . (int)$pr));
$pl = Db::getRow('select * from priems where id = ?', [$pr]);
@@ -1732,8 +1697,8 @@ class Priems
/** Получает строку data c шаблонной записью типа add_m11=2*{lvl1} и конвертирует в реальную строку.
*
Шаблон:
lvl1 = $uid[level]
ts5 = $uid[s5]
mpAll = $uid[mpAll]
- * @param string $pl строка в формате data
- * @param int $uid пользователь, параметры которого используются для подставки в шаблон.
+ * @param string $pl строка в формате data
+ * @param int $uid пользователь, параметры которого используются для подставки в шаблон.
* @return string строка в формате data с развёрнутыми шаблонами.
*/
public function redate($pl, $uid)
@@ -1981,8 +1946,7 @@ class Priems
} else {
//бьем противника с пропуском хода
mysql_query(
- 'INSERT INTO `battle_act` (`battle`,`uid1`,`uid2`,`time`,`out1`,`type`,`tpo1`) VALUES ("' . $btl->i->id . '","' . $this->u->info['id'] . '","' . $this->u->info['enemy'] . '","' . time(
- ) . '","1","1","2")'
+ 'INSERT INTO `battle_act` (`battle`,`uid1`,`uid2`,`time`,`out1`,`type`,`tpo1`) VALUES ("' . $btl->i->id . '","' . $this->u->info['id'] . '","' . $this->u->info['enemy'] . '","' . time() . '","1","1","2")'
);
}
}
@@ -2046,6 +2010,8 @@ class Priems
}
}
+ //выводим приемы $id - 1 (вне боя), 2 - в бою
+
/** Одеть приём в слот?
* @param $id
* @return void
@@ -2086,11 +2052,11 @@ class Priems
);
if ($upd) {
TrainingManager::getInstance()
- ->addPoint(
- 'my_user_fourth_quest', function (TrainingManager $manager) {
- $manager->store();
- }
- );
+ ->addPoint(
+ 'my_user_fourth_quest', function (TrainingManager $manager) {
+ $manager->store();
+ }
+ );
$this->u->info['priems'] = $p;
}
} else {
@@ -2099,28 +2065,15 @@ class Priems
}
}
- //выводим приемы $id - 1 (вне боя), 2 - в бою
-
public function getTechniquesInfo(?int $id = null): array
{
- # SELECT * FROM `priems` WHERE `level`<="' . $this->u->info['level'] . '" AND `activ` > "0" AND `id` = "' . $id . '" LIMIT 1
-
if (isset($id)) {
return Db::getRow('select * from priems where level <= ? and activ > 0 and id = ? order by img,level', [$this->u->info['level'], $id]);
- // return Db::getRow(
- // 'select * from techniques_categories left join priems on techniques_categories.technique_id = priems.id
- // where priems.level <= ? and priems.activ > 0 and priems.id = ? order by priems.img,priems.level', [User::start()->info['level'], $id]
- // );
}
return Db::getRows('select * from priems where level <= ? and activ > 0 order by img,level', [$this->u->info['level']]);
- // return Db::getRows(
- // 'select * from techniques_categories left join priems on techniques_categories.technique_id = priems.id
- // where priems.level <= ? and priems.activ > 0 order by priems.img,priems.level', [User::start()->info['level']]
- // );
}
-
public function seeMyPriems(): void
{
$i = 0;
@@ -2172,7 +2125,7 @@ class Priems
/**
* Летит в js, двойные кавычки не использовать.
* @param array $pl
- * @param int $id
+ * @param int $id
* @return array
*/
private function priemInfo(array $pl, int $id = -1): array
@@ -2243,6 +2196,8 @@ class Priems
return [0 => $lvar, 1 => $pz];
}
+ //Мощность / подавление / сопротивление и т.д.
+
/**
* Генерирует html строку для вставки в JS $("#priems").html(" сюда ");
* @return string
@@ -2281,11 +2236,11 @@ class Priems
$cl = 'href="javascript:void(0);" onClick="top.priemOnUser(' . $i . ',1,\'' . $pl['name'] . '\',\'' . $oninuser . '\',\'' . $pl['img'] . '\');"';
unset($oninuser);
} else {
- $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ',1,\'' . $pl['img'] . '\');"';
+ $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ');"';
}
} elseif ($pl['type'] == 2) {
//длительное
- $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ',1,\'' . $pl['img'] . '\');"';
+ $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ');"';
} elseif ($pl['type'] == 3) {
$cl = 'href="javascript:void(0);" onClick="alert(\'Возможно используем?\');"';
}
@@ -2323,12 +2278,9 @@ class Priems
$i++;
}
if ($this->u->info['animal'] > 0) {
- $use_lst = $this->u->testAction(
- '`uid` = "' . $this->u->info['id'] . '" AND `vars` = "animal_use' . $btl->i->id . '" LIMIT 1',
- 1
- );
- if (!isset($use_lst['id'])) {
- $pr .= '';
+ $use_lst = (bool)ActionModel::testCount(["uid = {$this->u->info['id']}", "vars = animal_use{$btl->i->id}"]);
+ if (!$use_lst) {
+ $pr .= '';
} else {
$pr .= '';
}
@@ -2337,8 +2289,6 @@ class Priems
return str_replace('"', '\\"', $pr);
}
- //Мощность / подавление / сопротивление и т.д.
-
public function getByCategory(?int $category_id = null)
{
@@ -2437,10 +2387,16 @@ class Priems
);
}
+ /**
+ * Что-то для подключаемых файлов приёмов.
+ *
+ * @param $uid
+ * @param $mg
+ * @return bool|mysqli_result|resource
+ */
private function rezadEff($uid, $mg)
{
global $btl;
- //$this->rezadEff($this->u->info['id'],'wis_fire_');
$md = '';
$md2 = '';
$ex = explode('|', $btl->users[$btl->uids[$uid]]['priems']);
@@ -2787,7 +2743,7 @@ class Priems
* Конечный damage после множителей делится на 5 и пишется в БД (atgm=).
* Файлы: 33, 56, 57, 58, 59, 60.
* @param $id
- * @param array $pl массив значений из БД priems.
+ * @param array $pl массив значений из БД priems.
* @param Battle $btl
* @return void
*/
@@ -2819,7 +2775,7 @@ class Priems
* Если есть одинаковые статы из них выбирается случайный.
* Файл:267, приём 268. Понимай как хочешь.
* @param $id
- * @param array $pl
+ * @param array $pl
* @param Battle $btl
* @return void
*/
diff --git a/_incl_data/class/Quests.php b/_incl_data/class/Quests.php
index c3246e42..ce73dd64 100644
--- a/_incl_data/class/Quests.php
+++ b/_incl_data/class/Quests.php
@@ -2,6 +2,7 @@
use Core\Db;
use Helper\Conversion;
+use Model\ActionModel;
use User\ItemsModel;
class Quests
@@ -67,16 +68,18 @@ class Quests
}
//Сколько раз можно пройти квест
if (isset($d['tr_raz'])) {
- $qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" LIMIT ' . $d['tr_raz'], 2);
- if ($d['tr_raz'] > 0 && $d['tr_raz'] - $qlst[0] <= 0) {
+ $qlst = ActionModel::testCount(["uid = {$u->info['id']}", "vars = start_quest{$pl['id']}"], $d['tr_raz']);
+ //$qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" LIMIT ' . $d['tr_raz'], 2);
+ if ($d['tr_raz'] > 0 && $d['tr_raz'] - $qlst <= 0) {
$r = 0;
}
unset($qlst);
}
//Попыток пройти квест
if (isset($d['tr_raz2'])) {
- $qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" AND `vals` != "go" AND `vals` != "win" LIMIT ' . $d['tr_raz2'], 2);
- if ($d['tr_raz2'] - $qlst[0] <= 0) {
+ $qlst = ActionModel::testCount(["uid = {$u->info['id']}", "vars = start_quest{$pl['id']}", "vals != go", "vals != win"], $d['tr_raz2']);
+ //$qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" AND `vals` != "go" AND `vals` != "win" LIMIT ' . $d['tr_raz2'], 2);
+ if ($d['tr_raz2'] - $qlst <= 0) {
$r = 0;
}
unset($qlst);
@@ -212,8 +215,7 @@ class Quests
$bot2 = mysql_fetch_array(mysql_query('SELECT * FROM `test_bot` WHERE `id` = "' . $ex2[0] . '" LIMIT 1'));
if (isset($bot2['id'])) {
if (isset($qst['id'])) {
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $qst['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $ex2[1], 2);
- $x2 = 0 + $x2[0];
+ $x2 = ActionModel::testCount(["uid = {$u->info['id']}", "vars = win_bot_$ex2[0]", "time > {$qst['time']}"], $ex2[1]);
}
if (isset($d['all_kill']) && $d['all_kill'] > 0) {
$r = $d['all_kill'];
@@ -393,15 +395,17 @@ class Quests
if ($d['tr_raz'] == -1) {
$t .= 'Сколько еще раз можно выполнить задание: бесконечно
';
} else {
- $qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" LIMIT ' . $d['tr_raz'], 2);
- $t .= 'Сколько раз можно выполнить задание: ' . ($d['tr_raz'] - $qlst[0]) . '
';
+ $qlst = ActionModel::testCount(["uid = {$u->info['id']}", "vars = start_quest{$pl['id']}"], $d['tr_raz']);
+ //$qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" LIMIT ' . $d['tr_raz'], 2);
+ $t .= 'Сколько раз можно выполнить задание: ' . ($d['tr_raz'] - $qlst) . '
';
}
unset($qlst);
}
//Попыток пройти квест
if (isset($d['tr_raz2'])) {
- $qlst = $u->testAction('SELECT `id` FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" AND `vals` != "go" AND `vals` != "win" LIMIT ' . $d['tr_raz2'], 2);
- $t .= 'Осталось попыток выполнить задание: ' . ($d['tr_raz2'] - $qlst[0]) . '
';
+ $qlst = ActionModel::testCount(["uid = {$u->info['id']}", "vars = start_quest{$pl['id']}", "vals != go", "vals != win"], $d['tr_raz2']);
+ //$qlst = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" AND `vals` != "go" AND `vals` != "win" LIMIT ' . $d['tr_raz2'], 2);
+ $t .= 'Осталось попыток выполнить задание: ' . ($d['tr_raz2'] - $qlst) . '
';
unset($qlst);
}
@@ -479,28 +483,32 @@ class Quests
//Убить ботов
if (isset($d['kill_bot'])) {
-
+ $ex = explode(',', $d['kill_bot']);
if (isset($d['all_kill']) && (int)$d['all_kill'] > 0) {
$x = '';
- $ex = explode(',', $d['kill_bot']);
$i = 0; # Количество циклов для каждого типа бота.
- $q = '';
+ $botid = 0;
+ $sqlWhere = [];
+ $sqlParams = [];
while ($i < count($ex)) {
$ex2 = explode('=', $ex[$i]);
- if ($q != '') {
- $q .= ' OR ';
- }
- $q .= ' (`uid` = "' . $u->info['id'] . '" AND `time` > ' . $qst['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" )';
+ $botid = $ex2[0];
+ $sqlWhere[] = "(uid = :uid$i and time > :time$i and vars = :vars$i)";
+ $sqlParams["uid$i"] = $u->info['id'];
+ $sqlParams["time$i"] = $qst['time'];
+ $sqlParams["vars$i"] = "win_bot_$ex2[0]";
$i++;
}
- $x2 = $u->testAction($q, 2);
- $x2 = $x2[0];
+ $sqlWhere = implode(' or ', $sqlWhere);
+ $x2 = ActionModel::testCountCustom($sqlWhere, $sqlParams);
+
if ($d['all_kill'] < $x2) {
$x2 = $d['all_kill'];
}
- $bot2 = mysql_fetch_array(mysql_query('SELECT * FROM `test_bot` WHERE `id` = "' . $ex2[0] . '" LIMIT 1'));
- if (isset($bot2['id'])) {
- $x .= ' • ' . $bot2['login'] . ' [' . $x2 . '/' . $d['all_kill'] . ']
';
+
+ $botlogin = Db::getValue('select login from test_bot where id = ?', [$botid]);
+ if (isset($botlogin)) {
+ $x .= ' • ' . $botlogin . ' [' . $x2 . '/' . $d['all_kill'] . ']
';
} else {
$x .= ' • ' . $pl['name'] . ' [' . $x2 . '/' . $d['all_kill'] . ']
';
}
@@ -509,13 +517,12 @@ class Quests
while ($i < count($ex)) {
$x2 = 0;
$ex2 = explode('=', $ex[$i]);
- $bot2 = mysql_fetch_array(mysql_query('SELECT * FROM `test_bot` WHERE `id` = "' . $ex2[0] . '" LIMIT 1'));
- if (isset($bot2['id'])) {
+ $botlogin = Db::getValue('select login from test_bot where id = ?', [$ex2[0]]);
+ if (isset($botlogin)) {
if (isset($qst['id'])) {
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $qst['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $ex2[1], 2);
- $x2 = 0 + $x2[0];
+ $x2 = ActionModel::testCount(["uid = {$u->info['id']}", "vars = win_bot_$ex2[0]", "time > {$qst['time']}"], $ex2[1]);
}
- $x .= ' • ' . $bot2['login'] . ' [' . $x2 . '/' . $ex2[1] . ']
';
+ $x .= ' • ' . $botlogin . ' [' . $x2 . '/' . $ex2[1] . ']
';
}
$i++;
}
@@ -525,7 +532,7 @@ class Quests
$x = trim($x, ', ');
$t .= 'Убить ботов:
' . $x;
}
- unset($x, $ex, $x2, $bot2, $ex2);
+ unset($x, $ex, $x2, $ex2, $botlogin);
}
//Собрать ресурсы
@@ -585,72 +592,86 @@ class Quests
public function testquest(): void
{
global $u;
- if ($u->info['battle'] == 0 && $u->room['name'] != 'Башня Смерти') {
- $sp = mysql_query('SELECT * FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` LIKE "%start_quest%" AND `vals` = "go" LIMIT 100');
+ if ($u->info['battle'] != 0 || $u->room['name'] === 'Башня Смерти') {
+ return;
+ }
- while ($pl2 = mysql_fetch_array($sp)) {
- $pl = mysql_fetch_array(mysql_query('SELECT * FROM `quests` WHERE `id` = "' . (str_replace('start_quest', '', $pl2['vars'])) . '" LIMIT 1'));
+ $sp = mysql_query('SELECT * FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` LIKE "%start_quest%" AND `vals` = "go" LIMIT 100');
- $g = 1;
- //Действия квеста
- $d = $this->expl($pl['act_date']);
+ while ($pl2 = mysql_fetch_array($sp)) {
+ $pl = mysql_fetch_array(mysql_query('SELECT * FROM `quests` WHERE `id` = "' . (str_replace('start_quest', '', $pl2['vars'])) . '" LIMIT 1'));
- //Поговорить с NPS
- if (isset($d['dlg_nps'])) {
+ $g = 1;
+ //Действия квеста
+ $d = $this->expl($pl['act_date']);
+
+ //Поговорить с NPS
+ if (isset($d['dlg_nps'])) {
+ $g = 0;
+ unset($x);
+ }
+
+ //Убить игроков
+ if (isset($d['kill_user'])) {
+ $x = 0;
+ if ($x < $d['kill_user']) {
$g = 0;
- unset($x);
}
-
- //Убить игроков
- if (isset($d['kill_user'])) {
- $x = 0;
- if ($x < $d['kill_user']) {
+ //$d['kill_user'] - стольких нужно убить
+ unset($x);
+ }
+ //Убить ботов
+ if (isset($d['kill_bot'])) {
+ $ex = explode(',', $d['kill_bot']);
+ $ii = 0; // Количество циклов для каждого типа бота.
+ $smth2 = 0; // неизвестное.
+ $sqlFilter = [];
+ $sqlParams = [];
+ while ($ii < count($ex)) {
+ $ex2 = explode('=', $ex[$ii]);
+ $smth2 = $ex2[1];
+ $sqlFilter[] = "(uid = :uid$ii and time > :time$ii and vars = :vars$ii)";
+ $sqlParams["uid$ii"] = $u->info['id'];
+ $sqlParams["time$ii"] = $pl2['time'];
+ $sqlFilter["vars$ii"] = "win_bot_$ex2[0]";
+ $ii++;
+ }
+ $sqlFilter = implode(' or ', $sqlFilter);
+ if (isset($d['all_kill']) && $d['all_kill'] > 0) {
+ $x2 = ActionModel::testCountCustom($sqlFilter, $sqlParams, $d['all_kill']);
+ if ($x2 < $d['all_kill']) {
$g = 0;
}
- //$d['kill_user'] - стольких нужно убить
- unset($x);
- }
- //Убить ботов
- if (isset($d['kill_bot'])) {
- $ex = explode(',', $d['kill_bot']);
- $ii = 0; // Количество циклов для каждого типа бота.
- $q = '';
- while ($ii < count($ex)) {
- $ex2 = explode('=', $ex[$ii]);
- if ($q != '') {
- $q .= ' OR ';
- }
- $q .= ' (`uid` = "' . $u->info['id'] . '" AND `time` > ' . $pl2['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" )';
- $ii++;
+ } else {
+ $x2 = ActionModel::testCountCustom($sqlFilter, $sqlParams, $smth2);
+ if (!isset($d['all_kill']) && $x2 < $smth2) {
+ $g = 0;
}
- if (isset($d['all_kill']) && $d['all_kill'] > 0) {
- $x2 = $u->testAction($q . ' LIMIT ' . $d['all_kill'], 2);
- if ($x2[0] < $d['all_kill']) {
- $g = 0;
- }
- } else {
- $x2 = $u->testAction($q . ' LIMIT ' . $ex2[1], 2);
- if (!isset($d['all_kill']) && $x2[0] < $ex2[1]) {
- $g = 0;
- }
- }
- unset($x, $ex, $x2, $x3, $bot2, $ex2);
}
+ }
- //Собрать ресурсы
- if (isset($d['tk_itm'])) {
- $g = $this->collect_01(explode(',', $d['tk_itm']), $u);
- }
- //Собирание трофеев
- if (isset($d['tkill_itm'])) {
- $g = $this->collect_01(explode(',', $d['tkill_itm']), $u);
- }
- if ($g == 1) {
- $pl['time'] = $pl2['time'];
- $this->endq($pl['id'], 'win');
- $this->winQuest($pl);
- echo $pl['name'];
+ //Собрать ресурсы
+ if (isset($d['tk_itm'])) {
+ $g = $this->collect_01(explode(',', $d['tk_itm']), $u);
+ }
+ //Собирание трофеев
+ if (isset($d['tkill_itm'])) {
+ $g = $this->collect_01(explode(',', $d['tkill_itm']), $u);
+ }
+ if ($g == 1) {
+ $pl['time'] = $pl2['time'];
+ $this->endq($pl['id'], 'win');
+ $status = $this->winQuest($u->info['id'], $pl, $pl2['time']);
+ //Отправляем сообщение в чат
+ if ($status) {
+ $chatDto = new ChatMessage();
+ $chatDto->setRoom($u->info['room']);
+ $chatDto->setTo($u->info['login']);
+ $chatDto->setText($status);
+ $chatDto->setType(5);
+ (new Chat())->sendMsg($chatDto);
}
+ echo $pl['name'];
}
}
}
@@ -688,125 +709,117 @@ class Quests
# Функция отвечает за ПРОВЕРКУ на ЗАВЕРШЕНИЕ квестов для ПОДЗЕМОК
- private function winQuest($pl)
+ private function winQuest($uid, $pl, $time): string
{
- global $u, $c, $magic;
+ global $magic;
- if (isset($pl['id'])) {
- $d = $this->expl($pl['act_date']);
-
- $d = array_merge($d, $this->expl($pl['win_date']));
-
- if ($_COOKIE['login'] == 'R' || $_COOKIE['login'] == 'r') {
- echo '';
- die();
- }
-
- // Забираем ресурсы
- if (isset($d['tk_itm'])) {
- $ex = explode(',', $d['tk_itm']);
- $i = 0;
- while ($i < count($ex)) {
- $ex2 = explode('=', $ex[$i]);
- $ex2 = explode('=', $ex[$i]);
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $pl2['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $ex2[1], 2);
- ItemsModel::deleteItemsById($ex2[0], $ex2[1]);
- $i++;
- }
- }
- // Забираем трофеи
- if (isset($d['tkill_itm'])) {
- $ex = explode(',', $d['tkill_itm']);
- $i = 0;
- while ($i < count($ex)) {
- $ex2 = explode('=', $ex[$i]);
- $ex2 = explode('=', $ex[$i]);
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $pl2['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $ex2[1], 2);
- ItemsModel::deleteItemsById($ex2[0], $ex2[1]);
- $i++;
- }
- }
-
- $t = '';
- if (isset($d['add_rep'])) { // Получаем репутацию за квест, если это убийства ботов.
- if (isset($d['kill_bot']) && isset($d['all_kill']) && $d['add_rep'] > 0) {
- $ex = explode(',', $d['kill_bot']);
- $ii = 0;
- $d['add_rep'] = 0;
- while ($ii < count($ex)) {
- $i = 0;
- $ex2 = explode('=', $ex[$i]);
- while ($i < $d['all_kill']) {
- $x2 = 0;
- $d['add_rep'] = $d['add_rep'] + $ex2[1];
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $pl2['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $d['all_kill'], 2);
- $i++;
- }
- $ii++;
- }
- }
- unset($x, $i, $ii, $ex, $x2, $bot2, $ex2);
- if ($pl['city'] != '') {
- $t .= '' . $d['add_rep'] . ' ед. репутации ' . $pl['city'] . ', ';
- $rep = mysql_fetch_array(mysql_query('SELECT * FROM `rep` WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'));
-
- if ($rep['rep' . $pl['city']] < 24999 && $rep['rep' . $pl['city']] + $d['add_rep'] >= 24999 && $pl['kin'] != 2) {
- $rep['rep' . $pl['city']] = 24999;
- } else {
- $rep['rep' . $pl['city']] += $d['add_rep'];
- }
- mysql_query('UPDATE `rep` SET `rep' . $pl['city'] . '` = "' . $rep['rep' . $pl['city']] . '" WHERE `id` = "' . $rep['id'] . '" LIMIT 1');
- }
- }
-
- if (isset($d['add_repizlom'])) {
- $t .= '' . $d['add_repizlom'] . ' ед. репутации Излома Хаоса, ';
- $rep = mysql_fetch_array(mysql_query('SELECT * FROM `rep` WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'));
- $rep['repizlom'] += $d['add_repizlom'];
- if ($rep['repizlom'] > 24999) {
- $rep['repizlom'] = 24999;
- }
- mysql_query('UPDATE `rep` SET `repizlom` = "' . $rep['repizlom'] . '" WHERE `id` = "' . $rep['id'] . '" LIMIT 1');
- }
-
- if (isset($d['add_eff'])) {
- $i = 0;
- $j = explode('=', $d['add_eff']);
- while ($i < count($j)) {
- if ($j[$i] > 0) {
- $magic->addEffect($u->info['id'], $j[$i], 1);
- }
- $i++;
- }
- }
-
- if (isset($d['add_cr'])) {
- $t .= '' . $d['add_cr'] . ' кр., ';
- mysql_query('UPDATE `users` SET `money` = `money`+' . $d['add_cr'] . ' WHERE `id` = "' . $u->info['id'] . '" LIMIT 1');
- }
-
- if ($t != '') {
- $t = rtrim($t, ', ');
- $r = 'Задание ' . $pl['name'] . ' было успешно выполнено! Вы получили награду: ' . $t . '.';
- unset($t);
- } else {
- $r = 'Задание ' . $pl['name'] . ' было успешно выполнено!';
- }
- $r = '' . $r . '';
- //Отправляем сообщение в чат
- $chatDto = new ChatMessage();
- $chatDto->setCity($u->info['city']);
- $chatDto->setRoom($u->info['room']);
- $chatDto->setTo($u->info['login']);
- $chatDto->setText($r);
- $chatDto->setType(5);
- (new Chat())->sendMsg($chatDto);
+ if (!isset($pl['id'])) {
+ return '';
}
+
+ $d = $this->expl($pl['act_date']);
+
+ $d = array_merge($d, $this->expl($pl['win_date']));
+
+ if ($_COOKIE['login'] == 'R' || $_COOKIE['login'] == 'r') {
+ echo '';
+ die();
+ }
+
+ // Забираем ресурсы
+ if (isset($d['tk_itm'])) {
+ $ex = explode(',', $d['tk_itm']);
+ $i = 0;
+ while ($i < count($ex)) {
+ $ex2 = explode('=', $ex[$i]);
+ $x2 = ActionModel::testCount(["uid = $uid", "vars = win_bot_$ex[2]", "time > $time"], $ex2[1]);
+ ItemsModel::deleteItemsById($ex2[0], $ex2[1]);
+ $i++;
+ }
+ }
+ // Забираем трофеи
+ if (isset($d['tkill_itm'])) {
+ $ex = explode(',', $d['tkill_itm']);
+ $i = 0;
+ while ($i < count($ex)) {
+ $ex2 = explode('=', $ex[$i]);
+ $x2 = ActionModel::testCount(["uid = $uid", "vars = win_bot_$ex[2]", "time > $time"], $ex2[1]);
+ ItemsModel::deleteItemsById($ex2[0], $ex2[1]);
+ $i++;
+ }
+ }
+
+ $t = '';
+ if (isset($d['add_rep'])) { // Получаем репутацию за квест, если это убийства ботов.
+ if (isset($d['kill_bot']) && isset($d['all_kill']) && $d['add_rep'] > 0) {
+ $ex = explode(',', $d['kill_bot']);
+ $ii = 0;
+ $d['add_rep'] = 0;
+ while ($ii < count($ex)) {
+ $i = 0;
+ $ex2 = explode('=', $ex[$i]);
+ while ($i < $d['all_kill']) {
+ $d['add_rep'] = $d['add_rep'] + (int)$ex2[1];
+ $x2 = ActionModel::testCount(["uid = $uid", "vars = win_bot_$ex[2]", "time > $time"], $d['all_kill']);
+ $i++;
+ }
+ $ii++;
+ }
+ }
+ unset($x, $i, $ii, $ex, $x2, $bot2, $ex2);
+ if ($pl['city'] != '') {
+ $t .= '' . $d['add_rep'] . ' ед. репутации ' . $pl['city'] . ', ';
+ $rep = mysql_fetch_array(mysql_query('SELECT * FROM `rep` WHERE `id` = "' . $uid . '" LIMIT 1'));
+
+ if ($rep['rep' . $pl['city']] < 24999 && $rep['rep' . $pl['city']] + $d['add_rep'] >= 24999 && $pl['kin'] != 2) {
+ $rep['rep' . $pl['city']] = 24999;
+ } else {
+ $rep['rep' . $pl['city']] += $d['add_rep'];
+ }
+ mysql_query('UPDATE `rep` SET `rep' . $pl['city'] . '` = "' . $rep['rep' . $pl['city']] . '" WHERE `id` = "' . $rep['id'] . '" LIMIT 1');
+ }
+ }
+
+ if (isset($d['add_repizlom'])) {
+ $t .= '' . $d['add_repizlom'] . ' ед. репутации Излома Хаоса, ';
+ $rep = mysql_fetch_array(mysql_query('SELECT * FROM `rep` WHERE `id` = "' . $uid . '" LIMIT 1'));
+ $rep['repizlom'] += $d['add_repizlom'];
+ if ($rep['repizlom'] > 24999) {
+ $rep['repizlom'] = 24999;
+ }
+ mysql_query('UPDATE `rep` SET `repizlom` = "' . $rep['repizlom'] . '" WHERE `id` = "' . $rep['id'] . '" LIMIT 1');
+ }
+
+ if (isset($d['add_eff'])) {
+ $i = 0;
+ $j = explode('=', $d['add_eff']);
+ while ($i < count($j)) {
+ if ($j[$i] > 0) {
+ $magic->addEffect($uid, $j[$i], 1);
+ }
+ $i++;
+ }
+ }
+
+ if (isset($d['add_cr'])) {
+ $t .= '' . $d['add_cr'] . ' кр., ';
+ mysql_query('UPDATE `users` SET `money` = `money`+' . $d['add_cr'] . ' WHERE `id` = "' . $uid . '" LIMIT 1');
+ }
+
+ if ($t != '') {
+ $t = rtrim($t, ', ');
+ $r = 'Задание ' . $pl['name'] . ' было успешно выполнено! Вы получили награду: ' . $t . '.';
+ unset($t);
+ } else {
+ $r = 'Задание ' . $pl['name'] . ' было успешно выполнено!';
+ }
+
+ return "$r";
}
- public function questCheckEnd($pl)
+ public function questCheckEnd($pl): int
{
global $u;
$quest = mysql_fetch_array(mysql_query('SELECT * FROM `actions` WHERE `uid` = "' . $u->info['id'] . '" AND `vars` = "start_quest' . $pl['id'] . '" ORDER BY `time` DESC LIMIT 1'));
@@ -836,29 +849,31 @@ class Quests
if (isset($d['kill_bot'])) {
$ex = explode(',', $d['kill_bot']);
$i = 0; # Количество циклов для каждого типа бота.
- $q = '';
+ $smth1 = 0; // неизвестно что.
+ $sqlFilter = [];
+ $sqlParams = [];
while ($i < count($ex)) {
$ex2 = explode('=', $ex[$i]);
- if ($q != '') {
- $q .= ' OR ';
- }
- $q .= ' (`uid` = "' . $u->info['id'] . '" AND `time` > ' . $quest['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" )';
+ $smth1 = $ex2[1];
+ $sqlFilter[] = "(uid = :uid$i and time > :time$i and vars = :vars$i)";
+ $sqlParams[":uid$i"] = $u->info['id'];
+ $sqlParams[":time$i"] = $quest['time'];
+ $sqlParams[":vars$i"] = "win_bot_$ex2[0]";
$i++;
}
+ $sqlFilter = implode(' or ', $sqlFilter);
if (isset($d['all_kill']) && (int)$d['all_kill'] > 0) {
- $x2 = $u->testAction($q, 2);
- if ((int)$d['all_kill'] <= $x2[0]) {
+ $x2 = ActionModel::testCountCustom($sqlFilter, $sqlParams);
+ if ((int)$d['all_kill'] <= $x2) {
$x2 = (int)$d['all_kill'];
- } else {
- $x2 = $x2[0];
}
if ($x2 < (int)$d['all_kill']) {
$g = 0;
}
} else {
- $x2 = $u->testAction($q . ' LIMIT ' . $ex2[1], 2);
- $x2 = min($ex2[1], $x2[0]);
- if ($x2 < $ex2[1]) {
+ $x2 = ActionModel::testCountCustom($sqlFilter, $sqlParams, $smth1);
+ $x2 = min($smth1, $x2);
+ if ($x2 < $smth1) {
$g = 0;
}
}
@@ -886,10 +901,10 @@ class Quests
$x2 = Db::getValue('select count(*) from items_users where maidin = ? and item_id = ? and uid = ? and `delete` in (0,1000) and inTransfer = 0 and inShop = 0',
[$pl['city'], (int)$ex2[0], $u->info['id']]);
if ($x2 >= $ex2[1]) {
- if ($x2 <= ($ex2[1] + round($ex2[1] * 0.15))) {
+ if ($x2 <= ((int)$ex2[1] + round($ex2[1] * 0.15))) {
$ex2[1] = $x2;
} else {
- $ex2[1] = ($ex2[1] + round($ex2[1] * 0.15));
+ $ex2[1] = ((int)$ex2[1] + round($ex2[1] * 0.15));
}
}
if ($x2 < $ex2[1]) {
@@ -928,10 +943,10 @@ class Quests
$x2 = Db::getValue('select count(*) from items_users where maidin = ? and item_id = ? and uid = ? and `delete` in (0,1000) and inTransfer = 0 and inShop = 0',
[$quest['city'], (int)$ex2[0], $u->info['id']]);
if ($x2 >= $ex2[1]) {
- if ($x2 <= ($ex2[1] + round($ex2[1] * 0.15))) {
+ if ($x2 <= ((int)$ex2[1] + round($ex2[1] * 0.15))) {
$ex2[1] = $x2;
} else {
- $ex2[1] = ($ex2[1] + round($ex2[1] * 0.15));
+ $ex2[1] = ((int)$ex2[1] + round($ex2[1] * 0.15));
}
}
$d['add_rep'] = (int)$d['add_rep'] * (int)$ex2[1];
@@ -953,9 +968,8 @@ class Quests
$i = 0;
$ex2 = explode('=', $ex[$i]);
while ($i < $d['all_kill']) {
- $x2 = 0;
- $d['add_rep'] = $d['add_rep'] + $ex2[1];
- $x2 = $u->testAction('`uid` = "' . $u->info['id'] . '" AND `time` > ' . $action['time'] . ' AND `vars` = "win_bot_' . $ex2[0] . '" LIMIT ' . $d['all_kill'], 2);
+ $d['add_rep'] = $d['add_rep'] + (int)$ex2[1];
+ $x2 = ActionModel::testCount(["uid = {$u->info['id']}", "vars = win_bot_$ex2[0]", "time > {$action['time']}"], $d['all_kill']);
$i++;
}
$ii++;
diff --git a/_incl_data/class/User.php b/_incl_data/class/User.php
index 3a541255..4a25f7ed 100644
--- a/_incl_data/class/User.php
+++ b/_incl_data/class/User.php
@@ -243,17 +243,6 @@ class User
$this->statnames->getBonus();
$this->statnames->getRequirement();
- if (Core\Config::get('securetime') > 0) {
- if (!defined('IP')) {
- define('IP', $_SERVER['REMOTE_ADDR']);
- }
-
- if (isset($this->info['id']) && ($this->info['ip'] != IP || $this->info['banned'] > 0) && $_SERVER['REQUEST_URI'] != '/') {
- unset($this->info, $_COOKIE['login']);
- die(Config::get('exit'));
- }
- }
-
if (!isset ($_COOKIE['btl'], $this->info['battle']) || $this->info['battle'] != $_COOKIE['btl']) {
setcookie('btl', $this->info['battle'] ?? '', time() + 86400);
}
@@ -271,9 +260,9 @@ class User
if ($sb - 1 > $this->info['catch'] - $this->info['frg']) {
if ($this->info['frg'] == -1) {
- $sm = $this->testAction('`uid` = "' . $this->info['id'] . '" AND `vars` = "frg" LIMIT 1', 1);
+ $sm = (bool)ActionModel::testCount(["uid = {$this->info['id']}", 'vars = frg']);
}
- if (!isset($sm['id']) && $this->info['frg'] == -1) {
+ if (!$sm && $this->info['frg'] == -1) {
mysql_query(
'UPDATE `users` SET `catch` = "' . round(
$sb
@@ -298,6 +287,7 @@ class User
);
}
}
+ unset($sm);
}
if ($this->info['login2'] != '' && $this->info['battle'] == 0 && $this->info['zv'] == 0) {
@@ -315,8 +305,7 @@ class User
}
if (isset($_GET['homeworld']) && $this->info['zv'] == 0 && $this->info['battle'] == 0 && $this->info['dnow'] == 0) {
- $hgo = $this->testHome();
- if (!isset($hgo['id']) && $this->info['room'] != 274 && $this->info['align'] != 2 && $this->info['inTurnir'] == 0) {
+ if ($this->testHome() && $this->info['room'] != 274 && $this->info['align'] != 2 && $this->info['inTurnir'] == 0) {
$this->addAction(time(), 'go_homeworld', '');
$rmt = mysql_fetch_array(
mysql_query(
@@ -351,7 +340,6 @@ class User
} else {
$this->error = 'Вам запрещено пользоваться кнопкой возрата';
}
- unset($hgo);
}
//Заносим текст
@@ -517,17 +505,14 @@ class User
*/
//Статистика персонажа на сегодня
- $stat = $this->testAction(
- '`uid` = "' . $this->info['id'] . '" AND `time` >= ' . strtotime(
- 'now 00:00:00'
- ) . ' AND `vars` = "statistic_today" LIMIT 1', 1
- );
- if (!isset($stat['id'])) {
+ $stat = (bool)ActionModel::testCount(["uid = {$this->info['id']}", "time >= " . strtotime('now 00:00:00'), 'vars = statistic_today']);
+ if (!$stat) {
$this->addAction(
time(), 'statistic_today',
'e=' . $this->info['exp'] . '|w=' . $this->info['win'] . '|l=' . $this->info['lose'] . '|n=' . $this->info['nich']
);
}
+ unset($stat);
//Одеваем боевой комплект
if (isset($_GET['usec1']) && $this->info['battle'] == 0) {
@@ -611,11 +596,8 @@ class User
}
if (isset($_GET['obr_sel']) || isset($_GET['obraz'])) {
- $sm = $this->testAction(
- '`uid` = "' . $this->info['id'] . '" AND `time` > ' . (time() - 86400) . ' AND `vars` = "sel_obraz" LIMIT 1',
- 1
- );
- if (!isset($sm['id'])) {
+ $obrazTimeout = ActionModel::getOne(["uid = {$this->info['id']}", 'time > unix_timestamp() - 86400', 'vars = sel_obraz'], 'time');
+ if (!$obrazTimeout) {
if (isset($_GET['obr_sel'])) {
$tr = true;
$o = mysql_fetch_array(
@@ -686,7 +668,7 @@ class User
}
} else {
$this->error = 'Выбирать образ можно не чаще одного раза в сутки, следующая смена ' . date(
- 'd.m.Y H:i', $sm['time'] + 86400
+ 'd.m.Y H:i', $obrazTimeout + 86400
);
unset($_GET['obr_sel']);
$_GET['inv'] = 1;
@@ -822,22 +804,6 @@ class User
return Db::getRow('select * from users left join stats on users.id = stats.id where users.id = ?', [$id]);
}
- public function testAction($filter, $tp): array
- {
- if ($tp == 1) {
- $query = 'select * from actions where ' . $filter;
- } elseif ($tp == 2) {
- $query = 'select count(*) from actions where ' . $filter;
- } else {
- return [];
- }
- $arr = mysql_fetch_array(mysql_query($query));
-
- return !empty($arr) ? $arr : [];
- }
-
- //Удаление определенного типа предметов
-
public function addAction($time, $vars, $vls, $uid = null): bool
{
$info = $this->info;
@@ -848,7 +814,14 @@ class User
return true;
}
- public function testHome(): array
+ //Удаление определенного типа предметов
+
+ /**
+ * Кнопка "Возврат".
+ *
+ * @return bool
+ */
+ public function testHome(): bool
{
/*----Быстрый(Особенность)----*/
$timeforwait = 3600;
@@ -856,25 +829,27 @@ class User
$timeforwait = 3600 - (($st['os6'] * 5) * 60);
}
/*----Быстрый(Особенность)----*/
- $hgo = $this->testAction(
- '`uid` = "' . $this->info['id'] . '" AND `time` >= ' . (time() - $timeforwait) . ' AND `vars` = "go_homeworld" LIMIT 1',
- 1
- );
- if ($this->info['level'] == 0 || $this->info['active'] != '' || $this->info['inTurnir'] > 0 || $this->info['inTurnirnew'] > 0 || $this->info['zv'] > 0 || $this->info['dnow'] > 0) {
- $hgo['id'] = true;
+ $buttonUsed = (bool)ActionModel::testCount(["uid = {$this->info['id']}", "time >= unix_timestamp - $timeforwait", 'vars = go_homeworld']);
+
+ if (
+ $this->info['level'] == 0 ||
+ $this->info['active'] != '' ||
+ $this->info['inTurnir'] > 0 ||
+ $this->info['inTurnirnew'] > 0 ||
+ $this->info['zv'] > 0 ||
+ $this->info['dnow'] > 0 ||
+ !empty($this->info['noreal'])
+ ) {
+ $buttonUsed = true;
}
- if (isset($this->info['noreal']) || $this->info['dnow'] > 0) {
- $hgo['id'] = true;
- }
- if (!isset($hgo['id'])) {
- $ku = mysql_fetch_array(
- mysql_query('SELECT `id` FROM `katok_zv` WHERE `uid` = ' . $this->info['id'])
- );
- if (isset($ku['id'])) {
- $hgo['id'] = true;
+
+ if (!$buttonUsed) {
+ $onKatok = (bool)Db::getValue('select id from katok_zv where uid = ?', [$this->info['id']]);
+ if ($onKatok) {
+ $buttonUsed = true;
}
}
- return $hgo ?? [];
+ return !$buttonUsed;
}
public function wipe()
@@ -955,44 +930,41 @@ class User
//Расчет урона от оружия
- public function allActionsStart()
+ public function allActionsStart(): void
{
global $magic;
+ define('VAREZHKI_ITEM_ID', 998);
+
if (!isset($_GET['use_snowball'])) {
return;
}
$this->stats = $this->getStats($this->info, 0);
//Начинаем лепить снежок на ЦП
- if (!isset($this->stats['items'][$this->stats['wp13id']]['id']) || $this->stats['items'][$this->stats['wp13id']]['item_id'] != 998) {
+ if (!isset($this->stats['items'][$this->stats['wp13id']]['id']) || $this->stats['items'][$this->stats['wp13id']]['item_id'] != VAREZHKI_ITEM_ID) {
return;
}//варежки одеты, все ок
if ($this->room['name'] != 'Центральная площадь') {
$this->error2 = 'Собирать снег можно только на Центральной площади';
- } else {
- $smt = $this->testAction(
- '`uid` = "' . $this->info['id'] . '" AND `time`>=' . (time() - 120) . ' AND `vars` = "create_snowball_cp" LIMIT 1',
- 1
- );
- if (isset($smt['id'])) {
- $this->error2 = 'Нельзя лепить несколько снежков одновременно ;)';
- } else {
- $smt = $this->testAction(
- '`uid` = "' . $this->info['id'] . '" AND `time`>=' . strtotime(
- 'now 00:00:00'
- ) . ' AND `vars` = "create_snowball_cp" LIMIT 25',
- 2
- );
- $smt = $smt[0];
- if ($smt < 10) {
- $this->addAction(time(), 'create_snowball_cp', $this->info['city']);
-
- $magic->addEffect($this->info['id'], 24);
- $this->error2 = 'Начинаем лепить снежок, осталось ' . (10 - $smt) . ' раз на сегодня ...';
- } else {
- $this->error2 = 'Вы уже слепили 10 снежка за сегодня ...';
- }
- }
+ return;
}
+
+ $isMakingSnowball = (bool)ActionModel::testCount(["uid = {$this->info['id']}", "time >= unix_timestamp() - 120", 'vars = create_snowball_cp']);
+
+ if ($isMakingSnowball) {
+ $this->error2 = 'Нельзя лепить несколько снежков одновременно ;)';
+ return;
+ }
+
+ $createdToday = ActionModel::testCount(["uid = {$this->info['id']}", 'vars = create_snowball_cp', 'time >= ' . strtotime('now 00:00:00')], 25);
+
+ if ($createdToday >= 10) {
+ $this->error2 = 'Вы уже слепили 10 снежка за сегодня ...';
+ return;
+ }
+
+ $this->addAction(time(), 'create_snowball_cp', $this->info['city']);
+ $magic->addEffect($this->info['id'], 24);
+ $this->error2 = 'Начинаем лепить снежок, осталось ' . (10 - $createdToday) . ' раз на сегодня ...';
}
//Расчет защиты
@@ -2774,7 +2746,7 @@ class User
Delo::add(
2,
'System.remont.upatack',
- $u->info['id'],
+ $this->info['id'],
'"System.remont.upatack": Заточка "' . $data['upatack_name'] . '" была успешно встроена в предмет "' . $id['name'] . '" [itm:' . $id['id'] . ']',
);
@@ -4905,7 +4877,7 @@ class User
return 0;
}
- $sleep = $this->testAction('`vars` = "sleep" AND `uid` = "' . $e['uid'] . '" LIMIT 1', 1);
+ $sleep = ActionModel::getOne(["uid = {$e['uid']}", 'vars = sleep'], 'vars');
if ($e['id_eff'] == 2) {
//Проверка
@@ -4929,6 +4901,7 @@ class User
if (isset($po['finish_file']) && file_exists('_incl_data/class/Magic/' . $po['finish_file'] . '.php')) {
require_once '_incl_data/class/Magic/' . $po['finish_file'] . '.php';
}
+
if (isset($u['id']) && ($e['type1'] < 11 || $e['type1'] > 16 && $e['type1'] < 23) && $e['noch'] == 0) {
$text = "Закончилось действие эффекта «{$e['name']}»";
$cmsg = new ChatMessage();
@@ -6103,7 +6076,7 @@ LIMIT 1'
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "' . $user['id'] . '", `data` = "' . $pl['data'] . '" WHERE `id` = "' . $pl['id'] . '"'
);
mysql_query(
- 'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "' . $type . '", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
+ 'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $cl . '", "' . time() . '", "' . $type . '", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
);
} elseif ($pl['uid'] == $user['id']) {
$col = $this->itemsX(((int)$pl['id']));
@@ -6114,7 +6087,7 @@ LIMIT 1'
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "-21' . $user['clan'] . '" WHERE `id` = "' . $pl['id'] . '"'
);
mysql_query(
- 'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "9", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
+ 'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $cl . '", "' . time() . '", "9", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
);
}
}
diff --git a/_incl_data/class/User/Confirmation.php b/_incl_data/class/User/Confirmation.php
index e4d0fc25..37dec423 100644
--- a/_incl_data/class/User/Confirmation.php
+++ b/_incl_data/class/User/Confirmation.php
@@ -6,30 +6,24 @@ use Core\Config;
use Core\Db;
use Helper\Mail;
use PassGen;
-use UserIp;
class Confirmation
{
/**
* Для однотипных писем с подтверждением.
* @param array $userinfo Данные из (User)->info.
- * @param mixed $value Новое значение
+ * @param string $value Новое значение
* @param ?int $code Проверочный код
* @param string $type Тип меняемого значения. С маленькой буквы, именительный падеж.
* @return void
*/
- public static function byEmail(array $userinfo, string $type, $value, ?int $code = null)
+ public static function byEmail(array $userinfo, string $type, string $value, ?int $code = null): void
{
- if ($type === 'pass2' && is_null($code)) {
- self::pass2ByEmailCustom($userinfo, $value);
- return;
- }
$ip = UserIp::get();
$date = date('d.m.y H:i');
$https = Config::get('https');
$support = Config::get('support');
- $activationLink = 'https://' . $userinfo['city'] . Config::get('host') .
- "/confirm.php?id={$userinfo['id']}&code=$code";
+ $activationLink = Config::get('https') . "/confirm.php?id={$userinfo['id']}&code=$code";
$fulllogin = $userinfo['login'] . "[{$userinfo['level']}]";
Mail::send(
$userinfo['mail'],
@@ -55,31 +49,7 @@ class Confirmation
);
}
- private static function pass2ByEmailCustom(array $userinfo, string $pass2)
- {
-
- $ip = UserIp::get();
- $fulllogin = $userinfo['login'] . "[{$userinfo['level']}]";
- Mail::send(
- $userinfo['mail'],
- <<
-
Вы можете попробовать Благодать 3 ранга бесплатно только 1 раз в 30 дней.
- - -
@@ -29,7 +28,6 @@ if (!isset($clan['id'])) {
- ' . $c['counters'] . '
'
);
}
diff --git a/ekr.php b/ekr.php
index 7bb9e066..27f81c6a 100644
--- a/ekr.php
+++ b/ekr.php
@@ -4,6 +4,7 @@ use Core\Config;
use Core\Database;
use Core\Db;
use Model\EkrExchangeRates;
+use Validator\Login;
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
@@ -431,142 +432,39 @@ if (isset($_POST['do']) && $_POST['do'] == 'newShadow') {
$day1 = round($day1def + $dc1, 2);
$day2 = round($day2def + $dc2, 2);
} elseif (isset($_POST['login'])) {
- //
- function en_ru($txt)
- {
- $g = false;
- $en = preg_match("/^(([0-9a-zA-Z _-])+)$/i", $txt);
- $ru = preg_match("/^(([0-9а-яА-Я _-])+)$/i", $txt);
- if (($ru && $en) || (!$ru && !$en)) {
- $g = true;
- }
- return $g;
- }
+ $newlogin = (new Login())->setLogin($_POST['login'])->get();
- //
- function testBad($txt)
- {
- $white = '-_ 0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNMїЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮїйцукенгшщзхъфывапролджэячсмитьбю';
- $r = false;
- $i = 0;
- while ($i != -1) {
- if (isset($txt[$i])) {
- $g = false;
- $j = 0;
- while ($j != -1) {
- if (isset($white[$j])) {
- if ($white[$j] == $txt[$i]) {
- $g = true;
- }
- } else {
- $j = -2;
- }
- $j++;
- }
- if (!$g) {
- $r = true;
- }
- } else {
- $i = -2;
- }
- $i++;
- }
- return $r;
- }
-
- function is_login($login)
- {
- $r = true;
- //
- $login = htmlspecialchars($login, null);
- //
- $bad = [
- 'Мусорщик' => 1,
- 'Мироздатель' => 1,
- ];
-
- //
- $login_db = mysql_fetch_array(
- mysql_query(
- 'SELECT `id` FROM `users` WHERE `login` = "' . mysql_real_escape_string($login) . '" LIMIT 1'
- )
- );
- if (isset($login_db['id']) || isset($bad[$login])) {
- $r = false;
- } else {
- $true = true;
- //
- /*
- Логин может содержать от 4 до 16 символов, и состоять только из букв русского ИЛИ английского алфавита, цифр, символов '_', '-' и пробела.
- Логин не может начинаться или заканчиваться символами '_', '-' или пробелом.
- */
- //
- $login = str_replace(' ', ' ', $login);
- $login = str_replace('%', ' ', $login);
- $login = str_replace(' ', ' ', $login);
- //
- if (strlen($login) > 16) {
- $true = false;
- } elseif (strlen($login) < 4) {
- $true = false;
- } elseif (strripos($login, ' ') == true) {
- $true = false;
- } elseif (substr($login, 1) == ' ' || substr($login, -1) == ' ') {
- $true = false;
- } elseif (substr($login, 1) == '-' || substr($login, -1) == '-') {
- $true = false;
- } elseif (substr($login, 1) == '_' || substr($login, -1) == '_') {
- $true = false;
- } elseif (testBad($login) == true) {
- $true = false;
- } elseif (en_ru(str_replace('ї', 'е', str_replace('ї', 'Е', $login))) == true) {
- $true = false;
- }
- //
- if ($true == false) {
- $r = false;
- } else {
- $r = true;
- }
- }
- return $r;
- }
-
- if ($u->info['login'] == $_POST['login']) {
+ if (!empty($newlogin) && $u->info['login'] === $newlogin) {
$u->error = 'Выберите другой логин...';
} elseif ($u->info['money2'] < 25) {
$u->error = 'Недостаточно средств.';
} else {
- $login = htmlspecialchars($_POST['login'], null);
- if (is_login($login) == true) {
- mysql_query(
- 'INSERT INTO `lastnames` ( `uid`,`login`,`newlogin`,`time` ) VALUES (
+ mysql_query(
+ 'INSERT INTO `lastnames` ( `uid`,`login`,`newlogin`,`time` ) VALUES (
"' . $u->info['id'] . '","' . $u->info['login'] . '","' . mysql_real_escape_string(
- $login
- ) . '","' . time() . '"
+ $newlogin
+ ) . '","' . time() . '"
)'
- );
- $u->info['login_last'] = $u->info['login'];
- $u->info['login'] = $login;
- $u->info['money2'] -= 25;
- //
- mysql_query(
- "UPDATE `items_users` SET `data` = replace( `data` , 'sudba=" . $u->info['login_last'] . "', 'sudba=" . mysql_real_escape_string(
- $u->info['login']
- ) . "') WHERE `data` LIKE '%sudba=" . mysql_real_escape_string(
- $u->info['login_last']
- ) . "%' AND `uid` = '" . $u->info['id'] . "'"
- );
- //
- mysql_query(
- 'UPDATE `users` SET `login` = "' . mysql_real_escape_string(
- $u->info['login']
- ) . '", `money2` = "' . $u->info['money2'] . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
- );
- $u->error = 'Вы успешно сменили логин на "' . $u->info['login'] . '" перезайдите в игру с главной страницы.';
- } else {
- $u->error = 'Выберите другой логин...';
- }
+ );
+ $u->info['login_last'] = $u->info['login'];
+ $u->info['login'] = $newlogin;
+ $u->addEkr(-25);
+
+ mysql_query(
+ "UPDATE `items_users` SET `data` = replace( `data` , 'sudba=" . $u->info['login_last'] . "', 'sudba=" . mysql_real_escape_string(
+ $u->info['login']
+ ) . "') WHERE `data` LIKE '%sudba=" . mysql_real_escape_string(
+ $u->info['login_last']
+ ) . "%' AND `uid` = '" . $u->info['id'] . "'"
+ );
+
+ mysql_query(
+ 'UPDATE `users` SET `login` = "' . mysql_real_escape_string(
+ $u->info['login']
+ ) . '" WHERE `id` = "' . $u->info['id'] . '" LIMIT 1'
+ );
+ $u->error = 'Вы успешно сменили логин на "' . $u->info['login'] . '" перезайдите в игру с главной страницы.';
+
}
} elseif (isset($_GET['buy_ekr'])) {
//
diff --git a/enter.php b/enter.php
index d3c4537b..5214f01a 100644
--- a/enter.php
+++ b/enter.php
@@ -3,6 +3,8 @@
use Core\Config;
use Core\Database;
use Core\Db;
+use Core\TOTP;
+use JetBrains\PhpStorm\NoReturn;
use User\Password;
use User\UserIp;
@@ -15,43 +17,36 @@ require_once __DIR__ . DIRECTORY_SEPARATOR . '_incl_data/autoload.php';
Database::init();
define('IP', UserIp::get());
+
$chat = new Chat();
+$login = $_SESSION['login'] ?? '';
+$password = '';
+$otp = '';
-if (isset($_GET['login'])) {
- $_POST['login'] = $_GET['login'];
- $_POST['pass'] = $_GET['pass'];
- $_POST['code'] = $_GET['code'];
+if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ if (isset($_POST['login'])) {
+ $login = $_POST['login'];
+ }
+ if (isset($_POST['password'])) {
+ $password = $_POST['password'];
+ }
+ if (isset($_POST['otp'])) {
+ $otp = $_POST['otp'];
+ }
}
-if (isset($_POST['psw'])) {
- $_POST['pass'] = $_POST['psw'];
-}
-
-if (isset($_SESSION['login'])) {
- $_POST['login'] = $_SESSION['login'];
- $_POST['pass'] = $_SESSION['pass'];
-}
-
-function error($e)
+#[NoReturn] function error($e): void
{
- die(
- '
-
-
" : '
';
- error($blockstr);
-} elseif (!Password::isGood($_POST['pass'], $u['pass'], $u['login'])) {
- error("Неверный пароль к персонажу {$u['login']}.");
- Db::sql(
- 'insert into logs_auth (uid, ip, browser, type, time) values (?,?,?,3,unix_timestamp())',
- [$u['id'], IP, $_SERVER['HTTP_USER_AGENT']]
- );
-} else {
-
- //Второй пароль
- if (!empty($u['pass2'])) {
- $_SESSION['login'] = $_POST['login'];
- $_SESSION['pass'] = $_POST['pass'];
- $good2 = false;
- $koko = '';
- if (password_verify($_POST['code'], $u['pass2'])) {
- $good2 = true;
- unset($_SESSION['login'], $_SESSION['pass']);
- } else {
- if (isset($_POST['code'])) {
- $koko = 'Неверный второй пароль
';
- }
- setcookie('login', '', time() - 60 * 60 * 24, '', Config::get('host'));
- }
-
- if ($koko) {
- $koko = '' . $koko . '';
- }
- if (!$good2) {
- ?>
-
-
-
-
-
-
- Запрос второго пароля к персонажу.
- = $koko ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
" : '
';
+ error($blockstr);
+ } elseif (!Password::isGood($password, $u['pass'], $u['login'])) {
Db::sql(
- 'insert into logs_auth (uid, ip, browser, type, time) VALUES (?,?,?,1,unix_timestamp())',
- [$u['id'], $_COOKIE['ip'], $_SERVER['HTTP_USER_AGENT']]
+ 'insert into logs_auth (uid, ip, browser, type, time) values (?,?,?,3,unix_timestamp())',
+ [$u['id'], IP, $_SERVER['HTTP_USER_AGENT']]
);
+ error("Неверный пароль к персонажу {$u['login']}.");
}
- setcookie('login', $_POST['login'] ?? '', time() + 60 * 60 * 24 * 7, '', Config::get('host'));
- setcookie('ip', IP, time() + 60 * 60 * 24 * 150, '');
-
- if ($u['online'] < time() - 520) {
- $sp = Db::getRows('select room, city, login from users where online > unix_timestamp() - 600 and id in (select user from friends where friend = ?)', [$u['id']]);
- foreach ($sp as $usr) {
- $chatDto = new ChatMessage();
- $chatDto->setRoom($usr['room']);
- $chatDto->setCity($usr['city']);
- $chatDto->setTo($usr['login']);
- $chatDto->setText('Вас приветствует: ' . $u['login'] . '.');
- $chatDto->setType(6);
- $chat->sendMsg($chatDto);
- }
+ $_SESSION['login'] = $u['login'];
+ if (!empty($u['totp'])) {
+ $_SESSION['totp'] = new TOTP($u['totp']);
}
-
- $apu = '';
- Db::sql('update dump set ver = 1, upd = 2 where uid = ?', [$u['id']]);
-
- if (
- $u['auth'] != md5($u['login'] . 'AUTH' . IP) ||
- $_COOKIE['auth'] != md5($u['login'] . 'AUTH' . IP) ||
- $u['auth'] == '' || $u['auth'] == '0'
- ) {
- if (
- $u['auth'] != '' &&
- $u['auth'] != '0' &&
- $u['ip'] != IP
- ) {
- $cmsg = new ChatMessage();
- $cmsg->setTo($u['login']);
- $cmsg->setText('В предыдущий раз этим персонажем заходили с другого компьютера ' . date('d.m.Y H:i', $u['online']) . "(Предыдущий ip: %{$u['ip']})");
- $cmsg->setType(6);
- $chat->sendMsg($cmsg);
- }
- $apu = "auth = '" . md5($u['login'] . 'AUTH' . IP) . "',";
- setcookie('auth', md5($u['login'] . 'AUTH' . IP), time() + 60 * 60 * 24 * 365, '', Config::get('host'));
- }
-
- $ipnew = IP;
-
- Db::sql('insert into logs_auth (uid, ip, browser, time) values (?,?,?,unix_timestamp())', [
- $u['id'], IP, $_SERVER['HTTP_USER_AGENT'],
- ]);
-
- Db::sql("update users set $apu ip = ?, dateEnter = ?, online = unix_timestamp() where id = ?", [$ipnew, $_SERVER['HTTP_USER_AGENT'], $u['id']]);
-
- $_SESSION['uid'] = $u['id'];
- header('location: /bk');
- exit();
}
+
+if (!empty($_SESSION['totp']) && !empty($_SESSION['login'])) {
+ if (empty($otp)) {
+ ?>
+
+
+
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
- + Внимание!Смените пароль на уникальный,который не использовался ранее в подобных проектах,это обезопасит вашего персонажа от взлома. - Администрация. - = $rowonmax; ?> - - + = $rowonmax; ?> + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
- + Внимание!Смените пароль на уникальный,который не использовался ранее в подобных проектах,это обезопасит вашего персонажа от взлома. - Администрация. - = $rowonmax; ?> - - - + = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
- error != '' ) { ?>
-
- = $u->error; ?>
-
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
- testHome(); if(!isset($hgo['id'])){ ?> - - - - - + testHome()) { ?> + + + + + Внимание!Смените пароль на уникальный,который не использовался ранее в подобных проектах,это обезопасит вашего персонажа от взлома. - Администрация. - = $rowonmax; ?> - - - + = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
- testHome(); if(!isset($hgo['id'])){ ?> - - - - - + testHome()) { ?> + + + + + Внимание!Смените пароль на уникальный,который не использовался ранее в подобных проектах,это обезопасит вашего персонажа от взлома. - Администрация. - = $rowonmax; ?> - - - |
- |
- |
- + = $rowonmax; ?> + + |
+ |||||||||
+ | + | + |
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
- testHome(); if(!isset($hgo['id'])){ ?> - - - - - + testHome()) { ?> + + + + + Внимание!Смените пароль на уникальный,который не использовался ранее в подобных проектах,это обезопасит вашего персонажа от взлома. - Администрация. - = $rowonmax; ?> - - - |
- |
- |
- + = $rowonmax; ?> + + |
+ |||||||||
+ | + | + |
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; } ?> - | -- |
-
+ = $rowonmax; ?> + + |
+
- getInfoPers($u->info['id'],0); if($usee!=false){ echo $usee[0]; }else{ echo 'information is lost.'; }
- echo ' |
- - |
-
+ = $rowonmax; ?> + + |
+