[ "label" => "Тип операции", "type" => "select", "multiple" => false, "column" => "operation_type", "reverse_search" => true, "main_field" => true ], "object_type" => [ "label" => "Тип объекта", "type" => "select", "multiple" => false, "column" => "type", "reverse_search" => true, "main_field" => true ], "object_source" => [ "label" => "Источник", "type" => "select", "multiple" => false, "column" => null, "reverse_search" => true, "main_field" => true ], "category_type" => [ "label" => "Категория", "type" => "select", "multiple" => true, "column" => "type_category", "reverse_search" => true, "main_field" => true ], "stoim" => [ "label" => "Цена", "type" => "number", "column" => "stoim", "reverse_search" => true, "main_field" => true ], "stoim_ot" => [ "label" => "Цена, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "stoim_do" => [ "label" => "Цена, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], /*"komn" => [ "label" => "Комнат", "type" => "number", "column" => "komnat", "reverse_search" => true, "main_field" => true ], "komn_ot" => [ "label" => "Комнат, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "komn_do" => [ "label" => "Комнат, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ],*/ "rooms" => [ "label" => "Комнат", "type" => "select", "multiple" => true, "reverse_search" => true, "main_field" => true ], "sq_all" => [ "label" => "Общая площадь", "type" => "number", "column" => "ploshad", "reverse_search" => true, "main_field" => true ], "sq_all_ot" => [ "label" => "Общая площадь, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "sq_all_do" => [ "label" => "Общая площадь, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "ploshad_k" => [ "label" => "Площадь кухни", "type" => "number", "column" => "ploshad_k", "reverse_search" => true, "main_field" => true ], "ploshad_k_ot" => [ "label" => "Площадь кухни, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "ploshad_k_do" => [ "label" => "Площадь кухни, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "rent_srok" => [ "label" => "Срок аренды объекта", "type" => "select", "multiple" => false, "column" => "srok", "reverse_search" => true, "main_field" => true ], "metro_stations" => [ "label" => "Ближ. станции метро", "type" => "select", "multiple" => true, "column" => "id_metro", "reverse_search" => true, "main_field" => true ], "do_metro" => [ // должен быть выше ["regions" => ...] "label" => "Время до метро", "type" => "number", "column" => ["peshkom", "transport"], "reverse_search" => true, "main_field" => true ], "do_metro_type" => [ "label" => "До метро", "type" => "select", "multiple" => false, "column" => "do_metro_type", "reverse_search" => true, "main_field" => true ], "regions" => [ "label" => "Регион(ы) объекта", "type" => "select", "multiple" => true, "column" => "id_rf_region", "reverse_search" => true, "main_field" => true ], "rayons" => [ "label" => "Район(ы) объекта", "type" => "select", "multiple" => true, "column" => "rayon", "reverse_search" => true, "main_field" => true ], "etazhnost" => [ "label" => "Не первый/последний этаж", "type" => "checkbox", "column" => null, "reverse_search" => true, "main_field" => true ], "newbilding_date" => [ "label" => "Срок сдачи новостроя", "type" => "date", "column" => null ], "ipoteka" => [ "label" => "Ипотека", "type" => "checkbox", "column" => null ], "use_area_price" => [ "label" => "Цена за квадратный метр", "type" => "checkbox", "column" => null ], "voen_ipoteka" => [ "label" => "Воен. ипотека", "type" => "checkbox", "column" => null ], "subsidya" => [ "label" => "Субсидия", "type" => "checkbox", "column" => null ], "mather_kapital" => [ "label" => "Материнский капитал", "type" => "checkbox", "column" => null ], "house_type" => [ "label" => "Тип дома", "type" => "select", "multiple" => false, "column" => "house_type" ], "house_material" => [ "label" => "Материал дома", "type" => "select", "multiple" => false, "column" => "house_material" ], "build_year" => [ "label" => "Год постройки", "type" => "select", "multiple" => false, "column" => "build_year" ], "tax_number" => [ "label" => "Номер налоговой", "type" => "text", "multiple" => false, "column" => "tax_number" ], "legal_address" => [ "label" => "Юридический адрес", "type" => "select", "multiple" => false, "column" => "legal_address" ], "etazh_all" => [ "label" => "Всего этажей", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "etazh" => [ "label" => "Этаж", "type" => "number", "column" => "etazh", "reverse_search" => true, "main_field" => true ], "etazh_ot" => [ "label" => "Этаж, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "etazh_do" => [ "label" => "Этаж, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "etazhnost_ot" => [ "label" => "Этажность, от", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "etazhnost_do" => [ "label" => "Этажность, до", "type" => "number", "column" => null, "reverse_search" => true, "main_field" => true ], "is_occupied" => [ "label" => "Помещение занято", "type" => "select", "multiple" => false, "column" => "isOccupied" ], "layout_id" => [ "label" => "Планировка", "type" => "select", "multiple" => false, "column" => "layout_id" ], "wet_spots" => [ "label" => "Мокрых точек", "type" => "select", "multiple" => false, "column" => "number_wet_spots" ], "el_power" => [ "label" => "Эл. мощность", "type" => "number", "column" => "electricity_power" ], "el_power_ot" => [ "label" => "Эл. мощность, от", "type" => "number", "column" => null ], "el_power_do" => [ "label" => "Эл. мощность, до", "type" => "number", "column" => null ], "commer_condition" => [ "label" => "Состояние", "type" => "select", "multiple" => false, "column" => "commer_condition" ], "is_furniture" => [ "label" => "Мебель", "type" => "select", "multiple" => false, "column" => "isFurniture" ], "commer_access" => [ "label" => "Доступ", "type" => "select", "multiple" => false, "column" => "commer_access" ], "parking_types" => [ "label" => "Тип парковки", "type" => "select", "multiple" => true, "column" => null ], "parking_id" => [ "label" => "Парковка", "type" => "select", "multiple" => true, "column" => "parking_type_id" ], "parking_price" => [ "label" => "Стоимость парковки", "type" => "number", "column" => "parking_price" ], "parking_price_free" => [ "label" => "Бесплатная парковка", "type" => "checkbox", "multiple" => false, "column" => "parkingIsFree" ], "ceiling_height" => [ "label" => "Высота потолков", "type" => "number", "column" => "ceiling_height" ], "ceiling_height_ot" => [ "label" => "Высота потолков, от", "type" => "number", "column" => null ], "ceiling_height_do" => [ "label" => "Высота потолков, до", "type" => "number", "column" => null ], "column_grid" => [ "label" => "Сетка колон", "type" => "text", "column" => "column_grid" ], "vat_type_id" => [ "label" => "Налог", "type" => "select", "multiple" => false, "column" => "vat_type_id" ], "commerc_site" => [ "label" => "Участок", "type" => "number", "column" => "commerc_site" ], "commerc_owned1" => [ "label" => "Участок в собственности", "type" => "checkbox", "column" => "commerc_owned" ], "commerc_owned2" => [ "label" => "Участок в аренде", "type" => "checkbox", "column" => "commerc_owned2" ], "floor_material_id" => [ "label" => "Материал пола", "type" => "select", "multiple" => false, "column" => "floor_material_id" ], "commerc_portal_id" => [ "label" => "Ворота", "type" => "select", "multiple" => false, "column" => "commerc_portal_id" ], "commerc_purpose" => [ "label" => "Назначение", "type" => "select", "multiple" => true, "column" => "commerc_purpose" ], "commerc_land_category_id" => [ "label" => "Категория земли", "type" => "select", "multiple" => true, "column" => "commerc_land_category_id" ], "commerc_permitted_use_id" => [ "label" => "Вид разрешенного использования", "type" => "select", "multiple" => true, "column" => "commerc_permitted_use_id" ], "commerc_electricity_id" => [ "label" => "Электричество", "type" => "select", "multiple" => false, "column" => "commerc_electricity_id" ], "can_electricity" => [ "label" => "Можно подключить электричество", "type" => "checkbox", "column" => "can_electricity" ], "commerc_gas_id" => [ "label" => "Газ", "type" => "select", "multiple" => false, "column" => "commerc_gas_id" ], "can_gas" => [ "label" => "Можно подключить газ", "type" => "checkbox", "column" => "can_gas" ], "commerc_water_id" => [ "label" => "Вода", "type" => "select", "multiple" => false, "column" => "commerc_water_id" ], "can_water" => [ "label" => "Можно подключить воду", "type" => "checkbox", "column" => "can_water" ], "commerc_sewage_id" => [ "label" => "Канализация", "type" => "select", "multiple" => false, "column" => "commerc_sewage_id" ], "can_sewage" => [ "label" => "Можно подключить канализацию", "type" => "checkbox", "column" => "can_sewage" ], "commerc_driveways" => [ "label" => "Подъездные пути", "type" => "select", "multiple" => false, "column" => "commerc_driveways_id" ], "commerc_year" => [ "label" => "Год постройки", "type" => "number", "column" => "commerc_year" ], "commerc_year_ot" => [ "label" => "Год постройки, от", "type" => "number", "column" => null ], "commerc_year_do" => [ "label" => "Год постройки, до", "type" => "number", "column" => null ], "commerc_building_type_id" => [ "label" => "Тип здания", "type" => "select", "multiple" => true, "column" => "commerc_building_type_id" ], "commerc_building_class_id" => [ "label" => "Класс здания", "type" => "select", "multiple" => true, "column" => "commerc_building_class_id" ], "building_area" => [ "label" => "Площадь здания", "type" => "number", "column" => "building_area" ], "building_area_ot" => [ "label" => "Площадь здания, от", "type" => "number", "column" => null ], "building_area_do" => [ "label" => "Площадь здания, до", "type" => "number", "column" => null ], "commerc_houseline_type_id" => [ "label" => "Линия домов", "type" => "select", "multiple" => true, "column" => "commerc_houseLineType_id" ], "commerc_building_category_id" => [ "label" => "Категория", "type" => "select", "multiple" => false, "column" => "commerc_building_category_id" ], "commerc_opened_id" => [ "label" => "Вход", "type" => "select", "multiple" => true, "column" => "commerc_opened_id" ], "commerc_building_ventilation" => [ "label" => "Вентиляция", "type" => "select", "multiple" => false, "column" => "commerc_building_ventilation" ], "commerc_building_conditioning" => [ "label" => "Кондиционирование", "type" => "select", "multiple" => false, "column" => "commerc_building_conditioning" ], "commerc_building_heating" => [ "label" => "Отопление", "type" => "select", "multiple" => false, "column" => "commerc_building_heating" ], "commerc_building_fire" => [ "label" => "Система пожаротуш-я", "type" => "select", "multiple" => false, "column" => "commerc_building_fire" ], "garage_type_id" => [ "label" => "Тип", "type" => "select", "multiple" => false, "column" => "garage_type_id" ], "garage_vid_id" => [ "label" => "Тип гаража", "type" => "select", "multiple" => false, "column" => "garage_vid_id" ], "boks_vid_id" => [ "label" => "Тип бокса", "type" => "select", "multiple" => false, "column" => "boks_vid_id" ], "commerc_status_id" => [ "label" => "Статус", "type" => "select", "multiple" => false, "column" => "commerc_status_id" ], "commerc_specifications" => [ "label" => "Технические хар-ки", "type" => "select", "multiple" => true, "column" => "commerc_specifications" ], "commerc_infrastructure" => [ "label" => "Инфраструктура", "type" => "select", "multiple" => true, "column" => "commerc_infrastructure" ], "commerc_infrastructure1" => [ "label" => "Инфраструктура", "type" => "select", "multiple" => true, "column" => "commerc_infrastructure1" ], "commerc_infrastructure2" => [ "label" => "Инфраструктура", "type" => "select", "multiple" => true, "column" => "commerc_infrastructure2" ], "commerc_lift1" => [ "label" => "Грузовой лифт", "type" => "number", "column" => "commerc_lift1" ], "lift1_carrying" => [ "label" => "Грузовой лифт, грузоподъемность", "type" => "number", "column" => "lift1_carrying" ], "commerc_lift2" => [ "label" => "Тельфер", "type" => "number", "column" => "commerc_lift2" ], "lift2_carrying" => [ "label" => "Тельфер, грузоподъемность", "type" => "number", "column" => "lift2_carrying" ], "commerc_lift3" => [ "label" => "Пассажирский лифт", "type" => "number", "column" => "commerc_lift3" ], "lift3_carrying" => [ "label" => "Пассажирский лифт, грузоподъемность", "type" => "number", "column" => "lift3_carrying" ], "commerc_crane1" => [ "label" => "Мостовой кран", "type" => "number", "column" => "commerc_crane1" ], "crane1_carrying" => [ "label" => "Мостовой кран, грузоподъемность", "type" => "number", "column" => "crane1_carrying" ], "commerc_crane2" => [ "label" => "Кран-балка", "type" => "number", "column" => "commerc_crane2" ], "crane2_carrying" => [ "label" => "Кран-балка, грузоподъемность", "type" => "number", "column" => "crane2_carrying" ], "commerc_crane3" => [ "label" => "Ж/д кран", "type" => "number", "column" => "commerc_crane3" ], "crane3_carrying" => [ "label" => "Ж/д кран, грузоподъемность", "type" => "number", "column" => "crane3_carrying" ], "commerc_crane4" => [ "label" => "Козловой кран", "type" => "number", "column" => "commerc_crane4" ], "crane4_carrying" => [ "label" => "Козловой кран, грузоподъемность", "type" => "number", "column" => "crane4_carrying" ], "opis" => [ "label" => "Слова в описании", "type" => "textarea", "column" => "opis" ], "comment" => [ "label" => "Комментарий", "type" => "textarea", "column" => null ] ]; private $viewed_limit = 5000; private $ignored_limit = 1000; private $favoured_limit = 1000; private $sended_limit = 1000; public function __construct($db = null) { if (isset($_SESSION['id'])) { if (!isset($user) || is_null($user)) { $user_id = intval($_SESSION['id']); $user = new User; $user->get($user_id); $this->_user = $user; } else { $this->_user = $user; } } else { $this->_user = null; } if (!is_null($db)) { $this->db = $db; } else { //$this->db = new MysqlPdo(hstsph, null, null, null, true, '9306'); $pdo = new MysqlPdo(hstsph, ndb, user, pass, true, '9306'); $pdo->query("SET NAMES 'utf8'"); $this->db = $pdo; } } private function getViewedObjects($filter_id = null) { if (!$filter_id) return false; $sql = "SELECT `object_id` FROM `autosearch_viewed` WHERE `filter_id` = '$filter_id' LIMIT $this->viewed_limit"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query)) { $objects_id = []; while ($row = mysql_fetch_assoc($query)) { $objects_id[] = (int)$row['object_id']; } return array_unique($objects_id); } else { return []; } } return false; } private function getIgnoredObjects($filter_id = null) { if (!$filter_id) return false; $sql = "SELECT `object_id` FROM `autosearch_ignored` WHERE `filter_id` = '$filter_id' LIMIT $this->ignored_limit"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query)) { $objects_id = []; while ($row = mysql_fetch_assoc($query)) { $objects_id[] = (int)$row['object_id']; } return array_unique($objects_id); } else { return []; } } return false; } private function getFavouredObjects($filter_id = null) { if (!$filter_id) return false; $sql = "SELECT af.`object_id` FROM `autosearch_favoured` af JOIN `objects` o on o.`id` = af.`object_id` WHERE af.`filter_id` = '$filter_id' LIMIT $this->favoured_limit"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query)) { $objects_id = []; while ($row = mysql_fetch_assoc($query)) { $objects_id[] = (int)$row['object_id']; } return array_unique($objects_id); } else { return []; } } return false; } private function getSendedObjects($filter_id = null) { if (!$filter_id) return false; $sql = "SELECT `object_id` FROM `autosearch_sended` WHERE `filter_id` = '$filter_id' LIMIT $this->sended_limit"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query)) { $objects_id = []; while ($row = mysql_fetch_assoc($query)) { $objects_id[] = (int)$row['object_id']; } return array_unique($objects_id); } else { return []; } } return false; } public function getFilter($id = null, $user_id = null, $only_active = true, $formatDate = false) { if (!is_null($id)) { $sql = "SELECT `filters`.*, `filters`.`telegram_notify` AS `telegram_notify`, `req`.`name` AS `req`, `req`.`type_id` AS `req_type_id`, `req`.`asfilter_id` AS `asfilter_id`, `req`.`who_work` AS `who_work`, `client`.`fio` AS `client_fio`, `client`.`id` AS `client_id`, `client`.`phone` AS `client_phone`, `client`.`email` AS `client_email`, DATE_FORMAT(`filters`.`newbilding_date`, '%d.%m.%Y') as `newbilding_date`, DATE_FORMAT(`filters`.`build_year`, '%Y') as `build_year`, COALESCE(MAX(`results`.`processed_at`) , '0000-00-00 00:00:00') AS `processed_at`, SUM(`results`.`count`) AS `count`, `results`.`total` AS `total`, GROUP_CONCAT(`results`.`error` SEPARATOR '|') AS `errors` FROM `autosearch_filters` AS `filters` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id` LEFT JOIN `clients` AS `client` ON `client`.`id` = `req`.`client_id` LEFT JOIN `autosearch_results` AS `results` ON `results`.`filter_id` = `filters`.`id` WHERE `filters`.`id` = '$id' "; $agents_ids = []; if ($user_id) { $agents_ids[] = $user_id; $user = new \User; $agency_id = $user->getAgencyIdForUser($user_id); if (!empty($agency_id)) { $agents_ids[] = $agency_id; $sql_users = "SELECT id FROM users WHERE id = '$user_id' or 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)))"; $query = mysql_query($sql_users); while ($row = mysql_fetch_assoc($query)) { $agents_ids[] = (int)$row['id']; } $agents_ids = array_unique($agents_ids); } } /*if (count($agents_ids) > 0) $sql .= " AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; else if (isset($_SESSION['id'])) $sql .= " AND (`filters`.`created_by` = '$_SESSION[id]' OR `filters`.`updated_by` = '$_SESSION[id]')";*/ if ($only_active) $sql .= " AND `filters`.`is_active` = '1'"; $sql .= " ORDER BY `processed_at` LIMIT 1"; if ($query = mysql_query($sql)) { if (mysql_num_fields($query)) $this->_filter = mysql_fetch_assoc($query); if ($formatDate) { if (in_array($this->_filter['newbilding_date'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['newbilding_date'] = null; else $this->_filter['newbilding_date'] = self::formatRusDatetime($this->_filter['newbilding_date'], true, true, true, false); if (in_array($this->_filter['build_year'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00', '01.01.1970', '1970'])) $this->_filter['build_year'] = null; else $this->_filter['build_year'] = self::formatRusDatetime($this->_filter['build_year'], true, false, false, false); } else { if (in_array($this->_filter['newbilding_date'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['newbilding_date'] = null; else $this->_filter['newbilding_date'] = date('Y-m-d', strtotime($this->_filter['newbilding_date'])); if (in_array($this->_filter['build_year'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00', '01.01.1970', '1970'])) $this->_filter['build_year'] = null; /*else $this->_filter['build_year'] = date('Y', strtotime($this->_filter['build_year']));*/ } if ($this->_filter['newbilding_date'] == "01.01.1970" || $this->_filter['newbilding_date'] == "1970-01-01") $this->_filter['newbilding_date'] = null; if ($this->_filter['build_year'] == "01.01.1970" || $this->_filter['build_year'] == "1970-01-01" || $this->_filter['build_year'] == "1970") $this->_filter['build_year'] = null; if (!empty($this->_filter['rooms'])) $this->_filter['rooms'] = $this->_filter['rooms']; else $this->_filter['rooms'] = '[]'; if (!empty($this->_filter['geo'])) $this->_filter['geo'] = str_replace(',,', ',', str_replace(' ', ',', $this->_filter['geo'])); $this->_filter['error'] = ''; if (!empty($this->_filter['errors'])) { $errors = explode('|', $this->_filter['errors']); $this->_filter['error'] = array_pop($errors); } if (intval($this->_filter['count'])){ $meta = self::getMetaResults($this->_filter['id']); $viewed_ids = array_unique(array_map('intval', $meta['viewed'])); $ignored_ids = array_unique(array_map('intval', $meta['ignored'])); $ids = array_diff(array_unique(array_map('intval', $meta['results']['match'])), $ignored_ids); $this->_filter['count'] = !empty($ids) ? count(array_diff($ids, $viewed_ids)) : 0; } return $this->_filter; } else { return mysql_error(); } } return null; } public function getFilterByReq($req_id = null, $user_id = null, $only_active = true, $formatDate = false, $is_list_req = false) { if (!is_null($req_id) && $req_id > 0) { $sql = "SELECT `filters`.*, `filters`.`telegram_notify` AS `telegram_notify`, `req`.`name` AS `req`, `req`.`type_id` AS `req_type_id`, `req`.`asfilter_id` AS `asfilter_id`, `req`.`who_work` AS `who_work`, `client`.`fio` AS `client_fio`, `client`.`id` AS `client_id`, `client`.`phone` AS `client_phone`, `client`.`email` AS `client_email`, DATE_FORMAT(`filters`.`newbilding_date`, '%d.%m.%Y') as `newbilding_date`, DATE_FORMAT(`filters`.`build_year`, '%Y') as `build_year`, COALESCE(MAX(`results`.`processed_at`) , '0000-00-00 00:00:00') AS `processed_at`, SUM(`results`.`count`) AS `count`, `results`.`total` AS `total`, GROUP_CONCAT(`results`.`error` SEPARATOR '|') AS `errors` FROM `autosearch_filters` AS `filters` LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id` LEFT JOIN `clients` AS `client` ON `client`.`id` = `req`.`client_id` LEFT JOIN `autosearch_results` AS `results` ON `results`.`filter_id` = `filters`.`id` WHERE `filters`.`req_id` = '$req_id' "; $agents_ids = []; if ($user_id) { $agents_ids[] = $user_id; $user = new \User; $agency_id = $user->getAgencyIdForUser($user_id); if (!empty($agency_id)) { $agents_ids[] = $agency_id; // $sql_users = "SELECT id FROM users WHERE id = '$user_id' or 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 company_id = $agency_id"; $query = mysql_query($sql_users); while ($row = mysql_fetch_assoc($query)) { $agents_ids[] = (int)$row['id']; } $agents_ids = array_unique($agents_ids); } } /*if (count($agents_ids) > 0) $sql .= " AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; else if (isset($_SESSION['id'])) $sql .= " AND (`filters`.`created_by` = '$_SESSION[id]' OR `filters`.`updated_by` = '$_SESSION[id]')";*/ if ($only_active) $sql .= " AND `filters`.`is_active` = '1'"; $sql .= " ORDER BY `processed_at` LIMIT 1"; if ($query = mysql_query($sql)) { if (mysql_num_fields($query)) $this->_filter = mysql_fetch_assoc($query); if ($formatDate) { if (in_array($this->_filter['newbilding_date'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['newbilding_date'] = null; else $this->_filter['newbilding_date'] = self::formatRusDatetime($this->_filter['newbilding_date'], true, true, true, false); if (in_array($this->_filter['build_year'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['build_year'] = null; else $this->_filter['build_year'] = self::formatRusDatetime($this->_filter['build_year'], true, false, false, false); } else { if (in_array($this->_filter['newbilding_date'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['newbilding_date'] = null; else $this->_filter['newbilding_date'] = date('Y-m-d', strtotime($this->_filter['newbilding_date'])); if (in_array($this->_filter['build_year'], ['0000-00-00 00:00:00', '1970-01-01 00:00:00', '00.00.0000 00:00:00', '01.01.1970 00:00:00'])) $this->_filter['build_year'] = null; /*else $this->_filter['build_year'] = date('Y', strtotime($this->_filter['build_year']));*/ } if ($this->_filter['newbilding_date'] == "01.01.1970" || $this->_filter['newbilding_date'] == "1970-01-01") $this->_filter['newbilding_date'] = null; if ($this->_filter['build_year'] == "01.01.1970" || $this->_filter['build_year'] == "1970-01-01") $this->_filter['build_year'] = null; if (!empty($this->_filter['rooms'])) $this->_filter['rooms'] = $this->_filter['rooms']; else $this->_filter['rooms'] = '[]'; if (!empty($this->_filter['geo'])) $this->_filter['geo'] = str_replace(',,', ',', str_replace(' ', ',', $this->_filter['geo'])); $this->_filter['error'] = ''; if (!empty($this->_filter['errors'])) { $errors = explode('|', $this->_filter['errors']); $this->_filter['error'] = array_pop($errors); } // $viewed_count = 0; // if ($viewed = $this->getViewedObjects($this->_filter['id'])) { // $viewed_count = count($viewed); // } if (intval($this->_filter['count'])){ if( !$is_list_req) $meta = self::getMetaResults($this->_filter['id']); $viewed_ids = array_unique(array_map('intval', $meta['viewed'])); $ignored_ids = array_unique(array_map('intval', $meta['ignored'])); $ids = array_diff(array_unique(array_map('intval', $meta['results']['match'])), $ignored_ids); $this->_filter['count'] = !empty($ids) ? count(array_diff($ids, $viewed_ids)) : 0; // $this->_filter['count'] = abs(intval($this->_filter['count']) - $viewed_count); } return $this->_filter; } else { return mysql_error(); } } return null; } public function getFiltersByReqs($req_ids, $agents_ids, $only_active = true) { $req_ids = implode(',', array_map('intval', $req_ids)); $agents_ids = implode(',', array_map('intval', $agents_ids)); $sql = " SELECT `filters`.* FROM `autosearch_filters` AS `filters` WHERE `filters`.`req_id` IN ($req_ids) AND (`filters`.`created_by` IN ($agents_ids) OR `filters`.`updated_by` IN ($agents_ids)) "; if ($only_active) { $sql .= " AND `filters`.`is_active` = '1'"; } $result = mysql_query($sql); $filters = []; while ($row = mysql_fetch_assoc($result)) { $filters[$row['req_id']] = $row; } if (empty($filters)) return []; $filter_ids = implode(',', array_column($filters, 'id')); $sql_stats = " SELECT filter_id, COALESCE(MAX(processed_at), '0000-00-00 00:00:00') AS processed_at, SUM(`count`) AS `count`, `total`, GROUP_CONCAT(`error` SEPARATOR '|') AS errors FROM `autosearch_results` WHERE filter_id IN ($filter_ids) GROUP BY filter_id "; $stats = []; $result = mysql_query($sql_stats); while ($row = mysql_fetch_assoc($result)) { $stats[$row['filter_id']] = $row; } foreach ($filters as &$filter) { $stat = isset($stats[$filter['id']]) ? $stats[$filter['id']] : [ 'processed_at' => '0000-00-00 00:00:00', 'count' => 0, 'total' => 0, 'errors' => '' ]; $filter += $stat; } return $filters; } public function getFilterByClient($client_id = null, $user_id = null, $only_active = true) { $agency_id = User::getUserAgencyID(); $sql_req = "SELECT id FROM `requisitions` WHERE `client_id` = '".intval($client_id)."' AND (`type_id` = '1' or `type_id` in (SELECT id FROM requisitions_type WHERE agency_id = {$agency_id} and heir=1)) AND `deleted` <> 1 LIMIT 1"; $req_id = (int)mysql_fetch_assoc(mysql_query($sql_req))['id']; return self::getFilterByReq($req_id, $user_id, $only_active); } public function buildFilterInput($filter = null, $field_id = null, $with_label = false) { if (is_null($filter) || is_null($field_id)) return null; $html = ''; $wrap = true; $input_id = strtolower(str_replace('_', '-', $field_id)); $input_name = strtolower($field_id); $field_id = trim($field_id); switch ($field_id) { case 'deal_type' : $html = ''; $list = AutoSearch::getCommonFields('deal_type', $filter['deal_type']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'object_type' : $html = ''; $list = AutoSearch::getCommonFields('object_type', $filter['object_type']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'object_source' : $html = ''; $list = AutoSearch::getCommonFields('object_source', $filter['object_source']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'stoim' : case 'stoim_ot' : case 'stoim_do' : $html = ''; $html .= ' из '; $html .= ''; $html .= ' руб.'; break; case 'komn' : case 'komn_ot' : case 'komn_do' : $html = ''; $html .= ' ~ '; $html .= ''; break; case 'sq_all' : case 'sq_all_ot' : case 'sq_all_do' : $html = ''; $html .= ' ~ '; $html .= ''; $html .= ' м. кв'; break; case 'ploshad_k' : case 'ploshad_k_ot' : case 'ploshad_k_do' : $html = ''; $html .= ' ~ '; $html .= ''; $html .= ' м. кв'; break; case 'rent_srok' : $html = ''; $list = AutoSearch::getCommonFields('rent_srok', $filter['rent_srok']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'regions' : $html = ''; $list = AutoSearch::getCommonFields('regions', $filter['regions']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'rayons' : $html = ''; $list = AutoSearch::getCommonFields('rayons', $filter['rayons']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'metro_stations' : $html = ''; $list = AutoSearch::getCommonFields('metro_stations', $filter['metro_stations']); foreach ($list as $key => $item) { $html .= ''; } $html = ''; $wrap = false; break; case 'do_metro' : $html = ''; $html .= 'минут, если: '; $html .= ''; break; case 'etazh_all' : case 'etazhnost_ot' : case 'etazhnost_do' : $html = ''; $html .= ' ~ '; $html .= ''; break; case 'etazhnost' : $html = '
Не указан ИД заявки
"; } if ($field == 'deal_type' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан тип сделки
"; } if ($field == 'object_type' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан тип объекта
"; } if ($field == 'object_source' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан источник поиска
"; } if ($field == 'regions' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан регион(ы)
"; } if ($fields['deal_type'] == 1 && $field == 'rent_srok' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан срок аренды
"; } if ($fields['object_type'] == 4 && $field == 'category_type' && self::isEmpty($value)) { $isError = true; $errorText .= "Не указан тип помещения
"; } if ($field == 'rooms' && !is_array($value)) $value = array((string)$value); if ($field == 'rooms' && is_array($value)) $value = array_map('strval', $value); if ($field == 'geo' && !is_array($value)) $value = json_encode($value); if (is_array($value)) { $value = json_encode($value); } else { if ($field == 'newbilding_date') $value = date('Y-m-d H:i:s', strtotime($value)); if ($field == 'build_year') $value = date('Y-m-d H:i:s', strtotime($value.'-01-01')); } if (!empty($query)) $query .= ", `$field` = '" . $value . "'"; else $query .= "`$field` = '" . $value . "'"; } if (!empty($query) && !$isError) { $sql = "UPDATE `autosearch_filters` SET $query, `updated_by` = $user_id WHERE id=$id AND ( created_by=$user_id OR updated_by=$user_id OR EXISTS ( SELECT 1 FROM requisitions WHERE requisitions.id = autosearch_filters.req_id AND requisitions.who_work = $user_id ) )"; if (mysql_query($sql) && $this->clearAllResults($id)) return ['success' => true, 'error' => false]; else return ['success' => false, 'error' => mysql_error()]; } else { return ['success' => false, 'error' => $errorText]; } } return false; } public static function getFields($reverse = false) { if ($reverse) { $output = []; $fields = self::$_fields; foreach ($fields as $field => $options) { if (is_array($options['column'])) { foreach ($options['column'] as $column) { $output[$column] = array_merge($options, ['column' => $field]); } } else { $key = $options['column']; $output[$key] = array_merge($options, ['column' => $field]); } } return $output; } else { return self::$_fields; } } public static function formatRusDatetime($datetime, $year = true, $month = true, $day = true, $time = true) { list($date, $time) = explode(" ", $datetime); list($d, $m, $y) = explode(".", $date); $date_tmp = ""; if ($year) $date_tmp = $y."г"; if ($month) $date_tmp = getRusMonth($m)." ".$date_tmp; if ($d) $date_tmp = $d." ".$date_tmp; if ($time) $date_tmp = $date_tmp. " в ".$time; return $date_tmp; } public static function getCommonFields($key, $selected = false, $cond = null) { $commons = []; switch ($key) { case 'deal_type' : $DEAL_TYPES = [ 1 => "Аренда", 2 => "Покупка", 3 => "Новостройки", ]; foreach($DEAL_TYPES as $key => $value) { $commons[$key] = [ 'value' => $key, 'label' => $value, 'selected' => ($key == $selected) ? true : false, ]; } break; case 'rooms' : case 'rooms_counts' : $ROOMS_COUNT = [ 1 => "1 комн.", 2 => "2 комн.", 3 => "3 комн.", 4 => "4+ комн.", 5 => "Студия", ]; foreach($ROOMS_COUNT as $key => $value) { $commons[$key] = [ 'value' => $key, 'label' => $value, 'selected' => in_array($key, $selected) ? true : false, ]; } break; case 'object_type' : global $OBJECT_TYPES; foreach($OBJECT_TYPES as $key => $value) { $commons[$key] = [ 'value' => $key, 'label' => $value, 'selected' => ($key == $selected) ? true : false, ]; } break; case 'object_source' : global $SEARCH_TARGETS; foreach($SEARCH_TARGETS as $key => $value) { if ($key == 4) // Архив собственников continue; $commons[$key] = [ 'value' => $key, 'label' => $value, 'selected' => ($key == $selected) ? true : false, ]; } $commons[5] = [ 'value' => 5, 'label' => 'Объекты компании' ]; $commons[6] = [ 'value' => 6, 'label' => 'Собственники и объекты компании' ]; break; case 'category_type' : $selected = array_map(function($category) { return intval($category); }, (array)$selected); // $categories = array(); $sql = "SELECT * FROM commercial_object"; if (!is_null($cond)) $sql .= " " . $cond; $sql .= " ORDER BY name"; $rez = mysql_query($sql); while ($category = mysql_fetch_assoc($rez)) { $categories[$category['id']] = $category; } if (!empty($categories)) { foreach($categories as $key => $category) { $commons[$category['id']] = [ 'value' => $category['id'], 'label' => $category['name'], 'selected' => (in_array($key, $selected)) ? true : false, ]; } } break; case 'rent_srok' : global $SROK_ARENDY_ASSOC; foreach($SROK_ARENDY_ASSOC as $key => $value) { $commons[$key] = [ 'value' => $key, 'label' => $value, 'selected' => ($key == intval($selected)) ? true : false, ]; } break; case 'regions' : $regions = array(); $sql_getRegion = "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 ORDER BY code ASC"; $rezRegion = mysql_query($sql_getRegion); while ($row = mysql_fetch_assoc($rezRegion)) { $regions[] = $row; } if (empty($regions)) { $sql_getRegion = "SELECT rf_regions.* FROM rf_regions LEFT JOIN users ON users.region_rf_id = rf_regions.id ORDER BY code ASC"; $rezRegion = mysql_query($sql_getRegion); while ($row = mysql_fetch_assoc($rezRegion)){ $regions[] = $row; } } if (empty($regions)) { $regions[0] = array( 'id' => 50, 'name' => 'Ленинградская обл', 'kladr' => '4700000000000', 'parent' => 2, 'code' => 47 ); $regions[1] =array( 'id' => 81, 'name' => 'Санкт-Петербург', 'kladr' => '7800000000000', 'parent' => 2, 'code' => 78 ); } if (!empty($regions)) { foreach($regions as $key => $region) { $commons[$region['id']] = [ 'value' => $region['id'], 'label' => $region['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'rayons' : $rayons = array(); $sql = "SELECT * FROM rayon"; if (!is_null($cond)) $sql .= " " . $cond; $sql .= " ORDER BY rayon"; $rez = mysql_query($sql); while ($rayon = mysql_fetch_assoc($rez)) { $rayons[$rayon['id']] = $rayon; } if (!empty($rayons)) { foreach($rayons as $key => $rayon) { $commons[$rayon['id']] = [ 'value' => $rayon['id'], 'label' => $rayon['rayon'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'metro_stations' : $metro = array(); $sql = "SELECT * FROM metro"; if (!is_null($cond)) $sql .= " " . $cond; $sql .= " ORDER BY metro"; $rez = mysql_query($sql); if (mysql_num_rows($rez) > 0) { while ($station = mysql_fetch_assoc($rez)) { $metro[$station['id']] = $station; } } if (!empty($metro)) { foreach($metro as $key => $rayon) { $commons[$rayon['id']] = [ 'value' => $rayon['id'], 'label' => $rayon['metro'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; /*case 'order_type' : $orders = array(); $sql = "SELECT * FROM deal_type"; if (!is_null($cond)) $sql .= " " . $cond; $sql .= " ORDER BY name"; $rez = mysql_query($sql); if (mysql_num_rows($rez) > 0) { while ($deal = mysql_fetch_assoc($rez)) { $orders[$deal['id']] = $deal; } } if (!empty($orders)) { foreach($orders as $key => $order) { $commons[$order['id']] = [ 'value' => $order['id'], 'label' => $order['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break;*/ case 'do_metro_type' : $commons[1] = [ 'value' => 1, 'label' => 'пешком', 'selected' => ($key == intval($selected)) ? true : false, ]; $commons[2] = [ 'value' => 2, 'label' => 'на транспорте', 'selected' => ($key == intval($selected)) ? true : false, ]; break; case 'build_year' : $range = range(date('Y', strtotime('-75 year')), date('Y')); foreach ($range as $key) { $commons[] = [ 'value' => $key, 'label' => $key, 'selected' => ($key == intval($selected)) ? true : false, ]; } break; case 'house_type' : $types = array(); $sql = "SELECT * FROM house_type"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY name"; $rez = mysql_query($sql); while ($houseType = mysql_fetch_assoc($rez)) { $types[$houseType['id']] = $houseType; } if (!empty($types)) { foreach($types as $key => $type) { $commons[$key] = [ 'value' => $type['id'], 'label' => $type['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'house_material' : $materials = array(); $sql = "SELECT * FROM house_material"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY name"; $rez = mysql_query($sql); while ($houseMaterial = mysql_fetch_assoc($rez)) { $materials[$houseMaterial['id']] = $houseMaterial; } if (!empty($materials)) { foreach($materials as $key => $material) { $commons[$key] = [ 'value' => $material['id'], 'label' => $material['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'legal_address' : $commons = [ 1 => [ 'value' => 1, 'label' => "Предоставляется", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Не предоставляется", 'selected' => (2 == intval($selected)) ? true : false, ], ]; break; case 'is_occupied' : $commons = [ 1 => [ 'value' => 1, 'label' => "Не занято", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Занято", 'selected' => (2 == intval($selected)) ? true : false, ], ]; break; case 'layout_id' : $list = array(); $sql = "SELECT * FROM layout_object"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY name"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'wet_spots' : $commons = [ 1 => [ 'value' => 1, 'label' => "1", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "2", 'selected' => (2 == intval($selected)) ? true : false, ], 3 => [ 'value' => 3, 'label' => "3", 'selected' => (3 == intval($selected)) ? true : false, ], 4 => [ 'value' => 4, 'label' => "4", 'selected' => (4 == intval($selected)) ? true : false, ], 5 => [ 'value' => 5, 'label' => "Нет", 'selected' => (5 == intval($selected)) ? true : false, ], ]; break; case 'commer_condition' : $list = array(); $sql = "SELECT * FROM `commer_condition`"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'is_furniture' : $commons = [ 1 => [ 'value' => 1, 'label' => "Нет", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Есть", 'selected' => (2 == intval($selected)) ? true : false, ] ]; break; case 'commer_access' : $commons = [ 1 => [ 'value' => 1, 'label' => "Свободный", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Пропускная система", 'selected' => (2 == intval($selected)) ? true : false, ] ]; break; case 'parking_id' : case 'parking_types' : $list = array(); $sql = "SELECT * FROM parking_type"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'vat_type_id' : $list = array(); $sql = "SELECT * FROM vat_type"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'floor_material_id' : $list = array(); $sql = "SELECT * FROM floor_material"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_portal_id' : $list = array(); $sql = "SELECT * FROM commerc_portal"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_purpose' : $list = array(); $sql = "SELECT * FROM commerc_purpose"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY name"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_land_category_id' : $list = array(); $sql = "SELECT * FROM commerc_land_category"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_permitted_use_id' : $list = array(); $sql = "SELECT * FROM commerc_permitted_use"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_electricity_id' : $list = array(); $sql = "SELECT * FROM commerc_electricity"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_gas_id' : $list = array(); $sql = "SELECT * FROM commerc_gas"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_water_id' : $list = array(); $sql = "SELECT * FROM commerc_gas"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_sewage_id' : $list = array(); $sql = "SELECT * FROM commerc_gas"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_driveways' : $list = array(); $sql = "SELECT * FROM commerc_driveways"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_building_type_id' : $list = array(); $sql = "SELECT * FROM commerc_building_type"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_building_class_id' : $list = array(); $sql = "SELECT * FROM commerc_building_class"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_houseline_type_id' : $list = array(); $sql = "SELECT * FROM commerc_houselinetype"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_building_category_id' : $list = array(); $sql = "SELECT * FROM commerc_building_category"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_opened_id' : $list = array(); $sql = "SELECT * FROM commerc_opened"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_building_ventilation' : $commons = [ 1 => [ 'value' => 1, 'label' => "Естественная", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Приточная", 'selected' => (2 == intval($selected)) ? true : false, ], ]; break; case 'commerc_building_conditioning' : $commons = [ 1 => [ 'value' => 1, 'label' => "Местное", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Центральное", 'selected' => (2 == intval($selected)) ? true : false, ], ]; break; case 'commerc_building_heating' : $commons = [ 1 => [ 'value' => 1, 'label' => "Автономное", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Центральное", 'selected' => (2 == intval($selected)) ? true : false, ], ]; break; case 'commerc_building_fire' : $commons = [ 1 => [ 'value' => 1, 'label' => "Гидрантная", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Спринклерная", 'selected' => (2 == intval($selected)) ? true : false, ], 3 => [ 'value' => 3, 'label' => "Порошковая", 'selected' => (2 == intval($selected)) ? true : false, ], 4 => [ 'value' => 4, 'label' => "Газовая", 'selected' => (2 == intval($selected)) ? true : false, ], 5 => [ 'value' => 5, 'label' => "Сигнализация", 'selected' => (2 == intval($selected)) ? true : false, ] ]; break; case 'garage_type_id' : $list = array(); $sql = "SELECT * FROM garage_type"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'garage_vid_id' : $list = array(); $sql = "SELECT * FROM garage_vid"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'boks_vid_id' : $commons = [ 1 => [ 'value' => 1, 'label' => "Кирпичный", 'selected' => (1 == intval($selected)) ? true : false, ], 2 => [ 'value' => 2, 'label' => "Металлический", 'selected' => (2 == intval($selected)) ? true : false, ] ]; break; case 'commerc_status_id' : $list = array(); $sql = "SELECT * FROM commerc_status"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_specifications' : $list = array(); $sql = "SELECT * FROM commerc_specifications"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; case 'commerc_infrastructure' : $list = array(); $sql = "SELECT * FROM commerc_infrastructure"; if (!is_null($cond)) $sql .= " " . $cond; // $sql .= " ORDER BY id"; $rez = mysql_query($sql); while ($source = mysql_fetch_assoc($rez)) { $list[$source['id']] = $source; } if (!empty($list)) { foreach($list as $key => $item) { $commons[$key] = [ 'value' => $item['id'], 'label' => $item['name'], 'selected' => ($key == intval($selected)) ? true : false, ]; } } break; } return $commons; } public static function getFormattedValue($key, $value) { switch ($key) { case 'deal_type' : $commons = AutoSearch::getCommonFields('deal_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'object_type' : $commons = AutoSearch::getCommonFields('object_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'category_type' : $commons = AutoSearch::getCommonFields('category_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'rent_srok' : $commons = AutoSearch::getCommonFields('rent_srok'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'regions' : $commons = AutoSearch::getCommonFields('regions'); $list = ''; foreach (json_decode($value) as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; break; case 'stoim' : case 'parking_price' : $value = $value . ' руб.'; break; case 'ceiling_height' : case 'ceiling_height_ot' : case 'ceiling_height_do' : $value = $value . ' м.'; break; case 'el_power' : case 'el_power_ot' : case 'el_power_do' : $value = $value . ' кВт'; break; case 'commerc_lift1' : case 'commerc_lift2' : case 'commerc_lift3' : case 'commerc_crane1' : case 'commerc_crane2' : case 'commerc_crane3' : case 'commerc_crane4' : $value = $value . ' шт'; break; case 'lift1_carrying' : case 'lift2_carrying' : case 'lift3_carrying' : case 'crane1_carrying' : case 'crane2_carrying' : case 'crane3_carrying' : case 'crane4_carrying' : $value = $value . ' т'; break; case 'commerc_site' : $value = $value . ' га'; break; case 'do_metro_type' : $commons = AutoSearch::getCommonFields('do_metro_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; /*case 'order_type' : $commons = AutoSearch::getCommonFields('order_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break;*/ case 'parking_id' : $commons = AutoSearch::getCommonFields('parking_id'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'rayons' : $commons = AutoSearch::getCommonFields('rayons'); $list = ''; foreach (json_decode($value) as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; break; case 'metro_stations' : $commons = AutoSearch::getCommonFields('metro_stations'); $list = ''; foreach (json_decode($value) as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; break; case 'rooms' : $commons = AutoSearch::getCommonFields('rooms'); $list = ''; foreach (json_decode($value) as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; break; case 'newbilding_date' : $value = 'не позднее '. $value . 'г.'; break; case 'build_year' : $value = 'не старше '. $value . 'г.'; break; case 'stoim_ot' : case 'stoim_do' : $value = number_format($value,0 , '.', ' ') . ' руб.'; break; case 'sq_all' : case 'sq_all_ot' : case 'sq_all_do' : case 'ploshad_k' : case 'ploshad_k_ot' : case 'ploshad_k_do' : case 'building_area' : case 'building_area_ot' : case 'building_area_do' : $value = $value . ' кв.м'; break; case 'ipoteka' : case 'use_area_price': case 'voen_ipoteka' : case 'subsidya' : case 'mather_kapital' : case 'parking_price_free' : case 'etazhnost' : case 'is_occupied' : case 'can_electricity' : case 'can_gas' : case 'can_water' : case 'can_sewage' : case 'commerc_owned1' : case 'commerc_owned2' : $value = boolval($value) ? 'да' : 'нет'; break; case 'house_type' : $commons = AutoSearch::getCommonFields('house_type'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; case 'house_material' : $commons = AutoSearch::getCommonFields('house_material'); $value = isset($commons[$value]) ? $commons[$value]['label'] : $value; break; default : $fields = self::getFields(); if (array_key_exists($key, $fields)) { if ($commons = AutoSearch::getCommonFields($key)) { if (is_array($value)) { $list = ''; foreach ($value as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; } else if ($fields[$key]['type'] == 'select' && $fields[$key]['multiple']) { $list = ''; $values = json_decode($value); foreach ($values as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; } else if ($fields[$key]['type'] == 'select') { if ($fields[$key]['multiple']) { $list = ''; $values = json_decode($value); foreach ($values as $val) { if (isset($commons[$val])) { if (!empty($list)) $list .= ', ' . $commons[$val]['label']; else $list .= $commons[$val]['label']; } } $value = !empty($list) ? $list : $value; } else { $value = (!empty($commons[$value]['label'])) ? $commons[$value]['label'] : $value; } } else if (isset($commons[$value])) { $value = $commons[$value]['label']; } } } break; } return $value; } public function isEmpty($value = false) { if (is_array($value)) { if (count($value) > 0) return false; else return true; } else { if ( !empty($value) && !is_null($value) && strtolower($value) !== "null" && strtolower($value) !== "false" && $value !== '0' && $value !== "Array" && $value !== "[]" && boolval($value) ) return false; else return true; } } public function getFilterInfo($filter = null, $extended = false, $noEmpty = true) { if (!is_array($filter) && !is_null($this->_filter)) $filter = $this->_filter; if (is_array($filter)) { $info = []; $fields = self::getFields(); foreach ($filter as $key => $value) { if (in_array($key, ['build_year', 'newbilding_date']) && in_array($value, ['0000-00-00 00:00:00', '0000-00-00', '1970-01-01 00:00:00', '1970-01-01', '00.00.0000 00:00:00', '00.00.0000', '01.01.1970 00:00:00', '01.01.1970', '1970'])) { $filter[$key] = null; continue; } if ($noEmpty) $proceed = !self::isEmpty($value); else $proceed = true; if ( isset($fields[$key]['label']) && $proceed ) { if ($key == "stoim_ot" && ($noEmpty && !self::isEmpty($filter['stoim_do']))) { $key = "stoim"; $value2 = $filter['stoim_do']; $value = $value . ' "~" ' . $value2; $filter[$key] = $value; } if (isset($filter['stoim']) && $key == 'stoim_do') continue; if ($key == "komn_ot" && ($noEmpty && !self::isEmpty($filter['komn_do']))) { $key = "komn"; $value2 = $filter['komn_do']; $value = $value . ' "~" ' . $value2; $filter[$key] = $value; } if (isset($filter['komn']) && $key == 'komn_do') continue; if ($key == "sq_all_ot" && ($noEmpty && !self::isEmpty($filter['sq_all_do']))) { $key = "sq_all"; $value2 = $filter['sq_all_do']; $value = $value . ' "~" ' . $value2; $filter[$key] = $value; } if (isset($filter['sq_all']) && $key == 'sq_all_do') continue; if ($key == "ploshad_k_ot" && ($noEmpty && !self::isEmpty($filter['ploshad_k_do']))) { $key = "ploshad_k"; $value2 = $filter['ploshad_k_do']; $value = $value . ' "~" ' . $value2; $filter[$key] = $value; } if (isset($filter['category_type']) && $key == 'category_type') { $value = json_decode($value, true); if (count($value)) { $sql = "SELECT `name` FROM commercial_object WHERE id IN (". implode(', ', $value) .")"; $rez = mysql_query($sql); $value = []; while ($category = mysql_fetch_assoc($rez)) { $value[] = $category['name']; } $value = implode(', ', $value); } } if (isset($filter['ploshad_k']) && $key == 'ploshad_k_do') continue; if ($key == "etazh_ot" && ($noEmpty && !self::isEmpty($filter['etazh_do']))) { $key = "etazh"; $value2 = $filter['etazh_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['etazh']) && $key == 'etazh_do') continue; if ($key == "etazhnost_ot" && ($noEmpty && !self::isEmpty($filter['etazhnost_do']))) { $key = "etazh_all"; $value2 = $filter['etazhnost_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['etazh_all']) && $key == 'etazhnost_do') continue; if ($key == "el_power_ot" && ($noEmpty && !self::isEmpty($filter['el_power_do']))) { $key = "el_power"; $value2 = $filter['el_power_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['el_power']) && $key == 'el_power_do') continue; if ($key == "el_power_ot" && ($noEmpty && !self::isEmpty($filter['el_power_do']))) { $key = "el_power"; $value2 = $filter['el_power_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['el_power']) && $key == 'el_power_do') continue; if ($key == "ceiling_height_ot" && ($noEmpty && !self::isEmpty($filter['ceiling_height_do']))) { $key = "ceiling_height"; $value2 = $filter['ceiling_height_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['ceiling_height']) && $key == 'ceiling_height_do') continue; if ($key == "commerc_year_ot" && ($noEmpty && !self::isEmpty($filter['commerc_year_do']))) { $key = "commerc_year"; $value2 = $filter['commerc_year_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['commerc_year']) && $key == 'commerc_year_do') continue; if ($key == "building_area_ot" && ($noEmpty && !self::isEmpty($filter['building_area_do']))) { $key = "building_area"; $value2 = $filter['building_area_do']; $value = $value . ' ~ ' . $value2; $filter[$key] = $value; } if (isset($filter['building_area']) && $key == 'building_area_do') continue; if ($key == "do_metro" && ($noEmpty && !self::isEmpty($filter['do_metro_type']))) { $key = "do_metro"; $value = $value . ' мин. ' . self::getFormattedValue('do_metro_type', $filter['do_metro_type']); $filter[$key] = $value; } if (isset($filter['do_metro']) && $key == 'do_metro_type') continue; $label = $fields[$key]['label']; $value = self::getFormattedValue($key, $value); if (!empty($value)) { if ($extended) { $info[$key] = [ 'id' => $key, 'label' => $label, 'value' => $value ]; } else { $info[$label] = $value; } } } if ($key == 'geo' && !empty($filter['geo'])) { $geo = (array)json_decode($filter['geo'], true); $geo = array_filter(array_map(function($item) { return !empty($item); }, $geo)); $value = declOfNum(count($geo), ['%d уточнение', '%d уточнения', '%d уточнений']); $info['geo'] = [ 'id' => $key, 'label' => 'Гео', 'value' => $value ]; } } return $info; } return null; } public function unsetFilterField($id = null, $user_id = null, $field_id = null) { if (is_null($id)) return null; if (is_null($user_id)) $user_id = $this->_user['id']; $sql = "UPDATE `autosearch_filters` SET `$field_id` = NULL WHERE `id` = '$id' AND ( `created_by` = $user_id OR `updated_by` = $user_id OR EXISTS ( SELECT 1 FROM requisitions WHERE requisitions.id = autosearch_filters.req_id AND requisitions.who_work = $user_id )) LIMIT 1"; if (mysql_query($sql) && $this->clearAllResults($id)) return true; else return mysql_error(); } private function processGeoData($geo = null, $geopoly2d = false) { $geo_data = []; /*if ($_SESSION['id'] == 6635) var_export([$geo, $geopoly2d]) && die();*/ if (!is_null($geo)) { if (!empty($geo[0])) { $cords = ''; if ($geopoly2d) { $poly = explode(' ', trim($geo[0])); foreach($poly as $cord) { $cords .= $cord . ","; } $cords = str_replace(',,', ',', $cords); } else { $i = 1; $poly = explode(',', trim($geo[0])); foreach($poly as $cord) { if ((boolean)($i % 2)) $cords .= $cord . " "; else $cords .= $cord . ", "; $i++; } $cords = ltrim(rtrim($cords, ', '), ','); } if (!empty($cords)) $geo_data["poly1"] = $cords; } if (!empty($geo[1])) { $cords = ''; if ($geopoly2d) { $poly = explode(' ', trim($geo[1])); foreach($poly as $cord) { $cords .= $cord . ","; } $cords = str_replace(',,', ',', $cords); } else { $i = 1; $poly = explode(',', trim($geo[1])); foreach ($poly as $cord) { if ((boolean)($i % 2)) $cords .= $cord . " "; else $cords .= $cord . ", "; $i++; } $cords = ltrim(rtrim($cords, ', '), ','); } if (!empty($cords)) $geo_data["poly2"] = $cords; } if (!empty($geo[2])) { $cords = ''; if ($geopoly2d) { $poly = explode(' ', trim($geo[2])); foreach($poly as $cord) { $cords .= $cord . ","; } $cords = str_replace(',,', ',', $cords); } else { $i = 1; $poly = explode(',', trim($geo[2])); foreach($poly as $cord) { if ((boolean)($i % 2)) $cords .= $cord . " "; else $cords .= $cord . ", "; $i++; } $cords = ltrim(rtrim($cords, ', '), ','); } if (!empty($cords)) $geo_data["poly3"] = $cords; } if (!empty($geo[3])) { $cords = ''; if ($geopoly2d) { $poly = explode(' ', trim($geo[3])); foreach($poly as $cord) { $cords .= $cord . ","; } $cords = str_replace(',,', ',', $cords); } else { $i = 1; $poly = explode(',', trim($geo[3])); foreach($poly as $cord) { if ((boolean)($i % 2)) $cords .= $cord . " "; else $cords .= $cord . ", "; $i++; } $cords = ltrim(rtrim($cords, ', '), ','); } if (!empty($cords)) $geo_data["poly4"] = $cords; } } return $geo_data; } public function addEditFilter($id = null, $post = null, $newReq = true, $onlyReverse = false) { // var_dump($post['category_type']);die; /*if ($_SESSION['id'] == 5427) { error_reporting(E_ALL | E_STRICT); ini_set('display_errors', 1); }*/ if (is_null($post)) return null; if ($post['newbilding_date'] && !empty($post['newbilding_date']) && $post['newbilding_date'] != "0" && strtoupper($post['newbilding_date']) != "NULL") $post['newbilding_date'] = date('Y-m-d 00:00:00', strtotime($post['newbilding_date'])); else $post['newbilding_date'] = 'NULL'; if ($post['build_year'] && !empty($post['build_year']) && $post['build_year'] != "0" && strtoupper($post['build_year']) != "NULL") $post['build_year'] = $post['build_year'] . "-01-01"; else $post['build_year'] = 'NULL'; $req_id = intval($post['req_id']); if ($req_id == 0) { $post['req_id'] = 'NULL'; $newReq = true; } else { $newReq = false; } $oldValues = []; $deleteAll = false; $fields = $this->getFields(false); if (intval($id) > 0) { $oldValues = $this->getFilter($id, $_SESSION['id'], false, false); } foreach ($post as $key => $value) { if ($key == 'geo' || $key == 'rooms' || $key == 'category_type') continue; if (intval($id) > 0) { if (!is_null($fields[$key]['main_field']) || !is_null($oldValues[$key])) { if ($fields[$key]['main_field'] && $value !== $oldValues[$key]) { $deleteAll = true; } } } if ($key === 'is_active' || $key === 'telegram_notify') { $post[$key] = "'" . intval($value) . "'"; } else { if ($this->isEmpty($value)) { $post[$key] = 'NULL'; } else { $post[$key] = "'" . $post[$key] . "'"; } } } $isError = false; $errorText = ''; if (self::isEmpty($post['deal_type'])) { $isError = true; $errorText .= "\r\nНе указан тип сделки
"; } if (self::isEmpty($post['object_type'])) { $isError = true; $errorText .= "\r\nНе указан тип объекта
"; } if (!is_null($this->_user) && $this->_user->can('autosearch')){ if (self::isEmpty($post['object_source'])) { $isError = true; $errorText .= "\r\nНе указан источник поиска
"; } } if (self::isEmpty($post['regions'])) { $isError = true; $errorText .= "\r\nНе указан регион(ы)
"; } if ($post['deal_type'] == 1 && self::isEmpty($post['rent_srok'])) { $isError = true; $errorText .= "\r\nНе указан срок аренды
"; } if ($post['object_type'] == 4 && self::isEmpty($post['category_type'])) { $isError = true; $errorText .= "\r\nНе указан тип помещения
"; } $user_id = $_SESSION['id']; if (!$isError) { $values = []; $fields_list = [ 'deal_type', 'object_type', 'object_source', 'category_type', 'stoim_ot', 'stoim_do', 'komn_ot', 'komn_do', 'sq_all_ot', 'sq_all_do', 'ploshad_k_ot', 'ploshad_k_do', 'rent_srok', 'regions', 'rayons', 'metro_stations', 'do_metro', 'do_metro_type', 'etazhnost', 'newbilding_date', 'ipoteka', 'use_area_price', 'voen_ipoteka', 'subsidya', 'mather_kapital', 'house_type', 'house_material', 'build_year', 'tax_number', 'legal_address', 'etazh_ot', 'etazh_do', 'etazhnost_ot', 'etazhnost_do', 'is_occupied', 'layout_id', 'wet_spots', 'el_power_ot', 'el_power_do', 'commer_condition', 'is_furniture', 'commer_access', 'parking_types', 'parking_id', 'parking_price', 'parking_price_free', 'ceiling_height_ot', 'ceiling_height_do', 'column_grid', 'vat_type_id', 'commerc_site', 'commerc_owned1', 'commerc_owned2', 'floor_material_id', 'commerc_portal_id', 'commerc_purpose', 'commerc_land_category_id', 'commerc_permitted_use_id', 'commerc_electricity_id', 'can_electricity', 'commerc_gas_id', 'can_gas', 'commerc_water_id', 'can_water', 'commerc_sewage_id', 'can_sewage', 'commerc_driveways', 'commerc_year_ot', 'commerc_year_do', 'commerc_building_type_id', 'commerc_building_class_id', 'building_area_ot', 'building_area_do', 'commerc_houseline_type_id', 'commerc_building_category_id', 'commerc_opened_id', 'commerc_building_ventilation', 'commerc_building_conditioning', 'commerc_building_heating', 'commerc_building_fire', 'garage_type_id', 'garage_vid_id', 'boks_vid_id', 'commerc_status_id', 'commerc_specifications', 'commerc_infrastructure', 'commerc_infrastructure1', 'commerc_infrastructure2', 'commerc_lift1', 'lift1_carrying', 'commerc_lift2', 'lift2_carrying', 'commerc_lift3', 'lift3_carrying', 'commerc_crane1', 'crane1_carrying', 'commerc_crane2', 'crane2_carrying', 'commerc_crane3', 'crane3_carrying', 'commerc_crane4', 'crane4_carrying', 'opis', 'comment', 'is_active', 'telegram_notify', 'geo', ]; if (intval($id) > 0) { // Сбрасываем параметры района и метро, если переданы гео-уточнения if (isset($post['geo'])) { unset($post['rayons']); unset($post['metro_stations']); unset($post['do_metro']); unset($post['do_metro_type']); } foreach ($fields_list as $field_name) { if ($field_name == 'req_id' || $field_name == 'rooms' || $field_name == 'geo' || $field_name == 'category_type') continue; if (isset($post[$field_name])) { $values[] = "`$field_name` = {$post[$field_name]}"; } else { $values[] = "`$field_name` = NULL"; } } if (isset($post['geo'])) { $geo_data = $this->processGeoData($post['geo']); $values[] = "`geo` = '" . json_encode($geo_data, JSON_UNESCAPED_UNICODE) . "'"; $values[] = "`rayons` = NULL"; $values[] = "`metro_stations` = NULL"; $values[] = "`do_metro` = NULL"; $values[] = "`do_metro_type` = NULL"; } else { $values[] = "`geo` = NULL"; } if (isset($post['rooms']) && $post['rooms'] != 'null') $values[] = "`rooms` = '" . json_encode(array_map('strval', $post['rooms']), JSON_UNESCAPED_UNICODE) . "'"; else $values[] = "`rooms` = NULL"; if (isset($post['category_type']) && $post['category_type'] != 'null') $values[] = "`category_type` = '" . json_encode(array_map('intval', $post['category_type']), JSON_UNESCAPED_UNICODE) . "'"; else $values[] = "`category_type` = NULL"; $values[] = "`updated_by` = '$user_id'"; if ($onlyReverse) { $values[] = "`is_search` = '0'"; $values[] = "`is_reverse` = '1'"; } else { $values[] = "`is_search` = '1'"; $values[] = "`is_reverse` = '1'"; } $values = array_unique($values); $sql = "UPDATE `autosearch_filters` SET " . implode(',', $values) . " WHERE `id` = '$id'"; if (isset($post['req_id']) && is_string($post['req_id'])) $sql .= " AND `req_id` = $post[req_id]"; else if (isset($post['req_id'])) $sql .= " AND `req_id` = '$req_id'"; else if ($newReq) $sql .= " AND `req_id` IS NULL"; $agents_ids = []; if ($user_id) { $agency_id = User::getUserAgencyID(); $agents_ids[] = $agency_id; $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)))"; $query = mysql_query($sql_users); while ($row = mysql_fetch_assoc($query)) { $agents_ids[] = (int)$row['id']; } $agents_ids = array_merge($agents_ids, [$user_id]); $agents_ids = array_unique($agents_ids); } if (!empty($agents_ids)) //$sql .= " AND (`created_by` IN (".implode(',', $agents_ids).") OR `updated_by` IN (".implode(',', $agents_ids).")) LIMIT 1"; $sql .= " AND ( `created_by` IN (".implode(',', $agents_ids).") OR `updated_by` IN (".implode(',', $agents_ids).") OR EXISTS ( SELECT 1 FROM requisitions WHERE requisitions.id = autosearch_filters.req_id AND requisitions.who_work = $user_id )) LIMIT 1"; else $sql .= " LIMIT 1"; if (mysql_query($sql) && $this->clearAllResults($id, $deleteAll)) { if ($req_id > 0) $this->setReqToFilter($req_id, $id, (int)$_SESSION['id']); return ['success' => true, 'id' => $id, 'sql' => $sql]; } else { return ['success' => false, 'error' => mysql_error(), 'sql' => $sql]; } } else { // Сбрасываем параметры района и метро, если переданы гео-уточнения if (isset($post['geo'])) { unset($post['rayons']); unset($post['metro_stations']); unset($post['do_metro']); unset($post['do_metro_type']); } foreach ($fields_list as $field_name) { if ($field_name == 'rooms' || $field_name == 'geo' || $field_name == 'category_type') continue; if (isset($post[$field_name])) { $values['`'.$field_name.'`'] = $post[$field_name]; } else { $values['`'.$field_name.'`'] = 'NULL'; } } if (isset($post['rooms'])) $values['`rooms`'] = "'" . json_encode($post['rooms'], JSON_UNESCAPED_UNICODE) . "'"; else $values['`rooms`'] = "NULL"; if (isset($post['category_type'])) $values['`category_type`'] = "'" . json_encode($post['category_type'], JSON_UNESCAPED_UNICODE) . "'"; else $values['`category_type`'] = "`category_type` = NULL"; if (isset($post['geo'])) { $geo_data = $this->processGeoData($post['geo']); $values['`geo`'] = "'" . json_encode($geo_data, JSON_UNESCAPED_UNICODE) . "'"; $values['`rayons`'] = "NULL"; $values['`metro_stations`'] = "NULL"; $values['`do_metro`'] = "NULL"; $values['`do_metro_type`'] = "NULL"; } else { $values['`geo`'] = "NULL"; } $values['`created_by`'] = "'$user_id'"; if ($onlyReverse) { if (intval($post['req_id'])) { $this->deleteFilterByReq(intval($post['req_id'])); } $values['`is_search`'] = "'0'"; $values['`is_reverse`'] = "'1'"; } else { $values['`is_search`'] = "'1'"; $values['`is_reverse`'] = "'0'"; } $sql = "INSERT INTO `autosearch_filters` (" . implode(',', array_keys($values)) . ") VALUES (" . implode(',', $values) . ")"; if (mysql_query($sql)) { $id = mysql_insert_id(); if ($req_id > 0) $this->setReqToFilter($req_id, $id, (int)$_SESSION['id']); return ['success' => true, 'id' => $id, 'sql' => $sql]; } else { return ['success' => false, 'error' => mysql_error(), 'sql' => $sql]; } } } return ['success' => false, 'error' => $errorText]; } public function setReqToFilter($req_id = null, $filter_id = null, $user_id = null) { if (is_null($req_id) || is_null($filter_id)) return null; if (is_null($user_id)) $user_id = $this->_user['id']; $sql1 = "UPDATE `requisitions` SET `asfilter_id`='$filter_id' WHERE `id` = '$req_id' LIMIT 1"; $sql2 = "UPDATE `autosearch_filters` SET `req_id`='$req_id' WHERE `id` = '$filter_id' AND (`created_by` = $user_id OR `updated_by` = $user_id) LIMIT 1"; if (mysql_query($sql1) && mysql_query($sql2)) return ['success' => true, 'filter_id' => $filter_id, 'req_id' => $req_id]; else return mysql_error(); } public function unsetReqToFilter($req_id = null, $filter_id = null) { if (is_null($req_id) && is_null($filter_id)) return null; $sql1 = 'true'; $sql2 = 'true'; if (!is_null($req_id)) $sql1 = "UPDATE `requisitions` SET `asfilter_id`=NULL WHERE `id` = '$req_id' LIMIT 1"; if (!is_null($filter_id)) $sql2 = "UPDATE `requisitions` SET `asfilter_id`=NULL WHERE `asfilter_id` = '$filter_id' LIMIT 1"; if (mysql_query($sql1) && mysql_query($sql2)) return true; else return mysql_error(); } public function deleteFilter($filter_id = null, $user_id = null) { if (is_null($filter_id)) return null; if (is_null($user_id)) $user_id = $this->_user['id']; $agents_ids = []; $agents_ids[] = $user_id; if ($user_id) { $agency_id = User::getUserAgencyID(); $agents_ids[] = $agency_id; $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)))"; $query = mysql_query($sql_users); while ($row = mysql_fetch_assoc($query)) { $agents_ids[] = (int)$row['id']; } $agents_ids = array_merge($agents_ids, [$user_id]); $agents_ids = array_unique($agents_ids); } $sql = "DELETE `filters`, `results` FROM `autosearch_filters` AS `filters` INNER JOIN `autosearch_results` AS `results` ON `results`.filter_id = `filters`.`id` WHERE `filters`.`id`='$filter_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; if (mysql_query($sql) && $this->clearAllResults($filter_id, true)) { self::unsetReqToFilter(null, $filter_id); mysql_query("DELETE * FROM `autosearch_viewed` WHERE `filter_id`='$filter_id'"); mysql_query("DELETE * FROM `autosearch_ignored` WHERE `filter_id`='$filter_id'"); mysql_query("DELETE * FROM `autosearch_favoured` WHERE `filter_id`='$filter_id'"); mysql_query("DELETE * FROM `autosearch_sended` WHERE `filter_id`='$filter_id'"); return true; } else { return mysql_error(); } } public function deleteFilterByReq($req_id = null, $user_id = null) { if (is_null($req_id)) return null; if (is_null($user_id)) $user_id = $this->_user['id']; $agents_ids = []; $agents_ids[] = $user_id; if ($user_id) { $agency_id = User::getUserAgencyID(); $agents_ids[] = $agency_id; $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)))"; $query = mysql_query($sql_users); while ($row = mysql_fetch_assoc($query)) { $agents_ids[] = (int)$row['id']; } $agents_ids = array_merge($agents_ids, [$user_id]); $agents_ids = array_unique($agents_ids); } $sql = "DELETE FROM `autosearch_viewed` AS `viewed` INNER JOIN `autosearch_filters` AS `filters` ON `filters`.`id` = `viewed`.`filter_id` WHERE `filters`.`req_id`='$req_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; $sql2 = "DELETE FROM `autosearch_ignored` AS `ignored` INNER JOIN `autosearch_filters` AS `filters` ON `filters`.`id` = `ignored`.`filter_id` WHERE `filters`.`req_id`='$req_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; $sql3 = "DELETE FROM `autosearch_favoured` AS `favoured` INNER JOIN `autosearch_filters` AS `filters` ON `filters`.`id` = `favoured`.`filter_id` WHERE `filters`.`req_id`='$req_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; $sql4 = "DELETE FROM `autosearch_sended` AS `sended` INNER JOIN `autosearch_filters` AS `filters` ON `filters`.`id` = `sended`.`filter_id` WHERE `filters`.`req_id`='$req_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; $sql5 = "DELETE FROM `autosearch_filters` AS `filters` INNER JOIN `autosearch_results` AS `results` ON `results`.filter_id = `filters`.`id` WHERE `filters`.`req_id`='$req_id' AND (`filters`.`created_by` IN (".implode(',', $agents_ids).") OR `filters`.`updated_by` IN (".implode(',', $agents_ids)."))"; if (mysql_query($sql) && mysql_query($sql2) && mysql_query($sql3) && mysql_query($sql4) && mysql_query($sql5)) { self::unsetReqToFilter($req_id); return true; } else { return mysql_error(); } } private function cleanUpResults($filter_id = null, $delete_all = false) { if (is_null($filter_id)) return false; if ($delete_all) { $sqld_1 = "DELETE FROM `autosearch_ignored` WHERE `filter_id` = '$filter_id'"; $sqld_2 = "DELETE FROM `autosearch_sended` WHERE `filter_id` = '$filter_id'"; $sqld_3 = "DELETE FROM `autosearch_viewed` WHERE `filter_id` = '$filter_id'"; $sqld_4 = "DELETE FROM `autosearch_favoured` WHERE `filter_id` = '$filter_id'"; $sqld_5 = "DELETE FROM `autosearch_results` WHERE `filter_id` = '$filter_id'"; if (mysql_query($sqld_1) && mysql_query($sqld_2) && mysql_query($sqld_3) && mysql_query($sqld_4) && mysql_query($sqld_5)) return true; else return mysql_error(); } else { // Чистим фильтры старше, старше 1 часа, которые не привязались к заявками $datetime = date('Y-m-d H:i:s', strtotime('-1 hour')); $sql = "DELETE FROM `autosearch_filters` WHERE ((`id` = '$filter_id' AND `req_id` IS NULL) OR `req_id` IS NULL) AND `created_at` < '$datetime'"; // Чистим все результаты старше 30 дней $datetime = date('Y-m-d H:i:s', strtotime('-30 days')); $sql1 = "DELETE FROM `autosearch_results` WHERE `filter_id` = '$filter_id' AND `processed_at` < '$datetime'"; // Чистим все пустые результаты старше 7 дней $datetime = date('Y-m-d H:i:s', strtotime('-7 days')); $sql2 = "DELETE FROM `autosearch_results` WHERE `filter_id` = '$filter_id' AND `match_ids` IS NULL AND `similar_ids` IS NULL AND `processed_at` < '$datetime'"; // Чистим пустые результаты за сегодня, но старше 30 мин. назад, т.к. другие необходимы // при составлении очереди по крону (processed_at), если интервал 15 мин. $datetime = date('Y-m-d H:i:s', strtotime('-30 minutes')); $sql3 = "DELETE FROM `autosearch_results` WHERE `filter_id` = '$filter_id' AND `match_ids` IS NULL AND `similar_ids` IS NULL AND `count` IS NULL AND `total` IS NULL AND `processed_at` < '$datetime'"; // Очищаем результаты подбора автопоиска (кроме избранных, игнорируемых, просмотренных и отправленных в PDF) $sql4 = "UPDATE `autosearch_results` SET `count` = 0 WHERE ((`match_ids` IS NULL AND `similar_ids` IS NULL) OR `count` < 0) AND `filter_id` = '$filter_id'"; if (mysql_query($sql) && mysql_query($sql1) && mysql_query($sql2) && mysql_query($sql3) && mysql_query($sql4)) return true; else return mysql_error(); } } private function buildSearchQuery($filter = null, $sphinx = true, $strict = true) { if (!is_array($filter) && !is_null($this->_filter)) $filter = $this->_filter; if (is_array($filter)) { $query = []; $proccessed = []; $fields = self::getFields(); $is_geo = false; $geo_data = null; if (!empty($filter['geo'])) { $is_geo = true; $geo_data = array_values((array)json_decode($filter['geo'])); } foreach ($filter as $key => $value) { if (isset($fields[$key]) && !self::isEmpty($value) && !in_array($key, $proccessed)) { if ($fields[$key]['type'] == "number") $value = intval($value); $proccessed[] = $key; switch (strtolower($key)) { case 'id' : case 'req_id' : break; case 'deal_type' : if ($value == 2) $value = 1; // Покупка (продажа) else if ($value == 1) $value = 0; // Аренда else if ($value == 3) $value = 2; // Новостройки if ($sphinx) $query['where'][] = "operation_type=" . $value; else $query['where'][] = "`objects`.`operation_type` = '" . $value . "'"; break; case 'object_type' : if ($sphinx) $query['where'][] = "type=" . $value; else $query['where'][] = "`objects`.`type` = '" . $value . "'"; break; case 'object_source' : if ($value == 1) { // Собственники if ($sphinx) { $query['where'][] = "(is_agent = 0 AND archive = 0)"; } else { $query['where'][] = "(`ads_objects`.`ads_agent` = 0) AND `objects`.`archive` = 0"; } } else if ($value == 2) { // Агенты if ($sphinx) { $query['where'][] = "(is_agent_ap = 1 AND archive < 1)"; } else { $query['where'][] = "(`objects`.`id_add_user` > 0 OR `ads_objects`.`ads_agent` > 0) AND `objects`.`archive` < 1"; } } else if ($value == 3) { // Собственники и агенты if ($sphinx) { $query['where'][] = "(is_agent_all = 1 AND archive = 0)"; } else { $query['where'][] = "`objects`.`archive` = 0"; } } else if ($value == 4) { // Архив собственников if ($sphinx) { $query['where'][] = "archive = 1"; $query['where'][] = "objects.id_add_user = 0"; } else { $query['where'][] = "`objects`.`archive` = 1"; $query['where'][] = "`objects`.`id_add_user` = 0"; } } else if ($value == 5) { // Объекты компании $usersIds = []; if (isset($filter['created_by'])) { $curr_agency_id = User::getUserAgencyID($filter['created_by']); $usersIds = User::getAllAgencyUsers($curr_agency_id); $usersIds[] = $filter['created_by']; } if (empty($usersIds) && isset($filter['updated_by'])) { $curr_agency_id = User::getUserAgencyID($filter['updated_by']); $usersIds = User::getAllAgencyUsers($curr_agency_id); $usersIds[] = $filter['updated_by']; } $usersIds = array_unique($usersIds); $usersIds = array_map('intval', $usersIds); /*if (isset($_GET['dev'])) { echo "" . var_export($filter, true) . ""; var_export($curr_agency_id); var_export($usersIds); }*/ if ($sphinx) { $query['where'][] = "archive = 0"; if (!empty($usersIds)) $query['where'][] = "id_add_user IN (" . implode(', ', $usersIds) . ")"; } else { $query['where'][] = "objects.archive = 0"; if (!empty($usersIds)) $query['where'][] = "`objects`.`id_add_user` IN (" . implode(',', $usersIds) . ")"; } } else if ($value == 6) { // Собственники и объекты компании $usersIds = []; if (isset($filter['created_by'])) { $curr_agency_id = User::getUserAgencyID($filter['created_by']); $usersIds = User::getAllAgencyUsers($curr_agency_id); $usersIds[] = $filter['created_by']; } if (empty($usersIds) && isset($filter['updated_by'])) { $curr_agency_id = User::getUserAgencyID($filter['updated_by']); $usersIds = User::getAllAgencyUsers($curr_agency_id); $usersIds[] = $filter['updated_by']; } $usersIds = array_unique($usersIds); $usersIds = array_map('intval', $usersIds); /*if (isset($_GET['dev'])) { echo "
" . var_export($filter, true) . ""; var_export($curr_agency_id); var_export($usersIds); }*/ if ($sphinx) { $query['where'][] = "archive = 0"; if (!empty($usersIds)) { $query['select'][] = "(is_agent = 0 OR id_add_user=" . implode(" OR id_add_user=", $usersIds) . ") AS object_source_cond"; $query['where'][] = "(archive = 0 and object_source_cond > 0)"; } else { $query['where'][] = "(is_agent = 0 AND archive = 0)"; } } else { if (!empty($usersIds)) { $query['where'][] = "(`ads_objects`.`ads_agent` = 0 OR `objects`.`id_add_user` IN (" . implode(',', $usersIds) . "))"; } else { $query['where'][] = "(`ads_objects`.`ads_agent` = 0) AND `objects`.`archive` = 0"; } } } else { if ($sphinx) { $query['where'][] = "archive = 0"; } else { $query['where'][] = "objects.archive = 0"; } } break; case 'category_type' : if (is_string($value)) { $value = json_decode($value, true); } if (count($value)) { if ($sphinx) $query['where'][] = "type_category IN (" . implode(", ", $value) . ")"; else $query['where'][] = "`objects`.`type_category` IN (" . implode(", ", $value) . ")"; } break; case 'rent_srok' : if ($sphinx) $query['where'][] = "srok=" . $value; else $query['where'][] = "`objects`.`srok` = '" . $value . "'"; break; case 'stoim_ot' : $price_key_to_check = $filter['use_area_price'] ? 'area_price' : 'stoim'; if ($sphinx) $sql = $price_key_to_check . ">=" . $value; else { if (!$filter['use_area_price']) { $sql = "`objects`.`stoim` >= '" . $value . "'"; } else { $sql = "objects.stoim / objects.ploshad >= '" . $value . "'"; } } if ($value2 = $filter['stoim_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND $price_key_to_check<=" . $value2; else { if (!$filter['use_area_price']) { $sql .= " AND `objects`.`stoim` <= '" . $value2 . "'"; } else { $sql = "AND objects.stoim / objects.ploshad <= '" . $value2 . "'"; } } $query['where'][] = "(".$sql.")"; $proccessed[] = 'stoim_do'; break; } $query['where'][] = $sql; break; case 'stoim_do' : $price_key_to_check = $filter['use_area_price'] ? 'area_price' : 'stoim'; if ($sphinx) $query['where'][] = "$price_key_to_check<=" . $value; else { if (!(bool)$fields['use_area_price']) { $query['where'][] = "`objects`.`stoim` <= '" . $value . "'"; } else { $query['where'][] = "objects.stoim / objects.ploshad <= '" . $value . "'"; } } break; case 'komn_ot' : if ($sphinx) $sql = "komnat>=" . $value; else $sql = "`objects`.`komnat` >= '" . $value . "'"; if ($value2 = $filter['komn_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND komnat<=" . $value2; else $sql .= " AND `objects`.`komnat` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'komn_do'; break; } $query['where'][] = $sql; break; case 'komn_do' : if ($sphinx) $query['where'][] = "komnat<=" . $value; else $query['where'][] = "`objects`.`komnat` <= '" . $value . "'"; break; case 'rooms' : $rooms = json_decode($value, true); $sql_where = []; if (in_array(1, array_map('intval', array_values($rooms)))) $sql_where[] = "komnat = 1"; if (in_array(2, array_map('intval', array_values($rooms)))) $sql_where[] = "komnat = 2"; if (in_array(3, array_map('intval', array_values($rooms)))) $sql_where[] = "komnat = 3"; if (in_array(4, array_map('intval', array_values($rooms)))) $sql_where[] = "komnat >= 4"; if ($sphinx && in_array(5, array_map('intval', array_values($rooms)))) $sql_where[] = "studio_flag = '1'"; if ($sphinx) { if (!empty($sql_where)) { $query['select'][] = "(".implode(' OR ', $sql_where).") AS rooms"; $query['where'][] = "rooms>0"; } } else { if (in_array(5, array_map('intval', array_values($rooms)))) $sql_where[] = "`objects`.`studio_flag` = '1'"; if (!empty($sql_where)) { $query['where'][] = "(".implode(' OR ', $sql_where).")"; } } break; case 'sq_all_ot' : $value = intval($value); $isLandObject = false; if (isset($filter['object_type']) && $filter['object_type'] == 7) { $isLandObject = true; } $fieldName = $isLandObject ? 'land_area' : 'ploshad'; if ($sphinx) $sql = "$fieldName>=" . $value; else $sql = "`objects`.`$fieldName` >= '" . $value . "'"; if ($value2 = $filter['sq_all_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); $value2 = intval($value2); if ($sphinx) $sql .= " AND $fieldName<=" . $value2; else $sql .= " AND `objects`.`$fieldName` <= '" . $value2 . "'"; $query['where'][] = "(" . $sql . ")"; $proccessed[] = 'sq_all_do'; break; } $query['where'][] = $sql; break; case 'sq_all_do' : $value = intval($value); $isLandObject = false; if (isset($filter['object_type']) && $filter['object_type'] == 7) { $isLandObject = true; } $fieldName = $isLandObject ? 'land_area' : 'ploshad'; if ($sphinx) $query['where'][] = "$fieldName<=" . $value; else $query['where'][] = "`objects`.`$fieldName` <= '" . $value . "'"; break; case 'ploshad_k_ot' : if ($sphinx) $sql = "ploshad_k>=" . $value; else $sql = "`objects`.`ploshad_k` >= '" . $value . "'"; if ($value2 = $filter['ploshad_k_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND ploshad_k<=" . $value2; else $sql .= " AND `objects`.`ploshad_k` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'ploshad_k_do'; break; } $query['where'][] = $sql; break; case 'ploshad_k_do' : if ($sphinx) $query['where'][] = "ploshad_k<=" . $value; else $query['where'][] = "`objects`.`ploshad_k` <= '" . $value . "'"; break; case 'regions' : $sql_r = "SELECT `rf_regions`.* FROM `rf_regions` WHERE `id` IN (" . implode(', ', json_decode($value)) . ") ORDER BY `id` ASC"; $region = []; $query_r = mysql_query($sql_r); while($row = mysql_fetch_assoc($query_r)) { $region[] = $row; } 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 ); } $parent_region = []; /*if (isset($region[0]['id'])) $parent_region[] = $region[0]['id'];*/ if (isset($region[0]['parent'])) $parent_region[] = $region[0]['parent']; if (!empty($parent_region)) { if ($sphinx) $query['match'][] = "@(id_rf_region,parent) " . implode('|', $parent_region) . ""; else $query['where'][] = "`objects`.`id_rf_region` IN (SELECT `id` FROM `rf_regions` WHERE `id` IN (" . implode(',', $parent_region) . ") OR `parent` IN (" . implode(',', $parent_region) . "))"; } else { if ($sphinx) $query['match'][] = "@(id_rf_region,parent) " . implode('|', json_decode($value)) . ""; else $query['where'][] = "`objects`.`id_rf_region` IN (" . implode(', ', json_decode($value)) . ")"; } break; case 'rayons' : if (!$is_geo) { // игнорируем при поиске с гео-уточнением $rayon = json_decode($value); $usl_rayon2 = []; foreach ($rayon as $key => $value) { if ($key == 0) { $usl_rayon[] = "`objects`.`id_rf_region` = '$value'"; } else { $usl_rayon[] = "`objects`.`rayon` = '$value'"; } $usl_rayon2[] = $value; } $usl_rayon2 = array_unique($usl_rayon2); if ($sphinx) $query['where'][] = "rayon_id in (" . implode(",", $usl_rayon2) . ")"; else $query['where'][] = "(" . implode(" OR ", $usl_rayon) . ")"; } break; case 'metro_stations' : if (!$is_geo) { // игнорируем при поиске с гео-уточнением $metro = json_decode($value); $usl_metro2 = []; foreach ($metro as $key => $value) { $usl_metro[] = "`sp_metro`.`id_metro` = '$value'"; $usl_metro2[] = $value; } $usl_metro2 = array_unique($usl_metro2); if ($sphinx) { $query['where'][] = "id_metro IN (" . implode(",", $usl_metro2) . ")"; } else { $query['where'][] = "(" . implode(" OR ", $usl_metro) . ")"; $query['join'][] = " LEFT JOIN `sp_metro` AS `sp_metro` ON `objects`.`id` = `sp_metro`.`id_obj` "; } } break; case 'do_metro' : if (!$is_geo) { // игнорируем при поиске с гео-уточнением if ($sphinx) $sql = "peshkom<=" . $value; else $sql = "`objects`.`peshkom` <= '" . $value . "'"; if ($value2 = $filter['do_metro_type']) { if ($value2 == 1) $value2 = 0; elseif ($value2 == 2) $value2 = 1; if ($sphinx) $sql .= " AND transport=" . $value2; else $sql .= " AND `objects`.`transport` = '" . $value2 . "'"; $query['where'][] = "(" . $sql . ")"; $proccessed[] = 'do_metro_type'; break; } $proccessed[] = 'do_metro_type'; $query['where'][] = $sql; } break; case 'etazh_ot' : if ($sphinx) $sql = "etazh>=" . $value; else $sql = "`objects`.`etazh` >= '" . $value . "'"; if ($value2 = $filter['etazh_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND etazh<=" . $value2; else $sql .= " AND `objects`.`etazh` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'etazh_do'; break; } $query['where'][] = $sql; break; case 'etazh_do' : if ($sphinx) $query['where'][] = "etazh<=" . $value; else $query['where'][] = "`objects`.`etazh` <= '" . $value . "'"; break; case 'etazhnost_ot' : if ($sphinx) $sql = "etazh_iz>=" . $value; else $sql = "`objects`.`etazh_iz` >= '" . $value . "'"; if ($value2 = $filter['etazhnost_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND etazh_iz<=" . $value2; else $sql .= " AND `objects`.`etazh_iz` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'etazhnost_do'; break; } $query['where'][] = $sql; break; case 'etazhnost_do' : if ($sphinx) $query['where'][] = "etazh_iz<=" . $value; else $query['where'][] = "`objects`.`etazh_iz` <= '" . $value . "'"; break; case 'etazhnost' : if ($sphinx && boolval($value)) { $query['select'][] = "IF(etazh <> 1 AND etazh <> etazh_iz AND etazh_iz > 0, 1, 0) as etazhnost"; $query['where'][] = "etazhnost = 1"; } else if (boolval($value)) { $query['where'][] = "'(`objects`.`etazh` <> 1 AND `objects`.`etazh` <> `objects`.`etazh_iz`)"; } break; case 'legal_address' : if (!$strict) break; if ($sphinx) $query['where'][] = "legal_address=" . $value; else $query['where'][] = "`objects`.`legal_address` = '" . $value . "'"; break; case 'is_occupied' : if (!$strict) break; if ($sphinx) $query['where'][] = "isOccupied=" . $value; else $query['where'][] = "`objects`.`isOccupied` = '" . $value . "'"; break; case 'layout_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "layout_id=" . $value; else $query['where'][] = "`objects`.`layout_id` = '" . $value . "'"; break; case 'wet_spots' : if (!$strict) break; if ($sphinx) $query['where'][] = "number_wet_spots=" . $value; else $query['where'][] = "`objects`.`number_wet_spots` = '" . $value . "'"; break; case 'house_type' : if (!$strict) break; if ($sphinx) $query['where'][] = "house_type=" . $value; else $query['where'][] = "`objects`.`house_type` = '" . $value . "'"; break; case 'house_material' : if (!$strict) break; if ($sphinx) $query['where'][] = "house_material = " . $value; else $query['where'][] = "`objects`.`house_material` = '" . $value . "'"; break; case 'build_year' : if (!$strict) break; if ($sphinx) { /*$query['select'][] = "UNIX_TIMESTAMP(build_year) AS build_year_u"; $query['where'][] = "build_year_u >= '" . strtotime($value) . "'";*/ //$query['select'][] = "build_year"; //$query['where'][] = "UNIX_TIMESTAMP(build_year) >= '" . strtotime($value) . "'"; $query['where'][] = "build_year >= " . $value . ""; } else { $query['where'][] = "`sale_objects`.`build_year` >= '" . $value . "'"; $query['join'][] = " LEFT JOIN `sale_objects` AS `sale_objects` ON `objects`.`id` = `sale_objects`.`object_id` "; } break; case 'el_power_ot' : if (!$strict) break; if ($sphinx) $sql = "electricity_power>=" . $value; else $sql = "`objects`.`electricity_power` >= '" . $value . "'"; if ($value2 = $filter['el_power_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND electricity_power<=" . $value2; else $sql .= " AND `objects`.`electricity_power` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'el_power_do'; break; } $query['where'][] = $sql; break; case 'el_power_do' : if (!$strict) break; if ($sphinx) $query['where'][] = "electricity_power<=" . $value; else $query['where'][] = "`objects`.`electricity_power` <= '" . $value . "'"; break; case 'commer_condition' : if (!$strict) break; if ($sphinx) $query['where'][] = "commer_condition=" . $value; else $query['where'][] = "`objects`.`commer_condition` = '" . $value . "'"; break; case 'is_furniture' : if (!$strict) break; if ($sphinx) $query['where'][] = "isFurniture=" . $value; else $query['where'][] = "`objects`.`isFurniture` = '" . $value . "'"; break; case 'commer_access' : if (!$strict) break; if ($sphinx) $query['where'][] = "commer_access=" . $value; else $query['where'][] = "`objects`.`commer_access` = '" . $value . "'"; break; case 'parking_types' : if (!$strict) break; if ($sphinx) $query['where'][] = "parking_type_id=" . $value; else $query['where'][] = "`objects`.`parking_type_id` = '" . $value . "'"; break; case 'parking_price' : if (!$strict) break; if ($sphinx) $query['where'][] = "parking_price=" . $value; else $query['where'][] = "`objects`.`parking_price` = '" . $value . "'"; break; case 'parking_price_free' : if (!$strict) break; if (boolval($value)) { if ($sphinx) $query['where'][] = "parkingIsFree = 'on'"; else $query['where'][] = "`objects`.`parkingIsFree` = 'on'"; } break; case 'ceiling_height_ot' : if (!$strict) break; if ($sphinx) $sql = "ceiling_height>=" . $value; else $sql = "`objects`.`ceiling_height` >= '" . $value . "'"; if ($value2 = $filter['ceiling_height_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND ceiling_height<=" . $value2; else $sql .= " AND `objects`.`ceiling_height` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'ceiling_height_do'; break; } $query['where'][] = $sql; break; case 'ceiling_height_do' : if (!$strict) break; if ($sphinx) $query['where'][] = "ceiling_height<=" . $value; else $query['where'][] = "`objects`.`ceiling_height` <= '" . $value . "'"; break; case 'vat_type_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "vat_type_id=" . $value; else $query['where'][] = "`objects`.`vat_type_id` = '" . $value . "'"; break; case 'commerc_site' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_site=" . $value; else $query['where'][] = "`objects`.`commerc_site` = '" . $value . "'"; break; case 'commerc_owned1' : if (!$strict) break; if ($sphinx) $sql = "commerc_owned=" . $value; else $sql = "`objects`.`commerc_owned` = '" . $value . "'"; if ($value2 = $filter['commerc_owned2']) { if ($sphinx) $sql = "commerc_owned=" . $value2; else $sql = "`objects`.`commerc_owned` = '" . $value2."'"; $proccessed[] = 'commerc_owned2'; break; } $query['where'][] = $sql; break; case 'floor_material_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "floor_material_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`floor_material_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_portal_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_portal_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_portal_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_lift1' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_lift1=" . $value; else $query['where'][] = "`objects`.`commerc_lift1` = '" . $value . "'"; break; case 'lift1_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "lift1_carrying=" . $value; else $query['where'][] = "`objects`.`lift1_carrying` = '" . $value . "'"; break; case 'commerc_lift2' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_lift2=" . $value; else $query['where'][] = "`objects`.`commerc_lift2` = '" . $value . "'"; break; case 'lift2_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "lift2_carrying=" . $value; else $query['where'][] = "`objects`.`lift2_carrying` = '" . $value . "'"; break; case 'commerc_lift3' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_lift3=" . $value; else $query['where'][] = "`objects`.`commerc_lift3` = '" . $value . "'"; break; case 'lift3_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "lift3_carrying=" . $value; else $query['where'][] = "`objects`.`lift3_carrying` = '" . $value . "'"; break; case 'commerc_crane1' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_crane1=" . $value; else $query['where'][] = "`objects`.`commerc_crane1` = '" . $value . "'"; break; case 'crane1_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "crane1_carrying=" . $value; else $query['where'][] = "`objects`.`crane1_carrying` = '" . $value . "'"; break; case 'commerc_crane2' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_crane2=" . $value; else $query['where'][] = "`objects`.`commerc_crane2` = '" . $value . "'"; break; case 'crane2_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "crane2_carrying=" . $value; else $query['where'][] = "`objects`.`crane2_carrying` = '" . $value . "'"; break; case 'commerc_crane3' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_crane3=" . $value; else $query['where'][] = "`objects`.`commerc_crane3` = '" . $value . "'"; break; case 'crane3_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "crane3_carrying=" . $value; else $query['where'][] = "`objects`.`crane3_carrying` = '" . $value . "'"; break; case 'commerc_crane4' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_crane4=" . $value; else $query['where'][] = "`objects`.`commerc_crane4` = '" . $value . "'"; break; case 'crane4_carrying' : if (!$strict) break; if ($sphinx) $query['where'][] = "crane4_carrying=" . $value; else $query['where'][] = "`objects`.`crane4_carrying` = '" . $value . "'"; break; case 'commerc_houseline_type_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_houseLineType_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_houseLineType_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_opened_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_opened_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_opened_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_year_ot' : if (!$strict) break; if ($sphinx) $sql = "commerc_year>=" . $value; else $sql = "`objects`.`commerc_year` >= '" . $value . "'"; if ($value2 = $filter['commerc_year_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND commerc_year<=" . $value2; else $sql .= " AND `objects`.`commerc_year` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'commerc_year_do'; break; } $query['where'][] = $sql; break; case 'commerc_year_do' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_year<=" . $value; else $query['where'][] = "`objects`.`commerc_year` <= '" . $value . "'"; break; case 'commerc_purpose' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_purpose IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_purpose` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_building_type_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_type_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_building_type_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_building_class_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_class_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_building_class_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_land_category_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_land_category_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_land_category_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_permitted_use_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_permitted_use_id IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_permitted_use_id` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'commerc_specifications' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_specifications IN (" . implode(', ', json_decode($value)) . ")"; else $query['where'][] = "`objects`.`commerc_specifications` IN (" . implode(', ', json_decode($value)) . ")"; break; case 'building_area_ot' : if (!$strict) break; if ($sphinx) $sql = "building_area>=" . $value; else $sql = "`objects`.`building_area` >= '" . $value . "'"; if ($value2 = $filter['building_area_do']) { if ($fields[$key]['type'] == "number") $value2 = intval($value2); if ($sphinx) $sql .= " AND building_area<=" . $value2; else $sql .= " AND `objects`.`building_area` <= '" . $value2 . "'"; $query['where'][] = "(".$sql.")"; $proccessed[] = 'building_area_do'; break; } $query['where'][] = $sql; break; case 'building_area_do' : if (!$strict) break; if ($sphinx) $query['where'][] = "building_area<=" . $value; else $query['where'][] = "`objects`.`building_area` <= '" . $value . "'"; break; case 'commerc_building_category_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_category_id=" . $value; else $query['where'][] = "`objects`.`commerc_building_category_id` = '" . $value . "'"; break; case 'commerc_building_ventilation' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_ventilation=" . $value; else $query['where'][] = "`objects`.`commerc_building_ventilation` = '" . $value . "'"; break; case 'commerc_building_conditioning' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_conditioning=" . $value; else $query['where'][] = "`objects`.`commerc_building_conditioning` = '" . $value . "'"; break; case 'commerc_building_heating' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_heating=" . $value; else $query['where'][] = "`objects`.`commerc_building_heating` = '" . $value . "'"; break; case 'commerc_building_fire' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_building_fire=" . $value; else $query['where'][] = "`objects`.`commerc_building_fire` = '" . $value . "'"; break; case 'column_grid' : if (!$strict) break; if ($sphinx) $query['where'][] = "column_grid=" . $value; else $query['where'][] = "`objects`.`column_grid` = '" . $value . "'"; break; case 'garage_type_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "garage_type_id=" . $value; else $query['where'][] = "`objects`.`garage_type_id` = '" . $value . "'"; break; case 'garage_vid_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "garage_vid_id=" . $value; else $query['where'][] = "`objects`.`garage_vid_id` = '" . $value . "'"; break; case 'boks_vid_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "boks_vid_id=" . $value; else $query['where'][] = "`objects`.`boks_vid_id` = '" . $value . "'"; break; case 'commerc_status_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_status_id=" . $value; else $query['where'][] = "`objects`.`commerc_status_id` = '" . $value . "'"; break; case 'commerc_electricity_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_electricity_id=" . $value; else $query['where'][] = "`objects`.`commerc_electricity_id` = '" . $value . "'"; break; case 'can_electricity' : if (!$strict) break; if ($sphinx) $query['where'][] = "can_electricity=" . $value; else $query['where'][] = "`objects`.`can_electricity` = '" . $value . "'"; break; case 'commerc_gas_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_gas_id=" . $value; else $query['where'][] = "`objects`.`commerc_gas_id` = '" . $value . "'"; break; case 'can_gas' : if (!$strict) break; if ($sphinx) $query['where'][] = "can_gas=" . $value; else $query['where'][] = "`objects`.`can_gas` = '" . $value . "'"; break; case 'commerc_water_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_water_id=" . $value; else $query['where'][] = "`objects`.`commerc_water_id` = '" . $value . "'"; break; case 'can_water' : if (!$strict) break; if ($sphinx) $query['where'][] = "can_water=" . $value; else $query['where'][] = "`objects`.`can_water` = '" . $value . "'"; break; case 'commerc_sewage_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_sewage_id=" . $value; else $query['where'][] = "`objects`.`commerc_sewage_id` = '" . $value . "'"; break; case 'can_sewage' : if (!$strict) break; if ($sphinx) $query['where'][] = "can_sewage=" . $value; else $query['where'][] = "`objects`.`can_sewage` = '" . $value . "'"; break; case 'commerc_driveways_id' : if (!$strict) break; if ($sphinx) $query['where'][] = "commerc_driveways_id=" . $value; else $query['where'][] = "`objects`.`commerc_driveways_id` = '" . $value . "'"; break; case 'tax_number' : if (!$strict) break; if ($sphinx) $query['where'][] = "tax_number=" . $value; //$query['match'][] = "@tax_number ". $value; else $query['where'][] = "`objects`.`tax_number` = '" . $value . "'"; break; case 'commerc_infrastructure' : if (!$strict) break; $value = json_decode($value); if ($value2 = $filter['commerc_infrastructure1']) { $value = array_merge($value, json_decode($value2)); $proccessed[] = 'commerc_infrastructure1'; } if ($value3 = $filter['commerc_infrastructure2']) { $value = array_merge($value, json_decode($value3)); $proccessed[] = 'commerc_infrastructure2'; } if ($sphinx) $query['match'][] = "@commerc_infrastructure ". implode(' | ', $value); else $query['where'][] = "`objects`.`commerc_infrastructure` IN (" . implode(', ', $value) . ")"; break; case 'commerc_infrastructure1' : if (!$strict) break; if ($sphinx) $query['match'][] = "@commerc_infrastructure ". implode(' | ', json_decode($value)); else $query['where'][] = "`objects`.`commerc_infrastructure` IN (" . implode(', ', $value) . ")"; break; case 'commerc_infrastructure2' : if (!$strict) break; if ($sphinx) $query['match'][] = "@commerc_infrastructure ". implode(' | ', json_decode($value)); else $query['where'][] = "`objects`.`commerc_infrastructure` IN (" . implode(', ', $value) . ")"; break; case 'opis' : if (!$strict) break; $value = strip_tags($value); $value = str_replace("\r\n", ' ', $value); $value = preg_replace('/[^a-zA-Zа-яА-Я0-9 ]/ui', '', $value); if ($sphinx) { $query['match'][] = "@opis " . $value; } else { $words = explode(' ', $value); $query['where'][] = "(`objects`.`opis` LIKE '%$value%' OR `objects`.`opis` REGEXP '" . implode('|', $words) . "')"; } break; default: break; } } } if ($is_geo && !empty($geo_data)) { $usl_geo = []; $usl_geo2 = []; foreach ($geo_data as $poly) { if (!empty($poly)) { $usl_geo[] = "CONTAINS(GEOPOLY2D(" . $poly . "),latitude,longitude)"; $usl_geo2[] = "CONTAINS(POLYGON(" . $poly . "), POINT(latitude, longitude))"; } } if (!empty($usl_geo)) { if ($sphinx) { $query['select'][] = "IF((" . implode(" OR ", $usl_geo). "), 1, 0) AS geo"; $query['where'][] = "geo=1"; } else { $query['where'][] = "(" . implode(" OR ", $usl_geo2) . ")"; } } } $delimiter = ' AND '; /*if (!$strict ) $delimiter = ' OR ';*/ $sql = []; $sql['select'] = ""; if (count($query['select']) > 0) $sql['select'] = implode(", ", $query['select']) . " "; if (count($query['join']) > 0) { if (!isset($sql['join'])) $sql['join'] .= implode($delimiter, $query['join']); else $sql['join'] .= " " . implode($delimiter, $query['join']); } if (count($query['where']) > 0) { if (!isset($sql['where'])) $sql['where'] .= implode($delimiter, $query['where']); else $sql['where'] .= " AND " . implode($delimiter, $query['where']); } if (count($query['match']) > 0) { if (!isset($sql['where'])) $sql['where'] .= "MATCH('" . implode(' ', $query['match']) . "')"; else $sql['where'] .= " AND MATCH('" . implode(' ', $query['match']) . "')"; } return $sql; } return null; } public function getSearchQuery($filter = null, $offset = 0, $perpage = 100, $sphinx = true) { if (!empty($filter)) { $match_q = self::buildSearchQuery($filter, $sphinx, true); $similar_q = self::buildSearchQuery($filter, $sphinx, false); if (!empty($match_q) && !empty($similar_q)) { $ex_ids = []; $filter_id = $filter['id']; if ($sphinx) { $where_q = 'black=0 AND moder=0 AND '; } else { $where_q = '`objects`.`black` = 0 AND `objects`.`moder` = 0 AND '; } $exclude_q = ''; if ($res_prev = self::getMetaResults($filter_id)) { $ex_ids = array_merge( (count($res_prev['results']['match']) > 0) ? $res_prev['results']['match'] : [], (count($res_prev['results']['similar']) > 0) ? $res_prev['results']['similar'] : [], /*(count($res_prev['viewed']) > 0) ? $res_prev['viewed'] : [],*/ (count($res_prev['ignored']) > 0) ? $res_prev['ignored'] : [], (count($res_prev['favoured']) > 0) ? $res_prev['favoured'] : [], (count($res_prev['sended']) > 0) ? $res_prev['sended'] : [] ); $ex_ids = array_unique($ex_ids); if (count($ex_ids) > 0) { if ($sphinx) { // $ex_hash = array_flip($ex_ids); // $filtered_match = []; // foreach ($raw_match as $obj) { // if (!isset($ex_hash[$obj['id']])) { // $filtered_match[] = $obj; // if (count($filtered_match) >= $perpage) break; // } // } $exclude_q = 'AND id NOT IN (' . implode(',', $ex_ids) . ')'; } else { $exclude_q = 'AND `objects`.`id` NOT IN (' . implode(', ', $ex_ids) . ')'; } } } $limit = "LIMIT 1000"; if (!is_null($offset) && !is_null($perpage)) { $limit = "LIMIT $offset, $perpage"; } elseif (!is_null($offset) && is_null($perpage)) { $limit = "LIMIT $offset, 1000"; } if ($sphinx) $order = 'ORDER BY date_add DESC, ads_source DESC'; else $order = 'ORDER BY `objects`.`date_add` DESC'; if ($sphinx) { $sql_obj_match_count = "SELECT count(*) as total" .(!empty($match_q['select']) ? ', ' . $match_q['select'] : ''). " FROM objects, objects_delta " .(!empty($match_q['join']) ? $match_q['join'] : ''). " WHERE $where_q $match_q[where] $exclude_q OPTION max_matches=10000"; $sql_obj_similar_count = "SELECT count(*) as total" .(!empty($similar_q['select']) ? ', ' . $similar_q['select'] : ''). " FROM objects, objects_delta " .(!empty($similar_q['join']) ? $similar_q['join'] : ''). " WHERE $where_q $similar_q[where] $exclude_q OPTION max_matches=10000"; $sql_obj_match = "SELECT *" .(!empty($match_q['select']) ? ', ' . $match_q['select'] : ''). " FROM objects, objects_delta " .(!empty($match_q['join']) ? $match_q['join'] : ''). " WHERE $where_q $match_q[where] $exclude_q $order $limit OPTION max_matches=10000"; $sql_obj_similar = "SELECT *" .(!empty($similar_q['select']) ? ', ' . $similar_q['select'] : ''). " FROM objects, objects_delta " .(!empty($similar_q['join']) ? $similar_q['join'] : ''). " WHERE $where_q $similar_q[where] $exclude_q $order $limit OPTION max_matches=10000"; } else { $sql_obj_match_count = "SELECT COUNT(DISTINCT `objects`.`id`) as total" .(!empty($match_q['select']) ? ', ' . $match_q['select'] : ''). " FROM `objects` AS objects " .(!empty($match_q['join']) ? $match_q['join'] : ''). " WHERE $where_q $match_q[where] $exclude_q"; $sql_obj_similar_count = "SELECT count(*) as total" .(!empty($similar_q['select']) ? ', ' . $similar_q['select'] : ''). " FROM `objects` AS objects " .(!empty($similar_q['join']) ? $similar_q['join'] : ''). " WHERE $where_q $similar_q[where] $exclude_q"; $sql_obj_match = "SELECT *" .(!empty($match_q['select']) ? ', ' . $match_q['select'] : ''). " FROM `objects` AS objects " .(!empty($match_q['join']) ? $match_q['join'] : ''). " WHERE $where_q $match_q[where] $exclude_q $order $limit"; $sql_obj_similar = "SELECT *" . (!empty($similar_q['select']) ? ', ' . $similar_q['select'] : '') . " FROM `objects` AS objects " .(!empty($similar_q['join']) ? $similar_q['join'] : ''). " WHERE $where_q $similar_q[where] $exclude_q $order $limit"; } return [ 'success' => true, 'ex_ids' => $ex_ids, 'match_count' => trim(preg_replace('/\s\s+/', ' ', $sql_obj_match_count)), 'similar_count' => trim(preg_replace('/\s\s+/', ' ', $sql_obj_similar_count)), 'match' => trim(preg_replace('/\s\s+/', ' ', $sql_obj_match)), 'similar' => trim(preg_replace('/\s\s+/', ' ', $sql_obj_similar)), ]; } } return false; } private function getMetaResults($filter_id = null) { if (is_null($filter_id) || !$filter_id) return []; $sql = "SELECT match_ids, similar_ids, error, processed_at FROM `autosearch_results` WHERE filter_id='$filter_id' ORDER BY processed_at DESC LIMIT 1000"; $results = [ 'results' => [ 'match' => [], 'similar' => [] ], 'viewed' => [], 'ignored' => [], 'favoured' => [], 'sended' => [], 'error' => null ]; if ($res = mysql_query($sql)) { if (mysql_num_rows($res) > 0) { while ($row = mysql_fetch_assoc($res)) { if (!isset($results['processed_at'])) $results['processed_at'] = $row['processed_at']; if (!isset($results['error'])) $results['error'] = $row['error']; if (!empty($row['match_ids'])) { if ($match_ids = json_decode($row['match_ids'])) { $results['results']['match'] = array_unique(array_merge( (is_array($match_ids)) ? $match_ids : [], $results['results']['match'] )); } } if (!empty($row['similar_ids'])) { if ($similar_ids = json_decode($row['similar_ids'])) { $results['results']['similar'] = array_unique(array_merge( (is_array($similar_ids)) ? $similar_ids : [], $results['results']['similar'] )); } } } } $results['viewed'] = $this->getViewedObjects($filter_id); $results['ignored'] = $this->getIgnoredObjects($filter_id); $results['favoured'] = $this->getFavouredObjects($filter_id); $results['sended'] = $this->getSendedObjects($filter_id); } else { $results['error'] = mysql_error(); } return $results; } public function addObjectToFavour($filter_id = null, $object_id = null, $sphinx = true, $raw = false) { $gmtmsk = get_time_zone_user(); $time_zone = ''; if($gmtmsk >= 0){ $time_zone = '+'.$gmtmsk.' hour'; } else { $time_zone = '-'.$gmtmsk.' hour'; } if (is_null($filter_id) || is_null($object_id)) return false; $state = false; $favoured = $this->getFavouredObjects($filter_id); $favoured = array_unique($favoured); if (in_array($object_id, $favoured)) { $state = false; mysql_query("DELETE FROM `autosearch_favoured` WHERE filter_id='$filter_id' AND `object_id`='$object_id'"); if (($key = array_search(intval($object_id), $favoured)) !== false) { unset($favoured[$key]); } } else { $state = true; mysql_query("INSERT INTO `autosearch_favoured` (`filter_id`, `object_id`) VALUES ('$filter_id', '$object_id')"); $favoured[] = intval($object_id); } $db = $this->db; $hasError = false; $post = clearInputData($_POST); $get = clearInputData($_GET); list($objects, $total) = [[],[]]; $favoured = array_unique($favoured); if (count($favoured) > 0) { $sql_favoured = "SELECT * FROM objects WHERE id IN (" . implode(',', $favoured) . ") ORDER BY date_add DESC LIMIT {$this->favoured_limit}"; $user = new User; $user->get($_SESSION['id']); if ($query = mysql_query($sql_favoured)) { while ($obj = mysql_fetch_assoc($query)) { $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 = $obj[id] ORDER BY oop.sort_order"; $rezPhotoInfo = mysql_query($sqlPhotoInfo); if (mysql_num_rows($rezPhotoInfo) > 0) { while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) { $obj['photo' . $photoInfo['sort_order']] = $photoInfo['photo']; } } if ($raw) { ob_start(); $hasAutoSearchLayout = true; $use_advert_budget = ($_SESSION['use_advert_budget']); include ($_SERVER['DOCUMENT_ROOT'] . "/templates/system__object_new.php"); $item = ob_get_clean(); $objects['favoured'][$obj['id']] = $item; } else { $objects['favoured'][$obj['id']] = $obj; } $total['favoured']++; } } else { $hasError = true; } } if ($hasError) return ['error' => mysql_error()]; else return [ 'success' => true, 'total' => $total['favoured'], 'state' => $state, 'favoured' => $objects['favoured'], 'perpage' => 10, ]; } public function addObjectToIgnored($filter_id = null, $object_id = null) { if (is_null($filter_id) || is_null($object_id)) return false; $ignored = $this->getIgnoredObjects($filter_id); $ignored = array_unique($ignored); if (is_array($ignored)) { if (!is_null($object_id)) { $sql = "INSERT INTO `autosearch_ignored` (`filter_id`, `object_id`) VALUES ('$filter_id', '$object_id')"; if (!mysql_query($sql)) { return ['success' => false, 'error' => mysql_error()]; } else { mysql_query("DELETE FROM `autosearch_favoured` WHERE filter_id='$filter_id' AND `object_id`='$object_id'"); return ['success' => true]; } } else { return ['success' => false, 'error' => "Не указан ИД объекта."]; } } return ['success' => false, 'error' => "Ошибка обновления списка игнорируемых объектов"]; } public function addObjectToViewed($filter_id = null, $object_id = null) { if (is_null($filter_id) || is_null($object_id)) return false; $viewed = $this->getViewedObjects($filter_id); $viewed = array_unique($viewed); if (is_array($viewed)) { if (!in_array($object_id, $viewed)) { $sql = "INSERT INTO `autosearch_viewed` (`filter_id`, `object_id`) VALUES ('$filter_id', '$object_id')"; if (!mysql_query($sql)) return ['error' => mysql_error()]; else return ['success' => true]; } else { return ['success' => false]; } } return ['error' => "Ошибка обновления списка просмотренных объектов"]; } public function addObjectToSended($filter_id = null, $object_id = null) { if (is_null($filter_id) || is_null($object_id)) return false; $sended = $this->getSendedObjects($filter_id); $sended = array_unique($sended); if (is_array($sended)) { if (!in_array($object_id, $sended)) { $sql = "INSERT INTO `autosearch_sended` (`filter_id`, `object_id`) VALUES ('$filter_id', '$object_id')"; if (!mysql_query($sql)) return ['error' => mysql_error()]; else return ['success' => true]; } else { return ['success' => false]; } } return ['error' => "Ошибка обновления списка отправленных объектов"]; } public function clearAllResults($filter_id = null, $clean_up = false) { if (is_null($filter_id)) return false; if ($clean_up) return self::cleanUpResults($filter_id, true); else return true; } public function syncObjectToFilter($filter_id = null, $object_id = null, $req_id = null, $clean_up = false, $onlyRegionUpdate = false) { $errors = []; if (is_null($object_id)) return false; if ($clean_up && !is_null($filter_id)) self::cleanUpResults($filter_id, true); $sql = "SELECT `objects`.*, `location`.address, `location`.latitude, `location`.longitude, `location`.rf_region_rayon, (SELECT `id` FROM `rayon` WHERE `rayon` = ( SELECT rf_region_rayon FROM object_location WHERE object_id = `objects`.`id`) AND `rayon` != '') AS `region_rayon` FROM `objects` AS `objects` LEFT JOIN `object_location` AS `location` on `location`.`object_id` = `objects`.`id` WHERE `objects`.`id` = '$object_id' LIMIT 1"; if ($query = mysql_query($sql)) { if (mysql_num_fields($query)) { if ($object = mysql_fetch_assoc($query)) { $deal_type = null; if (isset($object['operation_type'])) { if (intval($object['operation_type']) == 0) $deal_type = 1; else if (intval($object['operation_type']) == 1) $deal_type = 2; } $price = null; if (isset($object['stoim'])) $price = intval($object['stoim']); if (!$price && isset($object['initial_object_stoim'])) $price = intval($object['initial_object_stoim']); $target = 3; $address = trim($object['adres']); if (!empty($object['address'])) $address = trim($object['address']); $region = null; if (intval($object['id_rf_region']) > 0) { $region = $object['id_rf_region']; $sql = "SELECT * FROM `rf_regions` WHERE ( `id` = '$object[id_rf_region]' OR `parent` = '$object[id_rf_region]' ) AND `parent` != 0"; if ($query = mysql_query($sql)) { if (mysql_num_rows($query) > 0) { while($row = mysql_fetch_assoc($query)) { if (strpos(trim($row['name']), $address) !== false) $region = $row['id']; if (strpos(trim(str_replace('область', 'обл', $row['name'])), $address) !== false) $region = $row['id']; } } } else { $errors[] = mysql_error(); } } if ((int)$region == 1) { // Москва, Московская обл if (strpos(trim($address), "Москва") !== false) $region = 80; else if (strpos(trim($address), "Московская обл") !== false) $region = 53; } else if ((int)$region == 2) { // Санкт-Петербург, Ленинградская область if (strpos( trim($address), "Санкт-Петербург") !== false) $region = 81; else if (strpos(trim($address), "Ленинградская обл") !== false) $region = 50; } else if ((int)$region == 3) { // Крым и Севастополь if (strpos( trim($address), "Республика Крым") !== false) $region = 94; else if (strpos( trim($address), "Крым") !== false) $region = 94; if (strpos(trim($address), "Севастополь") !== false) $region = 95; } $regions_arr = []; if (!in_array((int)$region, [80, 53, 81, 50, 94, 95]) && strlen((string)$region) <= 2) { $sql_regions = "SELECT * FROM `rf_regions` WHERE `parent`='$region'"; if ($query_regions = mysql_query($sql_regions)) { if (mysql_num_rows($query_regions) > 0) { $regions_arr[] = (int)$region; while($row = mysql_fetch_assoc($query_regions)) { $regions_arr[] = (int)$row['id']; } } } else { $errors[] = mysql_error(); } } if (!empty($regions_arr)) $regions_arr = array_map('strval', $regions_arr); $rayon = null; if (intval($object['rayon']) > 0) $rayon = intval($object['rayon']); if (empty($rayon) && intval($object['region_rayon']) > 0) $rayon = trim($object['region_rayon']); if ($onlyRegionUpdate && (intval($filter_id) && intval($req_id))) { if (intval($req_id)) $params = $this->getFilterByReq(intval($req_id), (int)$_SESSION['id']); else $params = $this->getFilter(intval($filter_id), (int)$_SESSION['id']); $params['regions'] = ($region) ? (!empty($regions_arr) ? json_encode($regions_arr) : json_encode([(string)$region])) : null; $params['rayons'] = ($rayon) ? json_encode([(string)$rayon]) : null; $params['comment'] .= " Обновлен регион/район (".date('d.m.Y в H:i:s').")."; } else { $params = [ 'deal_type' => $deal_type, 'object_type' => intval($object['type']), 'category_type' => isset($object['type_category']) ? intval($object['type_category']) : null, 'object_source' => $target, 'regions' => ($region) ? (!empty($regions_arr) ? json_encode($regions_arr) : json_encode([(string)$region])) : null, 'rayons' => ($rayon) ? json_encode([(string)$rayon]) : null, 'rent_srok' => isset($object['srok']) ? intval($object['srok']) : null, 'stoim_ot' => ($price > 0) ? round($price - ($price / 100 * 10)) : null, 'stoim_do' => ($price > 0) ? round($price + ($price / 100 * 10)) : null, 'komn_ot' => isset($object['komnat']) ? intval($object['komnat']) : null, 'komn_do' => isset($object['komnat']) ? intval($object['komnat']) : null, 'rooms' => (isset($object['komnat']) && $object['komnat']) ? [$object['komnat']] : null, 'is_active' => 1, 'req_id' => intval($req_id), 'comment' => "Автоматический фильтр для Заявки «Спрос по нашему объекту» (".date('d.m.Y в H:i:s').").", ]; } $results = $this->addEditFilter($filter_id, $params, !(intval($req_id) > 0), true); if ($results['success']) { $filter_id = intval($results['id']); } else { $errors[] = $results['error']; } } } } else { $errors[] = mysql_error(); } return [ 'success' => (count($errors) == 0), 'filter_id' => $filter_id, 'sql' => $results['sql'], 'errors' => $errors, ]; } public function getSummaryResults($filter_id = null, $offset = null, $order = null, $perpage = null, $sphinx = true, $raw = false) { if ($match = $this->getResults($filter_id, 'match', $offset, $order, $perpage, $sphinx, $raw)) { $this->_filter['count'] += intval($match['count']); $this->_filter['total'] += intval($match['total']); if ($match['error'] !== $this->_filter['error']) $this->_filter['error'] .= (!empty($this->_filter['error']) ? " " : '') . $match['error']; } if ($similar = $this->getResults($filter_id, 'similar', $offset, $order, $perpage, $sphinx, $raw)) { $this->_filter['count'] += intval($similar['count']); $this->_filter['total'] += intval($similar['total']); if ($similar['error'] !== $this->_filter['error']) $this->_filter['error'] .= (!empty($this->_filter['error']) ? " " : '') . $similar['error']; } if (empty($this->_filter['error'])) $this->_filter['error'] = null; } public function buildTelegramMessage($results = null, $user_id = null, $max_objects = 5) { if (count($results) > 0 && !is_null($user_id)) { $message = ''; foreach ($results as $filter_id => $result) { if (isset($_GET['dev'])) { echo "
" . var_export([
'user_id' => (int)$user_id,
'who_work' => (int)$result['who_work'],
'filter_id' =>(int)$filter_id,
'asfilter_id' => (int)$result['filter_id'],
'telegram_notify' => (int)$result['telegram_notify'],
'try_to_build' => (intval($result['telegram_notify']) == 1 && ((int)$result['filter_id'] == (int)$filter_id) && ((int)$result['who_work'] == (int)$user_id)),
], true) . "";
}
if (intval($result['telegram_notify']) == 1 && (int)(int)$result['who_work'] == (int)$user_id) {
if (isset($_GET['dev'])) {
echo "+$result[match_count], вот некоторые из них:"."\n";
$count = 0;
foreach ($result['objects']['match'] as $object) {
if ($count >= $max_objects)
break;
switch ($object['operation_type']) {
case 0 :
$message .= '- объект аренды';
break;
case 1 :
$message .= '- объект продажи';
break;
case 2 :
$message .= '- объект в новостройке';
break;
}
$token = md5($object['id'].time().$user_id);
$sql_token = "INSERT INTO object_view_autosarch (object_id, user_id, token) VALUES ({$object['id']}, {$user_id}, '{$token}')";
//file_put_contents(__DIR__.'/log_obj.txt', $sql_token. "\n", FILE_APPEND);
mysql_query($sql_token);
//$message .= ' ' . $object['nazv'] . ' (ID: ' . $object['id'] . ')';
$message .= ' ' . $object['nazv'] . ' (ID: ' . $object['id'] . ')';
if (!empty($object['stoim']))
$message .= ' стоимостью ' . number_format($object['stoim'], 0, ',', ' ') . ' руб.';
if (!empty($object['adres']))
$message .= ' расположенный по адресу: ' . $object['adres'];
if (!empty($object['sobstv']) || !empty($object['phone']))
$message .= '. Контакты: ' . (!empty($object['sobstv']) ? $object['sobstv'] : "") .
(
(!empty($object['sobstv']) && !empty($object['phone'])) ? ", " . ''.$object['phone'].'' :
(!empty($object['phone']) ? ''.$object['phone'].'' : "")
);
$message .= "\n\n";
$count++;
}
} else {
$message .= "Нет точно соответствующих критериям поиска объектов."."\n\n";
}
// if (count($result['objects']['similar']) > 0) {
// $message .= "Подобные варианты +$result[similar_count], вот некоторые из них:"."\n";
// $count = 0;
// foreach ($result['objects']['similar'] as $object) {
// if ($count >= $max_objects)
// break;
// switch ($object['operation_type']) {
// case 0 :
// $message .= '- объект аренды';
// break;
// case 1 :
// $message .= '- объект продажи';
// break;
// case 2 :
// $message .= '- объект в новостройке';
// break;
// }
// $message .= ' ' . $object['nazv'] . ' (ID: ' . $object['id'] . ')';
// if (!empty($object['stoim']))
// $message .= ' стоимостью ' . number_format($object['stoim'], 0, ',', ' ') . ' руб.';
// if (!empty($object['adres']))
// $message .= ' расположенный по адресу: ' . $object['adres'];
// if (!empty($object['sobstv']) || !empty($object['phone']))
// $message .= '. Контакты: ' . (!empty($object['sobstv']) ? $object['sobstv'] : "") .
// (
// (!empty($object['sobstv']) && !empty($object['phone'])) ? ", " . ''.$object['phone'].'' :
// (!empty($object['phone']) ? ''.$object['phone'].'' : "")
// );
// $message .= "\n\n";
// $count++;
// }
// } else {
// $message .= "Подобных вариантов нет."."\n\n";
// }
}
}
}
if (!empty($message))
return $message."\n\n";
else
return false;
}
return false;
}
public function getSummaryInfo($agent_id = null, $only_active = false, $telegram_notify = false) {
if (!is_null($agent_id)) {
$sql = "SELECT `filters`.*,
`filters`.`telegram_notify` AS `telegram_notify`,
`results`.*,
`req`.`name` AS `req`,
`req`.`type_id` AS `req_type_id`,
`req`.`asfilter_id` AS `asfilter_id`,
`req`.`who_work` AS `who_work`,
`client`.`fio` AS `client_fio`,
`client`.`id` AS `client_id`,
`client`.`phone` AS `client_phone`,
`client`.`email` AS `client_email`,
DATE_FORMAT(`filters`.`newbilding_date`, '%d.%m.%Y %H:%i') as newbilding_date,
DATE_FORMAT(`filters`.`build_year`, '%Y') as build_year
FROM `autosearch_filters` AS `filters`
LEFT JOIN `autosearch_results` AS `results` ON `results`.`filter_id` = `filters`.`id`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id`
LEFT JOIN `clients` AS `client` ON `client`.`id` = `req`.`client_id`
WHERE (`filters`.`created_by` = '$agent_id' OR `filters`.`updated_by` = '$agent_id') ";
if ($only_active)
$sql .= " AND `is_active` = '1'";
if ($telegram_notify)
$sql .= " AND `telegram_notify` = '1'";
$sql .= " ORDER BY `results`.`processed_at` DESC";
$query = mysql_query($sql);
$summary = [];
if (mysql_num_rows($query)) {
while($filter = mysql_fetch_assoc($query)) {
$info = [];
$info['filter_id'] = $filter['id'];
$info['req_id'] = $filter['req_id'];
$info['req'] = $filter['req'];
$info['client_id'] = $filter['client_id'];
$info['client'] = [
'fio' => $filter['client_fio'],
'phone' => $filter['client_phone'],
'email' => $filter['client_email'],
];
$count_match = 0;
$count_similar = 0;
$objects = [];
if ($results = self::getResults($filter['id'], 'match', 0, 1000, true, false)) {
foreach($results['results'] as $obj) {
if (!in_array($obj['id'], $results['viewed'])) {
$objects['match'][] = $obj;
$count_match++;
}
}
}
if ($results = self::getResults($filter['id'], 'similar', 0, 1000, true, false)) {
foreach($results['results'] as $obj) {
if (!in_array($obj['id'], $results['viewed'])) {
$objects['similar'][] = $obj;
$count_similar++;
}
}
}
$info['match_count'] = $count_match;
$info['similar_count'] = $count_similar;
$info['objects'] = $objects;
$summary[] = $info;
}
}
return $summary;
}
return false;
}
public function getResults($filter_id = null, $section = null, $offset = null, $sort_order = null, $perpage = null, $sphinx = true, $raw = false) {
$gmtmsk = get_time_zone_user();
$time_zone = '';
if($gmtmsk >= 0){
$time_zone = '+'.$gmtmsk.' hour';
} else {
$time_zone = '-'.$gmtmsk.' hour';
}
if (!$this->enabled) {
return [
'results' => [],
'count' => 0,
'total' => 0,
'perpage' => intval($perpage),
'error' => 'Авто (-реверсивный) поиск выключены!',
'viewed' => [],
'ignored' => [],
'favoured' => [],
'sended' => []
];
}
if (is_null($filter_id))
return false;
if (is_null($section))
$section = 'match';
$ids = [];
$error = '';
$objects = [];
$meta = self::getMetaResults(intval($filter_id));
$favoured_ids = array_unique(array_map('intval', $meta['favoured']));
$viewed_ids = array_unique(array_map('intval', $meta['viewed']));
$sended_ids = array_unique(array_map('intval', $meta['sended']));
$ignored_ids = array_unique(array_map('intval', $meta['ignored']));
if (isset($meta['error']))
$error = $meta['error'];
switch($section) {
case 'match' :
$ids = array_diff(array_unique(array_map('intval', $meta['results']['match'])), $ignored_ids);
break;
case 'similar' :
$ids = array_diff(array_unique(array_map('intval', $meta['results']['similar'])), $ignored_ids);
break;
case 'favoured' :
//$ids = $favoured_ids;
$ids = array_diff(array_map('intval', $favoured_ids), array_map('intval', $ignored_ids));
break;
case 'sended' :
$ids = $sended_ids;
break;
default :
return false;
}
$ids = array_unique(array_map('intval', $ids));
$total = 0;
if (!is_null($this->_user) && !$this->_user->can('autosearch')) {
$error = 'У вас недостаточно прав для выполнения этой операции.';
} else {
if (count($ids) > 0) {
$where = [];
$order = [];
if ($sphinx) {
if (!is_null($sort_order) && is_array($sort_order)) {
if ($sort_order['company']) {
$agency_id = User::getUserAgencyID();
$usersIds = User::getAllAgencyUsers($agency_id);
if (empty($usersIds))
$usersIds = [$_SESSION['id']];
$where[] = "AND id_add_user IN (".implode(',', $usersIds).")";
$order[] = 'id_add_user DESC';
}
if ($sort_order['price']) {
$order[] = 'stoim ASC';
}
if ($sort_order['with_commission']) {
$where[] = 'AND commission > 0';
}
if ($sort_order['with_photo']) {
$where[] = 'AND is_photo = 1';
}
}
if (count($order) == 0) {
$order[] = 'date_add DESC, ads_source DESC';
$total = count($ids);
}
} else {
if (!is_null($sort_order) && is_array($sort_order)) {
if ($sort_order['company']) {
$agency_id = User::getUserAgencyID();
$usersIds = User::getAllAgencyUsers($agency_id);
$where[] = "AND `objects`.`id_add_user` IN (".implode(',', $usersIds).")";
$order[] = '`objects`.`id_add_user` DESC';
}
if ($sort_order['price']) {
$order[] = 'AND `objects`.`stoim` ASC';
}
if ($sort_order['with_commission']) {
$where[] = 'AND `objects`.`commission` > 0';
}
if ($sort_order['with_photo']) {
$photos = [];
for ($i = 1; $i <= 20; $i++) {
$photos[] = "`objects`.`photo$i` <> ''";
}
$where[] = "AND (" . implode(" OR ", $photos) . ")";
}
}
if (count($order) == 0) {
$order[] = '`objects`.`date_add` DESC, `ads_objects`.`ads_source` DESC';
$total = count($ids);
}
}
if ($sort_order['not_viewed']) {
$ids = array_diff($ids, $viewed_ids);
}
if ($sort_order['not_sended']) {
$ids = array_diff($ids, $sended_ids);
}
//$where[] = " AND is_advert_enabled_or_rscan = 1";
if ($sphinx)
$sql_objects_count = "SELECT count(*) as total FROM objects, objects_delta";
else
$sql_objects_count = "SELECT count(DISTINCT id) as total FROM objects";
$sql_objects_count .= " WHERE id IN (" . implode(',', $ids) . ")
" . implode(' ', $where);
if ($sphinx)
$sql_objects_count .= " OPTION max_matches=1000000";
$new_total = 0;
$sql_objects_count = trim(preg_replace('/\s\s+/', ' ', $sql_objects_count));
if ($query = $this->db->query($sql_objects_count)) {
$res = $this->db->fetch_assoc($query);
$new_total = intval($res['total']);
}
$limit = "LIMIT 1000";
if (!is_null($offset) && !is_null($perpage)) {
$limit = "LIMIT ".intval($offset).", ".intval($perpage);
}
if ($sphinx)
$sql_objects = "SELECT * FROM objects, objects_delta";
else
$sql_objects = "SELECT * FROM objects";
$sql_objects .= " WHERE id IN (" . implode(',', $ids) . ")
" . implode(' ', $where) . "
ORDER BY " . implode(', ', $order) . "
$limit";
if ($sphinx)
$sql_objects .= " OPTION max_matches=1000000";
$sql_objects = trim(preg_replace('/\s\s+/', ' ', $sql_objects));
if ($new_total && ($query = $this->db->query($sql_objects, true))) {
if (true || $new_total > 0) {
if ($total == 0)
$total = $new_total;
while ($obj = $this->db->fetch_assoc($query)) {
$sql_photo = "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 = $obj[id]
ORDER BY oop.sort_order";
$rezPhotoInfo = mysql_query($sql_photo);
if (mysql_num_rows($rezPhotoInfo) > 0) {
while ($photoInfo = mysql_fetch_assoc($rezPhotoInfo)) {
$obj['photo' . $photoInfo['sort_order']] = $photoInfo['photo'];
}
}
$obj_id = (string)$obj['id'];
if ($raw) {
ob_start();
if (!isset($user) || is_null($user))
$user = $this->_user;
global $SROK_ARENDY;
$hasAutoSearchLayout = true;
$use_advert_budget = ($_SESSION['use_advert_budget']);
include ($_SERVER['DOCUMENT_ROOT'] . "/templates/system__object_new.php");
$item = ob_get_clean();
$objects[$obj_id] = $item;
} else {
$objects[] = $obj_id;
}
}
} else {
$total = 0;
$error = "Нет объектов доступных для отображения.";
}
} else {
$total = 0;
}
} else {
$total = 0;
//$error = "Нет объектов доступных для отображения.";
}
}
return [
'ids' => !empty($ids) ? array_map('intval', $ids) : null,
'results' => $objects,
'count' => !empty($ids) ? count(array_diff($ids, $viewed_ids)) : 0,
'total' => $total,
'perpage' => intval($perpage),
'error' => (!empty($error) ? $error : (!empty($meta['error']) ? $meta['error'] : null)),
'sql' => (!empty($sql_objects) ? $sql_objects : null),
'viewed' => $viewed_ids,
'ignored' => $ignored_ids,
'favoured' => $favoured_ids,
'sended' => $sended_ids
];
}
public function reverseSearch($object_or_id = null, $offset = 0, $perpage = 25, $only_active = true, $only_count = true, $all_agency = true, $strict = true) {
$agents_ids = \User::getAllAgencyUsers();
$currentUserId = $_SESSION['id'];
session_write_close();
if (!$this->enabled) {
return [
'requisitions' => [],
'total' => 0,
'time' => "0s.",
'error' => 'Авто (-реверсивный) поиск выключены!',
];
}
$errors = [];
$object = null;
$start = microtime(true);
$fields = self::getFields(true);
if (!is_array($object_or_id)) {
$object_id = $object_or_id;
$sql = "SELECT `objects`.*,
(SELECT id_metro FROM sp_metro WHERE id_obj = `objects`.`id` LIMIT 1) AS `id_metro`,
(SELECT address FROM object_location WHERE object_id = `objects`.`id` LIMIT 1) AS `address`,
(SELECT latitude FROM object_location WHERE object_id = `objects`.`id` LIMIT 1) AS `latitude`,
(SELECT longitude FROM object_location WHERE object_id = `objects`.`id` LIMIT 1) AS `longitude`
FROM `objects`
WHERE `id` = '$object_id' LIMIT 1";
if ($query = mysql_query($sql)) {
if (mysql_num_fields($query))
$object = mysql_fetch_assoc($query);
}
} else {
$object = $object_or_id;
}
$requisitions = [];
if (!is_array($object)) {
return [
'requisitions' => [],
'total' => 0,
'time' => round((microtime(true) - $start), 2) . "s.",
'error' => 'Ошибка получения объекта к сравнению',
];
} else {
$object_id = $object['id'];
$sql_lazy = "SELECT `req`.`id`
FROM `autosearch_filters` AS `filters`
LEFT JOIN `autosearch_results` AS `results` ON `results`.`filter_id` = `filters`.`id`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id`
LEFT JOIN `requisitions_type` AS `type` ON `req`.`type_id` = `type`.`id`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `req`.`client_id`
WHERE `results`.`match_ids` LIKE CONCAT('%\"', '$object_id', '\"%') AND
`filters`.`is_reverse` = '1' AND
`filters`.`created_by` IN (" .implode(',', $agents_ids). ") AND `req`.`cancel` != 1 AND `req`.`deleted` != 1 AND (`type`.`id` IN (1, 4) OR `type`.`parent_id` IN (1, 4))
GROUP BY `req`.`id` LIMIT 1000;";
//var_export($sql_lazy) && die();
if ($query = mysql_query($sql_lazy)) {
if (mysql_num_rows($query)) {
while ($filter = mysql_fetch_assoc($query)) {
$requisitions[] = $filter['id'];
}
}
}
}
if ($object['type'] != 4 && $object['type_category'] != 0) // Fix: убираем тип коммерции для не коммерческой недвижимости
$object['type_category'] = 0;
if ($object['operation_type'] != 0 && $object['srok'] != 0) // Fix: убираем срок аренды для не арендных объектов
$object['srok'] = 0;
list($where, $join) = [[],[]];
foreach ($object as $prop => $value) {
$prop = trim($prop);
if (isset($fields[$prop]) && !empty($value) && $value != 0) {
if ($fields[$prop]['reverse_search']) {
if ($column = trim($fields[$prop]['column'])) {
if ($prop == 'operation_type')
continue;
if ($prop == 'type')
continue;
if ($prop == 'type_category')
continue;
switch ($column) {
case 'deal_type' :
case 'object_type' :
case 'category_type' :
case 'stoim' :
//case 'komn' :
case 'sq_all' :
case 'ploshad_k' :
case 'etazh' :
case 'el_power' :
case 'ceiling_height' :
case 'commerc_year' :
case 'building_area' :
$where[] = "((
`filters`.`".$column."_ot` IS NULL OR (`objects`.`$prop` != 0 AND `objects`.`$prop` >= `filters`.`".$column."_ot`)
) AND (
`filters`.`".$column."_do` IS NULL OR (`objects`.`$prop` != 0 AND `objects`.`$prop` <= `filters`.`".$column."_do`)
))";
break;
case 'do_metro' :
case 'do_metro_type' :
$where[] = "((`filters`.`geo` IS NULL AND (
`filters`.`do_metro` IS NULL OR (
(`objects`.`peshkom` <= `filters`.`do_metro` AND `filters`.`do_metro_type` = 1) OR
(`objects`.`transport` <= `filters`.`do_metro` AND `filters`.`do_metro_type` = 2)
)
)) OR `filters`.`geo` IS NOT NULL)";
break;
case 'metro_stations' :
if (!empty($value)) {
if ($object['rayon'] == 0)
$where[] = "((`filters`.`geo` IS NULL AND `filters`.`metro_stations` LIKE '%\"$value\"%') OR `filters`.`geo` IS NOT NULL)";
else
$where[] = "((`filters`.`geo` IS NULL AND (`filters`.`metro_stations` IS NULL OR `filters`.`metro_stations` LIKE '%\"$value\"%')) OR `filters`.`geo` IS NOT NULL)";
} else {
$where[] = "((`filters`.`geo` IS NULL AND `filters`.`metro_stations` LIKE CONCAT('%\"', `sp_metro`.`id_metro`, '\"%')) OR `filters`.`geo` IS NOT NULL)";
$join[] = "JOIN `sp_metro` AS `sp_metro` ON `sp_metro`.`id_obj` = `objects`.`id`";
}
break;
case 'regions' :
// Исключаем регион, если указана конкретная станция метро
if (isset($object['id_metro']))
break;
if (empty($object['address']))
$object['address'] = $object['adres'];
$region_id = null;
if ($object['id_rf_region'] == 1 || $object['id_rf_region'] == 2) {
if (!is_bool(strpos($object['address'], "Ленинградская обл")))
$region_id = 50; // Ленинградская область
else if (!is_bool(strpos($object['address'], "Санкт-Петербург")))
$region_id = 81; // Санкт-Петербург
else if (!is_bool(strpos($object['address'], "Санкт Петербург")))
$region_id = 81; // Санкт Петербург
else if (!is_bool(strpos($object['address'], "Московская обл")))
$region_id = 53; // Московская обл
else if (!is_bool(strpos($object['address'], "Москва")))
$region_id = 80; // Москва
if ($region_id)
$where[] = "(`filters`.`regions` IS NULL OR `filters`.`$column` LIKE '%\"$region_id\"%')";
} else {
$sql = "SELECT id, parent FROM rf_regions WHERE id=$object[id_rf_region] OR parent=$object[id_rf_region]";
$query = mysql_query($sql);
$regions = [];
while ($region = mysql_fetch_assoc($query)) {
if ($region['id'])
$regions[] = $region['id'];
if ($region['parent'])
$regions[] = $region['parent'];
}
$_where = [];
$regions = array_unique($regions);
foreach ($regions as $region) {
$_where[] = "`filters`.`$column` LIKE '%\"$region\"%'";
}
if (!empty($_where))
$where[] = "(`filters`.`regions` IS NULL OR (".implode(' OR ', $_where)."))";
}
// Только заявки автопоиска без указания станции метро
if (!isset($object['id_metro']))
$where[] = "(`filters`.`metro_stations` IS NULL)";
break;
case 'rayons' :
$where[] = "((`filters`.`geo` IS NULL AND (`filters`.`rayons` IS NULL OR `filters`.`$column` LIKE '%\"$value\"%')) OR `filters`.`geo` IS NOT NULL)";
break;
case 'opis' :
$where[] = "(`filters`.`opis` IS NULL OR `objects`.`opis` LIKE CONCAT('%"', `filters`.`opis`, '"%'))";
break;
default :
if ($fields[$prop]['multiple'])
$where[] = "(`filters`.`$column` IS NULL OR `filters`.`$column` LIKE CONCAT('%\"', `objects`.`$prop`, '\"%'))";
else
$where[] = "(`filters`.`$column` IS NULL OR `objects`.`$prop` = `filters`.`$column`)";
break;
}
}
}
} else {
$errors[] = 'Параметр `'.$prop.'` не найден в коллекции параметров автопоиска.';
}
}
$rooms_where = [];
if (!empty($object['komnat'])) {
if ((int)$object['komnat'] >= 1 && (int)$object['komnat'] <= 3)
$rooms_where[] = "`filters`.`rooms` LIKE '%\"$object[komnat]\"%'";
else if ((int)$object['komnat'] >= 4)
$rooms_where[] = "`filters`.`rooms` LIKE '%\"4\"%'";
}
if (isset($object['studio_flag'])) {
if (intval($object['studio_flag'] == 1)) {
$rooms_where[] = "`filters`.`rooms` LIKE '%\"5\"%'";
}
}
if (!empty($rooms_where)) {
$where[] = "(`filters`.`rooms` IS NULL OR `filters`.`rooms` = '[]' OR (".implode(' OR ', $rooms_where)."))";
}
if (!empty($object['latitude']) && !empty($object['longitude'])) {
$join[] = "JOIN `object_location` AS `location` ON `location`.`object_id` = `objects`.`id`";
$where[] = "(`filters`.`geo` IS NULL OR (
JSON_VALID(`filters`.`geo`) AND (
ST_CONTAINS(ST_PolygonFromText(CONCAT('POLYGON(( ', REPLACE(JSON_EXTRACT(`filters`.`geo`, '$.poly1[0]'), '\"', ''), ' ))')), POINT(`location`.`latitude`, `location`.`longitude`)) OR
ST_CONTAINS(ST_PolygonFromText(CONCAT('POLYGON(( ', REPLACE(JSON_EXTRACT(`filters`.`geo`, '$.poly2[0]'), '\"', ''), ' ))')), POINT(`location`.`latitude`, `location`.`longitude`)) OR
ST_CONTAINS(ST_PolygonFromText(CONCAT('POLYGON(( ', REPLACE(JSON_EXTRACT(`filters`.`geo`, '$.poly3[0]'), '\"', ''), ' ))')), POINT(`location`.`latitude`, `location`.`longitude`)) OR
ST_CONTAINS(ST_PolygonFromText(CONCAT('POLYGON(( ', REPLACE(JSON_EXTRACT(`filters`.`geo`, '$.poly4[0]'), '\"', ''), ' ))')), POINT(`location`.`latitude`, `location`.`longitude`))
)
))";
}
$sql = '';
$time = 0;
$total = 0;
//$total = count($requisitions);
if (count($where) > 0) {
$select_count = "SELECT COUNT(`req`.`id`) ";
$select = "SELECT `req`.`id` ";
$sql = "FROM `autosearch_filters` AS `filters`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id`
LEFT JOIN `requisitions_type` AS `type` ON `req`.`type_id` = `type`.`id`
LEFT JOIN `clients` AS `clients` ON `clients`.`id` = `req`.`client_id`
JOIN `objects` AS `objects` " . implode(' ', $join) . "
WHERE `req`.`cancel` != 1 AND `req`.`deleted` != 1 ";
$sql .= " AND (`type`.`id` IN (1, 4) OR `type`.`parent_id` IN (1, 4))";
if ($strict)
$sql .= " AND (" . implode(' AND ', $where) . ")";
else
$sql .= " AND (" . implode(' OR ', $where) . ")";
$deal_type = 0;
if ($object['operation_type'] == 0)
$deal_type = 1;
else if ($object['operation_type'] == 1)
$deal_type = 2;
else if ($object['operation_type'] == 3)
$deal_type = 3;
if ($deal_type)
$sql .= " AND `filters`.`deal_type` = '$deal_type'";
if ($object['type'])
$sql .= " AND `filters`.`object_type` = '$object[type]'";
if ($object['type_category'])
$sql .= " AND `filters`.`category_type` = '$object[type_category]'";
$user_id = $_SESSION['id'];
if ($all_agency) {
$agency_id = User::getUserAgencyID($currentUserId);
$usersIds = User::getAllAgencyUsers($agency_id);
$sql .= " AND (`filters`.`created_by` IN (" . implode(', ', $usersIds) . ") OR `filters`.`updated_by` IN (" . implode(', ', $usersIds) . "))";
} else {
$sql .= " AND (`filters`.`created_by` = '$user_id' OR `filters`.`updated_by` = '$user_id')";
}
if ($only_active)
$sql .= " AND `filters`.`is_active` = '1'";
$sql .= " AND `req`.`deleted` <> '1' AND `objects`.`id` = '$object[id]'";
$group = " GROUP BY `req`.`id`";
$order = " ORDER BY `req`.`created_at` DESC, `filters`.`created_by` ASC, `filters`.`updated_by` ASC, `filters`.`created_by` DESC";
$limit = " LIMIT 1000";
if (!is_null($offset) && !is_null($perpage)) {
$limit = " LIMIT $offset, $perpage";
}
$sql_count = $select_count . $sql . $group;
$sql_match = $select . $sql . $group . $order . $limit;
$total += mysql_num_rows(mysql_query($sql_count));
$sql_watched_count = "SELECT COUNT(req.id)
FROM watched_requisitions AS watched
LEFT JOIN requisitions AS req ON req.id = watched.req_id
WHERE watched.object_id = '$object[id]'
AND watched.watched = 1
AND watched.user_id = $user_id";
$result = mysql_query($sql_watched_count);
$watched_count = mysql_result($result, 0);
$has_items = false;
if ($total > 0) {
$has_items = true;
}
if ($only_count) {
return [
'total' => $total - $watched_count,
'time' => round((microtime(true) - $start), 2) . "s.",
'sql' => (in_array($_SESSION['id'], [4, 6635, 5427])) ? str_replace(["\n","\t","\r"], "", $sql_match) : null,
'sql_count' => (in_array($_SESSION['id'], [4, 6635, 5427])) ? str_replace(["\n","\t","\r"], "", $sql_count) : null,
'object' => $object,
'has_items' => $has_items,
];
}
$query = mysql_query($sql_match);
if (mysql_num_rows($query)) {
while ($filter = mysql_fetch_assoc($query)) {
$requisitions[] = $filter['id'];
}
}
} else {
$errors[] = 'Ошибка составления запроса сравнения';
}
return [
'requisitions' => $requisitions,
'sql' => (in_array($_SESSION['id'], [4, 6635, 5427, 13596])) ? str_replace(["\n","\t","\r"], "", $sql_match) : null,
'sql_count' => (in_array($_SESSION['id'], [4, 6635, 5427, 13596])) ? str_replace(["\n","\t","\r"], "", $sql_count) : null,
//'error' => null,
'offset' => $offset,
'perpage' => $perpage,
'time' => round((microtime(true) - $start), 2) . "s.",
'total' => $total,
'errors' => $errors
];
}
public function search($filter_id = null, $offset = 0, $perpage = null, $sphinx = true) {
if (!$this->enabled) {
$info = [];
if ($filter = self::getFilter($filter_id, null, true, false)) {
$info = [
'filter_id' => $filter['id'],
'req_id' => $filter['req_id'],
'who_work' => $filter['who_work'],
'req' => $filter['req'],
'telegram_notify' => (int)$filter['telegram_notify'],
'client_id' => $filter['client_id'],
'created_by' => $filter['created_by'],
'updated_by' => $filter['updated_by'],
'client' => [
'fio' => $filter['client_fio'],
'phone' => $filter['client_phone'],
'email' => $filter['client_email'],
],
];
}
return array_merge($info, [
'count' => 0,
'match_count' => 0,
'similar_count' => 0,
'total' => 0,
'objects' => [],
'time' => 0,
'error' => 'Авто (-реверсивный) поиск выключены!'
]);
}
$info = [];
$error = '';
$start = microtime(true);
///
list($total, $count) = [ 0,0 ];
# #
// // //
list($ids, $results) = [[],[]];//\\//\\
// // // //
if (!is_null($this->_user) && !$this->_user->can('autosearch')) {
$error = 'У вас недостаточно прав для выполнения этой операции.';
} else {
if (!(is_null($filter_id) || !$filter_id)) {
// Очистим старые результаты и сервисные записи
self::cleanUpResults($filter_id);
if ($filter = self::getFilter($filter_id, null, true, false)) {
$info = [
'filter_id' => $filter['id'],
'req_id' => $filter['req_id'],
'who_work' => $filter['who_work'],
'req' => $filter['req'],
'telegram_notify' => (int)$filter['telegram_notify'],
'client_id' => $filter['client_id'],
'created_by' => $filter['created_by'],
'updated_by' => $filter['updated_by'],
'client' => [
'fio' => $filter['client_fio'],
'phone' => $filter['client_phone'],
'email' => $filter['client_email'],
],
];
$sqls = self::getSearchQuery($filter, $offset, $perpage, $sphinx);
if ($sqls['success']) {
$ex_ids = $sqls['ex_ids'] || [];
$sql_obj_match_count = $sqls['match_count'];
$info['sql']['match_count'] = $sql_obj_match_count;
if ($res_query = $this->db->query($sql_obj_match_count)) {
$res_count = $this->db->fetch_assoc($res_query);
$total += intval($res_count['total']);
} else if (isset($_GET['dev'])) {
var_export($sql_obj_match_count);
var_export($total);
}
/*$sql_obj_similar_count = $sqls['similar_count'];
$info['sql']['similar_count'] = $sql_obj_similar_count;
if ($res_query2 = $this->db->query($sql_obj_similar_count)) {
$res_count2 = $this->db->fetch_assoc($res_query2);
$total += intval($res_count2['total']);
} else if (isset($_GET['dev'])) {
var_export($sql_obj_similar_count);
var_export($total);
}*/
$sql_obj_match = $sqls['match'];
$info['sql']['match'] = $sql_obj_match;
/*$sql_obj_similar = $sqls['similar'];
$info['sql']['similar'] = $sql_obj_similar;*/
if (isset($_GET['dev'])) {
var_export($sql_obj_match);
//var_export($sql_obj_similar);
}
if ($total > 0) {
$query_obj_match = $this->db->query($sql_obj_match);
//$query_obj_similar = $this->db->query($sql_obj_similar);
//$query_obj_similar = false;
if ($query_obj_match) {
// $results = array_merge($results, [
// 'match' => [],
// 'similar' => []
// ]);
$results['match'] = [];
$ids['match'] = [];
//if ($query_obj_match) {
if ($this->db->num_rows($query_obj_match)) {
while($object = $this->db->fetch_assoc($query_obj_match)) {
if (!in_array($object['id'], $ex_ids)) {
$results['match'][] = $object;
$ids['match'][] = $object['id'];
$count++;
} /*else {
$total--;
}*/
//$total--;
}
}
//}
$ex_ids_match = [];
// if ($query_obj_similar) {
// if ($this->db->num_rows($query_obj_similar)) {
// $ex_ids_match = array_merge($ex_ids, (count($ids['match']) > 0) ? $ids['match'] : []);
// while($object = $this->db->fetch_assoc($query_obj_similar)) {
// if (!in_array($object['id'], $ex_ids_match)) {
// $results['similar'][] = $object;
// $ids['similar'][] = $object['id'];
// $count++;
// } /*else {
// $total--;
// }*/
// $total--;
// }
// }
// }
$time_overage = round((microtime(true) - $start), 2);
if ($time_overage > 2.0) {
$log_entry = [
'timestamp' => date('Y-m-d H:i:s'),
'filter_id' => $filter_id,
'user_id' => isset($filter['created_by']) ? $filter['created_by'] : null,
'req_id' => isset($filter['req_id']) ? $filter['req_id'] : null,
'client_fio' => isset($filter['client_fio']) ? $filter['client_fio'] : null,
'execution_sec' => $time_overage,
'total_results' => $total,
'excluded_ids_count' => count(isset($ex_ids) ? $ex_ids : []),
'match_query' => isset($sql_obj_match) ? $sql_obj_match : null,
'error' => $error ?: null
];
$log_path = $_SERVER['DOCUMENT_ROOT'] . '/logs/autosarch_slow.log';
file_put_contents($log_path, json_encode($log_entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND | LOCK_EX);
}
// $match_ids = "[]";
// if (count($ids['match']) > 0)
// $match_ids = json_encode($ids['match']);
$sql_prev = "SELECT match_ids, similar_ids, processed_at FROM autosearch_results WHERE filter_id = " . intval($filter_id) . " ORDER BY processed_at DESC LIMIT 1";
$query_prev = mysql_query($sql_prev);
$prev_match_ids = [];
$prev_similar_ids = [];
$prev_processed_at = null;
if ($query_prev && mysql_num_rows($query_prev) > 0) {
$row_prev = mysql_fetch_assoc($query_prev);
$decoded_match = json_decode($row_prev['match_ids'], true);
$decoded_similar = json_decode($row_prev['similar_ids'], true);
$prev_processed_at = $row_prev['processed_at'];
// Убедимся, что это массивы
if (is_array($decoded_match)) {
$prev_match_ids = $decoded_match;
}
if (is_array($decoded_similar)) {
$prev_similar_ids = $decoded_similar;
}
} else {
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/telegramm_error_new.log',
date('Y-m-d H:i:s') . " - AutoSearch::search (filter_id: $filter_id): No previous results found in autosearch_results.\n",
FILE_APPEND | LOCK_EX
);
}
$all_prev_ids = array_unique(array_merge($prev_match_ids, $prev_similar_ids));
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/telegramm_error_new.log',
date('Y-m-d H:i:s') . " - AutoSearch::search (filter_id: $filter_id): Prev. processed_at: $prev_processed_at, Before array_diff - ids['match'] count: " . count($ids['match']) . ", prev_match_ids count: " . count($prev_match_ids) . ", prev_similar_ids count: " . count($prev_similar_ids) . ", all_prev_ids count: " . count($all_prev_ids) . "\n",
FILE_APPEND | LOCK_EX
);
if (!empty($ids['match'])) {
$new_match_ids = array_diff($ids['match'], $all_prev_ids);
// Логируем количество найденных новых ID
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/telegramm_error_new.log',
date('Y-m-d H:i:s') . " - AutoSearch::search (filter_id: $filter_id): array_diff result count: " . count($new_match_ids) . "\n",
FILE_APPEND | LOCK_EX
);
$ids['match'] = array_values($new_match_ids);
} else {
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/telegramm_error_new.log',
date('Y-m-d H:i:s') . " - AutoSearch::search (filter_id: $filter_id): ids['match'] was empty before array_diff.\n",
FILE_APPEND | LOCK_EX
);
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/telegramm_error_new.log',
date('Y-m-d H:i:s') . " - AutoSearch::search (filter_id: $filter_id): After array_diff - ids['match'] count: " . count($ids['match']) . "\n",
FILE_APPEND | LOCK_EX
);
}
$match_ids = !empty($ids['match']) ? json_encode($ids['match']) : '[]';
$similar_ids = "[]";
// if (count($ids['similar']) > 0)
// $similar_ids = json_encode($ids['similar']);
//$total = ($total/2) + $count;
$error2 = '';
// if ($total == $count)
// $error2 = 'Новые объекты не найдены.';
//
// if ($count < 0)
// $count = 0;
if ($count == 0)
$error2 = 'Новые объекты не найдены.';
$sql_res = "INSERT INTO `autosearch_results` (
`filter_id`,
`count`,
`total`,
`match_ids`,
`similar_ids`,
`time_overage`,
`error`
) VALUES (
'$filter_id',
'$count',
'$total',
'$match_ids',
'$similar_ids',
'$time_overage',
'$error2'
)";
if (!mysql_query($sql_res)) {
$error = 'Ошибка записи результатов поиска.';
//$error = $sql_res;
}
} else {
$error = 'Ошибка выборки результатов поиска.';
}
} else {
$error = 'Новые объекты не найдены.';
}
} else {
$error = 'Ошибка составления критериев поиска.';
}
}
/*if (isset($_GET['dev'])) {
var_export($info);
}*/
if (!empty($error)) {
self::cleanUpResults($filter_id);
$time_overage = round((microtime(true) - $start), 2);
$sql_res = "INSERT INTO `autosearch_results` (
`filter_id`,
`error`,
`time_overage`
) VALUES (
'$filter_id',
'$error',
'$time_overage'
)";
mysql_query($sql_res);
}
} else {
$error = 'Фильтр автопоиска не был найден.';
}
}
return array_merge($info, [
'count' => $count,
'match_count' => count($ids['match']),
'similar_count' => count($ids['similar']),
'total' => $total,
'objects' => $results,
'time' => (microtime(true) - $start),
'error' => (!empty($error)) ? $error : null
]);
}
public function run($limit = 500, $offset = 0, $telegram_notice = false, $direct_access = false) {
if (isset($_GET['dev'])) {
error_reporting(E_ALL & ~E_RECOVERABLE_ERROR);
ini_set('display_errors', 1);
ob_start();
}
if (!$this->enabled)
return [];
$sql = "SELECT `filters`.*,
`filters`.`telegram_notify` AS `telegram_notify`,
`req`.`name` AS `req`,
`req`.`type_id` AS `req_type_id`,
`req`.`asfilter_id` AS `asfilter_id`,
`req`.`who_work` AS `notify_user`,
`users`.`id` AS `user_id`,
`users`.`telegramm_chat_id` AS `telegramm_chat_id`,
`users`.`telegramm_date` AS `telegramm_date`,
`users`.`max_notice` AS `max_notice`,
`users`.`max_user_id` AS `max_user_id`,
`users`.`gmtmsk` AS `gmtmsk`
FROM `autosearch_filters` AS `filters`
LEFT JOIN `autosearch_results` AS `results` ON `results`.`filter_id` = `filters`.`id`
LEFT JOIN `requisitions` AS `req` ON `req`.`id` = `filters`.`req_id`
LEFT JOIN `users` AS `users` ON `users`.`id` = `req`.`who_work`";
if (!isset($_GET['user_id'])) {
if (intval(date('i')) <= 15)
$sql .= " WHERE `results`.`processed_at` IS NULL";
else
$sql .= " WHERE (`results`.`processed_at` IS NULL OR `results`.`processed_at` < DATE_SUB(NOW(), INTERVAL 15 MINUTE))";
} else {
$sql .= " WHERE true";
}
$sql .= " AND `filters`.`req_id` IS NOT NULL
AND `filters`.`is_active` = '1'
AND `filters`.`is_search` = '1'
AND `req`.`deleted` <> 1 ";
if (isset($_GET['user_id'])) {
$sql .= " AND `req`.`who_work` = " . intval($_GET['user_id']);
echo "Who work user ID: " . intval($_GET['user_id']) . ""; } $sql .= " GROUP BY `filters`.`id` ORDER BY `results`.`processed_at` DESC"; if (!is_null($limit)) $sql .= " LIMIT " . $limit; else $sql .= " LIMIT 1000"; if (isset($_GET['dev'])) { echo "
Filters SQL: " . var_export($sql, true) . ""; } $results = array(); if ($query = mysql_query($sql)) { if (mysql_num_rows($query)) { while ($row = mysql_fetch_assoc($query)) { if (isset($_GET['dev'])) { echo "
" . var_export($row, true) . ""; } $filter_id = $row['id']; $user_id = $row['notify_user']; $result = self::search($filter_id, $offset, 100, true); // выборка по 100 объектов за поиск для 1-го фильтра $results[] = $result; if (!empty($result) && $telegram_notice) { $max = new MaxClass(); $bot = new Telegram(false); if (isset($_GET['dev'])) { echo "
" . htmlspecialchars($debug_output) . "