container->get('mysql'); $manager_agents = null; $agency_managers = []; $department_managers = []; $groups = []; $employees = []; // Текущий пользователь $user = new \User; $user->get($user_id); $user->checkPermissions($user_id, false); // Получаем список отделов $dep = new \Department; $departments = $dep->getDepartment($user_id); $searchUserId = $user_id; $list_type = ''; if(isset($get['list_type'])){ $list_type = $get['list_type']; } $onlyActive = true; if (isset($get['active'])) $onlyActive = ($get['active'] == 'true'); $showBlocked = false; if (isset($get['blocked'])) $showBlocked = ($get['blocked'] == 'true'); $selfExclude = false; if (isset($get['self_exclude'])) $selfExclude = ($get['self_exclude'] == 'true'); $addGroups = false; if (isset($get['add_groups'])) $addGroups = ($get['add_groups'] == 'true'); $includeIds = false; if (isset($get['include_ids'])) { if (count($get['include_ids'])) { $includeIds = $get['include_ids']; } } $list_type = 'clients'; if (isset($get['list_type'])) { $list_type = $get['list_type']; } if ($showBlocked) $onlyActive = false; if (!$selfExclude && (!$includeIds || in_array($user_id, $includeIds))) { $group_id = null; if ($user->blocked) $group_id = -1; $employees[] = [ 'id' => intval($user_id), 'name' => 'Я', 'department' => null, 'group_id' => $group_id, 'is_agent' => boolval($_SESSION['agent']), 'is_manager' => boolval($_SESSION['manager']), ]; } $menuPermissions = $user->checkMenuPermissions(); if (($_SESSION['agency'] || $_SESSION['users_admin'] || $menuPermissions['menu_can_transfer_to_common'] == 1) && $list_type != 'objects') { if ($list_type == 'objects') { $agency_id = $_SESSION['agency_id'] ; $sql_name_agency_id = "SELECT last_name, first_name, middle_name FROM users WHERE id = $agency_id"; if ($query_name_agency_id = mysql_query($sql_name_agency_id)) { $name_agency_id_assoc = mysql_fetch_assoc($query_name_agency_id); } $name_agency_id = $name_agency_id_assoc['last_name']. ' '.$name_agency_id_assoc['first_name']. ' '.$name_agency_id_assoc['middle_name']; $employees[] = [ 'id' => $agency_id, 'name' => $name_agency_id, 'department' => null, 'group_id' => null, 'is_agent' => boolval($_SESSION['agent']), 'is_manager' => boolval($_SESSION['manager']), ]; } else { $employees[] = [ 'id' => -1, 'name' => 'Все агентство', 'department' => null, 'group_id' => null, 'is_agent' => boolval($_SESSION['agent']), 'is_manager' => boolval($_SESSION['manager']), ]; } } if ($user_id != $user->agencyId || $list_type == 'objects') { $agency = $user->get($user->agencyId); $group_id = null; if ($agency->blocked) $group_id = -1; $employees[] = [ 'id' => intval($user->agencyId), 'name' => $user->agencyName, 'department' => null, 'group_id' => $group_id, 'is_agent' => boolval($agency->agent), 'is_manager' => boolval($agency->manager), ]; } $agentsOfManager = \User::getAllManagers($user->agencyId, $onlyActive); if (isset($agentsOfManager)) { foreach($agentsOfManager as $agent) { $agent_id = (int)$agent['id']; if ($user_id == $agent_id) continue; $role_id = $agent['role']; $group_id = null; if ($agent['blocked']) $group_id = -1; $employees[] = [ 'id' => $agent_id, 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), 'department' => ($role_id > 0) ? $departments[$role_id]['role_name'] : null, 'group_id' => $group_id, 'is_agent' => boolval($agent['agent']), 'is_manager' => boolval($agent['manager']), ]; } } $agentsOfAgency = \User::getAllAgents($user->agencyId, $onlyActive); if (isset($agentsOfAgency)) { foreach($agentsOfAgency as $agent) { $agent_id = (int)$agent['id']; if ($user_id == $agent_id) continue; $role_id = $agent['role']; $group_id = null; if ($agent['blocked']) $group_id = -1; $employees[] = [ 'id' => $agent_id, 'name' => trim($agent['last_name'] . ' ' . $agent['first_name'] . ' ' . $agent['middle_name']), 'department' => ($role_id > 0) ? $departments[$role_id]['role_name'] : null, 'group_id' => $group_id, 'is_agent' => boolval($agent['agent']), 'is_manager' => boolval($agent['manager']), ]; } } if (!$onlyActive || $showBlocked) $groups[(int)'-1'] = 'Заблокированные/удаленные'; if (!$error && count($employees)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $sources = [ 'success' => true, 'user_id' => (int)$user_id, 'list' => $employees ]; if ($addGroups) $sources['groups'] = $groups; $app->response->setBody(json_encode($sources, 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getResponsibles($app, $get = null, $post = null) { $userIds = array(); $userId = $_SESSION['id']; $mdb = $app->container->get('mysql'); $result = array(); $responsibles = array(); // Текущий пользователь $user = new \User; $user->get($userId); $id = (int)$get['id']; $section = $get['section']; $userIds[] = $userId; $who_work = 0; if($id > 0){ $sql = "SELECT * FROM clients where id = {$id}"; if($section == 'requisitions'){ $sql = "SELECT * FROM requisitions where id = {$id}"; } if($section == 'objects'){ $sql = "SELECT id, id_add_user as who_work FROM objects WHERE id = {$id}"; } //echo $sql; $q = mysql_query($sql); $r = mysql_fetch_assoc($q); if (isset($r['doers']) && !empty($r['doers'])) { $doers = json_decode(html_entity_decode($r['doers']), true); foreach ($doers as $user_id => $d){ if ($d == 1){ $userIds[] = (int)$user_id; } } } if($r['who_work'] > 0){ $userIds[] = (int)$r['who_work']; $who_work = (int)$r['who_work']; } } //Определение отделов $sql_d = "SELECT d.name as dep_name, r.name as role_name, r.role, r.department_id, r.id FROM departments as d left join roles as r on d.id = r.department_id WHERE d.agency_id = ".$user->agencyId; $q_d = mysql_query($sql_d); $departments = array(); while($r_d = mysql_fetch_assoc($q_d)){ $departments[$r_d['id']] = $r_d; } $selected = ''; $userIds = array_unique($userIds); $sql_users = "SELECT * FROM users WHERE id in (".implode(',',$userIds).") AND blocked = 0"; //echo $sql_users; $q_users = mysql_query($sql_users); while($r_user = mysql_fetch_assoc($q_users)){ $name = trim($r_user['last_name'] . ' ' . $r_user['first_name'] . ' ' . $r_user['middle_name']); if($r_user['role_id'] > 0){ $name .= ' ('.$departments[$r_user['role_id']]['role_name']. ' ' . $departments[$r_user['role_id']]['dep_name'].')'; } $responsibles[] = [ 'id' => $r_user['id'], 'name' => $name, ]; } $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$userId, 'responsibles' => $responsibles, 'who_work' => $who_work, 'sql' => $sql, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getTypes($app, $get = null, $post = null, $need_return = false) { global $OBJECT_TYPES; global $WORK_TYPES; global $REQ_TYPES; global $SEARCH_TARGETS; global $etaz_first_types; global $TYPE_NEDV2_SORT; global $BANK_PRODUKT; $error = false; $section = $get['section']; if ($section && ($user_id = $_SESSION['id'])) { $types = []; switch ($section) { case 'objects' : foreach($OBJECT_TYPES as $key => $val) { if (intval($key) > 0 && $key != 6) { $types[] = ['id' => intval($key), 'name' => $val]; } } break; case 'clients' : foreach($WORK_TYPES as $key => $val) { if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } } break; case 'search' : case 'autosearch' : foreach($SEARCH_TARGETS as $key => $val) { if ($key == 4) continue; if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } } $types[] = ['id' => 5, 'name' => 'Архив компании']; if ($section == 'autosearch') $types[] = ['id' => 6, 'name' => 'Собственники и объекты компании']; break; case 'requisitions' : /*foreach($REQ_TYPES as $key => $val) { if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } }*/ // Открываем соединение с БД $mdb = $app->container->get('mysql'); $pdo = $app->container->get('mypdo'); $requisitions_inst = new \Requisitions($pdo); $users_inst = new \User(); $agency_id = $users_inst->getAgencyIdForUser($user_id); $requisitions_inst->set_agencyId($agency_id); $results = $requisitions_inst->get_type(false, true); //var_dump($results); //$types = $results['type']; if (!empty($results['type'])) { foreach ($results['type'] as $result) { if ($result['order'] != -1 && $result['code'] != '-1' && !empty($result['name'])) { $name_type = $result['name']; if($result['archive'] == 1){ $name_type = $result['name']." (архивный)"; } $types[] = [ 'id' => intval($result['code']), 'heir' => intval($result['heir']), 'name' => $name_type, 'archive'=>$result['archive'] ]; } } } break; case 'contract_types' : // Открываем соединение с БД $mdb = $app->container->get('mysql'); $user = new \User; $user->get($user_id); $agency_id = $user->getUserAgencyID(); $contracts = new \Contract(); $contracts->setAgencyId($agency_id); $list = $contracts->getTypesName(); foreach($list as $item) { $types[] = [ 'id' => (int)$item['id'], 'name' => $item['type'], 'heir' => intval($item['heir']), ]; } break; case 'bank_products' : foreach($BANK_PRODUKT as $key => $val) { if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } } break; case 'operations' : $types = [ [ 'id' => 1, 'name' => 'Аренда' ], [ 'id' => 2, 'name' => 'Продажа' ], ]; break; case 'to_metro' : $types = [ [ 'id' => 1, 'name' => 'Пешком' ], [ 'id' => 2, 'name' => 'На транспорте' ], ]; break; case 'lease' : $types = [ [ 'id' => 2, 'name' => 'Длительно' ], [ 'id' => 3, 'name' => 'Несколько месяцев' ], [ 'id' => 1, 'name' => 'Посуточно' ], ]; break; case 'first_floor' : foreach($etaz_first_types as $key => $val) { if (intval($key) > 0) { $types[] = ['id' => intval($key), 'name' => $val]; } } break; case 'estate_types' : $index = 1; foreach($TYPE_NEDV2_SORT as $key => $val) { if (!empty($key)) { $types[] = [ 'id' => $index, 'name' => $val ]; } $index++; } break; case 'avito_room' : // Открываем соединение с БД $mdb = $app->container->get('mysql'); $sql = "SELECT * FROM avito_room_types ORDER BY name"; $rez = mysql_query($sql); while($row = mysql_fetch_assoc($rez)) { $types[] = [ 'id' => (int)$row['id'], 'name' => $row['name'] ]; } break; case 'deal_type' : // Открываем соединение с БД $mdb = $app->container->get('mysql'); $sql = "SELECT * FROM deal_type ORDER BY name"; $rez = mysql_query($sql); while($row = mysql_fetch_assoc($rez)) { $types[] = [ 'id' => (int)$row['id'], 'name' => $row['name'] ]; } break; case 'house_types' : $mdb = $app->container->get('mysql'); $sql = "SELECT * FROM house_type ORDER BY name"; $rez = mysql_query($sql); while($row = mysql_fetch_assoc($rez)) { $types[] = [ 'id' => (int)$row['id'], 'name' => $row['name'] ]; } break; case 'house_materials' : $mdb = $app->container->get('mysql'); $sql = "SELECT * FROM house_material ORDER BY name"; $rez = mysql_query($sql); while($row = mysql_fetch_assoc($rez)) { $types[] = [ 'id' => (int)$row['id'], 'name' => $row['name'] ]; } break; } if (count($types)) { if ($need_return) { return $types; } 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' => $types ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => (int)$user_id ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } public function getStatus($app, $get = null, $post = null) { $errors = []; $status = false; $service = $get['service']; if ($service) { switch ($service) { case 'api' : $status = true; /*if ($_SESSION['id'] == 5427) $_SESSION['id'] = 5427;*/ break; case 'mysql' : try { $pdo = $app->container->get('pdo'); $mdb = $app->container->get('mysql'); if ($pdo && $mdb) $status = true; } catch (Exception $e) { $errors[] = $e; } break; case 'sphinx' : try { $sphinx = $app->container->get('sphinx'); if ($sphinx) $status = true; } catch (Exception $e) { $errors[] = $e; } $status = true; break; case 'sphinx2' : try { $sphinx2 = $app->container->get('sphinx2'); if ($sphinx2) $status = true; } catch (Exception $e) { $errors[] = $e; } $status = true; break; } $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'status' => ($status) ? 'up' : 'down', 'service' => $service, 'errors' => $errors, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'service' => $service, 'errors' => $errors, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getTags($app, $get = null, $post = null, $need_return = false) { $error = false; if ($user_id = $_SESSION['id']) { $pdo = $app->container->get('pdo'); $mdb = $app->container->get('mysql'); $list = []; $user = new \User(); $user->get($user_id); //$user->checkPermissions($user_id, false); $agency_id = $user->getUserAgencyID(); if (boolval($get['with_managers'])) { $sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user->id."' OR `manager_id` = '".$user->id."'"; if ($user->id_manager) $sql .= " OR `manager_id` = '".$user->id_manager."' OR `user_id` = '".$user->id_manager."'"; if ($user->agencyId) $sql .= " OR `manager_id` = '".$user->agencyId."' OR `user_id` = '".$user->agencyId."'"; } else { $sql = "SELECT * FROM `activities` WHERE `user_id` = '".$user_id."' OR `manager_id` = '".$user_id."'"; if ($agency_id) $sql .= " OR `manager_id` = '".$agency_id."' OR `user_id` = '".$agency_id."'"; } $sql .= ' GROUP BY `id` ORDER BY `name`'; $sth = $pdo->prepare($sql); if ($sth->execute()) { while($row = $sth->fetch(\PDO::FETCH_BOTH)) { if (intval($row["id"]) && !empty($row["name"])) { $list[] = [ 'id' => intval($row["id"]), 'name' => $row["name"], 'color' => $row["color"] ]; } } } else { $error = true; } if (!$error) { if ($need_return) { return $list; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'count' => count($list), //'$sql' => $sql, 'list' => $list ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => (int)$user_id ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } public function getClients($app, $get = null, $post = null, $need_return = false) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $user = new \User(); $user->checkPermissions($user_id, false); $agency_id = $_SESSION['agency_id']; $menuPermissions = $user->checkMenuPermissions(); $clients = []; $filters = []; if (isset($get['filters'])) $filters = json_decode($get['filters'], true); $only_active = true; if (isset($get['only_active'])) $only_active = ($get['only_active'] == 'true'); $offset = null; if (isset($get['offset'])) $offset = intval($get['offset']); $search_query = ''; if (isset($get['search_query'])) $search_query = trim($get['search_query']); // Проверяем точное совпадение по телефону (без учета иерархии) if(!empty($search_query)) { $phone_clean = preg_replace('/[\(\)\-\s]/', '', $search_query); $sql_exact_phone = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` FROM `clients` WHERE cancel = 0 AND `phone` = '".mysql_real_escape_string($phone_clean)."' LIMIT 1"; if ($rez = mysql_query($sql_exact_phone)) { $exact_match = mysql_fetch_assoc($rez); if($exact_match) { $phones = []; $phones_dop = []; if (!empty($exact_match['phone'])) $phones[] = $exact_match['phone']; if (!empty($exact_match['phone2'])) $phones = array_merge($phones, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true)); if (!empty($exact_match['phone2'])) $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($exact_match['phone2'], ENT_QUOTES), true)); // Маскируем телефоны клиента в массиве phones_dop до implode, // если у текущего пользователя включено `hide_client_contacts`. if (!empty($phones_dop)) { foreach ($phones_dop as &$_pdop) { $_pdop = mask_phone_value_if_needed($_pdop); } unset($_pdop); } $clientItem = [ 'id' => (int)$exact_match['id'], 'name' => $exact_match['fio'], 'phone' => $exact_match['phone'], 'phones' => !empty($phones) ? $phones : null, 'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '', 'email' => !empty($exact_match['email']) ? $exact_match['email'] : null, 'date_add' => $exact_match['date_add'] ]; // Маскируем phone/email/имя клиента, если у текущего пользователя // включено право `user_permissions.hide_client_contacts`. // Helper сам проверяет право — если выключено, ничего не делает. mask_client_contacts_inplace($clientItem); $response = [ 'success' => true, 'user_id' => $user_id, 'count' => 1, 'list' => [$clientItem], 'exact_match' => true ]; if ($need_return) return $response; $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode($response, JSON_UNESCAPED_UNICODE)); $app->stop(); return; } } } $users = [(int)$user_id]; $managers = [(int)$agency_id]; $bd_usl = " AND cancel = 0"; $clients_ids = []; $bd_managers = ''; $bd_user_j = ''; $searchUserId = $_SESSION['id']; $adminDep = false; $depClass = new \Department(); $dep_user = $depClass->getDepartment((int)$_SESSION['id']); if ($_SESSION['users_admin']) { $currentUser = new \User(); $currentUser->checkPermissions(); $searchUserId = $currentUser->agencyId; } else if ($menuPermissions['menu_all_clients'] == 1) { $currentUser = new \User(); $currentUser->checkPermissions(); $searchUserId = $currentUser->agencyId; } else if($dep_user['role'] == 'manager_office'){ $currentUser = new \User(); $currentUser->checkPermissions(); $searchUserId = $dep_user['admin']; $adminDep = true; } else if($dep_user['role'] == 'manager_office_menager') { $searchUserId = $_SESSION['id_manager']; $adminDep = true; } if (!empty($search_query)) { $phone = preg_replace('/[+\-\(\)\/\?,.;:%№!\s]/', '', $search_query); $bd_usl .= " AND (`fio` LIKE '%$search_query%' OR `phone` LIKE '%$phone%' OR `email` LIKE '%$phone%')"; // $sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$agency_id or id_manager=$agency_id or id_manager in // (select id from users where id_manager=$agency_id or id_manager in // (select id from users where id_manager=$agency_id)))"; $sql_users = "SELECT id FROM users WHERE id in (select id from users where id=$searchUserId or id_manager=$searchUserId or id_manager in (select id from users where id_manager=$searchUserId or id_manager in (select id from users where id_manager=$searchUserId)))"; if ($rez = mysql_query($sql_users)) { while($r_users = mysql_fetch_assoc($rez)){ $users[] = (int)$r_users['id']; } } $users = array_unique($users); } $bd_user = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; if (!empty($filters['employees'])) { $users = []; $managers = []; $employees = array_unique($filters['employees']); foreach ($employees as $employee) { if (strripos($employee, 'u')) $users[] = preg_replace('/[^0-9]/', '', $employee); if (strripos($employee, 'm')) $managers[] = preg_replace('/[^0-9]/', '', $employee); } if ($managers) { /*$bd_managers_j = " AND id_agent IN (SELECT id FROM `users` WHERE id IN (". implode(',', $managers) .") OR id_manager IN (". implode(',', $managers) .") OR id_manager IN (SELECT id FROM users WHERE id_manager IN (". implode(',', $managers) .")))";*/ $bd_managers = " IN (". implode(',', $managers) .")"; } if ($users) { $bd_user_j = " `who_work` IN (". implode(',', $users) .") OR `id_agent` IN (SELECT `id` FROM `users` WHERE `id` IN (". implode(',', $users) .") OR `id_manager` IN (". implode(',', $users) .") OR `id_manager` IN (SELECT `id` FROM `users` WHERE `id_manager` IN (". implode(',', $users) .")))"; } } else { if ($menuPermissions['menu_all_clients'] == 1 ) { $users[] = $agency_id; } $bd_user_j = " (`who_work` IN (". implode(',', $users) .") or `id_agent` IN (". implode(',', $users) ."))"; if (isset($get['client_id'])) $clients_ids[] = $get['client_id']; elseif (isset($get['clients_ids'])) $clients_ids = (array)$get['clients_ids']; if (count($clients_ids) > 0) { $bd_usl = " `id` IN (" . implode(',', $clients_ids) . ") "; $bd_user_j = ''; } } if (!empty($filters['types'])) { $where = []; $types = $filters['types']; foreach ($types as $type) { $where[] = "`work_type` LIKE '%" {$type}"%'"; } $bd_usl .= " AND (".implode(" OR ",$where).")"; } if (!empty($filters['tags'])) { $tags_ids = $filters['tags']; $bd_usl .= " AND `id` IN ( SELECT `client_id` FROM `clients_activities` WHERE `activity_id` IN (" . implode(", ", $tags_ids) . ") )"; } if (!empty($filters['source'])) { $sources = $filters['source']; $where = []; foreach ($sources as $source) { if ($source == 0) { $where[] = "`source` IS NULL"; $where[] = "`source` = ''"; $where[] = "`source` = 'null'"; } else { $where[] = "`source` = ' {$source}'"; } } $bd_usl .= " AND (" . implode(" OR ", $where) . ")"; } if (!empty($filters['clients_ids'])) { $clients_ids = $filters['clients_ids']; $bd_usl .= " AND `id` IN (" . implode(", ", $clients_ids) . ")"; } if (!empty($filters['is_deleted'])) $bd_usl .= " AND `confirm` > 0 AND `deleted` = 1 "; else if (empty($clients_ids)) $bd_usl .= " AND `confirm` > 0 "; else if ($only_active) $bd_usl .= " AND `deleted` <> 1 "; if (in_array(6358, $managers) || in_array(93, $managers)) { $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` FROM `clients` WHERE ( (true $bd_user) OR (`clients`.`who_work` = 0 AND `clients`.`id_agent` IN ( SELECT id FROM `users` WHERE `id` $bd_managers OR `id_manager` $bd_managers OR `id_manager` IN ( SELECT `id` FROM `users` WHERE `id_manager` $bd_managers)) ) ) $bd_usl ORDER BY `clients`.`id` DESC"; } else { $sql = "SELECT `id`, `email`, `fio`, `phone`, `phone2`, DATE_FORMAT(`date_add`, '%d.%m.%Y') AS `date_add`, `objects`, `deleted`, `confirm` FROM `clients` WHERE $bd_user_j $bd_usl ORDER BY `clients`.`id` DESC"; } if ($offset) $sql .= " LIMIT $offset, 10"; else if ($offset == 0) $sql .= " LIMIT 0, 10"; else $sql .= " LIMIT 100"; if ($rez = mysql_query($sql)) { while($client = mysql_fetch_assoc($rez)) { // Телефоны клиента $phones = []; $phones_dop = []; if (!empty($client['phone'])) $phones[] = $client['phone']; if (!empty($client['phone2'])) $phones = array_merge($phones, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); if (!empty($client['phone2'])) $phones_dop = array_merge($phones_dop, json_decode(html_entity_decode($client['phone2'], ENT_QUOTES), true)); if (empty($phones)) $phones = null; // Маскируем телефоны клиента в массиве phones_dop до implode, // если у текущего пользователя включено `hide_client_contacts`. if (!empty($phones_dop)) { foreach ($phones_dop as &$_pdop) { $_pdop = mask_phone_value_if_needed($_pdop); } unset($_pdop); } $clientItem = [ 'id' => (int)$client['id'], 'name' => $client['fio'], 'phone' => $client['phone'], 'phones' => $phones, 'phones_dop' => (!empty($phones_dop)) ? implode(', ', $phones_dop) : '', 'email' => (!empty($client['email'])) ? $client['email'] : null, 'date_add' => $client['date_add'], /*'objects' => $client['objects'], 'is_deleted' => boolval($client['deleted']), 'is_confirm' => boolval($client['confirm']), 'id_agent' => $client['id_agent'], 'who_work' => $client['who_work'], 'source' => $client['source'],*/ ]; // Маскируем phone/email/имя клиента, если у текущего пользователя // включено право `user_permissions.hide_client_contacts`. // Helper сам проверяет право — если выключено, ничего не делает. mask_client_contacts_inplace($clientItem); $clients[] = $clientItem; } } else { $error = true; $errors[] = mysql_error(); } if (!$error) { $sources = [ 'success' => true, 'user_id' => $user_id, 'count' => count($clients), 'list' => $clients, '$sql' => $sql, '$get' => $get, ]; if ($need_return) { return $sources; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode($sources, JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => $user_id, 'errors' => $errors, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } public function getСommercialTypes($app, $get = null, $post = null) { $error = false; if ($user_id = $_SESSION['id']) { $pdo = $app->container->get('pdo'); $list = []; $sql = "SELECT * FROM commercial_object"; $sql .= ' GROUP BY `id` ORDER BY `name`'; $sth = $pdo->prepare($sql); if ($sth->execute()) { while($row = $sth->fetch(\PDO::FETCH_BOTH)) { $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; } } else { $error = true; } if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $list ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getRegions($app, $get = null, $post = null) { $error = false; $sub_regions = false; if (isset($get['sub_regions'])) $sub_regions = true; if ($user_id = $_SESSION['id']) { $pdo = $app->container->get('pdo'); $list = []; if ($sub_regions) $sql = "SELECT * FROM rf_regions "; else $sql = "SELECT * FROM rf_regions WHERE parent = 0"; $sql .= ' GROUP BY `id` ORDER BY `id`, `name`'; $sth = $pdo->prepare($sql); if ($sth->execute()) { while($row = $sth->fetch(\PDO::FETCH_BOTH)) { $kladr = []; if (intval($row["kladr"])) { $kladr[] = $row["kladr"]; } else { if (intval($row["id"]) == 1) { // Москва и Московская область $kladr = [ '7700000000000', '5000000000000' ]; } else if (intval($row["id"]) == 2) { // Санкт-Петербург и Ленинградская обл $kladr = [ '7800000000000', '4700000000000' ]; } else if (intval($row["id"]) == 3) { // Крым и Севастополь $kladr = [ '9100000000000', '9200000000000' ]; } } $list[] = [ 'id' => intval($row["id"]), 'name' => $row["name"], 'kladr' => $kladr, 'code_id' => intval($row["code"]), 'parent_id' => intval($row["parent"]), ]; } } else { $error = true; } if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $list ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getDistricts($app, $get = null, $post = null) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { $region_rf_id = null; if (isset($get['region_id'])) $region_rf_id = $get['region_id']; $list = []; $groups = []; $mdb = $app->container->get('mysql'); $region = []; if ($region_rf_id) { if (is_array($region_rf_id)) { if (in_array(80, $region_rf_id)) $region_rf_id[] = 1; if (in_array(81, $region_rf_id)) $region_rf_id[] = 2; $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC"; } else { $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id = $region_rf_id ORDER BY id ASC"; } } else { $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[] = $row; } } else { $error = true; $errors[] = mysql_error(); } if (empty($region)) { $region = [ [ 'id' => 47, 'name' => 'Ленинградская обл', 'kladr' => '4700000000000', 'parent' => 94, 'code' => 47 ], [ 'id' => 78, 'name' => 'Санкт-Петербург', 'kladr' => '7800000000000', 'parent' => 94, 'code' => 78 ] ]; } if ($region[1]['code'] == 78) { $sql = "SELECT * FROM rayon WHERE id IN (15,3,6,7,1,23,13,22,33,25,11,10,8,26,12,27,5,2,28,9) OR is_lo = 1 ORDER BY is_lo, rayon"; if ($rez = mysql_query($sql)) { $group_id = (int)$region[1]['id']; $group_name = 'Санкт-Петербург'; while($rayon = mysql_fetch_assoc($rez)) { if ($rayon['is_lo'] == 1) $group_name = 'Ленинградская область'; $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; } $groups[] = ['id' => $group_id, 'name' => $group_name]; } else { $error = true; $errors[] = mysql_error(); } } else if ($region[1]['code'] == 77) { $group_id = (int)$region[1]['id']; $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; $sql = "SELECT * FROM rf_regions WHERE parent = $group_id"; if ($rez = mysql_query($sql)) { if (mysql_num_rows($rez) > 0) { while($sub_region = mysql_fetch_assoc($rez)) { $group_id = $sub_region['id']; $groups[] = ['id' => $group_id, 'name' => $sub_region['name']]; $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; $rez_rayon = mysql_query($sql); while ($rayon = mysql_fetch_assoc($rez_rayon)) { $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; } } } } else { $error = true; $errors[] = mysql_error(); } } else { $group_id = (int)$region[1]['id']; $groups[] = ['id' => $group_id, 'name' => $region[1]['name']]; $sql = "SELECT * FROM rayon WHERE id IN (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = $group_id)"; if ($rez = mysql_query($sql)) { if (mysql_num_rows($rez) > 0) { while($rayon = mysql_fetch_assoc($rez)) { $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; } } else { $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; } } else { $error = true; $errors[] = mysql_error(); } } if (!empty($region[0]['id']) && isset($group_id)) { $sql = "SELECT * FROM rayon where id in (SELECT rayon_id FROM rf_region_rayons WHERE rf_region_id = ".$region[0]['id'].")"; if ($rez = mysql_query($sql)) { if (mysql_num_rows($rez) > 0) { while($rayon = mysql_fetch_assoc($rez)) { $list[] = ['id' => (int)$rayon['id'], 'name' => $rayon['rayon'], 'group_id' => (int)$group_id]; } } else { $list[] = ['id' => 0, 'name' => 'Весь город', 'group_id' => (int)$group_id]; } } else { $error = true; $errors[] = mysql_error(); } } if (!$error) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); if (!is_array($region_rf_id)) { $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'count' => count($list), 'list' => $list, 'groups' => $groups, 'parent_region' => (int)$region[1]['parent'], 'region_type' => (int)$region[1]['id'], ], JSON_UNESCAPED_UNICODE)); } else { $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'count' => count($list), 'list' => $list, 'groups' => $groups, 'sql' => $sql, ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getMetro($app, $get = null, $post = null) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { $region_rf_id = null; if (isset($get['region_id'])) $region_rf_id = $get['region_id']; $list = []; $mdb = $app->container->get('mysql'); $region = []; if ($region_rf_id) { if (is_array($region_rf_id)) { $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id IN (" . implode(',', $region_rf_id) . ") ORDER BY id ASC"; } else { $sql = "SELECT rf_regions.* FROM rf_regions AS parent JOIN rf_regions ON rf_regions.parent = parent.id WHERE parent.id = $region_rf_id ORDER BY id ASC"; } } else { $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[] = $row; } } else { $error = true; $errors[] = mysql_error(); } if (empty($region)) { $region[0] = array( 'id' => 47, 'name' => 'Ленинградская обл', 'kladr' => '4700000000000', 'parent' => 94, 'code' => 47 ); $region[1] = array( 'id' => 78, 'name' => 'Санкт-Петербург', 'kladr' => '7800000000000', 'parent' => 94, 'code' => 78 ); } $sql = "SELECT * FROM metro WHERE region_rf_id = ".$region[0]['id']; if (isset($region[1])) $sql .=" OR region_rf_id = ".$region[1]['id']; if ($rez = mysql_query($sql)) { if (mysql_num_rows($rez) > 0) { if ($region[1]['code'] !== 78) { while ($metro = mysql_fetch_assoc($rez)) { $list[] = ['id' => (int)$metro['id'], 'name' => $metro['metro']]; } } } } else { $error = true; $errors[] = mysql_error(); } 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' => count($list), 'list' => $list, 'sql' => $sql, ], 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 getHighway($app, $get = null, $post = null) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { $region_rf_id = null; if (isset($get['region_id'])) $region_rf_id = $get['region_id']; $list = []; $mdb = $app->container->get('mysql'); $region = []; if ($region_rf_id) { $sql = "SELECT highways.* FROM highways WHERE highways.region_id = $region_rf_id"; } else { $sql = "SELECT highways.* FROM highways AS h LEFT JOIN users ON users.region_rf_id = h.region_id WHERE users.id = $user_id AND h.region_id=users.region_rf_id ORDER BY id ASC"; } if ($rez = mysql_query($sql)) { if (mysql_num_rows($rez) > 0) { while ($highway = mysql_fetch_assoc($rez)) { $list[] = ['id' => (int)$highway['cian_id'], 'name' => $highway['name']]; } } } else { $error = true; $errors[] = mysql_error(); } 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' => count($list), 'list' => $list, 'sql' => $sql, ], 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 getLayouts($app, $get = null, $post = null) { $error = false; if ($user_id = $_SESSION['id']) { $pdo = $app->container->get('pdo'); $list = []; $sql = "SELECT * FROM layout_object"; $sql .= ' GROUP BY `id` ORDER BY `name`'; $sth = $pdo->prepare($sql); if ($sth->execute()) { while($row = $sth->fetch(\PDO::FETCH_BOTH)) { $list[] = ['id' => intval($row["id"]), 'name' => $row["name"]]; } } else { $error = true; } if (!$error && count($list)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $list ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function is_see($app, $is_no_see, $users_no_see){ $mdb = $app->container->get('mysql'); $is_see = true; $tempArrNoSee = json_decode($users_no_see, true); if($is_no_see == 1 && !empty($users_no_see) && !empty($tempArrNoSee)){ $is_see = false; $arrNoSeeUsers = array(); foreach($tempArrNoSee as $u){ if(strpos($u, 'all_') !== false){ $manId = str_replace('all_', '', $u); $sql_u = "SELECT id FROM `users` WHERE id = $manId OR id_manager = $manId OR id_manager IN (SELECT id FROM users WHERE id_manager = $manId)"; $q_u = mysql_query($sql_u); while($r_u = mysql_fetch_row($q_u)){ $arrNoSeeUsers[] = (int)$r_u[0]; } } else { $arrNoSeeUsers[] = (int)$u; } } if(in_array($_SESSION['id'], $arrNoSeeUsers)){ $is_see = true; } } return $is_see; } public function getRoles($app, $get = null, $post = null) { global $ROLES_CLIENTS; $error = false; $section = $get['section']; if ($section && ($user_id = $_SESSION['id'])) { $roles = []; switch ($section) { case 'clients' : if ($_SESSION['agency_id'] == 7911 && !in_array("Страхование", $ROLES_CLIENTS)) $ROLES_CLIENTS[] = "Страхование"; if ($_SESSION['agency_id'] == 7911 && !in_array("Путевки", $ROLES_CLIENTS)) $ROLES_CLIENTS[] = "Путевки"; if ($_SESSION['agency_id'] == 7911 && !in_array("Юр.услуги", $ROLES_CLIENTS)) $ROLES_CLIENTS[] = "Юр.услуги"; foreach($ROLES_CLIENTS as $key => $val) { if (intval($key) > 0) { $roles[] = ['id' => intval($key), 'name' => $val]; } } break; } if (count($roles)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'list' => $roles ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getRequisitions($app, $get = null, $post = null) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { $requisitions = []; $mdb = $app->container->get('mysql'); $users_ids[] = (int)$user_id; $user = new \User(); $user->get($user_id); if ($_SESSION['users_admin']) $user_id = $user->getUserAgencyID(); $users_ids[] = $user_id; if ($user->get($user_id)) { if ($user->agency) { if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id' AND `manager`=1")) { while ($row = mysql_fetch_row($query)) { if (!empty($row[0])) { $users_ids[] = $row[0]; if ($query2 = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$row[0]'")) { while ($row2 = mysql_fetch_row($query2)) { if (!empty($row[0])) $users_ids[] = $row2[0]; } } else { $error = true; $errors[] = mysql_error(); } } } } else { $error = true; $errors[] = mysql_error(); } } else if ($user->manager) { if ($query = mysql_query("SELECT `id` FROM `users` WHERE `id_manager`='$user_id'")) { while ($row = mysql_fetch_row($query)) { if (!empty($row[0])) $users_ids[] = $row[0]; } } else { $error = true; $errors[] = mysql_error(); } } } $users_ids = array_unique($users_ids); $bd_usl_managers = " AND `user_id` IN (" . implode(',', $users_ids) . ")"; $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE 1 $bd_usl_managers AND `deleted` <> 1"; if (isset($post['ids']) && count($post['ids'])) { $sql = "SELECT `id`, `name`, `client_id` FROM `requisitions` WHERE `id` IN (" . implode(',', $post['ids']) . ")"; } if ($query = mysql_query($sql)) { while ($row = mysql_fetch_assoc($query)) { $requisitions[] = [ 'id' => (int)$row['id'], 'name' => $row['name'], ]; } } else { $error = true; $errors[] = mysql_error(); } if (count($requisitions)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'list' => $requisitions, 'errors' => $errors ], 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' => $errors ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getSources($app, $get = null, $post = null) { $error = false; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $pdo = $app->container->get('pdo'); $mdb = $app->container->get('mysql'); $user = new \User; $user->get($user_id); $sources = []; $search = null; $page = 1; if (isset($get['page'])) $page = $get['page']; // Number of records fetch $numberOfRecords = 1000; if (isset($get['searchTerm'])) $search = $get['searchTerm']; // Search text if ($search == null || strpos("объекты нашей компании", strtolower($search)) !== false) { $sources[] = array( "id" => 10000, "name" => "Объекты нашей компании", "source_see" => 1 ); $numberOfRecords--; } $list = []; $sql_where = " `user_id` = '".$user->id."' or `manager_id` = '".$user->id."'"; if ($user->id_manager) $sql_where .= " or `manager_id` = '".$user->id_manager."' or `user_id` = '".$user->id_manager."'"; if ($user -> agencyId) $sql_where .= " or `manager_id` = '".$user -> agencyId."' or `user_id` = '".$user -> agencyId."'"; if ($search == null) $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE $sql_where"; else $sqlCount = "SELECT COUNT(id) FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%'"; $rez = mysql_query($sqlCount); // @todo: implement to PDO $all_count = mysql_result($rez, 0); $all_pages = ceil($all_count / $numberOfRecords); $limit = ($page - 1) * $numberOfRecords; if ($search == null) { $sql = "SELECT * FROM `advertising_sources` WHERE $sql_where ORDER BY source, id LIMIT $limit, $numberOfRecords"; } else { $sql = "SELECT * FROM `advertising_sources` WHERE ($sql_where) AND source LIKE '%" . trim($search) . "%' ORDER BY source, id LIMIT $limit, $numberOfRecords"; } if ($rez = mysql_query($sql)) { // @todo: implement to PDO while ($block = mysql_fetch_assoc($rez)) { $block['source_see'] = 1; if($this->is_see($app, $block['is_no_see'], $block['users_no_see']) === false){ $block['source_see'] = 0; } $list[] = $block; } } else { $error = true; } // Read Data foreach ($list as $item) { $sources[] = [ "id" => intval($item['id']), "name" => $item['source'], "source_see" => $item['source_see'] ]; } if ($search == null || strpos("источник не выбран", strtolower($search)) !== false) { $sources[] = [ "id" => 0, "name" => "Источник не выбран", "source_see" => 1 ]; } if (count($sources)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'total_count' => $all_count, 'list' => $sources ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getFunnels($app, $get = null, $post = null, $need_return = false) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $user = new \User(); $user->get($user_id); $agency_id = $user->agencyId; $funnels = []; $section = $get['section']; // requisitions, clients $filters = $get['filters']; $use_counters = $get['use_counters'] || null; if (!in_array($agency_id, [6841, 6426, 7384, 7478, 8353, 8867, 9588])) $use_custom = true; else $use_custom = false; $default = "Обычные"; $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; if ($section == 'requisitions') $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = '$agency_id'"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query) > 0) { $row = mysql_fetch_assoc($query); if (!empty($row['name'])) $default = $row['name']; if ($section == 'clients' && $row['is_client'] == 0) $use_custom = false; if ($section == 'requisitions' && $row['is_req'] == 0) $use_custom = false; } } else { $error = true; $errors[] = mysql_error(); } $new_ids = []; $funnelCounts = []; // Счётчики в воронках if ($use_counters) { if ($section == 'clients') $_SESSION['new_transfers']['clients'] = null; else if ($section == 'requisitions') $_SESSION['new_transfers']['requisitions'] = null; if ($section == 'clients') { $bd_stage = ""; if ($filters['filter_stage_work']) { if ($filters['is_confirm'] || $filters['stage_send']) { $bd_stage = " AND `clients`.`deleted` <> '1'"; } else { $bd_stage = " AND `clients`.`deleted` <> '1' AND `clients`.`confirm` > 0"; } } if ($filters['is_hot']) $bd_stage .= " AND `clients`.`hot` = 1"; if (empty($bd_stage)) $bd_stage = " AND `clients`.`deleted` = '0'"; $sql1 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`clients`.`confirm` = 1 OR `clients`.`doers_confirm` = 1) AND `events`.`req_id` = 0 $bd_stage AND (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND `clients`.`funnel_id` = 0 GROUP BY `clients`.`funnel_id`"; $sql1_list = "SELECT `clients`.`funnel_id`, `clients`.`id` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`clients`.`confirm` = 1 OR `clients`.`doers_confirm` = 1) AND `events`.`req_id` = 0 $bd_stage AND (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND `clients`.`funnel_id` = 0"; $sql2 = "SELECT `clients`.`funnel_id`, COUNT(DISTINCT `clients`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` JOIN `funnel` AS `funnel` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`clients`.`confirm` = 1 OR `clients`.`doers_confirm` = 1) AND `events`.`req_id` = 0 $bd_stage AND (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND `clients`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0 GROUP BY `clients`.`funnel_id`"; $sql2_list = "SELECT `clients`.`funnel_id`, `clients`.`id` FROM `events_clients` AS `events` LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `events`.`client_id` JOIN `funnel` AS `funnel` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`clients`.`confirm` = 1 OR `clients`.`doers_confirm` = 1) AND `events`.`req_id` = 0 $bd_stage AND (`clients`.`who_work` = '$user_id' OR `clients`.`doers` LIKE '%"".$user_id."":1%') AND `clients`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0"; } else if ($section == 'requisitions') { $sql1 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND `events`.`client_id` = 0 AND `req`.`deleted` = 0 AND (`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND `req`.`funnel_id` = 0 GROUP BY `req`.`funnel_id`"; $sql1_list = "SELECT `req`.`funnel_id`, `req`.`id` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND `events`.`client_id` = 0 AND `req`.`deleted` = 0 AND (`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND `req`.`funnel_id` = 0"; $sql2 = "SELECT `req`.`funnel_id`, COUNT(DISTINCT `req`.`id`) AS `count` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` JOIN `funnel` AS `funnel` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND `events`.`client_id` = 0 AND `req`.`deleted` = 0 AND (`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND `req`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0 GROUP BY `req`.`funnel_id`"; $sql2_list = "SELECT `req`.`funnel_id`, `req`.`id` FROM `events_clients` AS `events` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `events`.`req_id` JOIN `funnel` AS `funnel` WHERE (`events`.`user_id` = '$user_id' AND `events`.`from_id` = '$user_id') AND (`events`.`event` = 'accepted' OR `events`.`event` = 'accepted_doer') AND `events`.`viewed` = 0 AND `events`.`read` = 1 AND (`req`.`confirm` = 1 OR `req`.`doers_confirm` = 1) AND `events`.`client_id` = 0 AND `req`.`deleted` = 0 AND (`req`.`who_work` = '$user_id' OR `req`.`doers` LIKE '%"".$user_id."":1%') AND `req`.`funnel_id` = `funnel`.`id` AND `funnel`.`agency_id` = '$agency_id' AND `funnel`.`deleted` = 0"; } $res1 = mysql_query($sql1); if (mysql_num_rows($res1)) { while($counter = mysql_fetch_assoc($res1)) { $funnelCounts[$counter['funnel_id']] = $counter['count']; } } $res1_list = mysql_query($sql1_list); if (mysql_num_rows($res1_list)) { while($row = mysql_fetch_assoc($res1_list)) { $new_ids[] = $row['id']; } } $res2 = mysql_query($sql2); if (mysql_num_rows($res2)) { while($counter = mysql_fetch_assoc($res2)) { $funnelCounts[$counter['funnel_id']] = $counter['count']; } } $res2_list = mysql_query($sql2_list); if (mysql_num_rows($res2_list)) { while($row = mysql_fetch_assoc($res2_list)) { $new_ids[] = $row['id']; } } if (count($new_ids) > 0) { if (($section == 'clients')) $_SESSION['new_transfers']['clients'] = $new_ids; else if (($section == 'requisitions')) $_SESSION['new_transfers']['requisitions'] = $new_ids; } } $is_default = false; if ($use_custom) { $is_default = true; $funnels[] = [ 'id' => 0, 'name' => $default, 'count' => ($funnelCounts[0] > 0) ? intval($funnelCounts[0]) : null, 'is_default' => $is_default ]; } $sql = "SELECT * FROM `funnel` WHERE `agency_id` = '$agency_id'"; if ($section == 'clients') $sql .= " AND `is_client` = 1"; elseif ($section == 'requisitions') $sql .= " AND `is_req` = 1"; if (!empty($filters['is_deleted'])) $sql .= " AND `deleted` == 1"; else $sql .= " AND `deleted` <> 1"; $sql .= " ORDER BY `id`"; if ($query = mysql_query($sql)) { while($funnel = mysql_fetch_assoc($query)) { $is_default_custom = false; if (!$is_default && (int)$funnel['$funnel'] == 0) { $is_default_custom = true; $is_default = true; } $funnels[] = [ 'id' => (int)$funnel['id'], 'name' => $funnel['name'], 'count' => ($funnelCounts[intval($funnel['id'])] > 0) ? intval($funnelCounts[intval($funnel['id'])]) : null, 'is_default' => $is_default_custom ]; } } else { $error = true; $errors[] = mysql_error(); } if (!$error) { if ($need_return) { return $funnels; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'count' => count($funnels), 'list' => $funnels ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $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 getAllFunnelsData($app, $get = null, $post = null, $need_return = false) { $error = false; $errors = []; $only_active = $get['only_active'] || true; $section = $get['section']; // requisitions, clients if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $pdo = $app->container->get('mypdo'); $users_inst = new \User(); $agency_id = $users_inst->getAgencyIdForUser($user_id); /*error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1);*/ $items = []; $response = []; // Нулевая воронка $sql = "SELECT * FROM `funnel_default` WHERE `agency_id` = {$agency_id}"; if ($query = $pdo->query($sql)) { $default_steps = [ 1 => [ 'id' => 1, 'name' => 'Новый', ], 2 => [ 'id' => 2, 'name' => 'В работе', ], 3 => [ 'id' => 3, 'name' => 'Презентация', ], 4 => [ 'id' => 4, 'name' => 'Показ', ], 5 => [ 'id' => 5, 'name' => 'Бронь', ], 6 => [ 'id' => 6, 'name' => 'Подаем на ипотеку', ], 7 => [ 'id' => 7, 'name' => 'Сделка', ], 8 => [ 'id' => 8, 'name' => 'Закрыт', ], ]; if ($pdo->num_rows($query)) { $row = $pdo->fetch_assoc($query); $name = 'Обычные'; if (!empty($row['name'])) $name = $row['name']; $items[] = [ 'id' => 0, 'name' => $name, 'is_default' => true, 'is_client' => (bool)$row['is_client'], 'is_req' => (bool)$row['is_req'], 'is_stage' => (bool)$row['is_stage'], 'is_show_funnels' => (bool)$row['is_show_funnels'], 'steps' => $default_steps, 'order' => 0, ]; } else { $items[] = [ 'id' => 0, 'name' => 'Обычные', 'is_default' => true, 'is_client' => true, 'is_req' => true, 'is_stage' => true, 'is_show_funnels' => true, 'steps' => $default_steps, 'order' => 0, ]; } } else { $error = true; } // Остальные (кастомные) воронки if ($only_active) $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id} AND `deleted` = 0"; else $sql = "SELECT * FROM `funnel` WHERE `agency_id` = {$agency_id}"; if ($section == 'clients') $sql .= " AND `is_client` = 1"; else if ($section == 'requisitions') $sql .= " AND `is_req` = 1"; $sql .= " ORDER BY `id`"; if ($query = $pdo->query($sql)) { if ($pdo->num_rows($query)) { while($row = $pdo->fetch_assoc($query)) { $row['date'] = date('d.m.Y H:i:s', strtotime($row['date_create'])); $row['role'] = htmlspecialchars_decode($row['role']); $row['client_type'] = htmlspecialchars_decode($row['client_type']); $row['main_step'] = ''; $row['is_default'] = 0; // Этапы по воронкам $sql = "SELECT * FROM `funnel_steps` WHERE `funnel_id` = ".$row['id']." AND deleted = 0 ORDER BY `main` DESC"; if ($steps = $pdo->query($sql)) { if ($pdo->num_rows($steps)) { $prev_steps = []; $steps_data = []; while($step = $pdo->fetch_assoc($steps)) { $steps_data[(int)$step['id']] = $step; } foreach ($steps_data as $step_id => $step) { $step['name_number'] = $step['name']; if ($step['main'] == 1) $step['name_number'] = '1. '.$step['name']; else if ($step['order_number'] > 0) $step['name_number'] = $step['order_number'].'. '.$step['name']; if (!empty($step['next_step'])) { $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); foreach ($next_steps_ids as $next_step_id) { $prev_steps[(int)$next_step_id][] = ['id' => (int)$step['id'], 'name' => $step['name']]; } } $row['branches'][$step['branch']][$step['id']] = self::clearInputArray($step); $row['steps'][$step['id']] = self::clearInputArray($step); if (!empty($row['steps'][$step['id']]['users_mes'])) $row['steps'][$step['id']]['users_mes'] = json_decode($row['steps'][$step['id']]['users_mes'], true); if (!empty($row['steps'][$step['id']]['arr_next_steps'])) { $arr_next_steps = json_decode($row['steps'][$step['id']]['arr_next_steps'], true); $row['steps'][$step['id']]['arr_next_steps'] = []; if (is_array($arr_next_steps)) { foreach ($arr_next_steps as $arr_next_step) { if (!empty($arr_next_step['id'])) { $next_step = $arr_next_step['id']; $row['steps'][$step['id']]['arr_next_steps'][] = [ 'id' => (int)$next_step['id'], 'name' => trim($next_step['name']) ]; } } } } else { $row['steps'][$step['id']]['arr_next_steps'] = []; $next_steps_ids = json_decode(html_entity_decode($step['next_step']), ENT_QUOTES); foreach ($next_steps_ids as $next_step_id) { $next_step = $steps_data[$next_step_id]; if (!empty($next_step)) { $row['steps'][$step['id']]['arr_next_steps'][] = ['id' => (int)$next_step['id'], 'name' => $next_step['name']]; } } } if (!empty($prev_steps[(int)$step['id']])) $row['steps'][$step['id']]['arr_prev_steps'] = $prev_steps[(int)$step['id']]; else $row['steps'][$step['id']]['arr_prev_steps'] = []; $files = []; $sql = "SELECT * FROM `funnel_files` WHERE `etap_id` = '".$step['id']."' AND `funnel_id` = ".$row['id']; if ($query_files = $pdo->query($sql)) { if ($pdo->num_rows($query_files)) { while($file_row = $pdo->fetch_assoc($query_files)) { $path = "https://uf.joywork.ru/upload/funnels/".$row['id']."/".$file_row['guid'].".".$file_row['type']; $files[] = ['guid' => $file_row['guid'], 'isUpload' => true, 'uploads' => false, 'name' => $file_row['name']]; } } } $row['steps'][$step['id']]['files'] = $files; $row['main_steps'][] = ['id' => $step['id'], 'name' => $step['name']]; if ($step['main'] == 1) $row['main_step'] = ['id' => $step['id'], 'name' => $step['name']]; } } } else { $error = true; } $items[] = $row; } } } else { $error = true; } if (!empty($items)) { foreach($items as $item) { $steps = []; foreach($item['steps'] as $step_id => $step) { $steps[] = [ 'id' => (int)$step_id, 'name' => $step['name'], 'prev_steps' => (!empty($step['arr_prev_steps'])) ? $step['arr_prev_steps'] : ((!empty($default_steps[(int)$step_id-1]) && $item['is_default']) ? [$default_steps[(int)$step_id-1]] : null), 'next_steps' => (!empty($step['arr_next_steps'])) ? $step['arr_next_steps'] : ((!empty($default_steps[(int)$step_id+1]) && $item['is_default']) ? [$default_steps[(int)$step_id+1]] : null), 'files' => (!empty($step['files'])) ? $step['files'] : [], 'tasks' => (!empty($step['tasks_list'])) ? json_decode($step['tasks_list']) : null, 'fields' => (!empty($step['pole_end_list'])) ? json_decode($step['pole_end_list']) : null, 'doers' => (!empty($step['doers'])) ? json_decode($step['doers']) : [null], 'is_next_variable' => ($step['next_step_change'] === "Зависит от поля Ветвление этапов"), ]; } $response[] = [ 'id' => (int)$item['id'], 'name' => trim($item['name']), 'order' => (!empty($item['order_number'])) ? (int)$item['order_number'] : 0, 'is_client' => (bool)$item['is_client'], 'is_default' => (bool)$item['is_default'], 'is_deleted' => (bool)$item['deleted'], 'is_req' => (bool)$item['is_req'], 'steps' => $steps, 'client_types' => (!empty($item['client_type'])) ? json_decode($item['client_type']) : null, 'roles' => (!empty($item['role'])) ? json_decode($item['role']) : null, 'agency_id' => (int)$item['agency_id'], 'created_by' => (int)$item['user_id'], 'created_at' => $item['date_create'], ]; } } if (!$error) { if ($need_return) { return $response; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $response, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $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 getList($app, $get = null, $post = null, $need_return = false) { $error = false; $errors = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $sql = ""; $list = []; $section = $get['section']; switch ($section) { case 'rooms_count' : $ROOMS_COUNT = [ 1 => "1 комн.", 2 => "2 комн.", 3 => "3 комн.", 4 => "4+ комн.", 5 => "Студия", ]; $list = []; foreach($ROOMS_COUNT as $key => $value) { $list[$key] = [ 'id' => $key, 'name' => $value ]; } break; case 'complexes': $sql = "SELECT `id`, `name` FROM `blocks` ORDER BY `name`"; break; case 'banks_list': $sql = "SELECT `id`, `name` FROM `banks` ORDER BY `name`"; break; case 'denial_work': { $user = new \User; $user->get($user_id); $agency_id = $user->agencyId; $sql = "SELECT `id`, `name` FROM `denial_work` WHERE (agency_id = 0 or agency_id={$agency_id}) and del = 0"; } break; case 'floor_materials': $sql = "SELECT `id`, `name` FROM `floor_material`"; break; case 'house_categories': $sql = "SELECT `id`, `name` FROM `house_category`"; break; case 'commerce_portal': $sql = "SELECT `id`, `name` FROM `commerc_portal`"; break; case 'commerce_purpose': $sql = "SELECT `id`, `name` FROM `commerc_purpose`"; break; case 'commerce_land_categories': $sql = "SELECT `id`, `name` FROM `commerc_land_category`"; break; case 'commerce_permitted_use': $sql = "SELECT `id`, `name` FROM `commerc_permitted_use`"; break; case 'commerce_electricity': $sql = "SELECT `id`, `name` FROM `commerc_electricity`"; break; case 'electricity_types': $sql = "SELECT `id`, `name` FROM `electricity_type` order by `id`"; break; case 'commerce_gas': $sql = "SELECT `id`, `name` FROM `commerc_gas`"; break; case 'gas_types': $sql = "SELECT `id`, `name` FROM `gas_type` order by `id`"; break; case 'commerce_water': $sql = "SELECT `id`, `name` FROM `commerc_gas`"; break; case 'commerce_sewage': $sql = "SELECT `id`, `name` FROM `commerc_gas`"; break; case 'sewerage_types': $sql = "SELECT `id`, `name` FROM `sewerage_type` order by `id`"; break; case 'commerce_driveways': $sql = "SELECT `id`, `name` FROM `commerc_driveways`"; break; case 'commerce_services': $sql = "SELECT `id`, `name` FROM `commerc_services`"; break; case 'building_types' : $sql = "SELECT `id`, `name` FROM `commerc_building_type`"; break; case 'building_classes' : $sql = "SELECT `id`, `name` FROM `commerc_building_class`"; break; case 'houseline_types' : $sql = "SELECT `id`, `name` FROM `commerc_houselinetype`"; break; case 'building_categories' : $sql = "SELECT `id`, `name` FROM `commerc_building_category`"; break; case 'entrance_types' : $sql = "SELECT `id`, `name` FROM `commerc_opened`"; break; case 'building_ventilations' : $list = [ [ 'id' => 0, 'name' => 'Нет', ], [ 'id' => 1, 'name' => 'Естественная', ], [ 'id' => 2, 'name' => 'Приточная', ], ]; break; case 'periods' : $list = [ [ 'id' => 1, 'name' => 'Сегодня', ], [ 'id' => 2, 'name' => 'Неделя', ], [ 'id' => 3, 'name' => 'Месяц', ], [ 'id' => 4, 'name' => 'Последние 30 дней', ], [ 'id' => 5, 'name' => 'Квартал', ], [ 'id' => 6, 'name' => 'Последние 90 дней', ], [ 'id' => 7, 'name' => 'Год', ], [ 'id' => 8, 'name' => 'Все время', ], [ 'id' => 9, 'name' => 'Период', ], ]; break; case 'building_conditioning' : $list = [ [ 'id' => 0, 'name' => 'Нет', ], [ 'id' => 1, 'name' => 'Местное', ], [ 'id' => 2, 'name' => 'Центральное', ], ]; break; case 'building_heating' : $list = [ [ 'id' => 0, 'name' => 'Нет', ], [ 'id' => 1, 'name' => 'Автономное', ], [ 'id' => 2, 'name' => 'Центральное', ], ]; break; case 'building_firefighting' : $list = [ [ 'id' => 0, 'name' => 'Нет', ], [ 'id' => 1, 'name' => 'Гидрантная', ], [ 'id' => 2, 'name' => 'Спринклерная', ], [ 'id' => 3, 'name' => 'Порошковая', ], [ 'id' => 4, 'name' => 'Газовая', ], [ 'id' => 5, 'name' => 'Сигнализация', ], ]; break; case 'garages' : $sql = "SELECT `id`, `name` FROM `garage_type`"; break; case 'garages_types' : $sql = "SELECT `id`, `name` FROM `garage_vid`"; break; case 'boxes_types' : $list = [ [ 'id' => 1, 'name' => 'Кирпичный', ], [ 'id' => 2, 'name' => 'Металлический', ], [ 'id' => 3, 'name' => 'Железобетонный', ], ]; break; case 'commerce_status' : $sql = "SELECT `id`, `name` FROM `commerc_status`"; break; case 'commerce_specifications' : $sql = "SELECT `id`, `name` FROM `commerc_specifications`"; break; case 'commerce_infrastructures' : $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE id < 27"; break; case 'commerce_infrastructures2' : $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid` = 1"; break; case 'commerce_infrastructures3' : $sql = "SELECT `id`, `name` FROM `commerc_infrastructure` WHERE `vid1` = 1"; break; case 'sale_types' : $list = [ [ 'id' => 1, 'name' => 'Договор уступки права требования', ], [ 'id' => 2, 'name' => 'Договор ЖСК', ], [ 'id' => 3, 'name' => 'Свободная продажа', ], [ 'id' => 4, 'name' => '214-ФЗ', ], [ 'id' => 5, 'name' => 'Договор инвестирования', ], [ 'id' => 6, 'name' => 'Предварительный договор купли-продажи', ], ]; break; case 'legal_address' : $list = [ [ 'id' => 1, 'name' => 'Предоставляется', ], [ 'id' => 2, 'name' => 'Не предоставляется', ], ]; break; case 'decoration_types' : $sql = "SELECT `id`, `name` FROM `avito_decoration_types` ORDER BY `id`"; break; case 'flat_types' : $sql = "SELECT `id`, `name` FROM `zipal_new_flat_type` ORDER BY `id`"; break; case 'investor_types' : $sql = "SELECT `id`, `name` FROM `investor_type` ORDER BY `id`"; break; case 'access' : $list = [ [ 'id' => 1, 'name' => 'Свободный', ], [ 'id' => 2, 'name' => 'Пропускная система', ], ]; break; case 'conditions' : $sql = "SELECT `id`, `name` FROM `commer_condition` ORDER BY `id`"; break; case 'furnitures' : $list = [ [ 'id' => 1, 'name' => 'Нет', ], [ 'id' => 2, 'name' => 'Есть', ], ]; break; case 'layouts' : $sql = "SELECT `id`, `name` FROM `layout_object` ORDER BY `id`"; break; case 'occupieds' : $list = [ [ 'id' => 1, 'name' => 'Не занято', ], [ 'id' => 2, 'name' => 'Занято', ], ]; break; case 'property_types' : $sql = "SELECT `id`, `name` FROM `property_type` ORDER BY `id`"; break; case 'rent_house_types' : $sql = "SELECT `id`, `name` FROM `house_type` ORDER BY `id`"; break; case 'wall_types' : $sql = "SELECT `id`, `name` FROM `wall_type` ORDER BY `id`"; break; case 'house_wcs_types' : $sql = "SELECT `id`, `name` FROM `house_wcs_type` ORDER BY `id`"; break; case 'land_purposes_types' : $sql = "SELECT `id`, `name` FROM `land_purpose` ORDER BY `id`"; break; case 'shape_types' : $sql = "SELECT `id`, `name` FROM `shape_type` ORDER BY `id`"; break; case 'plumbing_types' : $sql = "SELECT `id`, `name` FROM `plumbing_type` ORDER BY `id`"; break; case 'relief_types' : $sql = "SELECT `id`, `name` FROM `relief_type` ORDER BY `id`"; break; case 'land_usage_types' : $sql = "SELECT `id`, `name` FROM `land_usage_type` ORDER BY `id`"; break; case 'lease_deposit_types' : $sql = "SELECT `id`, `name` FROM `lease_deposit` ORDER BY `id`"; break; case 'window_view_types' : $sql = "SELECT `id`, `name` FROM `window_view` ORDER BY `id`"; break; case 'renovation_types' : $sql = "SELECT `id`, `name` FROM `renovation` ORDER BY `id`"; break; case 'bathroom_types' : $sql = "SELECT `id`, `name` FROM `bath_type` ORDER BY `id`"; break; case 'hot_water_types' : $sql = "SELECT `id`, `name` FROM `hot_water` ORDER BY `id`"; break; case 'parking_types' : $sql = "SELECT `id`, `name` FROM `parking_type` ORDER BY `id`"; break; case 'parking_types1' : $sql = "SELECT * FROM parking_type where vid = 0 ORDER BY id"; break; case 'parking_types2' : $sql = "SELECT * FROM parking_type where vid1 = 1 ORDER BY id"; break; case 'parking_types3' : $sql = "SELECT * FROM parking_type where vid = 1 ORDER BY id"; break; case 'vat_types' : $sql = "SELECT `id`, `name` FROM `vat_type` ORDER BY `id`"; break; case 'wet_spots' : $list = [ [ 'id' => 1, 'name' => '1', ], [ 'id' => 2, 'name' => '2', ], [ 'id' => 3, 'name' => '3', ], [ 'id' => 4, 'name' => '4', ], [ 'id' => 5, 'name' => 'Нет', ], ]; break; case 'countries' : $sql = "SELECT * FROM `country_list` WHERE `id` = 171 UNION SELECT * FROM `country_list` WHERE `id` <> 1 ORDER BY `id`"; break; case 'cottage_village' : $sql = "SELECT * FROM cottage_village order by id"; } if (!isset($list) || empty($list)) { $list = array(); } if (!empty($sql)) { if ($query = mysql_query($sql)) { if (mysql_num_rows($query) > 0) { while ($row = mysql_fetch_assoc($query)) { if($section == 'cottage_village') { if(!isset($list[$row['region_id']])) $list[$row['region_id']] = array(); $list[$row['region_id']][] = [ 'value' => (int)$row['id'], 'name' => trim($row['name']), ]; } else $list[] = [ 'id' => (int)$row['id'], 'name' => trim($row['name']), ]; } } } else { $error = true; $errors[] = mysql_error(); } } if (!$error) { if (count($list) && $section == 'denial_work') { $list[] = [ 'id' => 0, 'name' => 'Другое', ]; } if ($need_return) { return $list; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'count' => count($list), 'list' => $list ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $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 getLists($app, $get = null, $post = null) { $lists = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $sections = $get['sections']; foreach ($sections as $section) { $list = $this->getList($app, ['section' => $section], null, true); if ($list) $lists[$section] = $list; else $lists[$section] = false; } } if (count($lists)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'lists' => $lists ], JSON_UNESCAPED_UNICODE)); $app->stop(); } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => (int)$user_id ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } public function getFiles($app, $get = null, $post = null) { $error = false; $errors = []; $source_id = null; if (isset($get['source_id'])) $source_id = (int)$get['source_id']; $section = null; if (isset($get['section'])) $section = trim($get['section']); if (($user_id = $_SESSION['id']) && $source_id && $section) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $pdo = $app->container->get('mypdo'); $list = []; $row = []; $field = ''; $table = 'user_client_events'; if ($section == 'clients') { $field = 'client_id'; $table = 'user_client_events'; } else if ($section == 'requisitions') { $field = 'req_id'; $table = 'user_client_events'; } else if ($section == 'objects') { $field = 'object_id'; $table = 'user_object_events'; } if (!empty($field) && !empty($table)) { $protocol = (self::is_ssl()) ? 'https://' : 'http://'; $host = $protocol . $_SERVER['SERVER_NAME']; $sql = "SELECT * FROM clients_files as c WHERE {$field} = {$source_id} AND event_id > 0 AND (SELECT id from {$table} WHERE id = c.event_id) > 0"; if ($q = $pdo->query($sql)) { if ($pdo->num_rows($q) > 0) { while ($r = $pdo->fetch_assoc($q)) { if (!empty($r['name'])) { $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; if ($r['client_id'] > 0) $file .= "clients/" . $r['client_id'] . "/"; else if ($r['req_id'] > 0) $file .= "reqs/" . $r['req_id'] . "/"; else if ($r['object_id'] > 0) $file .= "objects/" . $r['object_id'] . "/"; $file .= $r['guid'] . '.' . $r['type']; $r['type'] = 'id'; $r['link'] = $host . '/download_file.php?id=' . $r['id']; $unix_time = filemtime($file); $r['date'] = date('d.m.Y в H:i', $unix_time); if (!isset($list['names'][$r['name_id']])) $list['names'][$r['name_id']] = array('type' => 'id', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['name_id']); if (file_exists($file)) $row[$r['name_id']][] = $r; } } } } else { $error = true; $errors[] = $q->pdo->errorInfo(); } if ($section == 'clients' || $section == 'requisitions' || $section == 'free') { $sql = "SELECT * FROM `funnel_files` WHERE {$field} = {$source_id}"; if ($q = $pdo->query($sql)) { if ($pdo->num_rows($q) > 0) { while ($r = $pdo->fetch_assoc($q)) { if (!empty($r['name'])) { $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; if ($r['client_id'] > 0) $file .= "clients/" . $r['client_id'] . "/"; else if ($r['req_id'] > 0) $file .= "req/" . $r['req_id'] . "/"; $file .= $r['guid'] . '.' . $r['type']; $r['type'] = 'guid'; $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; $unix_time = filemtime($file); $r['date'] = date('d.m.Y в H:i', $unix_time); if (!isset($list['names'][$r['etap_id']])) $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => $section, 'from_id' => $source_id, 'id' => (int)$r['etap_id']); if (file_exists($file)) $row[$r['etap_id']][] = $r; } } } } else { $error = true; $errors[] = $q->pdo->errorInfo(); } } if ($section == 'requisitions') { //поиск файлов по объекту $sql = "SELECT id, type_id, object_id FROM requisitions WHERE id = {$source_id}"; if ($q = $pdo->query($sql)) { $r = $pdo->fetch_assoc($q); if ($r['type_id'] == 2 && $r['object_id'] > 0) { $sql = "SELECT * FROM `clients_files` as c WHERE object_id = {$r['object_id']} AND (SELECT id from user_object_events WHERE id=c.event_id)>0"; if ($q = $pdo->query($sql)) { if ($pdo->num_rows($q) > 0) { while ($r = $pdo->fetch_assoc($q)) { if (!empty($r['name'])) { $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; if ($r['object_id'] > 0) $file .= "objects/" . $r['object_id'] . "/"; $file .= $r['guid'] . '.' . $r['type']; $r['type'] = 'id'; $r['link'] = $host . '/download_file.php?id=' . $r['id']; $unix_time = filemtime($file); $r['date'] = date('d.m.Y в H:i', $unix_time); if (!isset($list['names'][$r['name_id']])) $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'object', 'from_id' => $r['object_id'], 'id' => (int)$r['name_id']); if (file_exists($file)) $row[$r['name_id']][] = $r; } } } } else { $error = true; $errors[] = $q->pdo->errorInfo(); } } } else { $error = true; $errors[] = $q->pdo->errorInfo(); } } if ($section == 'objects') { //Поиск файлов по заявкам $sql_r = "SELECT id, type_id, object_id FROM requisitions WHERE object_id = {$source_id} AND type_id = 2 and deleted = 0"; if ($q_r = $pdo->query($sql_r)) { if ($pdo->num_rows($q_r) > 0) { $req = $pdo->fetch_assoc($q_r); $sql = "SELECT * FROM `clients_files` as c WHERE req_id = {$req['id']} AND (SELECT id from user_client_events WHERE id=c.event_id)>0"; if ($q = $pdo->query($sql)) { if ($pdo->num_rows($q) > 0) { while ($r = $pdo->fetch_assoc($q)) { if (!empty($r['name'])) { $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/"; if ($r['req_id'] > 0) $file .= "reqs/" . $req['id'] . "/"; $file .= $r['guid'] . '.' . $r['type']; $r['type'] = 'id'; $r['link'] = $host . '/download_file.php?id=' . $r['id']; $unix_time = filemtime($file); $r['date'] = date('d.m.Y в H:i', $unix_time); if (!isset($list['names'][$r['name_id']])) $list['names'][$r['name_id']] = array('type' => 'id', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['name_id']); if (file_exists($file)) $row[$r['name_id']][] = $r; } } } } else { $error = true; $errors[] = $q->pdo->errorInfo(); } $sql = "SELECT * FROM `funnel_files` WHERE req_id = {$req['id']}"; $q = $pdo->query($sql); if ($pdo->num_rows($q) > 0) { while ($r = $pdo->fetch_assoc($q)) { if (!empty($r['name'])) { $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/"; if ($r['req_id'] > 0) { $file .= "req/" . $r['req_id'] . "/"; } $file .= $r['guid'] . '.' . $r['type']; $r['type'] = 'guid'; $r['link'] = $host . '/download_file.php?guid=' . $r['guid']; $unix_time = filemtime($file); $r['date'] = date('d.m.Y в H:i', $unix_time); if (!isset($list['names'][$r['etap_id']])) { $list['names'][$r['etap_id']] = array('type' => 'guid', 'from' => 'req', 'from_id' => $req['id'], 'id' => (int)$r['etap_id']); } if (file_exists($file)) { $row[$r['etap_id']][] = $r; } } } } } } else { $error = true; $errors[] = $q_r->pdo->errorInfo(); } } $list['files'] = $row; foreach ($list['names'] as $key => $res) { if ($res['type'] == 'id') { if ($key == 0) { $list['names'][$key]['name'] = "Без названия"; } else { $sql_n = "SELECT * FROM names_client_files WHERE id={$key}"; if ($q_n = $pdo->query($sql_n)) { $r_n = $pdo->fetch_assoc($q_n); $list['names'][$key]['name'] = $r_n['name']; } else { $error = true; $errors[] = $q_n->pdo->errorInfo(); } } } else if ($res['type'] == 'guid') { $sql_n = "SELECT * FROM funnel_steps WHERE id={$key}"; if ($q_n = $pdo->query($sql_n)) { $r_n = $pdo->fetch_assoc($q_n); $list['names'][$key]['name'] = $r_n['name']; } else { $error = true; $errors[] = $q_n->pdo->errorInfo(); } } } } if (!empty($errors)) $error = true; if (!$error) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => $user_id, 'section' => $section, 'list' => $list ], 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 getEvents($app, $get = null, $post = null) { $error = false; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $pdo = $app->container->get('pdo'); $events = []; // Выборка событий о передачи объектов, объектов с клиентами $sth = $pdo->prepare("SELECT * FROM objects_to_send WHERE new_user_id = ".$user_id." AND `accept_state` = 'NEW'"); if ($sth->execute()) { if ($sth->rowCount() > 0) { while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$row['sended_user_id']."'"; $sth_in = $pdo->prepare($sql_in); if ($sth_in->execute()) { if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { $sender_name = trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); if ($r_in['agency'] == 1) { $sender_name = "Агентство " . $r_in['agency_name']; } else { if ($r_in['manager'] == 1) { $sender_name = "Менеджер " . trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); } } $clientsNum = 0; $clientsString = ''; $sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$row['object_id'].""%'"; $sth_clients = $pdo->prepare($sql_clients); if ($sth_clients->execute()) { if ($sth_clients->rowCount() > 0) { while($client = $sth_clients->fetch(\PDO::FETCH_ASSOC)) { $clientsNum++; $clientsString = $clientsString . ($clientsNum > 1 ? ", " : "") . $client['fio']; } } } else { $error = true; } $sql_obj = "SELECT nazv FROM `objects` WHERE id= $row[object_id]"; $sth_obj = $pdo->prepare($sql_obj); if ($sth_obj->execute()) { if ($row_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { $first_line = "передал Вам объект `" . $row_obj['nazv'] . "`"; $sec_line = "Взять "; $subject = "Передача объекта"; if ($clientsNum > 0) { if ($clientsNum > 1) { $subject = "Передача объекта\клиентов"; $first_line = $first_line . " и клиентов " . $clientsString . "."; $sec_line = $sec_line . " объект и клиентов в работу?"; } else { $subject = "Передача объекта\клиента"; $first_line = $first_line . " и клиента " . $clientsString . "."; $sec_line = $sec_line . " объект и клиента в работу?"; } } else { $first_line = $first_line . "."; $sec_line = $sec_line . " в работу?"; } $source_id = $row['id']; $events[] = [ 'id' => $source_id, 'type' => 'transfer-object', 'object_id' => $row['object_id'], 'sender_id' => $row['sended_user_id'], 'datetime' => $row['create_date'], 'subject' => $subject, 'sender_name' => $sender_name, 'message' => $sender_name . ' ' .$first_line . '
' . $sec_line ]; } } else { $error = true; } } } else { $error = true; } } } } else { $error = true; } // Выборка событий о передачи клиентов, заявок $sth = $pdo->prepare("SELECT * FROM events_clients WHERE from_id = ".$user_id." AND `read` = 0"); if ($sth->execute()) { if ($sth->rowCount() > 0) { while($r = $sth->fetch(\PDO::FETCH_ASSOC)) { $sql_in = "SELECT `agency_name`, `first_name`, `last_name`, `middle_name`, `agency`, `manager` FROM `users` WHERE `id` = '".$r['user_id']."'"; $sth_in = $pdo->prepare($sql_in); if ($sth_in->execute()) { if ($r_in = $sth_in->fetch(\PDO::FETCH_ASSOC)) { $sender_name = "Сотрудник "; if ($r_in['agency'] == 1) $sender_name = "Агентство "; else if ($r_in['manager'] == 1) $sender_name = "Менеджер "; $sql_cl = "SELECT `fio` FROM `clients` WHERE `id` = ".$r['client_id']; if ($r['req_id'] > 0) $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$r['req_id']; $sth_cl = $pdo->prepare($sql_cl); if ($sth_cl->execute()) { if ($r_cl = $sth_cl->fetch(\PDO::FETCH_ASSOC)) { $tr = 0; $objectString = ''; $objectNum = 0; $type_req = 0; if ($r['event'] == 'transmitted_parallel') { $tr = 1; } else { if ($r['req_id'] > 0 && $r_cl['object_id'] > 0) { $objectNum++; $sql_obj = "SELECT nazv FROM `objects` WHERE id= $r_cl[object_id]"; $sth_obj = $pdo->prepare($sql_obj); if ($sth_obj->execute()) { if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { $type_req = $r_cl['type_id']; $objectString = $objectString . ($objectNum > 1 ? ", " : "") . $r_obj['nazv']; } } else { $error = true; } } else { $sql_client = "SELECT objects FROM clients WHERE id=$r[client_id]"; $sth_client = $pdo->prepare($sql_client); if ($sth_client->execute()) { if ($r_client = $sth_client->fetch(\PDO::FETCH_ASSOC)) { $objects = json_decode(html_entity_decode($r_client['objects']), true); foreach ($objects as $object) { $objectNum++; $sql_obj = "SELECT nazv FROM `objects` WHERE id= $object"; $sth_obj = $pdo->prepare($sql_obj); if ($sth_obj->execute()) { if ($r_obj = $sth_obj->fetch(\PDO::FETCH_ASSOC)) { $objectString = $objectString . ($objectNum > 1 ? ", " : "") . "`".$r_obj['nazv']."`"; } } else { $error = true; } } } } else { $error = true; } } } if ($tr == 1) { $first_line = "приглашает Вас к совместной работе."; $subject = "Приглашение"; } else { $first_line = "передал Вам"; $subject = "Передача клиента"; } $sec_line = ""; if ($objectNum > 1) { if ($r['req_id'] > 0) { if ($tr != 1) $subject = 'Передача заявки/объектов'; if (!empty($objectString)) { if ($tr != 1) $first_line .= ' заявку и объекты.'; $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; } else { if ($tr != 1) $first_line .= ' заявку.'; $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; } } else { if ($tr != 1) $subject = 'Передача клиента/объектов'; if (!empty($objectString)) { if ($tr != 1) $first_line .= ' клиента и объекты.'; $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объекты ' . $objectString . ' в работу?'; } else { if ($tr != 1) $first_line .= ' клиента.'; $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; } } } else { if ($r['req_id'] > 0) { if ($tr != 1) $subject = 'Передача заявки/объекта'; if (!empty($objectString)) { if ($tr != 1) $first_line .= ' заявку и объект.'; $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; } else { if ($tr != 1) $first_line .= ' заявку.'; $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` в работу?'; } } else { if ($tr != 1) $subject = 'Передача клиента/объекта'; if (!empty($objectString)) { if ($tr != 1) $first_line .= ' клиента и объект.'; $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` и объект ' . $objectString . ' в работу?'; } else { if ($tr != 1) $first_line .= ' клиента.'; $sec_line .= ' Взять клиента `' . $r_cl['fio'] . '` в работу?'; } } } if ($r['req_id'] > 0 && $type_req == 4) { $subject = 'Передача заявки'; $first_line .= ' заявку.'; if (!empty($objectString)) $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту ' . $objectString . ' в работу?'; else $sec_line .= ' Взять заявку `' . $r_cl['fio'] . '` по объекту в работу?'; } $sender_name .= trim($r_in['last_name'] . ' ' . $r_in['first_name'] . ' ' . $r_in['middle_name']); if ($r_in['agency'] == 1) $sender_name .= $r_in['agency_name']; $source_id = $r['id']; $events[] = [ 'id' => $source_id, 'type' => 'transfer-client', 'datetime' => $r['date'], 'subject' => $subject, 'sender_id' => $r['user_id'], 'sender_name' => $sender_name, 'client_id' => $r['client_id'], 'requisition_id' => $r['req_id'], 'tr' => $tr, // @todo: tr ?? 'message' => $sender_name . ' ' . $first_line . '
' . $sec_line ]; } } else { $error = true; } } } else { $error = true; } } } } else { $error = true; } $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !($error), 'user_id' => (int)$user_id, 'count' => count($events), 'events' => $events, ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getObjectReasons($app, $get = null, $post = null) { $error = false; $reasons = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $pdo = $app->container->get('pdo'); // Выборка событий о передачи объектов, объектов с клиентами $sth = $pdo->prepare("SELECT * FROM archive_object_reason order by id"); if ($sth->execute()) { if ($sth->rowCount() > 0) { while($row = $sth->fetch(\PDO::FETCH_ASSOC)) { $reasons[] = $row; } } } else { $error = true; } $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !($error), 'user_id' => (int)$user_id, 'count' => count($reasons), 'list' => $reasons, ], 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 ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getNewBuilding($app, $get = null, $post = null) { $errors = []; if ($user_id = $_SESSION['id']) { $list = []; // Открываем соединение с БД $mdb = $app->container->get('mysql'); $id = null; if (isset($get['id'])) $id = trim($get['id']); if (!$id) { $errors[] = "Нет ИД"; } $sql = "SELECT * FROM `newbuildings` WHERE "; $sql .= " `id` = '" . trim($id) . "'"; $sql .= " ORDER BY `name`, `id`"; if ($query = mysql_query($sql)) { while ($block = mysql_fetch_assoc($query)) { $list[] = $block; } } else { $errors[] = mysql_error(); } if (!(count($errors))) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $list ], 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 getNewBuildings($app, $get = null, $post = null) { $errors = []; if ($user_id = $_SESSION['id']) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $list = []; $where = ''; $total = 0; $all_pages = 0; $search = null; if (isset($get['search'])) $search = trim($get['search']); $page = 1; if (isset($get['page'])) $page = (int)$get['page']; $per_page = 10; if (isset($get['per_page'])) $per_page = (int)$get['per_page']; $region_id = null; if (isset($get['region_id'])) $region_id = (int)$get['region_id']; if ($region_id == null) { $curUser = new \User(); $curUser->get($user_id); $region_id = $curUser->region_rf_id; } $where = '`rf_region_id` = ' . $region_id; if ($region_id == 1 || $region_id == 2 || $region_id == 3) $where = '(`rf_region_id` IN (SELECT `id` FROM `rf_regions` WHERE `parent` = ' . $region_id . '))'; $sql = "SELECT count(id) FROM `newbuildings` WHERE ". $where; if ($search != null) $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; $sql .= " ORDER BY `name`, `id`"; if ($query = mysql_query($sql)) { $total = mysql_result($query, 0); $all_pages = ceil($total / $per_page); $offset = ($page - 1) * $per_page; $sql = "SELECT * FROM `newbuildings` WHERE ". $where; if ($search != null) $sql .= " AND `name` LIKE '%" . trim($search) . "%'"; $sql .= " ORDER BY `name`, `id` LIMIT $offset, $per_page"; if ($query = mysql_query($sql)) { while ($block = mysql_fetch_assoc($query)) { $list[] = $block; } } else { $errors[] = mysql_error(); } } else { $errors[] = mysql_error(); } if (!(count($errors))) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, 'list' => $list, 'total' => $total, 'page' => $page, 'all_pages' => $all_pages, ], 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 setEventState($app, $get = null, $post = null) { $error = false; $errors = []; $body = $app->request->getBody(); $data = json_decode(stripcslashes($body), true); if (($user_id = $_SESSION['id']) && isset($data['type']) && isset($data['state']) && isset($data['event_id'])) { $type = $data['type']; $state = $data['state']; $event_id = $data['event_id']; // Открываем соединение с БД $mdb = $app->container->get('mysql'); $db_sphinx = $app->container->get('sphinx2'); if ($event_id && $type == 'transfer-object' && isset($data['object_id'])) { $object_id = (int)$data['object_id']; $sql = "SELECT * FROM objects_to_send WHERE id = $event_id AND object_id = $object_id"; if ($rez = mysql_query($sql)) { $row = mysql_fetch_assoc($rez); $source_id = $row['id']; if ($source_id && $state == 'accepted') { $new_user_id = (int)$row['new_user_id']; $object_id = (int)$row['object_id']; $new_user = new \User; $new_user->get($new_user_id); if (!$new_user->agencyId) $new_user->agencyId = $new_user_id; $current_user = new \User; $current_user->get($user_id); if (!$current_user->agencyId) $current_user->agencyId = $user_id; $phone = $new_user->phone; $num_search = \User::num_search($phone); /*if(!empty($new_user->phone2)){ $phone = $phone.' '.$new_user->phone2; }*/ $sobstv = trim($new_user->last_name . ' ' . $new_user->first_name . ' ' . $new_user->middle_name); if ($new_user->agency == 0) { $sql = "SELECT * FROM users WHERE id=$new_user->id_manager"; if ($rez = mysql_query($sql)) $manager = mysql_fetch_assoc($rez); else $errors[] = mysql_error(); if ($manager['id_manager']) $agency = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE id=$manager[id_manager]")); else $agency = $manager; if ($agency) $sobstv = trim($current_user->last_name . ' ' . $current_user->first_name . ' ' . $current_user->middle_name) . ", агентство " . $agency['agency_name']; } else { $sobstv = $sobstv . ", агентство " . $new_user->agency_name; } // перенос всех объектов $sql = "UPDATE objects SET id_add_user = $new_user->id, phone = '$phone', phone_search = '$num_search', sobstv = '$sobstv' WHERE id=$object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } //Запись в сфинкс $sql_sph = "UPDATE objects SET id_add_user = $new_user->id, phone_search = '$num_search' WHERE id=$object_id"; if (!$db_sphinx->query($sql_sph)) { $error = true; $errors[] = mysql_error(); } //перенос событий объектов $sql = "UPDATE user_object_events SET user_id = $new_user->id WHERE object_id = $object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } //перенос комментариев объектов $sql = "UPDATE user_object_comments SET user_id = $new_user->id WHERE object_id = $object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } // перенос Зипал $sql = "UPDATE zipal_objects SET user_id = $new_user->id, send_to_update = 1 WHERE object_id = $object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $sql = "UPDATE advertising_package_object_publish SET send_to_update = '1', error_when_send_to_update = '' WHERE object_id = $object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } /** * Передача заявок Реализация */ $sql_req = "SELECT id, `name`, object_id, type_id, who_work, funnel_id, confirm FROM `requisitions` WHERE object_id = {$object_id} AND cancel=0 AND deleted=0 AND (type_id = 2 or (SELECT heir FROM requisitions_type WHERE id = requisitions.type_id) = 2) AND who_work != '".$new_user->id."'"; //echo $sql_req."\n"; $q_req = mysql_query($sql_req); if(mysql_num_rows($q_req) > 0){ while($r_req = mysql_fetch_assoc($q_req)){ $sql_up = "UPDATE requisitions SET confirm=1, who_work={$new_user->id} WHERE id={$r_req['id']}"; //echo $sql_up."\n"; if(mysql_query($sql_up)){ $sql_ev = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, dop_text) VALUES ('".$user_id."', '{$r_req['id']}', '".$new_user->id."', 'update', '1', 'Переведена на ответственного при принятии объекта ID {$object_id}')"; //file_put_contents($_SERVER['DOCUMENT_ROOT']."/log_task_telega.txt", date('d.m.y H:i:s').' chat_id '.$chatId.' id:'.$event_id." ". $sql_ev."\n", FILE_APPEND); mysql_query($sql_ev); } } } //передаем клиентов /*$sql_clients = "SELECT `id`, `fio`, `email` FROM `clients` WHERE `objects` LIKE '%"".$object_id.""%'"; $q_client = mysql_query($sql_clients); if (mysql_num_rows($q_client) > 0) { while($client = mysql_fetch_assoc($q_client)) { $sql = "UPDATE clients SET confirm = 1, who_work = $new_user->id WHERE id = $client[id]"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $sql="UPDATE user_client_events SET user_id = $new_user->id WHERE client_id = $client[id]"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client[id] and from_id = ".$user_id; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client['id']."', '".$user_id."', 'accepted', '1')"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } }*/ $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='ACCEPTED' WHERE id = $source_id AND object_id=$object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } else if ($source_id && $state == 'rejected') { $sql = "UPDATE objects_to_send SET accept_date = NOW(), accept_state='REJECTED' WHERE id=$source_id AND object_id=$object_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } else { $errors[] = mysql_error(); } } else if ($type == 'transfer-client' && (isset($data['client_id']) || isset($data['req_id']))) { $tr = $data['tr']; // @todo: `tr` ??? $who_work = $user_id; $sender_id = (int)$data['sender_id']; $client_id = (int)$data['client_id']; $requisition_id = (int)$data['requisition_id']; if ($state == 'accepted') { if ($tr != 1) { $sql = "UPDATE clients SET confirm=1, who_work=$who_work WHERE id=$client_id"; if ($requisition_id > 0) $sql = "UPDATE requisitions SET confirm=1, who_work=$who_work WHERE id=$requisition_id"; if (mysql_query($sql)) { // Автопривязка ответственного по заявке к клиенту из заявки if ($requisition_id > 0) { $sql = "UPDATE `clients` JOIN `requisitions` AS `req` ON `clients`.`id` = `req`.`client_id` AND `clients`.`who_work` = 0 AND `clients`.`confirm` = 0 AND `req`.`id` = '$requisition_id' AND `clients`.`who_work` = 0 AND `clients`.`confirm` = 0 SET `clients`.`who_work` = '$who_work', `clients`.`confirm` = 1"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } else { $error = true; $errors[] = mysql_error(); } } else { $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; if ($requisition_id > 0) $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; if ($q_client = mysql_query($sql_client)) { $r_client = mysql_fetch_assoc($q_client); if (!empty($r_client['doers'])) { $confirm = 1; $doers = json_decode(html_entity_decode($r_client['doers']), true); $doers[$user_id] = 1; foreach($doers as $doer) { if ($doer == 0) $confirm = 0; } $sql = "UPDATE clients SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $client_id"; if ($requisition_id > 0) $sql = "UPDATE requisitions SET doers = '".self::clearInput(json_encode($doers))."', doers_confirm = $confirm WHERE id = $requisition_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE client_id = $client_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; if ($requisition_id > 0) $sql = "UPDATE doers_emp_client SET confirm = 1 WHERE req_id = $requisition_id AND who_work = $r_client[who_work] AND doer_id = $user_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } else { $error = true; $errors[] = mysql_error(); } } if ($tr != 1) { $sql = "UPDATE user_client_events SET user_id = $who_work WHERE client_id = $client_id AND type != 'step' AND type != 'file'"; if ($requisition_id > 0) $sql = "UPDATE user_client_events SET user_id = $who_work WHERE req_id = $requisition_id AND type != 'step' AND type != 'file'"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE client_id = $client_id AND from_id = $user_id"; if ($requisition_id > 0) $sql = "UPDATE `events_clients` SET `read` = 1, date_update = '".date('Y-m-d H:i:s')."' WHERE req_id = $requisition_id AND from_id = $user_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $accepted = 'accepted'; if ($tr == 1) $accepted = 'accepted_doer'; $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`) VALUES ('".$user_id."', '".$client_id."', '".$user_id."', '".$accepted."', '1')"; if ($requisition_id > 0) $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`) VALUES ('".$user_id."', '".$requisition_id."', '".$user_id."', '".$accepted."', '1')"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } $rUser = null; $sobstv = ''; $sqlUser = "SELECT `first_name`, `last_name`, `middle_name`, `phone` FROM `users` WHERE id=".$user_id; if ($qUser = mysql_query($sqlUser)) { $rUser = mysql_fetch_assoc($qUser); $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); if ($_SESSION['agency']) { $sobstv = $sobstv . ", агентство " . $rUser['agency_name']; } else { $agency = new \User; if (isset($agency->agencyName)) { $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']) . ", агентство " . $agency->agencyName; } else { $sobstv = trim($rUser['last_name'] . ' ' . $rUser['first_name'] . ' ' . $rUser['middle_name']); } } } else { $error = true; $errors[] = mysql_error(); } if ($rUser && $tr != 1) { //$num_search = num_search($rUser['phone']); //Передача объекта if ($requisition_id > 0) { $sql_cl = "SELECT `name` as `fio`, object_id, type_id FROM `requisitions` WHERE `id` = ".$requisition_id; $q_cl = mysql_query($sql_cl); $r_cl = mysql_fetch_assoc($q_cl); if ($r_cl['object_id'] && $r_cl['type_id'] != 4) { $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$r_cl['object_id']; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } else { $sql_client = "SELECT objects FROM clients WHERE id=$client_id"; $q_client = mysql_query($sql_client); $r_client = mysql_fetch_assoc($q_client); $objects = json_decode(html_entity_decode($r_client['objects']), true); foreach($objects as $object) { $sql = "UPDATE objects SET id_add_user = '".$user_id."', phone='".$rUser['phone']."', sobstv='".$sobstv."' WHERE id = ".$object; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } } } else if ($state == 'rejected') { if ($tr != 1) { $confirm = 0; if ($user_id == $who_work) $confirm = 1; $sql = "UPDATE clients SET confirm=$confirm, who_work=$who_work WHERE id=$client_id"; if ($requisition_id > 0) $sql = "UPDATE requisitions SET confirm=$confirm, who_work=$who_work WHERE id=$requisition_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } else { $sql_client = "SELECT doers, who_work FROM clients WHERE id=$client_id"; if ($requisition_id > 0) $sql_client = "SELECT doers, who_work FROM requisitions WHERE id=$requisition_id"; if ($q_client = mysql_query($sql_client)) { $r_client = mysql_fetch_assoc($q_client); $doer_clients = 0; if (!empty($r_client['doers'])) { $confirm = 1; $doers = json_decode(html_entity_decode($r_client['doers']), true); unset($doers[$user_id]); if (empty($doers)) { $confirm = 1; } else { foreach($doers as $id_user => $doer) { if ($doer == 0) $confirm = 0; if ($id_user != $r_client['who_work']) $doer_clients = 1; } } $sql = "UPDATE clients SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$client_id"; if ($requisition_id > 0) $sql = "UPDATE requisitions SET doers='".self::clearInput(json_encode($doers))."', doers_confirm=$confirm, doer_clients=$doer_clients WHERE id=$requisition_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } else { $error = true; $errors[] = mysql_error(); } } $from = $user_id; if ($event_id) { $sql_from = "SELECT user_id FROM `events_clients` WHERE `id` = $event_id"; if ($q_from = mysql_query($sql_from)) { $r_from = mysql_fetch_assoc($q_from); $from = $r_from['user_id']; $sql = "UPDATE `events_clients` set `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $event_id"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } else { $error = true; $errors[] = mysql_error(); } } else { $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `client_id` = $client_id AND `from_id` = $from"; if ($requisition_id > 0) $sql_from = "SELECT id, user_id FROM `events_clients` WHERE `read` = 0 AND `req_id` = $requisition_id AND `from_id` = $from"; if ($q_from = mysql_query($sql_from)) { $r_from = mysql_fetch_assoc($q_from); $from = $r_from['user_id']; $id_event = $r_from['id']; $sql = "UPDATE `events_clients` SET `read` = 1, `date_update`='".date('Y-m-d H:i:s')."' WHERE `id` = $id_event"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } else { $error = true; $errors[] = mysql_error(); } } $read = 0; if ($from == $user_id || $tr == 1) $read = 1; $event = 'notadopted'; if ($tr == 1) { $read = 1; $event = 'notadopted_doer'; } $sql = "INSERT INTO `events_clients` (user_id, client_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$client_id."', '".$from."', '".$event."', '".$read."', '1')"; if ($requisition_id > 0) $sql = "INSERT INTO `events_clients` (user_id, req_id, from_id, event, `read`, send_telegramm) VALUES ('".$user_id."', '".$requisition_id."', '".$from."', '".$event."', '".$read."', '1')"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } 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 ], 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 setViewed($app, $get = null, $post = null) { $error = false; $errors = []; $body = $app->request->getBody(); $data = json_decode(stripcslashes($body), true); $object_id = null; if (isset($data['object_id'])) $object_id = (int)$data['object_id']; $client_id = null; if (isset($data['client_id'])) $client_id = (int)$data['client_id']; $requisition_id = null; if (isset($data['requisition_id'])) $requisition_id = (int)$data['requisition_id']; if (($user_id = $_SESSION['id']) && ($object_id || $client_id || $requisition_id)) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); if ($object_id && in_array($object_id, $_SESSION['new_transfers']['objects'])) { $key = array_search($object_id, $_SESSION['new_transfers']['objects']); if ($key !== false) { unset($_SESSION['new_transfers']['objects'][$key]); } } if ($client_id && in_array($client_id, $_SESSION['new_transfers']['clients'])) { $key = array_search($client_id, $_SESSION['new_transfers']['clients']); if ($key !== false) { unset($_SESSION['new_transfers']['clients'][$key]); } } if ($requisition_id && in_array($requisition_id, $_SESSION['new_transfers']['requisitions'])) { $key = array_search($requisition_id, $_SESSION['new_transfers']['requisitions']); if ($key !== false) { unset($_SESSION['new_transfers']['requisitions'][$key]); } } // Обновление инфо о том, что клиент/заявка были просмотрены пользователем if ($client_id > 0) { $sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `viewed` = 0 AND `read` = 1 AND `user_id` = '$user_id' AND `client_id` = '$client_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } if ($requisition_id > 0) { $sql = "UPDATE `events_clients` SET `viewed` = 1 WHERE `viewed` = 0 AND `read` = 1 AND `user_id` = '$user_id' AND `req_id` = '$requisition_id' AND `from_id` = '$user_id' AND (`event` = 'accepted' OR `event` = 'accepted_doer')"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } if (!$errors) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$errors, 'user_id' => (int)$user_id, ], 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' => $_SESSION['id'], 'errors' => $errors ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function setFunnels($app, $get = null, $post = null) { $body = $app->request->getBody(); $data = json_decode(stripcslashes($body), true); $errors = []; $section = null; if (isset($data['section'])) $section = trim($data['section']); $clients_ids = null; if (isset($data['sources_ids']) && $section == 'clients') $clients_ids = $data['sources_ids']; $req_ids = null; if (isset($data['sources_ids']) && $section == 'requisitions') $req_ids = $data['sources_ids']; $funnel_id = null; if (isset($data['funnel_id'])) $funnel_id = (int)$data['funnel_id']; if (($user_id = $_SESSION['id']) && $section && !empty($funnel_id) && ($req_ids || $clients_ids)) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); if ($clients_ids && $section == 'clients') { if (!is_array($clients_ids)) $clients_ids = [$clients_ids]; $client_inst = new \Clients(); foreach ($clients_ids as $client_id) { $result = $client_inst->updateFunnel([ 'id' => $client_id, 'new_funnel_id' => $funnel_id, ]); if ($result !== true) $errors[] = $result; } } else if ($req_ids && $section == 'requisitions') { if (!is_array($req_ids)) $req_ids = [$req_ids]; // Открываем соединение с БД $pdo = $app->container->get('mypdo'); $req_inst = new \Requisitions($pdo); foreach ($req_ids as $req_id) { $result = $req_inst->updateFunnel($funnel_id, $req_id); if ($result !== true) $errors[] = $result; } } if (!count($errors)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => true, 'user_id' => (int)$user_id, ], 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' => $_SESSION['id'], 'errors' => $errors, ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function setTags($app, $get = null, $post = null, $need_return = false) { if (!empty($post)) { $data = $post; } else { $body = $app->request->getBody(); $data = json_decode(stripcslashes($body), true); } if (($user_id = $_SESSION['id']) && isset($data['section']) && isset($data['source_id']) && isset($data['tags_list'])) { // Открываем соединение с БД $pdo = $app->container->get('pdo'); $section = (string)$data['section']; $source_id = (int)$data['source_id']; $tags_list = (array)$data['tags_list']; $set = []; $tags = []; foreach ($tags_list as $tag) { if (boolval($tag['isChecked'])) { $tag_id = (isset($tag['value'])) ? (int)$tag['value'] : (int)$tag['id']; $tags[] = $tag_id; $set[] = "('$source_id', '$tag_id')"; } } list($sql, $sql2) = ['' , '']; switch ($section) { case 'objects' : $sql = "DELETE FROM `objects_activities` WHERE `object_id` = '".$source_id."'"; if (count($set) > 0) $sql2 = "INSERT INTO `objects_activities` (`object_id`, `activity_id`) VALUES " . implode(', ', $set); break; case 'clients' : $sql = "DELETE FROM `clients_activities` WHERE `client_id` = '".$source_id."'"; if (count($set) > 0) $sql2 = "INSERT INTO `clients_activities` (`client_id`, `activity_id`) VALUES " . implode(', ', $set); break; case 'requisitions' : $sql = "DELETE FROM `requisitions_activities` WHERE `req_id` = '".$source_id."'"; if (count($set) > 0) $sql2 = "INSERT INTO `requisitions_activities` (`req_id`, `activity_id`) VALUES " . implode(', ', $set); break; } $error = false; if (!empty($sql)) { if (!$pdo->query($sql)) $error = true; } if (!empty($sql2)) { if (!$pdo->query($sql2)) $error = true; } if ($need_return) { if (!empty($error)) return false; else return $tags; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'tags_ids' => $tags, 'tags_list' => $tags_list ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } if ($need_return) { return false; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => $_SESSION['id'] ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } public function getPresentationLink($app, $get = null, $post = null) { $error = false; $errors = []; $body = $app->request->getBody(); $data = json_decode($body, true); if (($user_id = $_SESSION['id']) && (isset($data['object_id']) || isset($data['newbuilding_id']))) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $object_id = null; if (isset($data['object_id'])) $object_id = (int)$data['object_id']; $newbuilding_id = null; if (isset($data['newbuilding_id'])) $newbuilding_id = (int)$data['newbuilding_id']; $client_id = null; if (isset($data['client_id'])) $client_id = (int)$data['client_id']; $hide_contacts = []; if (isset($data['hide_contacts'])) $hide_contacts = array_unique(array_map('intval', $data['hide_contacts'])); $send_type = null; if (isset($data['with'])) $send_type = (int)$data['with']; $new_prices = []; $descriptions = []; if (isset($data['descriptions'])) { $array = (array)$data['descriptions']; foreach ($array as $object_id => $value) { $object_id = str_replace('object_', '', $object_id); if (isset($value['description'])) $descriptions[intval($object_id)] = $value['description']; if (isset($value['price'])) $new_prices[intval($object_id)] = $value['price']; }; } $link = null; if (!is_null($object_id) || !is_null($newbuilding_id)) { /*error_reporting(E_ERROR | E_WARNING | E_PARSE); ini_set('display_errors', 1);*/ if (!is_null($object_id)) { $sql = "SELECT * FROM objects WHERE id=$object_id"; if ($rez = mysql_query($sql)) { $obj = mysql_fetch_assoc($rez); if ($send_type == 2) { $pdfs = $this->_getPDF([$object_id], $descriptions, $new_prices, $hide_contacts); if (isset($pdfs[$object_id]['link'])) $linkUrl = $pdfs[$object_id]['link']; } else { if (self::is_ssl()) $linkUrl = "https://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id); else $linkUrl = "http://joywork.ru/object-view.php?id=$object_id&token=" . md5($user_id); } $new_price = 0; if (isset($new_prices[$object_id])) $new_price = $new_prices[$object_id]; if (!is_null($client_id)) $linkUrl .= "&client=" . md5($client_id); else $client_id = "0"; $close_contact = 0; if (in_array($object_id, $hide_contacts)) $close_contact = 1; $sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}"; if (!mysql_query($sql_up)) { $error = true; $errors[] = mysql_error(); } $token = md5(microtime()); $sql = "INSERT INTO sended_pdf(id_agent, id_object, date_send, id_client, nazv, path, send_type, close_contact, token, new_price) VALUES('$user_id', '$object_id', NOW(), '$client_id', '$obj[nazv] $obj[adres]', '$linkUrl', $send_type, $close_contact, '$token', '$new_price')"; if (mysql_query($sql)) { $id_pr = mysql_insert_id(); $token2 = md5($id_pr); if ($send_type != 2) { if (self::is_ssl()) $linkUrl = "https://joywork.ru/object-view.php?token=".$token2; else $linkUrl = "http://joywork.ru/object-view.php?token=".$token2; } $sql_up_pr = "UPDATE sended_pdf SET token = '{$token2}', path='{$linkUrl}' WHERE id={$id_pr}"; if (mysql_query($sql_up_pr)) { $link = $linkUrl; } else { $error = true; $errors[] = mysql_error(); } } else { $error = true; $errors[] = mysql_error(); } } } if (!is_null($newbuilding_id)) { $sql = "SELECT a.id, a.number, b.name, b.address FROM apartments a, blocks b WHERE b.id = a.block_id AND a.id='$newbuilding_id'"; if ($rez = mysql_query($sql)) { $obj = mysql_fetch_assoc($rez); if (self::is_ssl()) $linkUrl = "https://joywork.ru/newbuilding-view.php?id=$newbuilding_id&token=" . md5($user_id); else $linkUrl = "http://joywork.ru/newbuilding-view.php?id=$newbuilding_id&token=" . md5($user_id); if (!is_null($client_id)) $linkUrl .= "&client=" . md5($client_id); else $client_id = "NULL"; $close_contact = 0; if (in_array($newbuilding_id, $hide_contacts)) $close_contact = 1; $sql_up = "INSERT INTO user_object_contact_close SET close={$close_contact}, user_id={$user_id}, object_id = {$object_id}, client_id = {$client_id}"; if (!mysql_query($sql_up)) { $error = true; $errors[] = mysql_error(); } $nazv = "Квартира №$obj[number] в комплексе $obj[name]"; $sql = "INSERT INTO sended_pdf_newbuildings(id_agent, id_object, date_send, id_client, nazv, path, send_type) VALUES('$user_id', '$newbuilding_id', NOW(), '$client_id', '$nazv $obj[address]', '$linkUrl', $send_type)"; if (mysql_query($sql)) { $id_pr = mysql_insert_id(); $token2 = md5($id_pr); if (self::is_ssl()) $linkUrl = "https://joywork.ru/object-view.php?token=".$token2; else $linkUrl = "http://joywork.ru/object-view.php?token=".$token2; $link = $linkUrl; } else { $error = true; $errors[] = mysql_error(); } } } } if (!count($errors)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'link' => $link ], 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' => $_SESSION['id'], 'errors' => $errors ], JSON_UNESCAPED_UNICODE)); $app->stop(); } public function getCatalogLink($app, $get = null, $post = null, $need_return = false) { $error = false; $errors = []; $body = $app->request->getBody(); $data = json_decode($body, true); if (($user_id = $_SESSION['id']) && (isset($data['objects_ids']) || isset($data['newbuildings_ids']))) { // Открываем соединение с БД $mdb = $app->container->get('mysql'); $objects_ids = []; if (isset($data['objects_ids'])) $objects_ids = array_unique(array_map('intval', (array)$data['objects_ids'])); $newbuildings_ids = []; if (isset($data['newbuildings_ids'])) $newbuildings_ids = array_unique(array_map('intval', (array)$data['newbuildings_ids'])); $clients_ids = []; if (isset($data['clients_ids'])) $clients_ids = array_unique(array_map('intval', (array)$data['clients_ids'])); if (empty($clients_ids)) $clients_ids = [0]; $catalog_id = null; if (isset($data['catalog_id'])) $catalog_id = (int)$data['catalog_id']; $hide_contacts = []; if (isset($data['hide_contacts'])) $hide_contacts = array_unique(array_map('intval', (array)$data['hide_contacts'])); $hide_address = []; if (isset($data['hide_address'])) $hide_address = array_unique(array_map('intval', (array)$data['hide_address'])); $send_type = 0; if (isset($data['with'])) $send_type = (int)$data['with']; $new_prices = []; $descriptions = []; if (isset($data['descriptions'])) { $array = (array)$data['descriptions']; foreach ($array as $object_id => $value) { $object_id = str_replace('object_', '', $object_id); if (isset($value['description'])) $descriptions[intval($object_id)] = $value['description']; if (isset($value['price'])) $new_prices[intval($object_id)] = $value['price']; }; } $link = null; if (!empty($objects_ids) || !empty($newbuildings_ids)) { /*error_reporting(E_ERROR | E_WARNING | E_PARSE); ini_set('display_errors', 1);*/ $is_close_contacts = !empty($hide_contacts) ? 1 : 0; if (is_null($catalog_id)) { $sql = "INSERT INTO sent_catalog(agent_id, close_contact, date_send) VALUES ('$user_id', '$is_close_contacts', NOW())"; if (mysql_query($sql)) { $catalog_id = mysql_insert_id(); } else { $error = true; $errors[] = mysql_error(); } } else { $sql1 = "UPDATE sent_catalog SET agent_id = '$user_id', close_contact = '$is_close_contacts', date_send = NOW() WHERE id = '$catalog_id'"; $sql2 = "DELETE FROM sended_pdf WHERE sent_catalog_id = '$catalog_id'"; if (!mysql_query($sql1) || !mysql_query($sql2)) { $error = true; $errors[] = mysql_error(); } } if (!empty($objects_ids)) { $sql = "SELECT `id`, `nazv`, `adres`, `phone`, `sobstv` FROM `objects` WHERE `id` IN (".implode(',', $objects_ids).")"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query) > 0) { while ($object = mysql_fetch_assoc($query)) { $object_id = (int)$object['id']; foreach ($clients_ids as $client_id) { $new_price = isset($new_prices[$object_id]) ? $new_prices[$object_id] : 0; $is_hide_contacts = in_array($object_id, $hide_contacts) ? 1 : 0; $is_hide_address = in_array($object_id, $hide_address) ? 1 : 0; if ($is_hide_contacts) { $sql = "INSERT INTO `user_object_contact_close` SET `close`='{$is_hide_contacts}', `user_id`='{$user_id}', `object_id` = '{$object_id}', `client_id` = '{$client_id}'"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } $sql = "INSERT INTO `sended_pdf`(`id_agent`, `id_object`, `date_send`, `id_client`, `nazv`, `path`, `send_type`, `close_contact`, `hide_address`, `new_price`, `token`, `sent_catalog_id`) VALUES('$user_id', '$object_id', NOW(), '$client_id', '$object[nazv] $object[adres]', '', $send_type, $is_hide_contacts, $is_hide_address, '$new_price', '', '$catalog_id')"; if (mysql_query($sql)) { $id_pr = mysql_insert_id(); $token = md5($id_pr); $path = "https://joywork.ru/object-view.php?token=".$token; $sql = "UPDATE `sended_pdf` SET `token` = '{$token}', `path` = '{$path}' WHERE `id` = '{$id_pr}'"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } else { $error = true; $errors[] = mysql_error(); } } $sql = "INSERT INTO `archive` (`nazv`, `adres`, `phone`, `sobstv`, `id_obj`) VALUES('$object[nazv]', '$object[adres]', '$object[phone]', '$object[sobstv]', '$object_id') ON DUPLICATE KEY UPDATE `nazv` = '$object[nazv]', `adres` = '$object[adres]', `phone` = '$object[phone]', `sobstv` = '$object[sobstv]'"; if (!mysql_query($sql)) { $error = true; $errors[] = mysql_error(); } } } } else { $error = true; $errors[] = mysql_error(); } } /*if (!empty($newbuildings_ids)) { }*/ if (!is_null($catalog_id)) $link = "https://joywork.ru/catalog-view.php?catalog=" . $catalog_id; } if ($need_return) { return $link; } else { if (!count($errors)) { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => !$error, 'user_id' => (int)$user_id, 'link' => $link, 'catalog_id' => $catalog_id ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } } if ($need_return) { return false; } else { $app->response->header('Content-Type', 'application/json'); $app->response->setStatus(200); $app->response->setBody(json_encode([ 'success' => false, 'user_id' => $_SESSION['id'], 'errors' => $errors ], JSON_UNESCAPED_UNICODE)); $app->stop(); } } private function _getPDF($objects_ids = [], $descriptions = [], $new_prices = [], $hide_contacts = false) { global $app; require_once ROOT_PATH . '/../../ajax/engine/pdf_functions.php'; require_once ROOT_PATH . '/../../ajax/engine/props.php'; global $SROK_ARENDY; $error = false; $errors = []; $pdf_ready = []; // Открываем соединение с БД $mdb = $app->container->get('mysql'); $result = \SelectelApi::getTokenAndUrl(); $token = $result[0]; $storageUrl = $result[1]; if (($user_id = $_SESSION['id']) && count($objects_ids) > 0) { /*error_reporting(E_ERROR | E_WARNING | E_PARSE); ini_set('display_errors', 1);*/ $sql = "SELECT objects.id, objects.operation_type, objects.nazv, objects.etazh, objects.etazh_iz, objects.stoim, objects.peshkom, objects.transport, objects.adres, objects.dom, objects.korpus, objects.litera, objects.id_rf_region, rayon.rayon, objects.ploshad, objects.ploshad_komn, objects.ploshad_k, objects.srok, objects.opis, objects.type, objects.type_category FROM objects LEFT JOIN rayon rayon on objects.rayon = rayon.id WHERE objects.id IN (".implode(',', $objects_ids).")"; if ($query = mysql_query($sql)) { while($obj = mysql_fetch_assoc($query)) { $id = $obj['id']; $object_id = $obj['id']; $arrTop = []; $arrTop['type'] = $obj['type']; $close_contacts = in_array($id, $hide_contacts); if ($obj['type'] == 4) { $sqlCommerce = "SELECT * FROM commercial_object"; $resultCommerce = mysql_query($sqlCommerce); $arrTypeCommerc = []; while ($rCommerc = mysql_fetch_assoc($resultCommerce)) { $arrTypeCommerc[$rCommerc['id']] = $rCommerc['name']; } if (isset($arrTypeCommerc[$obj['type_category']])) { $arrTop['commerce_type'] = $arrTypeCommerc[$obj['type_category']]; } } $arrTop['operation_type'] = $obj['operation_type']; $arrTop['nazv'] = \Filter::name($obj['nazv']); if ($obj['etazh']*1 != 0) { $arrTop['etazh'] = $obj['etazh']; } if ($obj['etazh_iz']*1 != 0) $arrTop['etazh_iz'] = $obj['etazh_iz']; if (!$obj['etazh']) $arrTop['etazh'] = \Filter::getFloorFromName($arrTop['nazv'],true); else \Filter::getFloorFromName($arrTop['nazv'],true); if (!$obj['etazh_iz']) $arrTop['etazh_iz'] = \Filter::getMaxFloorFromName($arrTop['nazv'],true); else \Filter::getMaxFloorFromName($arrTop['nazv'],true); \Filter::getSpaceFromName($arrTop['nazv'],true); $new_price = 0; $arrTop['stoim'] = number_format($obj['stoim'], 0, ',', ' '); if (isset($new_prices[$object_id])) { $new_price = $new_prices[$object_id]; $arrTop['stoim'] = number_format($new_price, 0, ',', ' '); } $mtr = []; $sql = "SELECT metro.metro FROM metro, sp_metro WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = $obj[id]"; if ($result = mysql_query($sql)) { while($m = mysql_fetch_row($result)) $mtr[] = $m[0]; $metro_str = implode(", ",$mtr); $do_metro = ''; if ($obj['peshkom']) $do_metro = $obj['peshkom']." минут пешком"; if ($obj['peshkom'] and $obj['transport']) $do_metro .= " или "; if ($obj['transport']) $do_metro .= $obj['transport']." минут на транспорте"; $arrTop['metrostr'] = $metro_str; $arrTop['way'] = $do_metro; } else { $error = true; $errors[] = mysql_error(); } $sqlLocationInfo = "SELECT * FROM object_location WHERE object_id=".$obj['id']; if ($rezLocationInfo = mysql_query($sqlLocationInfo)) { if (mysql_num_rows($rezLocationInfo) > 0) { $objLocationInfo = mysql_fetch_assoc($rezLocationInfo); $adr = $objLocationInfo['address']; } else { $address = $obj['adres']; $adr = ''; if ($obj['id_rf_region'] == 81) { if (strpos($address, "Санкт-Петербург") === false) { $adr .= "Санкт-Петербург, "; } if ($obj['rayon']) { $arrTop['rayon'] = str_replace([' район', 'район', ' р-н', 'р-н'], '', $obj['rayon']).' район'; } else { $arrTop['rayon'] = ''; } } $adr .= $address; } } else{ $error = true; $errors[] = mysql_error(); } $arrTop['address'] = $adr; if ($obj['ploshad']*1 != 0) { $obj['ploshad'] *= 1; $arrTop['ploshad'] = $obj['ploshad']; } else { $arrTop['ploshad'] = ''; } if ($obj['ploshad_komn']*1 != 0) { if (stripos($obj['ploshad_komn'],"+") == false) $obj['ploshad_komn'] *= 1; $arrTop['ploshad_komn'] = $obj['ploshad_komn']; } else { $arrTop['ploshad_komn'] = ''; } if ($obj['ploshad_k']*1 != 0) { $obj['ploshad_k'] *= 1; $arrTop['ploshad_k'] = $obj['ploshad_k']; } else { $arrTop['ploshad_k'] = ''; } if ($obj['operation_type']==0) { $arrTop['sdelka'] = 'Сдается '.$SROK_ARENDY["$obj[srok]"]; } else { $arrTop['sdelka'] = 'Продажа'; } $useLocalPhoto = true; if ($useLocalPhoto) { $photos = []; $sqlPhotoInfo = "SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = $id ORDER BY oop.sort_order"; if ($rezPhotoInfo = mysql_query($sqlPhotoInfo)) { if (mysql_num_rows($rezPhotoInfo) > 0) { while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) { $p = $photoInfo['photo']; if (stripos($photoInfo['photo'], "http://") === false && stripos($photoInfo['photo'], "https://") === false) { $p = "https://joywork.ru/photos/" . $photoInfo['photo']; } array_push($photos, $p); } } } else { $error = true; $errors[] = mysql_error(); } } $arrTop['replace_plan'] = false; $sql = "SELECT * FROM objects_plan WHERE object_id = $id"; if ($rez_plan = mysql_query($sql)) { if (mysql_num_rows($rez_plan) > 0) { $obj_plan = mysql_fetch_assoc($rez_plan); if ($obj_plan['img_plan'] != '') { if (stripos($obj_plan['img_plan'], "http://") === false && stripos($obj_plan['img_plan'], "https://") === false) { if (self::is_ssl()) $obj_plan['img_plan'] = "https://joywork.ru/photos/" . $obj_plan['img_plan']; else $obj_plan['img_plan'] = "http://joywork.ru/photos/" . $obj_plan['img_plan']; } $arrTop['plan'] = $obj_plan['img_plan']; } else { // если все же там пусто if (is_array($photos) && count($photos) > 0) { $arrTop['replace_plan'] = true; $arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото } } } else { if (is_array($photos) && count($photos) > 0) { $arrTop['replace_plan'] = true; $arrTop['plan'] = array_shift($photos); // вместо плана берем первую фотографию из всех фото } } } else { $error = true; $errors[] = mysql_error(); } $sqlComment = "SELECT * FROM user_object_comments WHERE user_id = '$_SESSION[id]' AND object_id='$id'"; if ($rezComment = mysql_query($sqlComment)) { if (mysql_num_rows($rezComment) > 0) { $commentRow = mysql_fetch_assoc($rezComment); $obj['opis'] = $commentRow['comment']; } } else { $error = true; $errors[] = mysql_error(); } $opis = ''; if (isset($descriptions[intval($obj['id'])])) $opis = cleanHtml($descriptions[intval($obj['id'])], '