Joywork/engine/classes/Docs.php
2026-05-22 21:21:54 +03:00

2082 lines
104 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
class Docs {
public $errors = [];
public static $objectsVars = [
'sobstv.fio' => "Собственник (Ф.И.О.)",
'sobstv.email' => "Собственник (Эл. почта)",
'sobstv.phone' => "Собственник (Телефон)",
'sobstv.phone2' => "Собственник (Доп. телефон)",
'sobstv.birthday' => "Собственник (День рождения)",
'sobstv.type' => "Собственник (Тип клиента)",
'sobstv.opis' => "Собственник (Описание клиента)",
'sobstv.date_add' => "Собственник (Дата добавления)",
'sobstv.budget' => "Собственник (Бюджет)",
'sobstv.passport' => "Собственник (Серия/номер паспорта)",
'sobstv.date_of_issue_passport' =>"Собственник (Дата выдачи)",
'sobstv.passport_issued_by' => "Собственник (Кем выдан)",
'sobstv.birthplace' => "Собственник (Место рождения)",
'sobstv.registration_address' => "Собственник (Адрес регистрации)",
'sobstv.post_address' => "Собственник (Почтовый адрес)",
'sobstv.persone_snils' => "Собственник (СНИЛС)",
'sobstv.persone_nationality' =>"Собственник (Гражданство)",
'sobstv.persone_gender' => "Собственник (Пол)",
'sobstv.persone_full_name' => "Собственник (Полное наименование)",
'sobstv.persone_short_name' => "Собственник (Сокращённое наименование)",
'sobstv.persone_ogrn' => "Собственник (ОГРН/ОГРНИП)",
'sobstv.persone_inn' => "Собственник (ИНН)",
'sobstv.persone_kpp' => "Собственник (КПП)",
'sobstv.persone_legal_address' => "Собственник (Юридический адрес)",
'sobstv.persone_fact_address' => "Собственник (Фактический адрес)",
'sobstv.persone_name_bank' => "Собственник (Наименование банка)",
'sobstv.persone_info_bank' => "Собственник (Информация о банке)",
'sobstv.persone_bik_bank' => "Собственник (БИК банка)",
'sobstv.persone_rs_bank' => "Собственник (Расчётный счет)",
'sobstv.persone_kors_bank' => "Собственник (Корреспондентский счёт)",
'sobstv.persone_fio_rukovod' => "Собственник (ФИО руководителя)",
'sobstv.persone_powers' => "Собственник (Основание полномочий)",
'sobstv.persone_kod_podrazdelenia' => "Собственник (Код подразделения)",
'deal_type' => "Тип сделки",
'operation_type' => "Тип операции",
'type' => "Тип объекта",
'srok' => "Срок аренды",
//'nazv' => "Заголовок объявления",
//'opis' => "Описание из объявления",
//'video_url' => "Ссылка на видео",
'komnat' => "Комнат в квартире",
//'studio_flag' => "Квартира-студия?", // boolean
'part' => "Доля",
'ploshad' => "Общая площадь",
'ploshad_k' => "Площадь кухни",
'ploshad_komn' => "Сумма площади комнат",
'land_area' => "Площадь участка, сот.",
'address' => "Адрес объекта",
'rf_region_rayon' => "Район региона",
'city' => "Населенный пункт",
'rayon' => "Район города",
'street' => "Улица",
'dom' => "№ дома",
'flat_number' => "№ квартиры",
'korpus' => "Корпус",
'litera' => "Литера",
//'latitude' => "Широта",
//'longitude' => "Долгота",
'etazh' => "Этаж",
'etazhnost' => "Этажность",
'layout' => "Планировка",
'number_wet_spots' => "Мокрых точек",
'electricity_power' => "Электрическая мощность",
'commer_condition' => "Состояние объекта",
//'commer_access' => "Доступ к объекту",
//'metro' => "Станция метро",
//'minut' => "Минут до метро",
'stoim' => "Цена, в рублях",
'stoim_ky' => "Стоимость КУ, в рублях",
'commission' => "Комиссия, в процентах",
'commission_agency' => "Наша комиссия, в процентах",
'prepay' => "Предоплата, мес",
'cadastral_number' => "Кадастровый номер",
'cadastral_number_land' => "Кадастровый номер участка",
'lease_deposit' => "Залог, мес",
'lease' => "Залог, в рублях",
//'noPets' => "Без животных?", // boolean
//'noChild' => "Без детей?", // boolean
'window_view' => "Вид из окон",
'renovation' => "Ремонт объекта",
//'bath_type_id' => "Тип ванны",
//'hot_water_id' => "Горячая вода",
//'rubbish_chute' => "Мусоропровод?", // boolean
//'parking_type_id' => "Вид парковки",
//'parking_id' => "Парковка",
//'parking_type_id2' => "Тип парковки",
'parking_price' => "Стоимость парковки, руб.",
'ceiling_height' => "Высота потолков, м.",
//'column_grid' => "Сетка колон",
'vat_type' => "Налог",
'commerc_site' => "Участок, га",
'commerc_owned' => "Тип владения участком",
//'floor_material_id' => "Материал пола",
//'commerc_portal_id' => "Тип установки ворот",
'commerc_purpose' => "Коммерческое назначение",
'commerc_land_category' => "Категория земли",
'commerc_permitted_use' => "Разрешения земли",
//'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' => "Грузоподъемность козлового крана, т.",
//'commerc_investproject' => "Инвестпроект?", // boolean
'is_encumbrances' => "Наличие обременения?", // boolean
'commerc_electricity' => "Электричество",
'can_electricity' => "Возможна электрификация?", // boolean
'commerc_gas' => "Газификация",
'can_gas' => "Возможна газификация?", // boolean
'commerc_water' => "Водоснабжение",
'can_water' => "Возможно подкл. к водоснабжения?", // boolean
'commerc_sewage' => "Канализация",
'can_sewage' => "Возможно подкл. к канализации?", // boolean
'commerc_driveways' => "Подъездные пути",
//'commerc_services' => "Дополнительные услуги", // collected
//'building_nazv' => "Название здания",
'commerc_year' => "Год постройки здания",
'commerc_building_type' => "Тип здания",
'commerc_building_class' => "Класс здания",
'building_area' => "Площадь здания",
'commerc_houselinetype' => "Линия домов",
'commerc_building_category' => "Этап строительства",
'building_developer' => "Девелопер",
'building_management_company' => "Управляющая компания",
//'commerc_opened_id' => "Вход в здание",
//'commerc_building_ventilation' => "Вентиляция здания",
//'commerc_building_conditioning' => "Кондиционирование здания",
//'commerc_building_heating' => "Отопление здания",
//'commerc_building_fire' => "Система пожаротуш-я здания",
//'gsk_nazv' => "ГСК",
'garage_type' => "Тип гаража",
'commerc_status' => "Юр. статус гаража",
'commerc_specifications' => "Тех. хар-ки гаража", // collected
//'commerc_infrastructure' => "Инфраструктура вокруг гаража", // collected
//'holod' => "Холодильник?", // boolean
//'stirka' => "Стиральная машина?", // boolean
//'tv' => "Телевизор?", // boolean
//'mebel' => "С мебелью?", // boolean
];
public static $clientsVars = [
'fio' => "Ф.И.О.",
'email' => "Эл. почта",
'phone' => "Телефон",
'phone2' => "Доп. телефон",
'birthday' => "День рождения",
'type' => "Тип клиента",
'opis' => "Описание клиента",
'date_add' => "Дата добавления",
'budget' => "Бюджет",
'passport' => "Серия/номер паспорта",
'date_of_issue_passport' =>"Дата выдачи",
'passport_issued_by' => "Кем выдан",
'birthplace' => "Место рождения",
'registration_address' => "Адрес регистрации",
'post_address' => "Почтовый адрес",
'persone_snils' => "СНИЛС",
'persone_nationality' =>"Гражданство",
'persone_gender' => "Пол",
'persone_full_name' => "Полное наименование",
'persone_short_name' => "Сокращённое наименование",
'persone_ogrn' => "ОГРН/ОГРНИП",
'persone_inn' => "ИНН",
'persone_kpp' => "КПП",
'persone_legal_address' => "Юридический адрес",
'persone_fact_address' => "Фактический адрес",
'persone_name_bank' => "Наименование банка",
'persone_info_bank' => "Информация о банке",
'persone_bik_bank' => "БИК банка",
'persone_rs_bank' => "Расчётный счет",
'persone_kors_bank' => "Корреспондентский счёт",
'persone_fio_rukovod' => "ФИО руководителя",
'persone_powers' => "Основание полномочий",
'persone_kod_podrazdelenia' => "Код подразделения"
//'source' => "Источник",
];
public static $sobstvVars = [
'fio' => "Собственник (Ф.И.О.)",
'email' => "Собственник (Эл. почта)",
'phone' => "Собственник (Телефон)",
'phone2' => "Собственник (Доп. телефон)",
'birthday' => "Собственник (День рождения)",
'type' => "Собственник (Тип клиента)",
'opis' => "Собственник (Описание клиента)",
'date_add' => "Собственник (Дата добавления)",
'budget' => "Собственник (Бюджет)",
'passport' => "Серия/номер паспорта",
'date_of_issue_passport' =>"Дата выдачи",
'passport_issued_by' => "Кем выдан",
'birthplace' => "Место рождения",
'registration_address' => "Адрес регистрации",
'post_address' => "Почтовый адрес",
'persone_snils' => "СНИЛС",
'persone_nationality' =>"Гражданство",
'persone_gender' => "Пол",
'persone_full_name' => "Полное наименование",
'persone_short_name' => "Сокращённое наименование",
'persone_ogrn' => "ОГРН/ОГРНИП",
'persone_inn' => "ИНН",
'persone_kpp' => "КПП",
'persone_legal_address' => "Юридический адрес",
'persone_fact_address' => "Фактический адрес",
'persone_name_bank' => "Наименование банка",
'persone_info_bank' => "Информация о банке",
'persone_bik_bank' => "БИК банка",
'persone_rs_bank' => "Расчётный счет",
'persone_kors_bank' => "Корреспондентский счёт",
'persone_fio_rukovod' => "ФИО руководителя",
'persone_powers' => "Основание полномочий",
'persone_kod_podrazdelenia' => "Код подразделения"
];
public static $complexVars = [
'address' => 'Адрес',
'apartment_number' => 'Номер квартиры',
'floor' => 'Этаж',
'entrance_number' => 'Подъезд',
'rooms_count' => 'Количество комнат',
'area_price' => 'Цена квадрата',
'fullprice' => 'Полная цена',
'installment_price' => 'Цена в рассрочку',
'calculated_area' => 'Расчетная площадь',
'living_area' => 'Жилая площадь',
'kitchen_area' => 'Площадь кухни',
'area_without_balcony' => 'Площадь без балкона',
'hallway_area' => 'Площадь прихожей',
'total_area_excl_living' => 'Общая площадь без жилой',
'total_bathroom_area' => 'Общая площадь санузлов',
'total_balcony_loggia_area' => 'Общая площадь лоджий/балконов',
'rooms_list' => 'Список комнат',
'rooms_areas' => 'Площади комнат',
'bathroom_list' => 'Список санузлов',
'bathroom_areas' => 'Площади санузлов',
'balcony_loggia_list' => 'Список балконов/лоджий',
'balcony_loggia_areas' => 'Площади балконов/лоджий',
'apartments_on_floor_count' => 'Всего квартир на этаже',
];
private $_users_id;
private $_manager_id;
private $_agency_id;
private $_my_managers = [];
private $_serverPath = "/server/php/files/docs";
public function __construct()
{
$user_id = intval($_SESSION['id']);
$user = new User;
$user->get($user_id);
$this->_agency_id = $user->agencyId;
if ($this->_agency_id)
$this->_my_managers[] = $this->_agency_id;
$this->_manager_id = $user->id_manager;
if ($this->_manager_id)
$this->_my_managers[] = $this->_manager_id;
if ($this->_agency_id == $user_id || ($user->users_admin && $this->_agency_id == $user->id_manager)) {
$this->_my_managers = [];
$managers = $user->getMyManagers();
foreach ($managers as $manager) {
$this->_my_managers[] = $manager['id'];
}
}
if ($user->agency || $user->users_admin) {
$this->_users_id = [
$user->id,
$user->agencyId
];
if ($user->agency) {
$admins_id = [];
$admins = $user->getAllAdmins($this->_agency_id);
foreach ($admins as $admin) {
$admins_id[] = $admin['id'];
}
$this->_users_id = array_merge([
$user->id,
$user->agencyId
], $admins_id);
}
} else if ($user->manager || (!$user->agency || !$user->users_admin)) {
$admins_id = [];
$admins = $user->getAllAdmins($this->_agency_id);
foreach ($admins as $admin) {
$admins_id[] = $admin['id'];
}
$this->_users_id = array_merge([
$user->id
], $admins_id);
} else {
$this->_users_id = [
$user->id
];
}
}
public function getInnerBlank($agency_id = null, $blank_id = null) {
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
$blanks = [];
if ($agency_id) {
$sql = "SELECT blanks.*,
If(
blanks.created_by <> 0,
(
SELECT users.fio FROM users AS users
WHERE users.id = blanks.created_by
), (
SELECT users.fio FROM users AS users
WHERE users.id = blanks.updated_by
)
) AS author,
If(
blanks.updated_at <> 0,
DATE_FORMAT(blanks.updated_at,'%d.%m.%Y в %H:%i'),
DATE_FORMAT(blanks.created_at,'%d.%m.%Y в %H:%i')
) AS datetime
FROM `inner_blanks` AS blanks
WHERE `blanks`.`agency_id` = '$agency_id'";
if (!is_null($blank_id))
$sql .= " AND `blanks`.`id` = '$blank_id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
if (!is_null($blank_id)) {
return mysql_fetch_assoc($res);
} else {
while ($blank = mysql_fetch_assoc($res)) {
$blanks[] = $blank;
}
}
}
}
return $blanks;
}
public function getInnerBlanks($agency_id = null) {
return self::getInnerBlank($agency_id, null);
}
public static function stringToTranslit($str, $max = null) {
if (is_null($str))
return false;
$str = strip_tags(htmlspecialchars(trim($str)));
$str = str_replace(' ', '_', $str);
if (!mb_detect_encoding($str, 'UTF-8', true))
$str = utf8_encode($str);
if (function_exists('transliterator_transliterate'))
$str = transliterator_transliterate('Any-Latin; Latin-ASCII', $str);
else
$str = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str);
$str = preg_replace("/[^a-zA-Z0-9\.\[\]_| -]/", '', $str);
$str = str_replace('__', '_', $str);
if (intval($max) > 0)
$str = mb_substr($str, 0, intval($max));
return mb_strtolower($str);
}
public static function getVariable($field_id = null, $agency_id = null) {
if (is_null($field_id))
return false;
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql = "SELECT fields.*,
If(
fields.created_by <> 0,
(
SELECT users.fio FROM users AS users
WHERE users.id = fields.created_by
), (
SELECT users.fio FROM users AS users
WHERE users.id = fields.updated_by
)
) AS author,
If(
fields.updated_at <> 0,
DATE_FORMAT(fields.updated_at, '%d.%m.%Y в %H:%i'),
DATE_FORMAT(fields.created_at, '%d.%m.%Y в %H:%i')
) AS datetime
FROM `inner_blanks_fields` AS fields
WHERE `fields`.`id` = '$field_id' AND `fields`.`agency_id` = '$agency_id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$variable = mysql_fetch_assoc($res);
$name = $variable['name'];
$section = ((intval($variable['section']) == 1) ? "objects" : ((intval($variable['section']) == 2) ? "clients" : null));
return [
'id' => $variable['id'],
'name' => "\${" . (($section) ? $section . "." : "") . $name . "}",
'variable' => $name,
'section' => $variable['section'],
'title' => $variable['title'],
'default' => $variable['default'],
'author' => $variable['author'],
'datetime' => $variable['datetime'],
'created_by' => $variable['created_by'],
'updated_by' => $variable['updated_by'],
'agency_id' => $variable['agency_id'],
];
}
}
return null;
}
public static function getSourceValues($section = null, $source_id = null, $source_ids = []) {
if (is_null($section) || (is_null($source_id) && empty($source_ids)))
return false;
require_once(__DIR__ . '/../../ajax/engine/props.php');
global $TYPE_NEDV;
global $SROK_ARENDY;
$sql = '';
$object_id = null;
$client_id = null;
$props = [];
$values = [];
if ($section == "objects" || $section == 1) {
$sql = "SELECT layout_object.name as layout,
objects_additional_information.*,
object_location.*,
objects.*,
commer_condition.name as commer_condition,
lease_deposit.name as lease_deposit,
vat_type.name as vat_type,
renovation.name as renovation,
commerc_purpose.name as commerc_purpose,
commerc_land_category.name as commerc_land_category,
commerc_permitted_use.name as commerc_permitted_use,
commerc_electricity.name as commerc_electricity,
commerc_gas.name as commerc_gas,
commerc_driveways.name as commerc_driveways,
commerc_building_type.name as commerc_building_type,
commerc_building_class.name as commerc_building_class,
commerc_houselinetype.name as commerc_houselinetype,
commerc_building_category.name as commerc_building_category,
garage_type.name as garage_type,
commerc_status.name as commerc_status
FROM `objects` as objects
LEFT JOIN object_location on objects.id = object_location.object_id
LEFT JOIN objects_additional_information on objects.id = objects_additional_information.object_id
LEFT JOIN layout_object on objects_additional_information.layout_id = layout_object.id
LEFT JOIN commer_condition on objects_additional_information.commer_condition = commer_condition.id
LEFT JOIN lease_deposit on objects.lease_deposit_id = lease_deposit.id
LEFT JOIN vat_type on objects_additional_information.vat_type_id = vat_type.id
LEFT JOIN renovation on objects_additional_information.renovation = renovation.id
LEFT JOIN commerc_purpose on objects_additional_information.commerc_purpose like concat('%&quot;', commerc_purpose.id, '&quot;%')
LEFT JOIN commerc_land_category on objects_additional_information.commerc_land_category_id = commerc_land_category.id
LEFT JOIN commerc_permitted_use on objects_additional_information.commerc_permitted_use_id = commerc_permitted_use.id
LEFT JOIN commerc_electricity on objects_additional_information.commerc_electricity_id = commerc_electricity.id
LEFT JOIN commerc_gas on objects_additional_information.commerc_gas_id = commerc_gas.id
LEFT JOIN commerc_driveways on objects_additional_information.commerc_driveways_id = commerc_driveways.id
LEFT JOIN commerc_building_type on objects_additional_information.commerc_building_type_id = commerc_building_type.id
LEFT JOIN commerc_building_class on objects_additional_information.commerc_building_class_id = commerc_building_class.id
LEFT JOIN commerc_houselinetype on objects_additional_information.commerc_houseLineType_id = commerc_houselinetype.id
LEFT JOIN commerc_building_category on objects_additional_information.commerc_building_category_id = commerc_building_category.id
LEFT JOIN garage_type on objects_additional_information.garage_type_id = garage_type.id
LEFT JOIN commerc_status on objects_additional_information.commerc_status_id = commerc_status.id
WHERE `objects`.`id` = '$source_id' LIMIT 1";
} else if (($section == "clients" || $section == 2) && empty($source_ids)) {
$sql = "SELECT clients.*, clients_dop_info.persone_no_ip,
clients_dop_info.passport,
clients_dop_info.date_of_issue_passport,
clients_dop_info.passport_issued_by,
clients_dop_info.birthplace,
clients_dop_info.registration_address,
clients_dop_info.post_address,
clients_dop_info.persone_snils,
clients_dop_info.persone_nationality,
clients_dop_info.persone_gender,
clients_dop_info.persone_full_name,
clients_dop_info.persone_short_name,
clients_dop_info.persone_ogrn,
clients_dop_info.persone_inn,
clients_dop_info.persone_kpp,
clients_dop_info.persone_legal_address,
clients_dop_info.persone_fact_address,
clients_dop_info.persone_name_bank,
clients_dop_info.persone_info_bank,
clients_dop_info.persone_bik_bank,
clients_dop_info.persone_rs_bank,
clients_dop_info.persone_kors_bank,
clients_dop_info.persone_fio_rukovod,
clients_dop_info.persone_powers,
clients_dop_info.persone_kod_podrazdelenia
FROM `clients`
LEFT JOIN `clients_dop_info` ON `clients`.`id` = `clients_dop_info`.`client_id`
WHERE `clients`.`id` = '$source_id' LIMIT 1";
} else if(($section == "clients" || $section == 2) && !empty($source_ids)){
$sql = $sql1 = "SELECT clients.*, clients_dop_info.persone_no_ip,
clients_dop_info.passport,
clients_dop_info.date_of_issue_passport,
clients_dop_info.passport_issued_by,
clients_dop_info.birthplace,
clients_dop_info.registration_address,
clients_dop_info.post_address,
clients_dop_info.persone_snils,
clients_dop_info.persone_nationality,
clients_dop_info.persone_gender,
clients_dop_info.persone_full_name,
clients_dop_info.persone_short_name,
clients_dop_info.persone_ogrn,
clients_dop_info.persone_inn,
clients_dop_info.persone_kpp,
clients_dop_info.persone_legal_address,
clients_dop_info.persone_fact_address,
clients_dop_info.persone_name_bank,
clients_dop_info.persone_info_bank,
clients_dop_info.persone_bik_bank,
clients_dop_info.persone_rs_bank,
clients_dop_info.persone_kors_bank,
clients_dop_info.persone_fio_rukovod,
clients_dop_info.persone_powers,
clients_dop_info.persone_kod_podrazdelenia
FROM `clients`
LEFT JOIN `clients_dop_info` ON `clients`.`id` = `clients_dop_info`.`client_id`
WHERE `clients`.`id` in (".implode(',',$source_ids).")";
// echo $sql;
}
// echo $sql;
$res = mysql_query($sql);
if ($field = mysql_fetch_assoc($res)) {
/*if ($section == "objects" || $section == 1) {
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
var_dump($field);
die();
}*/
if ($section == "objects" || $section == 1) {
$section_name = "objects" . ".";
$object_id = (int)$field['id'];
$props = getProps($object_id);
} elseif ($section == "clients" || $section == 2) {
$section_name = "clients" . ".";
} else {
$section_name = "";
}
foreach ($field as $key => $value) {
// Алиасы
switch ($key) {
case (in_array($section, ["objects", 2]) && in_array($key, ["adres"])) :
$key = "address";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["stoim_ot"])) :
$key = "stoim";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["etazh_iz"])) :
$key = "etazhnost";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commerc_water_id"])) :
$key = "commerc_water";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commerc_sewage_id"])) :
$key = "commerc_sewage";
break;
}
// Значения
switch ($key) {
// Клиенты
case (in_array($section, ["clients", 2]) && in_array($key, ["type", "phone2"])) :
$value = (isset($value)) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($value)))) : "";
break;
case (in_array($section, ["clients", 2]) && in_array($key, ["birthday", "date_add"])) :
$value = date('d.m.Y', strtotime($value));
break;
case (in_array($section, ["clients", 2]) && in_array($key, ["persone_gender"])) :
$value = ((int)$value == 1) ? 'женский' : 'мужской';
break;
// Объекты
case (in_array($section, ["objects", 2]) && in_array($key, ["operation_type"])) :
$value = ($value == 1) ? "Продажа" : "Аренда";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["type"])) :
$value = (intval($value) && isset($TYPE_NEDV[intval($value)])) ? $TYPE_NEDV[intval($value)] : "";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["srok"])) :
$value = (intval($value) && isset($SROK_ARENDY[intval($value)])) ? $SROK_ARENDY[intval($value)] : "";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["ploshad", "ploshad_k", "ploshad_komn"])) :
$value = $value . " кв. м";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["land_area"])) :
$value = $value . " сот.";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["lease_deposit_id", "prepay"])) :
$value = $value . " мес.";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["stoim", "lease", "stoim_ky", "parking_price"])) :
$value = $value . " руб.";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commission", "commission_agency"])) :
$value = $value . " %";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["number_wet_spots"])) :
$value = (intval($value)) ? $value : "нет";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commerc_water", "commerc_sewage"])) :
$value = ((intval($value) == 1) ? "На участке" : (intval($value) == 2) ? "По границе участка" : "");
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["vat_type"])) :
$value = (!empty($value)) ? $value : "без налога";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commerc_site"])) :
$value = (!empty($value) && $value == 1) ? $value . " Га" : "не указана";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["commerc_owned"])) :
$value = (!empty($value) && $value == 1) ? "в аренде" : "в собственности";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["electricity_power"])) :
$value = $value . " кВт";
break;
case (in_array($section, ["objects", 2]) && in_array($key, ["is_encumbrances", "can_electricity", "can_gas", "can_water", "can_sewage"])) :
$value = (intval($value)) ? "да" : "нет";
break;
}
$name = $section_name . $key;
$values[$name] = $value;
}
if(!empty($source_ids)){
$res1 = mysql_query($sql1);
$valuesarrClients=array();
while($client = mysql_fetch_assoc($res1)){
//var_dump($client);
$valuesarr = [];
$valuesarr['id'] = (isset($client['id'])) ? $client['id'] : "";
$valuesarr['fio'] = (isset($client['fio'])) ? $client['fio'] : "";
$valuesarr['email'] = $client['email'];
$valuesarr['phone'] = (isset($client['phone'])) ? $client['phone'] : "";
$valuesarr['phone2'] = (isset($client['phone2'])) ? implode(', ', json_decode(htmlspecialchars_decode($client['phone2']))) : "";
$valuesarr['birthday'] = (isset($client['birthday'])) ? date('d.m.Y', strtotime($client['birthday'])) : "";
$valuesarr['type'] = (isset($client['type'])) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($client['type'])))) : "";
$valuesarr['opis'] = (isset($client['opis'])) ? $client['opis'] : "";
$valuesarr['date_add'] = (isset($client['date_add'])) ? date('d.m.Y', strtotime($client['date_add'])) : "";
$valuesarr['budget'] = (isset($client['budget'])) ? $client['budget'] : "";
$valuesarr['source'] = (isset($client['source'])) ? $client['source'] : "";
$valuesarr['passport'] = (isset($client['passport'])) ? $client['passport'] : "";
$valuesarr['date_of_issue_passport'] = (isset($client['date_of_issue_passport'])) ? date('d.m.Y', strtotime($client['date_of_issue_passport'])) : "";
$valuesarr['passport_issued_by'] = (isset($client['passport_issued_by'])) ? $client['passport_issued_by'] : "";
$valuesarr['birthplace'] = (isset($client['birthplace'])) ? $client['birthplace'] : "";
$valuesarr['registration_address'] = (isset($client['registration_address'])) ? $client['registration_address'] : "";
$valuesarr['post_address'] = (isset($client['post_address'])) ? $client['post_address'] : "";
$valuesarr['persone_info_bank'] = (isset($client['persone_info_bank'])) ? $client['persone_info_bank'] : "";
$valuesarr['persone_snils'] = (isset($client['persone_snils'])) ? $client['persone_snils'] : "";
$valuesarr['persone_nationality'] = (isset($client['persone_nationality'])) ? $client['persone_nationality'] : "";
$valuesarr['persone_gender'] = ((int)$client['persone_gender'] == 1) ? 'женский' : 'мужской';
$valuesarr['persone_full_name'] = (isset($client['persone_full_name'])) ? $client['persone_full_name'] : "";
$valuesarr['persone_short_name'] = (isset($client['persone_short_name'])) ? $client['persone_short_name'] : "";
$valuesarr['persone_ogrn'] = (isset($client['persone_ogrn'])) ? $client['persone_ogrn'] : "";
$valuesarr['persone_inn'] = (isset($client['persone_inn'])) ? $client['persone_inn'] : "";
$valuesarr['persone_kpp'] = (isset($client['persone_kpp'])) ? $client['persone_kpp'] : "";
$valuesarr['persone_legal_address'] = (isset($client['persone_legal_address'])) ? $client['persone_legal_address'] : "";
$valuesarr['persone_fact_address'] = (isset($client['persone_fact_address'])) ? $client['persone_fact_address'] : "";
$valuesarr['persone_name_bank'] = (isset($client['persone_name_bank'])) ? $client['persone_name_bank'] : "";
$valuesarr['persone_bik_bank'] = (isset($client['persone_bik_bank'])) ? $client['persone_bik_bank'] : "";
$valuesarr['persone_rs_bank'] = (isset($client['persone_rs_bank'])) ? $client['persone_rs_bank'] : "";
$valuesarr['persone_kors_bank'] = (isset($client['persone_kors_bank'])) ? $client['persone_kors_bank'] : "";
$valuesarr['persone_fio_rukovod'] = (isset($client['persone_fio_rukovod'])) ? $client['persone_fio_rukovod'] : "";
$valuesarr['persone_powers'] = (isset($client['persone_powers'])) ? $client['persone_powers'] : "";
$valuesarr['persone_kod_podrazdelenia'] = (isset($client['persone_kod_podrazdelenia'])) ? $client['persone_kod_podrazdelenia'] : "";
$valuesarrClients[] = $valuesarr;
}
$name = $section_name.'clients';
$values[$name] = $valuesarrClients;
}
}
if (!is_null($object_id) && ($section == "objects" || $section == 1 || $section == "sobstv")) {
$clientObjIds = [];
$sql_cl_obj = "SELECT client_id FROM client_objects WHERE object_id = {$object_id}";
$q_cl_obj = mysql_query($sql_cl_obj);
while($r_cl_obj = mysql_fetch_assoc($q_cl_obj)){
$clientObjIds[] = $r_cl_obj['client_id'];
}
$sql = "SELECT clients.id, clients.fio, clients.email, clients.phone, clients.phone2, clients.birthday, clients.type, clients.opis, clients.date_add, clients.budget, clients.source,
clients_dop_info.passport,
clients_dop_info.date_of_issue_passport,
clients_dop_info.passport_issued_by,
clients_dop_info.birthplace,
clients_dop_info.registration_address,
clients_dop_info.post_address,
clients_dop_info.persone_snils,
clients_dop_info.persone_nationality,
clients_dop_info.persone_gender,
clients_dop_info.persone_full_name,
clients_dop_info.persone_short_name,
clients_dop_info.persone_ogrn,
clients_dop_info.persone_inn,
clients_dop_info.persone_kpp,
clients_dop_info.persone_legal_address,
clients_dop_info.persone_fact_address,
clients_dop_info.persone_name_bank,
clients_dop_info.persone_info_bank,
clients_dop_info.persone_bik_bank,
clients_dop_info.persone_rs_bank,
clients_dop_info.persone_kors_bank,
clients_dop_info.persone_fio_rukovod,
clients_dop_info.persone_powers,
clients_dop_info.persone_kod_podrazdelenia
FROM `clients`
LEFT JOIN `clients_dop_info` ON `clients`.`id` = `clients_dop_info`.`client_id`
WHERE clients.id in (".implode(',', $clientObjIds).")";
$res = $res1 = mysql_query($sql);
// if($_SESSION['id'] == 5238){
$values['sobstv'] = array();
$i = 0;
while($client = mysql_fetch_assoc($res)){
$valuesarr=[];
$valuesarr['id'] = (isset($client['id'])) ? $client['id'] : "";
$valuesarr['fio'] = (isset($client['fio'])) ? $client['fio'] : "";
$valuesarr['email'] = $client['email'];
$valuesarr['phone'] = (isset($client['phone'])) ? $client['phone'] : "";
$valuesarr['phone2'] = (isset($client['phone2'])) ? implode(', ', json_decode(htmlspecialchars_decode($client['phone2']))) : "";
$valuesarr['birthday'] = (isset($client['birthday'])) ? date('d.m.Y', strtotime($client['birthday'])) : "";
$valuesarr['type'] = (isset($client['type'])) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($client['type'])))) : "";
$valuesarr['opis'] = (isset($client['opis'])) ? $client['opis'] : "";
$valuesarr['date_add'] = (isset($client['date_add'])) ? date('d.m.Y', strtotime($client['date_add'])) : "";
$valuesarr['budget'] = (isset($client['budget'])) ? $client['budget'] : "";
$valuesarr['source'] = (isset($client['source'])) ? $client['source'] : "";
$valuesarr['passport'] = (isset($client['passport'])) ? $client['passport'] : "";
$valuesarr['date_of_issue_passport'] = (isset($client['date_of_issue_passport'])) ? date('d.m.Y', strtotime($client['date_of_issue_passport'])) : "";
$valuesarr['passport_issued_by'] = (isset($client['passport_issued_by'])) ? $client['passport_issued_by'] : "";
$valuesarr['birthplace'] = (isset($client['birthplace'])) ? $client['birthplace'] : "";
$valuesarr['registration_address'] = (isset($client['registration_address'])) ? $client['registration_address'] : "";
$valuesarr['post_address'] = (isset($client['post_address'])) ? $client['post_address'] : "";
$valuesarr['persone_info_bank'] = (isset($client['persone_info_bank'])) ? $client['persone_info_bank'] : "";
$valuesarr['persone_snils'] = (isset($client['persone_snils'])) ? $client['persone_snils'] : "";
$valuesarr['persone_nationality'] = (isset($client['persone_nationality'])) ? $client['persone_nationality'] : "";
$valuesarr['persone_gender'] = ((int)$client['persone_gender'] == 1) ? 'женский' : 'мужской';
$valuesarr['persone_full_name'] = (isset($client['persone_full_name'])) ? $client['persone_full_name'] : "";
$valuesarr['persone_short_name'] = (isset($client['persone_short_name'])) ? $client['persone_short_name'] : "";
$valuesarr['persone_ogrn'] = (isset($client['persone_ogrn'])) ? $client['persone_ogrn'] : "";
$valuesarr['persone_inn'] = (isset($client['persone_inn'])) ? $client['persone_inn'] : "";
$valuesarr['persone_kpp'] = (isset($client['persone_kpp'])) ? $client['persone_kpp'] : "";
$valuesarr['persone_legal_address'] = (isset($client['persone_legal_address'])) ? $client['persone_legal_address'] : "";
$valuesarr['persone_fact_address'] = (isset($client['persone_fact_address'])) ? $client['persone_fact_address'] : "";
$valuesarr['persone_name_bank'] = (isset($client['persone_name_bank'])) ? $client['persone_name_bank'] : "";
$valuesarr['persone_bik_bank'] = (isset($client['persone_bik_bank'])) ? $client['persone_bik_bank'] : "";
$valuesarr['persone_rs_bank'] = (isset($client['persone_rs_bank'])) ? $client['persone_rs_bank'] : "";
$valuesarr['persone_kors_bank'] = (isset($client['persone_kors_bank'])) ? $client['persone_kors_bank'] : "";
$valuesarr['persone_fio_rukovod'] = (isset($client['persone_fio_rukovod'])) ? $client['persone_fio_rukovod'] : "";
$valuesarr['persone_powers'] = (isset($client['persone_powers'])) ? $client['persone_powers'] : "";
$valuesarr['persone_kod_podrazdelenia'] = (isset($client['source'])) ? $client['persone_kod_podrazdelenia'] : "";
$values['sobstv'][] = $valuesarr;
$part_index = '';
if($i > 0) $part_index = $i;
self::$objectsVars['sobstv'.$part_index.'.fio'] = "Собственник".$part_index." (Ф.И.О.)";
self::$objectsVars['sobstv'.$part_index.'.email'] = "Собственник".$part_index." (Эл. почта)";
self::$objectsVars['sobstv'.$part_index.'.phone'] = "Собственник".$part_index." (Телефон)";
self::$objectsVars['sobstv'.$part_index.'.phone2'] = "Собственник".$part_index." (Доп. телефон)";
self::$objectsVars['sobstv'.$part_index.'.birthday'] = "Собственник".$part_index." (День рождения)";
self::$objectsVars['sobstv'.$part_index.'.type'] = "Собственник".$part_index." (Тип клиента)";
self::$objectsVars['sobstv'.$part_index.'.opis'] = "Собственник".$part_index." (Описание клиента)";
self::$objectsVars['sobstv'.$part_index.'.date_add'] = "Собственник".$part_index." (Дата добавления)";
self::$objectsVars['sobstv'.$part_index.'.budget'] = "Собственник".$part_index." (Бюджет)";
$values['objects.sobstv'.$part_index.'.id'] = (isset($client['id'])) ? $client['id'] : "";
$values['objects.sobstv'.$part_index.'.fio'] = (isset($client['fio'])) ? $client['fio'] : "";
$values['objects.sobstv'.$part_index.'.email'] = $client['email'];
$values['objects.sobstv'.$part_index.'.phone'] = (isset($client['phone'])) ? $client['phone'] : "";
$values['objects.sobstv'.$part_index.'.phone2'] = (isset($client['phone2'])) ? implode(', ', json_decode(htmlspecialchars_decode($client['phone2']))) : "";
$values['objects.sobstv'.$part_index.'.birthday'] = (isset($client['birthday'])) ? date('d.m.Y', strtotime($client['birthday'])) : "";
$values['objects.sobstv'.$part_index.'.type'] = (isset($client['type'])) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($client['type'])))) : "";
$values['objects.sobstv'.$part_index.'.opis'] = (isset($client['opis'])) ? $client['opis'] : "";
$values['objects.sobstv'.$part_index.'.date_add'] = (isset($client['date_add'])) ? date('d.m.Y', strtotime($client['date_add'])) : "";
$values['objects.sobstv'.$part_index.'.budget'] = (isset($client['budget'])) ? $client['budget'] : "";
$values['objects.sobstv'.$part_index.'.source'] = (isset($client['source'])) ? $client['source'] : "";
if($i == 0){
$values['objects.sobstv.id'] = (isset($client['id'])) ? $client['id'] : "";
$values['objects.sobstv.fio'] = (isset($client['fio'])) ? $client['fio'] : "";
$values['objects.sobstv.email'] = $client['email'];
$values['objects.sobstv.phone'] = (isset($client['phone'])) ? $client['phone'] : "";
$values['objects.sobstv.phone2'] = (isset($client['phone2'])) ? implode(', ', json_decode(htmlspecialchars_decode($client['phone2']))) : "";
$values['objects.sobstv.birthday'] = (isset($client['birthday'])) ? date('d.m.Y', strtotime($client['birthday'])) : "";
$values['objects.sobstv.type'] = (isset($client['type'])) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($client['type'])))) : "";
$values['objects.sobstv.opis'] = (isset($client['opis'])) ? $client['opis'] : "";
$values['objects.sobstv.date_add'] = (isset($client['date_add'])) ? date('d.m.Y', strtotime($client['date_add'])) : "";
$values['objects.sobstv.budget'] = (isset($client['budget'])) ? $client['budget'] : "";
$values['objects.sobstv.source'] = (isset($client['source'])) ? $client['source'] : "";
$values['objects.sobstv.passport'] = (isset($client['passport'])) ? $client['passport'] : "";
$values['objects.sobstv.date_of_issue_passport'] = (isset($client['date_of_issue_passport'])) ? date('d.m.Y', strtotime($client['date_of_issue_passport'])) : "";
$values['objects.sobstv.passport_issued_by'] = (isset($client['passport_issued_by'])) ? $client['passport_issued_by'] : "";
$values['objects.sobstv.birthplace'] = (isset($client['birthplace'])) ? $client['birthplace'] : "";
$values['objects.sobstv.registration_address'] = (isset($client['registration_address'])) ? $client['registration_address'] : "";
$values['objects.sobstv.post_address'] = (isset($client['post_address'])) ? $client['post_address'] : "";
$values['objects.sobstv.persone_snils'] = (isset($client['persone_snils'])) ? $client['persone_snils'] : "";
$values['objects.sobstv.persone_nationality'] = (isset($client['persone_nationality'])) ? $client['persone_nationality'] : "";
$values['objects.sobstv.persone_gender'] = ((int)$client['persone_gender'] == 1) ? 'женский' : 'мужской';
$values['objects.sobstv.persone_full_name'] = (isset($client['persone_full_name'])) ? $client['persone_full_name'] : "";
$values['objects.sobstv.persone_short_name'] = (isset($client['persone_short_name'])) ? $client['persone_short_name'] : "";
$values['objects.sobstv.persone_ogrn'] = (isset($client['persone_ogrn'])) ? $client['persone_ogrn'] : "";
$values['objects.sobstv.persone_inn'] = (isset($client['persone_inn'])) ? $client['persone_inn'] : "";
$values['objects.sobstv.persone_kpp'] = (isset($client['persone_kpp'])) ? $client['persone_kpp'] : "";
$values['objects.sobstv.persone_legal_address'] = (isset($client['persone_legal_address'])) ? $client['persone_legal_address'] : "";
$values['objects.sobstv.persone_fact_address'] = (isset($client['persone_fact_address'])) ? $client['persone_fact_address'] : "";
$values['objects.sobstv.persone_name_bank'] = (isset($client['persone_name_bank'])) ? $client['persone_name_bank'] : "";
$values['objects.sobstv.persone_info_bank'] = (isset($client['persone_info_bank'])) ? $client['persone_info_bank'] : "";
$values['objects.sobstv.persone_bik_bank'] = (isset($client['persone_bik_bank'])) ? $client['persone_bik_bank'] : "";
$values['objects.sobstv.persone_rs_bank'] = (isset($client['persone_rs_bank'])) ? $client['persone_rs_bank'] : "";
$values['objects.sobstv.persone_kors_bank'] = (isset($client['persone_kors_bank'])) ? $client['persone_kors_bank'] : "";
$values['objects.sobstv.persone_fio_rukovod'] = (isset($client['persone_fio_rukovod'])) ? $client['persone_fio_rukovod'] : "";
$values['objects.sobstv.persone_powers'] = (isset($client['persone_powers'])) ? $client['persone_powers'] : "";
$values['objects.sobstv.persone_kod_podrazdelenia'] = (isset($client['persone_kod_podrazdelenia'])) ? $client['persone_kod_podrazdelenia'] : "";
}
$i++;
}
//var_dump(self::$objectsVars);
// } else
/*if ($client = mysql_fetch_assoc($res1)) {
$values['objects.sobstv.id'] = (isset($client['id'])) ? $client['id'] : "";
$values['objects.sobstv.fio'] = (isset($client['fio'])) ? $client['fio'] : "";
$values['objects.sobstv.email'] = $client['email'];
$values['objects.sobstv.phone'] = (isset($client['phone'])) ? $client['phone'] : "";
$values['objects.sobstv.phone2'] = (isset($client['phone2'])) ? implode(', ', json_decode(htmlspecialchars_decode($client['phone2']))) : "";
$values['objects.sobstv.birthday'] = (isset($client['birthday'])) ? date('d.m.Y', strtotime($client['birthday'])) : "";
$values['objects.sobstv.type'] = (isset($client['type'])) ? str_replace('_', ' ', implode(', ', json_decode(htmlspecialchars_decode($client['type'])))) : "";
$values['objects.sobstv.opis'] = (isset($client['opis'])) ? $client['opis'] : "";
$values['objects.sobstv.date_add'] = (isset($client['date_add'])) ? date('d.m.Y', strtotime($client['date_add'])) : "";
$values['objects.sobstv.budget'] = (isset($client['budget'])) ? $client['budget'] : "";
$values['objects.sobstv.source'] = (isset($client['source'])) ? $client['source'] : "";
$values['objects.sobstv.passport'] = (isset($client['passport'])) ? $client['passport'] : "";
$values['objects.sobstv.date_of_issue_passport'] = (isset($client['date_of_issue_passport'])) ? date('d.m.Y', strtotime($client['date_of_issue_passport'])) : "";
$values['objects.sobstv.passport_issued_by'] = (isset($client['passport_issued_by'])) ? $client['passport_issued_by'] : "";
$values['objects.sobstv.birthplace'] = (isset($client['birthplace'])) ? $client['birthplace'] : "";
$values['objects.sobstv.registration_address'] = (isset($client['registration_address'])) ? $client['registration_address'] : "";
$values['objects.sobstv.post_address'] = (isset($client['post_address'])) ? $client['post_address'] : "";
$values['objects.sobstv.persone_snils'] = (isset($client['persone_snils'])) ? $client['persone_snils'] : "";
$values['objects.sobstv.persone_nationality'] = (isset($client['persone_nationality'])) ? $client['persone_nationality'] : "";
$values['objects.sobstv.persone_gender'] = (isset($client['persone_gender'])) ? $client['persone_gender'] : "";
$values['objects.sobstv.persone_full_name'] = (isset($client['persone_full_name'])) ? $client['persone_full_name'] : "";
$values['objects.sobstv.persone_short_name'] = (isset($client['persone_short_name'])) ? $client['persone_short_name'] : "";
$values['objects.sobstv.persone_ogrn'] = (isset($client['persone_ogrn'])) ? $client['persone_ogrn'] : "";
$values['objects.sobstv.persone_inn'] = (isset($client['persone_inn'])) ? $client['persone_inn'] : "";
$values['objects.sobstv.persone_kpp'] = (isset($client['persone_kpp'])) ? $client['persone_kpp'] : "";
$values['objects.sobstv.persone_legal_address'] = (isset($client['persone_legal_address'])) ? $client['persone_legal_address'] : "";
$values['objects.sobstv.persone_fact_address'] = (isset($client['persone_fact_address'])) ? $client['persone_fact_address'] : "";
$values['objects.sobstv.persone_name_bank'] = (isset($client['persone_name_bank'])) ? $client['persone_name_bank'] : "";
$values['objects.sobstv.persone_bik_bank'] = (isset($client['persone_bik_bank'])) ? $client['persone_bik_bank'] : "";
$values['objects.sobstv.persone_rs_bank'] = (isset($client['persone_rs_bank'])) ? $client['persone_rs_bank'] : "";
$values['objects.sobstv.persone_kors_bank'] = (isset($client['persone_kors_bank'])) ? $client['persone_kors_bank'] : "";
$values['objects.sobstv.persone_fio_rukovod'] = (isset($client['persone_fio_rukovod'])) ? $client['persone_fio_rukovod'] : "";
$values['objects.sobstv.persone_powers'] = (isset($client['persone_powers'])) ? $client['persone_powers'] : "";
}*/
foreach ($props as $prop) {
if (!empty($prop['val'])) {
$values['objects.' . $prop['name']] = $prop['val'];
//$values['.' . $prop['name']] = $prop['val'];
}
}
}
return $values;
}
public static function getSourcesList($agency_id = null, $section = null, $required = null) {
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if (is_null($section))
return false;
$list = [];
$agentIds = array();//User::getAllAgencyUsers($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)))";
$q_users = mysql_query($sql_users);
while($r_users = mysql_fetch_assoc($q_users)){
$agentIds[] = (int)$r_users['id'];
}
if ($section == "objects" || $section == 1) {
$sql = "SELECT id,
nazv AS name,
adres AS address
FROM `objects`
WHERE `black` <> 1 AND
`moder` <> 1 AND
`archive` <> 1 AND
`id_add_user` IN (" . implode(',', $agentIds) . ")";
} else if ($section == "clients" || $section == 2) {
$sql = "SELECT id,
fio AS name,
phone AS phone,
email AS email
FROM `clients`
WHERE `who_work` IN (" . implode(',', $agentIds) . ")";
}
if (!empty($sql)) {
if (!empty($required) && is_array($required)) {
foreach ($required as $req) {
$sql .= " AND (`$req` != '' OR `$req` NOT NULL)";
}
} else if (!empty($required) && is_string($required)) {
$sql .= " AND (`$required` != '' OR `$required` != NULL)";
}
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
while($row = mysql_fetch_assoc($res)) {
$list[] = $row;
}
}
}
return $list;
}
public static function getSavedValues($section = null, $source_id = null, $source_ids = []) {
if (is_null($section) || (is_null($source_id) && empty($source_ids)))
return false;
$values = [];
$section_id = 0;
if ($section == "objects" || $section == 1)
$section_id = 1;
else if ($section == "clients" || $section == 2)
$section_id = 2;
if((is_null($source_id) || $source_id == 0) && !empty($source_ids)){
$source_id = $source_ids[0];
}
$sql = "SELECT *,
`blank_fields`.`title` AS `title`,
`blank_fields`.`name` AS `name`
FROM `inner_docs_fields` AS `docs_fields`
LEFT JOIN `inner_blanks_fields` AS `blank_fields` ON (`blank_fields`.`id` = `docs_fields`.`field_id`)
WHERE `docs_fields`.`section_id` = '$section_id' AND
`docs_fields`.`source_id` = '$source_id'";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
if ($section == "objects" || $section == 1)
$section = "objects" . ".";
elseif ($section == "clients" || $section == 2)
$section = "clients" . ".";
else
$section = "";
while ($field = mysql_fetch_assoc($res)) {
$name = $section . $field['name'];
$values[$name] = $field['field_value'];
}
}
return $values;
}
public static function getAllValues($section = null, $source_id = null, $source_ids = []) {
if (is_null($section) || (is_null($source_id) && empty($source_ids) ))
return false;
$values = [];
if (!is_null($section) /*&& (!is_null($source_id) && !empty($source_ids))*/) {
if ($source_values = self::getSourceValues($section, intval($source_id), $source_ids))
$values = array_merge($values, $source_values);
if ($saved_values = self::getSavedValues($section, intval($source_id), $source_ids))
$values = array_merge($values, $saved_values);
}
return $values;
}
public static function getVariablesList($agency_id = null, $section = null, $system_vars = false, $source_id = null, $source_ids = []) {
$variables = [];
$values = [];
//var_dump(!is_null($section) && (!is_null($source_id) || !empty($source_ids)));
if (!is_null($section) && (!is_null($source_id) || !empty($source_ids)))
$values = self::getAllValues($section, intval($source_id), $source_ids);
/* if($_SESSION['id'] == 5238){
var_dump($values);
}*/
if ($system_vars || (($section == "objects" || $section == 1) && is_null($source_id))) {
foreach (self::$objectsVars as $name => $title) {
$section_name = 'objects';
$variables[$section_name][$name] = [
'id' => null,
'name' => "\${" . $section_name . "." . $name . "}",
'variable' => $name,
'section' => $section_name,
'title' => $title,
'value' => (isset($values[$section_name . "." . $name]) ? $values[$section_name . "." . $name] : null),
'default' => "",
'author' => null,
'datetime' => null,
'created_by' => null,
'updated_by' => null,
'agency_id' => null
];
}
}
if ($system_vars || (($section == "complexes" || $section == 3) && is_null($source_id))) {
foreach (self::$complexVars as $name => $title) {
$section_name = 'premise';
$variables[$section_name][$name] = [
'id' => null,
'name' => "\${" . $section_name . "." . $name . "}",
'variable' => $name,
'section' => $section_name,
'title' => $title,
'value' => (isset($values[$section_name . "." . $name]) ? $values[$section_name . "." . $name] : null),
'default' => "",
'author' => null,
'datetime' => null,
'created_by' => null,
'updated_by' => null,
'agency_id' => null
];
}
}
if ($system_vars || (($section == "clients" || $section == 2) && is_null($source_id))) {
foreach (self::$clientsVars as $name => $title) {
$section_name = 'clients';
$variables[$section_name][$name] = [
'id' => null,
'name' => "\${" . $section_name . "." . $name . "}",
'variable' => $name,
'section' => $section_name,
'title' => $title,
'value' => (isset($values[$section_name . "." . $name]) ? $values[$section_name . "." . $name] : null),
'default' => "",
'author' => null,
'datetime' => null,
'created_by' => null,
'updated_by' => null,
'agency_id' => null
];
}
if(isset($values[$section_name . ".clients"])){
$variables[$section_name]['clients'] = $values[$section_name . ".clients"];
}
/* if(!empty($source_ids)){
var_dump($source_ids);
}*/
}
if ($system_vars || (($section == "infosob" || $section == 'sobstv') && is_null($source_id))) {
$section_name = 'sobstv';
$section_name1 = 'clients_more';
/* if($_SESSION['id'] == 5238){
echo $section_name."\n";
var_dump($values['sobstv']);
}*/
foreach (self::$sobstvVars as $name => $title) {
$variables[$section_name][$name] = [
'id' => null,
'name' => "%%" . $section_name . "." . $name . "%%",
'variable' => $name,
'section' => $section_name,
'title' => $title,
'value' => (isset($values[$section_name]) ? $values[$section_name] : null),
'default' => "",
'author' => null,
'datetime' => null,
'created_by' => null,
'updated_by' => null,
'agency_id' => null
];
$variables[$section_name1][$name] = [
'id' => null,
'name' => "%%" . $section_name1 . "." . $name . "%%",
'variable' => $name,
'section' => $section_name1,
'title' => $title,
//'value' => (isset($values[$section_name1]) ? $values[$section_name1] : null),
'default' => "",
'author' => null,
'datetime' => null,
'created_by' => null,
'updated_by' => null,
'agency_id' => null
];
}
}
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql = "SELECT fields.*,
If(
fields.created_by <> 0,
(
SELECT IF(users.last_name != '' AND users.first_name != '', CONCAT(users.last_name, ' ', users.first_name, ' ', users.middle_name), users.fio) FROM users AS users
WHERE users.id = fields.created_by
), (
SELECT IF(users.last_name != '' AND users.first_name != '', CONCAT(users.last_name, ' ', users.first_name, ' ', users.middle_name), users.fio) FROM users AS users
WHERE users.id = fields.updated_by
)
) AS author,
If(
fields.updated_at <> 0,
DATE_FORMAT(fields.updated_at, '%d.%m.%Y в %H:%i'),
DATE_FORMAT(fields.created_at, '%d.%m.%Y в %H:%i')
) AS datetime
FROM `inner_blanks_fields` AS fields
WHERE `fields`.`agency_id` = $agency_id";
if ($section == "objects" || $section == 1)
$sql .= " AND `fields`.`section_id` = 1";
else if ($section == "clients" || $section == 2 || $section == 'infosob')
$sql .= " AND `fields`.`section_id` = 2";
$sql .= " ORDER BY `fields`.`id` ASC";
/* if($_SESSION['id'] == 10876){
echo $sql;
}*/
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
while ($variable = mysql_fetch_assoc($res)) {
$name = $variable['name'];
switch ((int)$variable['section_id']) {
case 1:
$section_name = 'objects';
break;
case 2:
$section_name = 'clients';
break;
case 3:
$section_name = 'premise';
break;
default:
$section_name = null;
break;
}
$name1 = "\${" . (($section_name) ? $section_name . "." : "") . $name . "}";
if($section == 'infosob'){
$section_name = "sobstv";
$name1 = "%%" . (($section_name) ? $section_name . "." : "") . $name . "%%";
}
$variables[$section_name][$name] = [
'id' => $variable['id'],
'name' => $name1,
'variable' => $name,
'section' => $variable['section_id'],
'title' => $variable['title'],
'value' => (isset($values[$section_name . "." . $name]) ? $values[$section_name . "." . $name] : null),
'default' => $variable['default'],
'author' => $variable['author'],
'datetime' => $variable['datetime'],
'created_by' => ((int)$variable['created_by']) ? $variable['created_by'] : null,
'updated_by' => ((int)$variable['updated_by']) ? $variable['updated_by'] : null,
'agency_id' => $variable['agency_id'],
];
}
}
}
return $variables;
}
public static function deleteVariable($field_id = null, $agency_id = null) {
if (is_null($field_id))
return false;
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql1 = "DELETE FROM `inner_blanks_fields`
WHERE `inner_blanks_fields`.`id` = '$field_id' AND `inner_blanks_fields`.`agency_id` = '$agency_id' LIMIT 1";
$sql2 = "DELETE FROM `inner_docs_fields`
WHERE `inner_docs_fields`.`field_id` = '$field_id'";
if (mysql_query($sql1) && mysql_query($sql2)) {
return true;
} else {
return mysql_error();
}
}
return false;
}
public function getBlankTypes() {
return [
1 => 'Бланк договора',
2 => 'Бланк соглашения',
3 => 'Презентация',
];
}
public static function deleteBlank($blank_id = null, $agency_id = null) {
if (is_null($blank_id))
return false;
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql = "DELETE FROM `inner_blanks`
WHERE `inner_blanks`.`id` = '$blank_id' AND `inner_blanks`.`agency_id` = '$agency_id' LIMIT 1";
if (mysql_query($sql)) {
return true;
} else {
return mysql_error();
}
}
return false;
}
public static function cloneBlank($blank_id = null, $agency_id = null) {
if (is_null($blank_id))
return false;
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql = "SELECT * FROM `inner_blanks`
WHERE `inner_blanks`.`id` = '$blank_id' AND `inner_blanks`.`agency_id` = '$agency_id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$blank = mysql_fetch_assoc($res);
$blank_name = $blank['name'] . " (copy)";
$sql2 = "INSERT INTO `inner_blanks`
(`name`, `type`, `content`, `agency_id`, `created_by`) VALUES
('$blank_name', '$blank[type]', '$blank[content]', '$agency_id', '$_SESSION[id]')";
if (mysql_query($sql2)) {
return true;
} else {
return mysql_error();
}
}
}
return false;
}
public function addEditInnerBlank($blank_id = null, $post) {
if (!$post)
return false;
if ($agency_id = User::getUserAgencyID()) {
$content = addslashes(html_entity_decode($post['content']));
if (intval($blank_id) !== 0) {
$sql = "UPDATE `inner_blanks` SET
`name` = '$post[name]',
`type` = '$post[type]',
`prefix` = '$post[prefix]',
`content` = '$content'
/*`created_by` = '$_SESSION[id]'*/
WHERE `agency_id` = '$agency_id' AND `id` = '$blank_id'";
} else {
$sql = "INSERT INTO `inner_blanks`
(`name`, `type`, `prefix`, `content`, `agency_id`, `created_by`) VALUES
('$post[name]', '$post[type]', '$post[prefix]', '$content', '$agency_id', '$_SESSION[id]')";
}
if (mysql_query($sql))
return true;
return mysql_error();
}
return false;
}
public function validateInnerField($post, $byIndex = true) {
$indx = [];
$errors = [];
foreach ($post as $name => $value) {
if (!isset($indx[$name]))
$indx[$name] = 0;
$error = '';
if ($name == "section" || $name == "sections") {
if ($value == intval(0))
$error = "Поле «Назначение» обязательно к заполнению.";
if (!is_int((int)$value))
$error = "Поле «Назначение» должно быть числом.";
} else if ($name == "title" || $name == "titles") {
if (strlen($value) == 0)
$error = "Поле «Название» обязательно к заполнению.";
if (strlen($value) > 255)
$error = "Поле «Название» должно быть не больше 255 знаков.";
} else if ($name == "name" || $name == "names") {
if (strlen($value) == 0)
$error = "Поле «Переменная» обязательно к заполнению.";
if (strlen($value) > 64)
$error = "Поле «Переменная» должно быть не больше 64 знаков.";
if (!preg_match('/^[a-z0-9-_]+$/i', $value))
$error = "Не верный формат поля «Переменная». Разрешены латинские буквы, цифры и знак подчеркивания.";
} else if ($name == "default" || $name == "defaults") {
if (strlen($value) > 255)
$error = "Поле «Значение по-умолчанию» должно быть не больше 255 знаков.";
}
if (!empty($error)) {
if ($byIndex)
$errors[$name][$indx[$name]] = $error;
else
$errors[$name] = $error;
}
$indx[$name]++;
}
if (!empty($errors))
return ['errors' => $errors];
else
return true;
}
public function validateInnerFields($post, $byIndex = false) {
$indx = [];
$errors = [];
foreach ($post as $name => $values) {
foreach ($values as $value) {
if (!isset($indx[$name]))
$indx[$name] = 0;
$field = [$name => $value];
if (is_array($error = self::validateInnerField($field, $byIndex))) {
$errors[$name][$indx[$name]] = $error['errors'][$name];
}
$indx[$name]++;
}
}
if (!empty($errors))
return ['errors' => $errors];
else
return true;
}
public function addEditFields($post) {
if (!$post)
return false;
if (is_array($errors = self::validateInnerFields($post)))
return $errors;
$i = 0;
$errors = [];
$fields = [];
foreach ($post['names'] as $name) {
if (!empty($name)) {
$fields[] = [
'id' => isset($post['ids'][$i]) ? $post['ids'][$i] : null,
'section' => isset($post['sections'][$i]) ? $post['sections'][$i] : 0,
'title' => isset($post['titles'][$i]) ? $post['titles'][$i] : $name,
'name' => $name,
'default' => isset($post['defaults'][$i]) ? $post['defaults'][$i] : "",
];
}
$i++;
}
if ($agency_id = User::getUserAgencyID()) {
foreach ($fields as $field) {
if ($id = $field['id']) {
$sql = "UPDATE `inner_blanks_fields` SET
`section_id` = '$field[section]',
`title` = '$field[title]',
`name` = '$field[name]',
`default` = '$field[default]',
`updated_by` = '$_SESSION[id]'
WHERE `id` = '$id' AND `agency_id` = '$agency_id';";
} else {
$sql = "INSERT INTO `inner_blanks_fields`
(`section_id`, `title`, `name`, `default`, `agency_id`, `created_by`) VALUES
('$field[section]', '$field[title]', '$field[name]', '$field[default]', '$agency_id', '$_SESSION[id]');";
}
if (!mysql_query($sql))
$errors[] = mysql_error();
}
}
if (!empty($errors))
return $errors;
return true;
}
public function saveDocFields(
$source_id = null,
$section = null,
$post = null
) {
if (!$source_id || !$section || !$post) {
return false;
}
$errors = [];
$section_id = 0;
if ($section == 'objects' || $section == 1) {
$section_id = 1;
} else if ($section == 'clients' || $section == 2) {
$section_id = 2;
}
$source_id = (int)$source_id;
$user_id = (int)$_SESSION['id'];
foreach ($post as $field_id => $field_value) {
$field_id = intval(trim($field_id, '\''));
$field_value = mysql_real_escape_string(
htmlentities(trim($field_value, '\''))
);
if ($field_id) {
$sql = "INSERT INTO `inner_docs_fields`
(`section_id`, `source_id`, `field_id`, `field_value`, `created_by`)
VALUES
('$section_id', '$source_id', '$field_id', '$field_value', '$user_id')
ON DUPLICATE KEY UPDATE
`field_value` = VALUES(`field_value`),
`updated_by` = '$user_id',
`updated_at` = NOW()";
if (!mysql_query($sql)) {
$errors[] = mysql_error();
}
}
}
if (!empty($errors)) {
return $errors;
}
return true;
}
public function getInnerDoc($agency_id = null, $doc_id = null) {
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
$docs = [];
if ($agency_id) {
$sql = "SELECT docs.*,
If(
docs.created_by <> 0,
(
SELECT users.fio FROM users AS users
WHERE users.id = blanks.created_by
), (
SELECT users.fio FROM users AS users
WHERE users.id = blanks.updated_by
)
) AS author,
blanks.name AS blank,
blanks.id AS blank_id,
If(
docs.updated_at <> 0,
UNIX_TIMESTAMP(docs.updated_at),
UNIX_TIMESTAMP(docs.created_at)
) AS datetime
FROM `inner_docs` AS docs
LEFT JOIN `inner_blanks` AS blanks ON (`docs`.`blank_id` = `blanks`.`id`)
WHERE `docs`.`agency_id` = '$agency_id'";
if (!is_null($doc_id))
$sql .= " AND `docs`.`id` = '$doc_id' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
if (!is_null($doc_id)) {
return mysql_fetch_assoc($res);
} else {
while ($doc = mysql_fetch_assoc($res)) {
$docs[] = $doc;
}
}
}
}
return $docs;
}
public function getInnerDocs($agency_id = null) {
return self::getInnerDoc($agency_id, null);
}
public function editDocument($doc_id = null, $post) {
if ($agency_id = User::getUserAgencyID()) {
$content = mysql_real_escape_string(html_entity_decode($post['content']));
if (!is_null($doc_id)) {
$sql = "UPDATE `inner_docs` SET
`name` = '$post[name]',
`content` = '$content'
/*`created_by` = '$_SESSION[id]'*/
WHERE `agency_id` = '$agency_id' AND `id` = '$doc_id'";
if (mysql_query($sql))
return true;
return mysql_error();
}
}
return false;
}
public static function deleteDocument($doc_id = null, $agency_id = null) {
if (is_null($doc_id))
return false;
if (is_null($agency_id))
$agency_id = User::getUserAgencyID();
if ($agency_id) {
$sql = "DELETE FROM `inner_docs`
WHERE `inner_docs`.`id` = '$doc_id' AND `inner_docs`.`agency_id` = '$agency_id' LIMIT 1";
if (mysql_query($sql)) {
return true;
} else {
return mysql_error();
}
}
return false;
}
public static function getAllValuesForDocs($room , $premiseItems){
$house_id = intval($room['house_id']);
$floor_id = intval($room['floor_id']);
$entrance_id = intval($room['entrance_id']);
$query ="SELECT
(SELECT address FROM complex_houses WHERE id = $house_id LIMIT 1) AS address,
(SELECT COUNT(*) FROM complex_rooms WHERE floor_id = $floor_id) AS room_count,
(SELECT position FROM complex_entrances WHERE id = $entrance_id LIMIT 1) AS entrance_number
";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$room['address'] = $row['address'];
$room['apartments_on_floor_count'] = $row['room_count'];
$room['entrance_number'] = $row['entrance_number'];
$attributes = $room['attributes'];
$attributeRoom = array_filter($attributes, function($attr) {
return $attr['attribute_type'] === 'room';
});
$bathrooms = array_filter($attributes, function($attr) {
return $attr['attribute_type'] === 'bathroom';
});
$balconies = array_filter($attributes, function($attr) {
return in_array($attr['attribute_type'], ['balcony', 'loggia']);
});
$rooms_list = '';
foreach (array_values($attributeRoom) as $i => $r) {
$label = 'Комната № ' . ($i + 1);
if (isset($r['area']) && floatval($r['area']) > 0) {
$rooms_list .= $label;
} else {
$rooms_list .= '(нет данных)';
}
if ($i < count($attributeRoom) - 1) {
$rooms_list .= ', ';
}
}
$bathroom_list = '';
foreach (array_values($bathrooms) as $i => $b) {
$label = 'Санузел № ' . ($i + 1);
if (isset($b['area']) && floatval($b['area']) > 0) {
$bathroom_list .= $label;
} else {
$bathroom_list .= '(нет данных)';
}
if ($i < count($bathrooms) - 1) {
$bathroom_list .= ', ';
}
}
$balcony_loggia_list = '';
foreach (array_values($balconies) as $i => $b) {
$typeName = isset($b['attribute_type']) && $b['attribute_type'] === 'balcony' ? 'Балкон' : 'Лоджия';
$label = $typeName . ' № ' . ($i + 1);
if (isset($b['area']) && floatval($b['area']) > 0) {
$balcony_loggia_list .= $label;
} else {
$balcony_loggia_list .= '(нет данных)';
}
if ($i < count($balconies) - 1) {
$balcony_loggia_list .= ', ';
}
}
$rooms_areas = '';
foreach (array_values($attributeRoom) as $i => $r) {
$area = (isset($r['area']) && floatval($r['area']) > 0) ? floatval($r['area']) . ' м²' : 'нет данных';
$rooms_areas .= $area;
if ($i < count($attributeRoom) - 1) {
$rooms_areas .= ', ';
}
}
$bathroom_areas = '';
foreach (array_values($bathrooms) as $i => $b) {
$area = (isset($b['area']) && floatval($b['area']) > 0) ? floatval($b['area']) . ' м²' : 'нет данных';
$bathroom_areas .= $area;
if ($i < count($bathrooms) - 1) {
$bathroom_areas .= ', ';
}
}
$balcony_loggia_areas = '';
foreach (array_values($balconies) as $i => $b) {
$area = (isset($b['area']) && floatval($b['area']) > 0) ? floatval($b['area']) . ' м²' : 'нет данных';
$balcony_loggia_areas .= $area;
if ($i < count($balconies) - 1) {
$balcony_loggia_areas .= ', ';
}
}
$room['rooms_list'] = $rooms_list;
$room['rooms_areas'] = $rooms_areas;
$room['bathroom_list'] = $bathroom_list;
$room['bathroom_areas'] = $bathroom_areas;
$room['balcony_loggia_list'] = $balcony_loggia_list;
$room['balcony_loggia_areas'] = $balcony_loggia_areas;
$keyMap = [
'apartment_number' => 'number',
'floor' => 'floor',
'entrance_number' => 'entrance_number',
'rooms_count' => 'rooms_count',
'area_price' => 'area_price',
'fullprice' => 'total_amount',
'installment_price' => 'installment_price',
'calculated_area' => 'estimated_area',
'living_area' => 'living_area',
'kitchen_area' => 'kitchen_area',
'area_without_balcony' => 'area_without_balcony',
'hallway_area' => 'hallway_area',
'total_area_excl_living' => 'total_area_excl_living',
'total_bathroom_area' => 'total_bathroom_area',
'total_balcony_loggia_area' => 'total_balcony_loggia_area',
'address' => 'address',
'apartments_on_floor_count' => 'apartments_on_floor_count',
'rooms_list' => 'rooms_list',
'rooms_areas' => 'rooms_areas',
'bathroom_list' => 'bathroom_list',
'bathroom_areas' => 'bathroom_areas',
'balcony_loggia_list' => 'balcony_loggia_list',
'balcony_loggia_areas' => 'balcony_loggia_areas'
];
foreach ($keyMap as $templateKey => $roomKey) {
if (!isset($premiseItems[$templateKey])) {
$premiseItems[$templateKey] = [];
}
if (isset($room[$roomKey])) {
$premiseItems[$templateKey]['value'] = $room[$roomKey];
} else {
$premiseItems[$templateKey]['value'] = null;
}
}
return $premiseItems;
}
public function fillInnerDocument($blank_id = null, $client_id = null, $object_id = null, $client_ids=[], $debug = false, $room = null) {
if (is_null($room)) {
if (is_null($blank_id) || (is_null($client_id) && empty($client_ids)) || is_null($object_id))
return null;
} else {
if (is_null($blank_id) || is_null($client_id)) {
return null;
}
}
$agency_id = User::getUserAgencyID();
$list = [];
$clients = self::getVariablesList($agency_id, "clients", true, intval($client_id), $client_ids);
$list["clients"] = $clients["clients"];
$objects = self::getVariablesList($agency_id, "objects", true, intval($object_id));
$list["objects"] = $objects["objects"];
$sobstv = self::getVariablesList($agency_id, "sobstv", true, intval($object_id));
$list["sobstv"] = $objects["sobstv"];
if (!is_null($room)){
$premiseItems = self::getVariablesList($agency_id, "complexes", true, $room);
$premise = self::getAllValuesForDocs($room, $premiseItems['premise']);
$list["premise"] = $premise;
}
$blank = self::getInnerBlank($agency_id, intval($blank_id));
if (!empty($blank['content']) && count($list) > 0) {
/* if($_SESSION['id'] == 5238){
var_dump(stristr('${objects.sobstv.fio}', $blank['content']));
echo $blank['content']."\n";
//if(strpos())
}*/
$sobstvs = array();
$clients_vals = array();
list($patterns, $replacements) = [[],[]];
foreach ($list as $section => $variables) {
foreach ($variables as $variable => $data) {
if($section == 'sobstv'){
$sobstvs = $data['value'];
if($_SESSION['id'] == 5238){
//var_dump($sobstvs);
//var_dump($data);
}
}
if($section == 'clients' && $variable == 'clients'){
$clients_vals = $data;
}
if ($section == "objects" || $section == 1)
$section_name = "Объект: ";
else if ($section == "clients" || $section == 2)
$section_name = "Клиент: ";
else if ($section == "sobstv")
$section_name = "Собственник: ";
else if ($section == "3" || $section == "premise")
$section_name = "ЖК.Помещение: ";
else
$section_name = "";
$pattern = $data['name'];
if($section != 'sobstv'){
if (!($value = $data['value'])) {
if (!($value = $data['default'])) {
if(strpos($variable, 'sobstv') !== false){
for($i = 1; $i<=5; $i++){
if($variable === 'sobstv'.$i.'.fio'){
$value = '';
}
}
} else{
$value = '__{' . $section_name . $data['title'] . '}__';
}
}
}
if ($pattern && $value) {
$patterns[] = $pattern;
$replacements[] = ' ' . $value . ' ';
}
}
}
}
//if(!empty($sobstvs)){
$str = $blank['content'];
$strings = array();
$last = '${*{';
$pos = -1;
$result1 = [];
$result2 = [];
while(($pos = strpos($str, $last, $pos+1))!==false) {
$result1[] = $pos;
}
$last = '}*}';
$pos = -1;
while(($pos = strpos($str, $last, $pos+1))!==false) {
$result2[] = $pos;
}
foreach($result1 as $key => $rez){
$strd = substr($str, $rez, ($result2[$key] - $rez)+3);
$strings[] = $strd;
}
foreach($strings as $strCont){
$valuestr = '';
if(strpos($strCont, 'sobstv.') !== false){
foreach($sobstvs as $sob){
// var_dump($sob);
$patternsstr=[]; $replacementsstr=[];
$patternsstr[] = '${*{'; $replacementsstr[] = '';
//$patternsstr[] = '*}'; $replacementsstr[] = '';
$patternsstr[] = '}*}'; $replacementsstr[] = '';
// $patternsstr[] = '*'; $replacementsstr[] = '';
foreach($sob as $pole => $val){
$patternsstr[] = "{objects.sobstv.".$pole."}";
$replacementsstr[] = $val;
$patternsstr[] = "%%sobstv.".$pole."%%";
$replacementsstr[] = $val;
}
if(trim($valuestr) != '' && !empty(trim($valuestr))) $valuestr .= " и <br><br>";
$valuestr .= str_replace($patternsstr, $replacementsstr, $strCont);
}
} else if(strpos($strCont, 'clients_more.') !== false){
if(!empty($clients_vals)){
foreach($clients_vals as $sob){
$patternsstr=[]; $replacementsstr=[];
$patternsstr[] = '${*{'; $replacementsstr[] = '';
//$patternsstr[] = '*}'; $replacementsstr[] = '';
$patternsstr[] = '}*}'; $replacementsstr[] = '';
// $patternsstr[] = '*'; $replacementsstr[] = '';
foreach($sob as $pole => $val){
$patternsstr[] = "%%clients_more.".$pole."%%";
$replacementsstr[] = $val;
}
//var_dump($patternsstr);
//var_dump($replacementsstr);
if(trim($valuestr) != '' && !empty(trim($valuestr))) $valuestr .= " и <br><br>";
$valuestr .= str_replace($patternsstr, $replacementsstr, $strCont);
}
}
}
// var_dump($strCont);
//var_dump($valuestr);
$patternsprev[] = $strCont;
$replacementsprev[] = $valuestr;
/* echo json_encode($patternsprev, JSON_UNESCAPED_UNICODE)."\n";
echo json_encode($replacementsprev, JSON_UNESCAPED_UNICODE)."\n";
echo $str."\n";*/
}
// }
$gmtmsk = get_time_zone_user();
$time_zone = '';
if($gmtmsk >= 0){
$time_zone = '+'.$gmtmsk.' hour';
} else {
$time_zone = '-'.$gmtmsk.' hour';
}
$prefix_doc = self::generatePrefixDoc($blank['id'], $blank['agency_id'], $blank['prefix']);
$name = $blank['name']. ' ' .$prefix_doc.'от ' . date('d-m-Y H:i:s', strtotime($time_zone));
$content = $blank['content'];
if(isset($patternsprev) && isset($replacementsprev)){
$content = str_replace($patternsprev, $replacementsprev, $content);
}
$content = stripcslashes($content);
$content = str_replace($patterns, $replacements, $content);
$content = str_replace('${prefix.prefix_doc}', $prefix_doc, $content);
$content = stripcslashes($content);
$content = str_replace($patterns, $replacements, $content);
/* if ($section == "objects" || $section == 1){
$values = [];
for($part_index = 1; $part_index<=5; $part_index++){
// $values[] = '${objects.sobstv'.$part_index.'.id}';
$values[] = '${objects.sobstv'.$part_index.'.fio}';
$values[] = '${objects.sobstv'.$part_index.'.email}';
$values[] = '${objects.sobstv'.$part_index.'.phone}';
$values[] = '${objects.sobstv'.$part_index.'.phone2}';
$values[] = '${objects.sobstv'.$part_index.'.birthday}';
$values[] = '${objects.sobstv'.$part_index.'.type}';
$values[] = '${objects.sobstv'.$part_index.'.opis}';
$values[] = '${objects.sobstv'.$part_index.'.date_add}';
$values[] = '${objects.sobstv'.$part_index.'.budget}';
$values[] = '${objects.sobstv'.$part_index.'.source}';
}
if(!empty($values)){
$content = str_replace($values, '', $content);
}
}*/
$content = preg_replace('/(\$\{[a-zA-z0-9_.]+\})+/', ' __{Переменная ${1} не найдена}__ ', $content);
$content = str_replace(['${*{', '}*}'], '', $content);
$content = str_replace('$', '', $content);
$content = str_replace(' ', ' ', $content);
$content = addslashes(html_entity_decode($content));
if ($debug) {
echo $content;
die();
}
$blank_id = $blank['id'];
$json_client_ids = '';
if(!empty($client_ids)){
$json_client_ids = htmlentities(json_encode($client_ids));
}
if (is_null($room)) {
$params = json_encode([
'client_id' => intval($client_id),
'object_id' => intval($object_id),
'client_ids' => $json_client_ids
]);
}else {
$params = json_encode([
'client_id' => intval($client_id),
'room_id' => intval($room['id']),
'client_ids' => $json_client_ids
]);
}
$sql = "INSERT INTO `inner_docs`
(`name`, `content`, `blank_id`, `agency_id`, `params`, `created_by`) VALUES
('$name', '$content', '$blank_id', '$agency_id', '$params', '$_SESSION[id]')";
if (mysql_query($sql)) {
return [
'doc_id' => mysql_insert_id(),
'doc_name' => $name
];
} else {
return mysql_error();
}
}
return null;
}
public static function generatePrefixDoc($blank_id, $agency_id = null, $blank_prefix) {
if ($blank_prefix) {
if (!$agency_id) {
$agency_id = User::getUserAgencyID();
}
$sql = "SELECT COUNT(*) AS count FROM inner_docs WHERE `blank_id` = '$blank_id' AND `agency_id` = '$agency_id'";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$row = mysql_fetch_assoc($res);
$prefix_number = $row['count'] + 1;
} else {
$prefix_number = 1;
}
$currentYear = date('Y');
$prefix_name = $prefix_number . '/'.$blank_prefix .'/'.$currentYear. ' ';
} else {
$prefix_name = '';
}
return $prefix_name;
}
}
?>