Joywork/ajax/send_pdf.php
2026-05-22 21:21:54 +03:00

283 lines
10 KiB
PHP
Raw Permalink 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
require_once($_SERVER['DOCUMENT_ROOT']."/config.php");
ini_set('memory_limit', '8192M');
//error_reporting(E_ALL | E_STRICT);
//ini_set('display_errors', 1);
// hide_client_contacts: блокируем РЕАЛЬНУЮ отправку (mail/whatsapp/telegram) PDF-презентации.
// Генерацию PDF и ссылки (без отправки) разрешаем.
$_postSendType = isset($_POST['send_type']) ? $_POST['send_type'] : '';
$_isActualSend = in_array($_postSendType, ['mail', 'whatsapp', 'telegram'], true);
if ($_isActualSend
&& function_exists('should_hide_contacts_for_current_user')
&& should_hide_contacts_for_current_user()
) {
http_response_code(403);
echo json_encode([
'error' => 'hide_client_contacts',
'message' => 'Отправка PDF-презентаций через E-mail/WhatsApp/Telegram недоступна: контакты клиентов скрыты.'
]);
exit;
}
if($_POST['clients'])
{
$user = new User();
$user->get($_SESSION['id']);
if($user->agencyName) {
$title = 'Агентство недвижимости '.$user->agencyName;
} else {
$title = $user->fio;
}
if($user->phoneAgency) {
$phone = $user->phoneAgency;
} else {
$phone = $user->phone;
}
if($_SESSION['agency']) {
$manager = trim($user->last_name . ' ' . $user->first_name . ' ' . $user->middle_name);
} else {
$manager = $_SESSION['fio'];
}
$send_type = 0;
if(!empty($SEND_TYPE_PDF[$_POST['send_type']])){
$send_type = $SEND_TYPE_PDF[$_POST['send_type']];
}
$theme = !empty($_POST['theme']) ? $_POST['theme'] : "Презентации объектов недвижимости";
$txt = !empty($_POST['txt']) ? str_replace("\n","<br>",$_POST['txt']) : "Уважаемый клиент, отправляю Вам варианты объектов недвижимости. С удовольствием отвечу на ваши вопросы.";
$footer = "<br> $manager<br> ".$user->phone."<br> ".$user->email;
if ($_SESSION['individual'] == 0) {
$footer .= "<br> $title<br>$phone";
}
$pdfs = $adresses = array();
$clientIds = $_POST['clients'];
$requestId = isset($_POST['request']) ? (int)$_POST['request'] : null;
$userId = $_SESSION['id'];
$toSend = $_SESSION['to_send'];
$toSendNewBuildings = $_SESSION['to_send_newbuilding'];
$toSendComplexes = $_SESSION['to_send_complexes'];
$toSendASFilter = $_SESSION['to_send_asfilter'];
$_SESSION['to_send'] = array();
$_SESSION['to_send_newbuilding'] = array();
$_SESSION['to_send_complexes'] = array();
$_SESSION['to_send_asfilter'] = array();
session_write_close();
$closes_contact = array();
if($send_type == 0){
$closes_contact = json_decode($_POST['closes_contact'], true);
}
$prices = array();
if(isset($_POST['priсes'])){
$prices = json_decode($_POST['priсes'], true);
}
$hideAddresses = [];
if(isset($_POST['address'])){
$hideAddresses = json_decode($_POST['address'], true);
}
$result = SelectelApi::getTokenAndUrl();
$token = $result[0];
$storageUrl = $result[1];
foreach($toSend as $sts)
{
$pdfs[] = $_SERVER['DOCUMENT_ROOT']."/pdf/$sts-$userId.pdf";
$sql = "SELECT nazv, adres, phone, sobstv FROM objects WHERE id=$sts";
$rez = mysql_query($sql);
$obj = mysql_fetch_assoc($rez);
//Доп обработка
if(!$obj['etazh']) $obj['etazh']=Filter::getFloorFromName($obj['nazv'],true);
else Filter::getFloorFromName($obj['nazv'],true);
if(!$obj['etazh_iz']) $obj['etazh_iz']=Filter::getMaxFloorFromName($obj['nazv'],true);
else Filter::getMaxFloorFromName($obj['nazv'],true);
Filter::getSpaceFromName($obj['nazv'],true);
$obj['nazv']=Filter::name($obj['nazv']);
$adresses[] = $obj['nazv'];
if(isset($hideAddresses[$sts]) && $hideAddresses[$sts] == 1){
$obj['adres'] = '';
}
$sql = "INSERT INTO archive(nazv, adres, phone, sobstv, id_obj) VALUES('$obj[nazv]', '$obj[adres]', '$obj[phone]', '$obj[sobstv]', '$sts')";
mysql_query($sql);
foreach ($clientIds as $id_client) {
$close_contact = 0;
if(isset($closes_contact[$sts])){
$close_contact = $closes_contact[$sts];
}
$cena = 0;
if(isset($prices[$sts])){
$cena = $prices[$sts];
}
$urlToSave = "/pdf/$sts-$userId.pdf";
//сохраняем ПДФ в селектел
if ($token && $storageUrl) {
$fullPath = $_SERVER['DOCUMENT_ROOT']."/pdf/$sts-$userId.pdf";
$name = "$sts-$userId.pdf";
$x = mb_substr($name,0,1);
$y = mb_substr($name,1,1);
$z = mb_substr($name,2,1);
$dstFile = "$x/$y/$z/$name";
$r = SelectelApi::uploadPdfFile($storageUrl, $token, $fullPath, $dstFile);
if ($r) {
//заменяем путь на новый
$urlToSave = "https://pdf.joywork.ru/" . $dstFile;
}
}
$sql = "INSERT INTO sended_pdf(id_agent, id_object, date_send, id_client, nazv, path, close_contact, send_type, new_price, id_request) VALUES('$userId', '$sts', NOW(), '$id_client', '$obj[nazv] $obj[adres]', '$urlToSave', $close_contact, $send_type, '$cena', '$requestId')";
mysql_query($sql);
$sql = "UPDATE clients SET stage = 3 WHERE id = $id_client";
mysql_query($sql);
}
if (count($toSendASFilter) > 0) {
$asfilter = new AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
}
foreach($toSendNewBuildings as $sts)
{
$linkUrl = "https://joywork.ru/newbuilding-view.php?id=$sts&token=".md5($userId);
$sql = "SELECT a.id, a.number, b.name, b.address FROM apartments a, blocks b WHERE b.id = a.block_id AND a.id='$sts'";
$rez = mysql_query($sql);
if (mysql_num_rows($rez) > 0) {
$objts = mysql_fetch_assoc($rez);
if(isset($hideAddresses[$sts]) && $hideAddresses[$sts] == 1){
$objts['address'] = '';
}
$nazv = "Квартира №$objts[number] в комплексе $objts[name]";
if($send_type == 0) {
$txt .= "<br/><a href='$linkUrl' target='_blank'>$nazv</a><br/>";
} else {
$txt .= $nazv . " " . $linkUrl;
}
foreach ($clientIds as $id_client) {
$sql = "INSERT INTO sended_pdf_newbuildings(id_agent, id_object, date_send, id_client, nazv, path, send_type, id_request) VALUES('$userId', '$sts', NOW(), '$id_client', '$nazv $objts[address]', '$linkUrl', $send_type, '$requestId')";
mysql_query($sql);
}
if (count($toSendASFilter) > 0) {
$asfilter = new AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
}
}
foreach($toSendComplexes as $tsc)
{
$linkUrl = "https://joywork.ru/newbuilding-view.php?id=$sts&token=".md5($userId);
// $sql = "SELECT a.id, a.number, b.name, b.address FROM apartments a, blocks b WHERE b.id = a.block_id AND a.id='$tsc'";
$sql = "SELECT cr.id as id, cl.name as complex_name, cl.id as complex_id, cr.type as type, cr.number as number, ca.address as address FROM complex_list cl
JOIN complex_houses ch ON ch.complex_id = cl.id
JOIN complex_entrances ce ON ce.complex_house_id = ch.id
JOIN complex_floors cf ON cf.complex_entrance_id = ce.id
JOIN complex_rooms cr ON cr.floor_id = cf.id
LEFT JOIN complex_address ca on ca.complex_id = cl.id
where cr.id = $ts
";
$rez = mysql_query($sql);
if (mysql_num_rows($rez) > 0) {
$objts = mysql_fetch_assoc($rez);
if(isset($hideAddresses[$tsc]) && $hideAddresses[$tsc] == 1){
$objts['address'] = '';
// var_dump($objts);die;
}
$nazv = "Квартира №$objts[number] в комплексе $objts[name]";
if($send_type == 0) {
$txt .= "<br/><a href='$linkUrl' target='_blank'>$nazv</a><br/>";
} else {
$txt .= $nazv . " " . $linkUrl;
}
foreach ($clientIds as $id_client) {
$sql = "INSERT INTO sended_pdf_newbuildings(id_agent, id_object, date_send, id_client, nazv, path, send_type, id_request) VALUES('$userId', '$sts', NOW(), '$id_client', '$nazv $objts[address]', '$linkUrl', $send_type, '$requestId')";
mysql_query($sql);
}
if (count($toSendASFilter) > 0) {
$asfilter = new AutoSearch();
foreach ($toSendASFilter as $filter_id => $object_id) {
if (!is_null($filter_id) && !is_null($object_id))
$asfilter->addObjectToSended($filter_id, $object_id);
}
}
}
}
$txt .= $footer;
for($i=0; $i < count($pdfs); $i++)
{
$num = $i+1;
$pis[$x][] = $pdfs[$i];
$addr[$x][] = $adresses[$i];
if($num % 5 == 0) $x++;
}
foreach ($clientIds as $clientId) {
$mail = mysql_result(mysql_query("SELECT email FROM clients WHERE deleted <> 1 AND id = $clientId"),0);
if (isset($pis)) {
foreach ($pis as $x => $pismo) {
mailClientByIdWithConfirm($userId, trim($mail), $theme, $txt, $pismo, $addr[$x]);
if ($token && $storageUrl) {
foreach ($pismo as $i => $path) {
//удаляем файл с локального сервера
unlink($path);
}
}
sleep(1);
}
} else {
mailClientByIdWithConfirm($userId, trim($mail), $theme, $txt, [], []);
}
}
}