Joywork/api/v2/app/src/controllers/UsersController.php

912 lines
35 KiB
PHP
Raw Normal View History

2026-05-22 20:21:54 +02:00
<?php
namespace App\v2\Controller;
class UsersController extends ApiController
{
public function getUserInfo($app, $get = null, $post = null) {
$protocol = (self::is_ssl()) ? 'https://' : 'http://';
$host = $protocol . $_SERVER['SERVER_NAME'];
if ($user_id = $_SESSION['id']) {
$pdo = $app->container->get('pdo');
$mdb = $app->container->get('mysql');
$sql = "SELECT * FROM `users` WHERE `id` = '$user_id' LIMIT 1";
$sth = $pdo->prepare($sql);
$status = $sth->execute();
if ($result = $sth->fetch(\PDO::FETCH_ASSOC)) {
$user = new \User();
$user->get($user_id);
$user->checkPermissions($user_id, false);
$menuPermissions = $user->checkMenuPermissions();
$can_take_from_closed_req = false;
$daily_closed_req_left = $menuPermissions['daily_closed_req_limit'] - $menuPermissions['actual_daily_closed_req'];
if ($menuPermissions['menu_can_take_from_closed'] == 1 && $daily_closed_req_left > 0) {
$can_take_from_closed_req = true;
}
$agency_id = null;
$agency_name = null;
$agency_phone = null;
$show_all_objects_page = $user->show_all_objects_page;
$antiznak_count = 0;
if ($user->antiznak_request_count > 0 || (isset($user->agencyAntiznakRequestCount) && $user->agencyAntiznakRequestCount > 0)) {
if (!empty($user->antiznak_request_count)) {
$antiznak_count = $user->antiznak_request_count;
} else {
$antiznak_count = $user->agencyAntiznakRequestCount;
}
}
$tarif = new \Tarif;
if ($result['id_manager']) {
$is_manager = 1;
$agency = new \User;
$departmentClass = new \Department;
$departmentUser = $departmentClass->getDepartment($user_id);
$thisIdManager = $result['id_manager'];
if ($departmentUser['role'] == 'manager_office_menager' || $departmentUser['role'] == 'agent') {
$is_manager = 1;
if ($departmentUser['admin'] > 0) {
$thisIdManager = $departmentUser['admin'];
}
} else {
$is_manager = 0;
}
$agency->get($thisIdManager);
if ($agency->id_manager) {
$agency->get($agency->id_manager);
if ($agency->id_manager) {
$agency->get($agency->id_manager);
}
}
$agency_id = $agency->id;
$agency_name = $agency->agency_name;
$agency_phone = $agency->phone;
$id_tarif = $agency->id_tarif;
$date_tarif = $agency->date_tarif;
} else {
$is_manager = 0;
$id_tarif = $user->id_tarif;
$date_tarif = $user->date_tarif;
}
if ($result['id_manager'] == 0 && $result['agency'] == 0)
$is_individual = 1;
else
$is_individual = 0;
if ($result['agent'])
$is_agent = $_SESSION['agent'] = 1;
else
$is_agent = $_SESSION['agent'] = 0;
if ($result['agency'])
$is_agency = $_SESSION['agency'] = 1;
else
$is_agency = $_SESSION['agency'] = 0;
if ($is_agency) {
$agency_id = (int)$result['id'];
$agency_name = $result['agency_name'];
$agency_phone = $result['phone'];
}
//пользователь, который может управлять другими
if ($user->agency || $user->users_admin)
$is_users_admin = 1;
else
$is_users_admin = 0;
$watermark = null;
if ($agency_id) {
$sql = "SELECT `watermark` FROM `agency_watermark` WHERE `agency_id` = $agency_id";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$watermark = mysql_fetch_assoc($query)['watermark'];
}
}
// Кастомный ватермарк (имеет приоритет над дефолтным)
$watermark2 = null;
if ($agency_id == 7507)
$watermark2 = $host . '/images/stamp-midom-one.png';
else if ($agency_id == 8826)
$watermark2 = $host . '/images/trend_logo.png';
else if ($agency_id == 12482)
$watermark2 = $host . '/images/estate_logo.png';
else if ($agency_id == 11397)
$watermark2 = $host . '/images/const_logo.png';
else if ($agency_id == 12556)
$watermark2 = $host . '/images/utrielt_logo.png';
else if ($agency_id == 11965)
$watermark2 = $host . '/images/cap_gar_logo.png';
else if ($agency_id == 13357)
$watermark2 = $host . '/images/13357_logo.png';
else if ($agency_id == 11584)
$watermark2 = $host . '/images/stimul56_logo.png';
else if ($agency_id == 13596)
$watermark2 = $host . '/images/th_logo.png';
else if ($agency_id == 12259)
$watermark2 = $host . '/images/lion_logo.png';
else if ($agency_id == 10638)
$watermark2 = $host . '/images/gr_est_logo.png';
else if ($agency_id == 11325)
$watermark2 = $host . '/images/p_city_logo.png';
else if ($agency_id == 4)
$watermark2 = $host . '/images/ag_4.png';
else if ($agency_id == 13735)
$watermark2 = $host . '/images/logo_PL.png';
else if ($agency_id == 10041)
$watermark2 = $host . '/images/logo_rk.png';
else if ($agency_id == 14794)
$watermark2 = $host . '/images/logo_souz.png';
else if ($agency_id == 13058)
$watermark2 = $host . '/images/logo_nplus.png';
else if ($agency_id == 14942)
$watermark2 = $host . '/images/logo_comfort.png';
else if ($agency_id == 15401)
$watermark2 = $host . '/images/logo_mega.png';
else if ($agency_id == 15710)
$watermark2 = $host . '/images/logo_metrics.png';
else if ($user_id == 15276)
$watermark2 = $host . '/images/15276_logo.png';
else if ($agency_id == 15704)
$watermark2 = $host . '/images/ruy.png';
else if ($agency_id == 14568)
$watermark2 = $host . '/images/vme_logo.png';
else if ($agency_id == 16785)
$watermark2 = $host . '/images/kristall_logo.png';
else if ($agency_id == 17627)
$watermark2 = $host . '/images/white_test.png';
else if ($agency_id == 17596)
$watermark2 = $host . '/images/IMG_1080.PNG';
else if ($user_id == 17733)
$watermark2 = $host . '/images/logo_17733.png';
else if ($user_id == 18354)
$watermark2 = $host . '/images/logo_saz.png';
else if ($user_id == 16795)
$watermark2 = $host . '/images/logo_kve.png';
else if ($user_id == 18748)
$watermark2 = $host . '/images/logo_telex.png';
else if ($agency_id == 18846)
$watermark2 = $host . '/images/18846_logo.png';
else if ($user_id == 19608)
$watermark2 = $host . '/images/19608_logo.png';
else if ($user_id == 21208)
$watermark2 = $host . '/images/logo_21208.png';
else if ($user_id == 6027)
$watermark2 = $host . '/images/logo_6027.png';
else if ($agency_id == 22289)
$watermark2 = $host . '/images/logo_22289.png';
else if ($user_id == 22173)
$watermark2 = $host . '/images/logo_22173.png';
else if ($user_id == 21238)
$watermark2 = $host . '/images/logo_21238.png';
else if ($user_id == 22924)
$watermark2 = $host . '/images/logo_22924.png';
else if ($user_id == 17266)
$watermark2 = $host . '/images/logo_17266.png';
else if ($user_id == 22680)
$watermark2 = $host . '/images/logo_22680.png';
/*$id_tarif = $result['id_tarif'];
$date_tarif = $result['date_tarif'];*/
$tarif->get((int)$id_tarif);
$date_tarif = strtotime($date_tarif);
$date_end = $date_tarif + $tarif->period * 3600 * 24;
$date_end_f = date("d.m.Y H:i", $date_end);
$paid_days = ceil(($date_end - time()) / 24 / 3600);
if ($paid_days < 0)
$paid_days = 0;
if ($paid_days == -0)
$paid_days = 0;
$show_balance = false;
$show_request = false;
if (($_SESSION['individual'] == 1 && !empty($user->zipal_login) && !empty($user->zipal_password)) ||
($_SESSION['agency'] == 1 && !empty($user->zipal_login) && !empty($user->zipal_password)) ||
(((!empty($user->zipal_login) && !empty($user->zipal_password)) ||
(!empty($user->agencyZipalLogin) && !empty($user->agencyZipalPassword))))) {
$show_balance = true;
}
if ($user->egrn_request_count > 0 || (isset($user->agencyEgrnRequestCount) && $user->agencyEgrnRequestCount > 0)) {
$show_request = true;
}
$tarif_restricted = false;
if ($_SESSION['pay'])
$tarif_restricted = true;
$tarif_expired = false;
if ($tarif_restricted && $_SESSION['individual'] == 1)
$tarif_expired = true;
$sql = "SELECT id FROM `users`
WHERE id = 4 OR id = 93 OR id = 117 OR id = 3455 OR id IN (
SELECT id FROM `users` WHERE newbuildings_access = 1
) OR id_manager IN (
SELECT id FROM `users` WHERE newbuildings_access = 1
) OR id_manager IN (
select id from users where id_manager IN (
SELECT id FROM `users` WHERE newbuildings_access = 1
)
)";
$is_newbuildings_access = false;
if ($query = mysql_query($sql)) {
while($userId = mysql_fetch_assoc($query)) {
if ($userId['id'] == $user_id) {
$is_newbuildings_access = true;
break;
}
}
} else {
$errors[] = mysql_error();
}
$showAds = \User::isCurrentUserShowAdvertButton();
// Автоматический ватермарк
$auto_watermark = false;
if (in_array($user_id, [5427, 8826, 12482, 11397, 12556, 11965, 13357, 11584, 13596, 12259, 10638, 11325, 14028, 17733, 15276])) {
$auto_watermark = true;
}
if (in_array($agency_id, [8826, 12482, 11397, 12556, 11965, 13357, 11584, 13596, 12259, 10638, 11325, 4, 13735, 17596, 17627, 16785, 14568, 15704, 15710, 15401, 14942, 13058, 14794, 10041])) {
$auto_watermark = true;
}
$search_regions = [];
if ($user->region_rf_id == 1) {
$search_regions = [53, 80];
} else if ($user->region_rf_id == 2) {
$search_regions = [50, 81];
} else if ($user->region_rf_id == 3) {
$search_regions = [94, 95];
} else {
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
WHERE parent.id = {$user->region_rf_id} ORDER BY id ASC";
if ($rez = mysql_query($sql)) {
while($row = mysql_fetch_assoc($rez)) {
$search_regions[] = $row['id'];
}
}
}
// Предмодерация рекламы по объектам
$sql = "SELECT * FROM `advert_moderation_agency` WHERE `agency_id` = {$user->agencyId}";
$add_to_moderation = false; // Рекламый модератор (руковод.)
$adverts_moderate = false; // Агенты, которые могут отправлять рекламу на модерацию
if ($query = mysql_query($sql)) {
if (mysql_num_rows($query) > 0) {
$add_to_moderation = true;
if ($show_all_objects_page == 1 || boolval($result['show_all_objects_page'])) {
$adverts_moderate = true;
}
}
} else {
$errors[] = mysql_error();
}
$budgets = [];
$use_advert_budget = false;
if ($_SESSION['use_advert_budget']) {
$use_advert_budget = true;
/*$adverts_inst = new AdvertsController();
$budgets = $adverts_inst->getBudget($app, $get, $post, true);*/
}
$first_page_sql = "SELECT jp.page_url FROM users
JOIN jw_pages jp ON users.jw_page_id = jp.id
WHERE users.id = $user_id";
$first_page_query = mysql_query($first_page_sql);
$first_page_res = mysql_fetch_assoc($first_page_query);
$first_page = $first_page_res['page_url'];
$user = [
'id' => (int)$result['id'],
'first_page' => $first_page,
'agency_id' => (int)$agency_id,
'email' => $result['email'],
'phone' => $result['phone'],
'agency_phone' => $agency_phone,
'agency_name' => $agency_name,
'first_name' => $result['first_name'],
'middle_name' => $result['middle_name'],
'last_name' => $result['last_name'],
'region' => $this->getUserRegion($app, null, null, true),
//'region_id' => $result['region_rf_id'],
'region_id' => (int)$user->region_rf_id,
'search_regions_id' => $search_regions,
'logotype' => (!empty($result['photo'])) ? $host . '/photos/agency/' . $result['photo'] . '?=' . time() : null,
'avatar' => (!empty($result['user_logo'])) ? $host . '/photos/agency/' . $result['user_logo'] . '?=' . time() : null,
'birthday' => $result['birthday'],
'site' => [
'name' => $result['sitename'],
'url' => $result['site']
],
'tarif' => [
'id' => $result['id_tarif'],
'end_of' => $result['date_tarif'],
],
'services' => [
'tarif' => [
'id' => (int)$id_tarif,
'days' => (int)$paid_days,
'expired' => (bool)$tarif_expired,
'restricted' => (bool)$tarif_restricted,
],
//'egrn_count' => (int)$result['egrn_request_count'],
'egrn_count' => (!empty($user->egrn_request_count)) ? (int)$user->egrn_request_count : (int)$user->agencyEgrnRequestCount,
//'balance' => (double)$result['zipal_balance'],
'balance' => (!empty($user->zipal_balance)) ? (double)$user->zipal_balance : (double)$user->agencyZipalBalance,
'show_balance' => $show_balance,
'show_request' => $show_request,
'zipal' => ((!empty($user->zipal_login) && !empty($user->zipal_password)) || (!empty($user->agencyZipalLogin) && !empty($user->agencyZipalPassword))),
'antiznak_count' => (int)$antiznak_count,
'use_advert_budget' => $use_advert_budget,
'advert_budget' => $budgets,
],
'user_can' => [
'autosearch' => true,
'adverts' => $showAds,
'add_to_adverts' => !(bool)$tarif_restricted,
'add_to_moderation' => ($adverts_moderate) ? false : $add_to_moderation,
'adverts_moderate' => $adverts_moderate,
'object_fields' => ($is_agency || $is_manager || $is_users_admin),
'delete_clients' => ($is_agency || $is_users_admin),
'delete_requisition' => ($is_agency || $is_manager || $is_users_admin),
'advert_stats' => ($is_agency || $is_users_admin),
'add_employees' => (($is_agency || $is_manager) && $user_id != 5839),
'view_all_objects' => boolval($result['show_all_objects_page']),
'view_newbuildings' => boolval($result['newbuildings_access']),
'vk_post' => boolval($result['vk_token']),
'advertise' => [
'free' => true,
'avito' => true,
'cian' => true,
'zipal' => true,
'domclick' => true,
'emls' => true,
'jcat' => ((int)$agency_id != 12482),
'yandex' => true,
'promotion' => true,
],
],
'permissions' => $menuPermissions,
'is_users_admin' => $is_users_admin,
'is_agency' => $is_agency,
'is_agent' => $is_agent,
'is_individual' => $is_individual,
'is_manager' => $is_manager || $user->manager,
'is_restricted_access' => boolval($tarif_restricted), // даем пользоваться системой (частичный доступ)
'is_newbuildings_access' => boolval($is_newbuildings_access), // доступ к брони по новостройкам
//'is_restricted_access' => true, // даем пользоваться системой (частичный доступ)
'is_earn_access' => boolval($is_individual && $tarif_expired), // флаг необходимости оплаты
'is_test_tarif' => boolval($result['test_tarif']), // флаг тестового тарифа
'is_msk_gmt' => boolval($result['gmtmsk']),
'is_moder' => boolval($result['moder']),
'is_blocked' => boolval($result['blocked']),
'telegram' => [
'notify' => boolval($result['telegramm_notice']),
'chat_id' => trim($result['telegramm_chat_id']),
'last_send' => $result['telegramm_date'],
],
'ip_telephony' => [
'is_dispatcher' => $result['is_dispatcher'],
'vpbx_id' => $result['vpbx_id'],
],
'send_message' => strip_tags(trim($result['txt'])),
'date_reg' => $result['date_reg'],
'last_auth' => $result['last_auth'],
'watermark' => (!is_null($watermark2)) ? $watermark2 : (!is_null($watermark) ? $host . '/photos/agency/watermark/' . $watermark : null),
'client_ip' => (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : null,
'auto_watermark' => $auto_watermark,
'can_take_from_closed_req' => $can_take_from_closed_req,
/*'birthday' => $result['birthday'],
'id_manager' => $result['id_manager'],
'superadmin' => boolval($result['superadmin']),
'moder' => boolval($result['moder']),
'blocked' => boolval($result['blocked']),
'date_reg' => $result['date_reg'],
'last_auth' => $result['last_auth'],
'tarif' => [
'id' => $result['id_tarif'],
'end_of' => $result['date_tarif'],
'test_tarif' => boolval($result['test_tarif']),
],
'services' => [
'tarif' => date_diff(time(), strtotime($result['date_tarif']))->format('%R%a'),
'egrn' => $result['egrn_request_count'],
'balance' => $result['zipal_balance'],
],
'gmt' => $result['gmtmsk'],
'site' => [
'sitename' => $result['sitename'],
'url' => $result['site']
],*/
];
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => $status,
'user_id' => $user_id,
'user' => $user,
'is_https' => self::is_ssl(),
'remember_me' => isset($_SESSION['remember_me']) ? $_SESSION['remember_me'] : false,
'session_id' => session_id()
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
'is_https' => self::is_ssl()
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getUser($app, $get = null, $post = null) {
$id = null;
if (isset($get['id']))
$id = (int)$get['id'];
if (!is_null($id) && ($user_id = $_SESSION['id'])) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$user->get($id, true);
$user->checkPermissions($id, false);
if ($user->id) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$fullname = trim($user->last_name . ' ' . $user->first_name . ' ' . $user->middle_name);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => $user_id,
'item' => [
'id' => (int)$user->user_id,
'fullname' => $fullname,
'company' => $user->agencyName,
'phone' => $user->phone,
'email' => $user->email,
'position' => (isset($user->position)) ? $user->position : null,
'birthday' => (isset($user->birthday)) ? $user->birthday : null,
'vkontakte' => (isset($user->soc_vk)) ? $user->soc_vk : null,
'telegram' => (isset($user->soc_tg)) ? $user->soc_tg : null,
'facebook' => (isset($user->soc_fb)) ? $user->soc_fb : null,
'instagram' => (isset($user->soc_inst)) ? $user->soc_inst : null,
'twitter' => (isset($user->soc_tw)) ? $user->soc_tw : null,
'whatsapp' => (isset($user->soc_wa)) ? $user->soc_wa : null,
'whatsapp_enabled' => (isset($user->wa_enabled)) ? $user->wa_enabled : null,
],
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => [],
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public static function getUserRegion($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$sql = "SELECT rf_regions.* FROM rf_regions AS parent
JOIN rf_regions ON rf_regions.parent = parent.id
LEFT JOIN users ON users.region_rf_id = parent.id
WHERE users.id = $user_id ORDER BY id ASC";
if ($rez = mysql_query($sql)) {
while($row = mysql_fetch_assoc($rez)) {
$region[] = [
"id" => (int)$row['id'],
"name" => trim($row['name']),
"kladr" => (int)$row['kladr'],
"code" => (int)$row['code'],
"parent" => (int)$row['parent']
];
}
} else {
$error = true;
$errors[] = mysql_error();
}
$output = isset($region[1]) ? $region[1] : null;
if ($need_return) {
return $output;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'region' => $output
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return null;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public static function getUserVKGroups($app, $get = null, $post = null, $need_return = false) {
$error = false;
$errors = [];
$meta = [];
if (isset($get['meta']))
$meta = $get['meta'];
if ($user_id = $_SESSION['id']) {
$mdb = $app->container->get('mysql');
$user = new \User;
$user->get($user_id);
if (!isset($user->agencyId)) {
$user->agencyId = $user_id;
$user->agencyName = $user->agency_name;
$user->fio = trim($user->last_name . ' ' . $user->first_name . ' ' . $user->middle_name);
}
$groups = [];
$groups[] = [
'id' => intval($user->vk_user_id),
'name' => null,
'is_group' => false,
];
if (!empty($meta))
$_SESSION['meta'] = $meta;
$vkGroupIds = explode(",", trim($user->vk_group_id, ","));
if (count($vkGroupIds) >= 1) {
try {
$vkGroups = json_decode(file_get_contents("https://api.vk.com/method/groups.getById?group_ids=" . trim($user->vk_group_id) . "&fields=name&access_token=" . trim($user->vk_token) . "&v=5.130"));
foreach ($vkGroups->response as $response) {
$groups[] = [
'id' => intval($response->id),
'name' => trim($response->name),
'is_group' => true,
];
}
} catch (\Exception $e) {
$error = true;
$errors[] = $e->getMessage();
}
} else {
$error = true;
$errors[] = 'Не указано ни одной группы в настройках профиля.';
}
if ($need_return) {
return $groups;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => !$error,
'user_id' => (int)$user_id,
'list' => $groups,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
if ($need_return) {
return null;
} else {
$app->response->header('Content-Type', 'application/json');
$app->response->setBody(json_encode([
'success' => false,
'user_id' => $_SESSION['id'],
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
public static function clearInputDataInput($input, $app) // очистка входящего массива
{
$mdb = $app->container->get('mysql');
$mas2 = '';
//while (list($k, $el) = each($mas)) {
$el = $input;
$el = strip_tags($el); // от тегов
$el = htmlspecialchars($el); // от кавычек и прочего
$el = str_replace("\n", "<br>", $el);
$el = str_replace("\r", "", $el);
$el = stripslashes($el); // от слэшей
$el = mysql_real_escape_string($el); // от MySQL-инъекций
$el = trim($el); // от лишних пробелов
$mas2 = $el;
return $mas2;
}
public function setUserLogin($app, $get = null, $post = null) {
$body = $app->request->getBody();
$data = json_decode($body, true);
$user_id = trim($data['user_id']);
$phone = trim($data['phone']);
$password = trim($this->clearInputDataInput($data['password'], $app));
$remember_me = boolval($data['remember_me']);
$restore = boolval($data['restore']);
$code = 200;
$results = [];
if (!empty($phone) && !empty($password)) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$results = $user->check_sms([
'phone' => preg_replace("/[^0-9]/","", $phone),
'pwd' => $password,
],true, false);
/*if ($_SESSION['id'] == 5427) {
$_SESSION['id'] = 12066;
$user = new \User();
$user->get($_SESSION['id']);
$user->checkPermissions($_SESSION['id'], false);
}*/
$user_id = intval($_SESSION['id']);
if ($results['success'] == true) {
if ($remember_me)
$_SESSION['remember_me'] = true;
else
$_SESSION['remember_me'] = false;
$app->response->header('Content-Type', 'application/json');
$app->response->header('Access-Token', session_id());
$app->response->setStatus($code);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'options' => [
'direct_auth' => false,
'gc_lifetime' => (int)ini_get('session.gc_maxlifetime'),
'cookie_lifetime' => (int)ini_get('session.cookie_lifetime'),
'upload_max' => self::returnBytes(ini_get('upload_max_filesize')),
'post_max' => self::returnBytes(ini_get('post_max_size')),
],
], JSON_UNESCAPED_UNICODE));
$app->stop();
} else {
if (empty($results['message']))
$results['message'] = 'Ошибка авторизации.';
}
} else if (!empty($user_id) && $restore) {
$session_id = null;
if (isset(getallheaders()["Access-Token"]))
$session_id = trim(getallheaders()["Access-Token"]);
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
if ($session_id !== null && preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0) {
session_id($session_id);
$sql = "SELECT * FROM `users` WHERE `id` = $user_id AND `last_auth` >= NOW() - INTERVAL 180 MINUTE LIMIT 1";
if ($query = mysql_query($sql)) {
$user = mysql_fetch_assoc($query);
if ($user['moder'] != 0 && $user['blocked'] !== 1)
$_SESSION['id'] = $user['id'];
if (intval($_SESSION['id']) == $user_id) {
$app->response->header('Content-Type', 'application/json');
$app->response->header('Access-Token', $session_id);
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'options' => [
'direct_auth' => true,
'gc_lifetime' => (int)ini_get('session.gc_maxlifetime'),
'cookie_lifetime' => (int)ini_get('session.cookie_lifetime'),
'upload_max' => self::returnBytes(ini_get('upload_max_filesize')),
'post_max' => self::returnBytes(ini_get('post_max_size')),
],
], JSON_UNESCAPED_UNICODE));
$app->stop();
} else {
$code = 401;
$results['message'] = 'Данные авторизации уже устарели1. Попробуйте войти по логину и паролю.';
}
} else {
$code = 401;
$results['message'] = 'Данные авторизации уже устарели2. Попробуйте войти по логину и паролю.';
}
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->header('Set-Access-Token', null);
$app->response->setStatus($code);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => [
isset($results['message']) ? $results['message'] : null
]
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function setUserOnline($app, $get = null, $post = null) {
$error = false;
$errors = [];
$users_count = 0;
$users_online = [];
if ($user_id = $_SESSION['id']) {
// Открываем соединение с БД
$mdb = $app->container->get('mysql');
$user = new \User();
$agency_id = $user->getUserAgencyID();
$users_ids = $user->getAllAgencyUsers($agency_id);
$users_ids = array_values(array_map('intval', $users_ids));
$users_online[] = $user_id;
$sql = "SELECT online.id_user
FROM online, users
WHERE online.id_user=users.id AND
id_user <> {$user_id} AND
id_user IN (" . implode(", ", $users_ids) . ")";
if ($query = mysql_query($sql)) {
if ($users_count = mysql_num_rows($query)) {
while ($row = mysql_fetch_assoc($query)) {
$users_online[] = $row['id_user'];
}
}
} else {
$error = true;
$errors[] = mysql_error();
}
$users_online = array_unique(array_map('intval', $users_online));
$users_offline = array_unique(array_map('intval', array_diff($users_ids, $users_online)));
if (!$error) {
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'count' => $users_count,
'online' => $users_online,
'offline' => array_values($users_offline)
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$user_id,
'errors' => $errors,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
public function getSubordinates($app, $get = null, $post = null) {
if ($user_id = $_SESSION['id']) {
$mdb = $app->container->get('mysql');
$subordinatesJson = \User::getSubordinatesJson($user_id);
$subordinates = json_decode($subordinatesJson, true);
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => true,
'user_id' => (int)$user_id,
'list' => $subordinates,
'listJson' => $subordinatesJson,
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
$app->response->header('Content-Type', 'application/json');
$app->response->setStatus(200);
$app->response->setBody(json_encode([
'success' => false,
'user_id' => (int)$_SESSION['id'],
'errors' => ['Не авторизован']
], JSON_UNESCAPED_UNICODE));
$app->stop();
}
}