2025-09-26 10:43:05 +03:00
< ? php
/*********************************************************************************
* Н а б о р методов для отправки заказных писем на бумаге через сервис pochta - sud . ru
* All Rights Reserved .
* Contributor ( s ) : Илья Руденко itsaturn @ yandex . ru
********************************************************************************/
require_once 'include/utils/utils.php' ;
require_once 'include/Webservices/Revise.php' ;
require_once 'modules/Users/Users.php' ;
require_once 'includes/Loader.php' ;
include_once 'include/Webservices/Query.php' ;
require_once 'include/Webservices/Utils.php' ;
vimport ( 'includes.runtime.Globals' );
vimport ( 'includes.runtime.BaseModel' );
vimport ( 'includes.runtime.LanguageHandler' );
2025-10-16 11:17:21 +03:00
/**
* Очищает временные файлы , скачанные из S3
*/
function cleanupTempFiles ( $files ) {
foreach ( $files as $file ) {
if ( isset ( $file [ 'is_temp_file' ]) && $file [ 'is_temp_file' ] === true && file_exists ( $file [ 'filepath' ])) {
unlink ( $file [ 'filepath' ]);
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - удален временный файл: ' . $file [ 'filepath' ] . PHP_EOL , FILE_APPEND );
}
}
}
/**
* Получает временный файл из S3 для использования в multipart запросе
*/
function getTempFileFromS3 ( $s3Bucket , $s3Key , $tempFilename ) {
try {
// Убираем #realfile из ключа если есть
$cleanKey = str_replace ( '#realfile' , '' , $s3Key );
// Создаем правильный URL с правильной кодировкой S3 ключа
$encodedKey = implode ( '/' , array_map ( 'rawurlencode' , explode ( '/' , $cleanKey )));
$s3Url = " https://s3.twcstorage.ru/ $s3Bucket / $encodedKey " ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - скачиваем файл из S3: ' . $s3Url . PHP_EOL , FILE_APPEND );
$ch = curl_init ();
curl_setopt ( $ch , CURLOPT_URL , $s3Url );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
curl_setopt ( $ch , CURLOPT_TIMEOUT , 30 );
curl_setopt ( $ch , CURLOPT_FOLLOWLOCATION , true );
$fileContent = curl_exec ( $ch );
$httpCode = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
curl_close ( $ch );
if ( $httpCode === 200 && $fileContent !== false ) {
$tempPath = sys_get_temp_dir () . '/' . $tempFilename ;
file_put_contents ( $tempPath , $fileContent );
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - файл сохранен во временную папку: ' . $tempPath . PHP_EOL , FILE_APPEND );
return $tempPath ;
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - ошибка скачивания файла из S3, HTTP код: ' . $httpCode . PHP_EOL , FILE_APPEND );
return false ;
}
} catch ( Exception $e ) {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - исключение при скачивании из S3: ' . $e -> getMessage () . PHP_EOL , FILE_APPEND );
return false ;
}
}
2025-09-26 10:43:05 +03:00
function getDoc ( $projectid , $letter_id , $lettertype , $doctype ) {
$lettertype = mb_strtolower ( $lettertype );
$type = mb_strtolower ( $doctype );
file_put_contents ( 'logs/Letters.log' , PHP_EOL . date ( 'Y-m-d H:i:s' ) . ' - Запрос ' . $doctype . ' для отправления ' . $letter_id . ' - ' . $lettertype . PHP_EOL , FILE_APPEND );
$allowed = array ( 'справка' , 'опись' );
if ( ! in_array ( $doctype , $allowed )) {
file_put_contents ( 'logs/Letters.log' , PHP_EOL . date ( 'Y-m-d H:i:s' ) . ' - Н о это недопустимый тип документа - поэтому выходим' . PHP_EOL , FILE_APPEND );
return 'Неизвестный тип документа : ' . $doctype ;
}
if ( ! is_numeric ( $letter_id )) {
return 'Н е указан № отправления letter_id' ;
}
// Инициализация cURL
$ch = curl_init ();
// $token = 'ead6ccca0c820b63286cd0f2fca5821d'; // Тестовый
//$token = '9e9dce7a0cef9d90404169286762669f'; // Боевой
$token = '8da7669523a916b2862824dbf77a4198' ; // Боевой
if ( $doctype == 'справка' ) {
$url = 'https://api.pochta-sud.ru/letter/' . $letter_id . '/invoice' ;
} else {
$url = 'https://api.pochta-sud.ru/letter/' . $letter_id . '/listing' ;
}
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - сформировали url: ' . $url . PHP_EOL , FILE_APPEND );
curl_setopt ( $ch , CURLOPT_URL , $url );
curl_setopt ( $ch , CURLOPT_POST , 0 );
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ( $ch , CURLOPT_HTTPHEADER , [
'Authorization: Bearer ' . $token ,
2025-10-16 11:17:21 +03:00
// Content-Type: multipart/form-data автоматически добавляется cURL с правильным boundary
2025-09-26 10:43:05 +03:00
]);
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
// Выполнение запроса
$output = curl_exec ( $ch );
// Проверка на ошибки
if ( curl_errno ( $ch )) {
$output = 'Ошибка:' . curl_error ( $ch );
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - получили ошибку от сервера: ' . curl_error ( $ch ) . PHP_EOL , FILE_APPEND );
} else {
if ( $output == 'Not Found: Invoice not found' ) {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - получили ответ от сервера - Not Found: Invoice not found' . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - получили корректный ответ от сервера, начинаем сохранять файл' . PHP_EOL , FILE_APPEND );
global $adb , $current_user ;
// 0. Готовим имя файла
$noteid = $adb -> getUniqueID ( " vtiger_crmentity " );
$attachid = $adb -> getUniqueID ( " vtiger_crmentity " );
if ( $lettertype == 'претензионное' ) {
if ( $doctype == 'опись' ) {
$filename = 'До ка за те льс тво _на пр а вле ния_пр е те нзии_о тве тчику .pdf' ;
$description = 'Доказательство направления претензии ответчику' ;
} elseif ( $doctype == 'справка' ) {
$filename = 'До ка за те льс тво _о пла ты_на пр а вле ния_пр е те нзии_о тве тчику .pdf' ;
$description = 'Доказательство оплаты направления претензии ответчику' ;
} else {
$filename = 'Н е изве с ный_до ку ме нт.pdf' ;
$description = 'Неизвесный документ при отправке претензионного' ;
}
} elseif ( $lettertype == 'исковое' ) {
if ( $doctype == 'опись' ) {
$filename = 'До ка за те льс тво _на пр а вле ния_ис ка _о тве тчику .pdf' ;
$description = 'Доказательство направления иска ответчику' ;
} elseif ( $doctype == 'справка' ) {
$filename = 'До ка за те льс тво _о пла ты_на пр а вле ния_ис ка _о тве тчику .pdf' ;
$description = 'Доказательство оплаты направления иска ответчику' ;
} else {
$filename = 'Н е изве с ный_до ку ме нт.pdf' ;
$description = 'Неизвесный документ при отправке искового' ;
}
} else {
$filename = 'Н е изве с ный_до ку ме нт.pdf' ;
$description = 'Запрос ' . $doctype . ' по отправлению неизвестного типа: ' . $lettertype ;
}
$upload_file_path = decideFilePath (); // Получили папку для сохранения
$file = $upload_file_path . $attachid . " _ " . $filename ; // Собрали имя новому файлу
file_put_contents ( $file , $output );
// 1. Создаем сущность Документ
$date_var = date ( 'Y-m-d H:i:s' );
$ownerid = getUserId ( $projectid ); // Поднимем ответственного из проекта, куда добавляем файл
// 1.1 Запись в crmentity
$sql1 = " insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,createdtime,modifiedtime) values(?,?,?,?,?,?) " ;
$params1 = array ( $noteid , $ownerid , $ownerid , 'Documents' , $adb -> formatDate ( $date_var , true ), $adb -> formatDate ( $date_var , true ));
$adb -> pquery ( $sql1 , $params1 );
$logstring = date ( 'Y-m-d H:i:s' ) . ' Добавили Документ в crmentity' . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
// 1.2 Запись в notes
/*
$logstring = date ( 'Y-m-d H:i:s' ) . ' Готовимся добавлять: noteid: ' . $noteid . ';' ;
$logstring .= ' description: ' . $description . ';' ;
$logstring .= ' filename: ' . $filename . ';' ;
$logstring .= ' filesize: ' . filesize ( $file ) . ';' . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
*/
$sql2 = " insert into vtiger_notes(notesid, title, filename, folderid, filetype, filelocationtype, filedownloadcount, filestatus, filesize) values(?,?,?,?,?,?,?,?,?) " ;
$params2 = array ( $noteid , $description , $filename , 3 , 'application/pdf' , 'I' , 0 , 1 , filesize ( $file ));
$adb -> pquery ( $sql2 , $params2 );
$logstring = date ( 'Y-m-d H:i:s' ) . ' Добавили Документ в notes: https://crm.clientright.ru/index.php?module=Documents&view=Detail&record=' . $noteid . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
// 2. Создаем сущность Аттачи Документов
// 2.1 Запись в crmentity
$sql1 = " insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,createdtime,modifiedtime) values(?,?,?,?,?,?) " ;
$params1 = array ( $attachid , $ownerid , $ownerid , 'Documents Attachment' , $adb -> formatDate ( $date_var , true ), $adb -> formatDate ( $date_var , true ));
$adb -> pquery ( $sql1 , $params1 );
$logstring = date ( 'Y-m-d H:i:s' ) . ' Добавили файл в crmentity' . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
// 2.2 Запись в attachments
$sql2 = " insert into vtiger_attachments(attachmentsid, name, type, path, storedname) values(?,?,?,?,?) " ;
$params2 = array ( $attachid , $filename , 'application/pdf' , $upload_file_path , $filename );
$adb -> pquery ( $sql2 , $params2 );
$logstring = date ( 'Y-m-d H:i:s' ) . ' Добавили файл в attachments: ' . $attachid . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
// 3. Связываем Документ с Аттачем
$sql3 = " insert into vtiger_seattachmentsrel(crmid, attachmentsid) values(?,?) " ;
$adb -> pquery ( $sql3 , array ( $noteid , $attachid ));
$logstring = date ( 'Y-m-d H:i:s' ) . ' связали файл с Документом' . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
// 4. Привязываем Документ к Проекту (или другой сущности) по crmid
$sql4 = " insert into vtiger_senotesrel(crmid, notesid) values(?,?) " ;
$adb -> pquery ( $sql4 , array ( $projectid , $noteid ));
$logstring = date ( 'Y-m-d H:i:s' ) . ' связали Документ с Проектом' . PHP_EOL ;
file_put_contents ( 'logs/Letters.log' , $logstring , FILE_APPEND );
$output = 'YES' ;
}
return $output ;
}
// Закрытие cURL сессии
curl_close ( $ch );
}
function SendLetter ( $projectid , $type ) {
$type = mb_strtolower ( $type );
file_put_contents ( 'logs/Letters.log' , PHP_EOL . date ( 'Y-m-d H:i:s' ) . ' - Отправляем ' . $type . ' по Проекту ' . $projectid . PHP_EOL , FILE_APPEND );
$allowed = array ( 'претензионное' , 'исковое' );
if ( ! in_array ( $type , $allowed )) {
file_put_contents ( 'logs/Letters.log' , PHP_EOL . date ( 'Y-m-d H:i:s' ) . ' - Н о это недопустимый тип отправления - поэтому выходим ' . $projectid . PHP_EOL , FILE_APPEND );
return 'Неизвестный тип отправления : ' . $type ;
}
$output = 'YES' ;
global $adb ;
$query = ' select u . index_notice , u . addr_notice , u . id as userid , a . accountid , a . accountname , a . inn , a . kpp , la . bill_code , la . bill_city , la . bill_street , ra . ship_code , ra . ship_city , ra . ship_street , a . phone , a . email1 , pcf . cf_1511 as price , ca . mailingstreet , acf . cf_1951 as ogrn , u . email1 as usermail , pcf . cf_2274 as acc1 , pcf . cf_2276 as acc2 , pcf . cf_2292 as jurisdiction , pcf . cf_2294 as agrplace , oa . bill_code as offindex , oa . bill_city as offcity , oa . bill_street as offstreet , p . linktoaccountscontacts as contactid , pcf . cf_1507 as casenumber , o . accountname as offname
from vtiger_project p
left join vtiger_projectcf pcf on pcf . projectid = p . projectid
left join vtiger_contactdetails cd on cd . contactid = p . linktoaccountscontacts
left join vtiger_contactaddress ca on ca . contactaddressid = p . linktoaccountscontacts
left join vtiger_account a on a . accountid = pcf . cf_1994
left join vtiger_accountscf acf on acf . accountid = pcf . cf_1994
left join vtiger_accountbillads la on la . accountaddressid = pcf . cf_1994
left join vtiger_accountshipads ra on ra . accountaddressid = pcf . cf_1994
left join vtiger_account o on o . accountid = pcf . cf_2274
left join vtiger_accountbillads oa on oa . accountaddressid = pcf . cf_2274
left join vtiger_crmentity e on e . crmid = p . projectid
left join vtiger_users u on u . id = e . smownerid
where e . deleted = 0 and p . projectid = ' . $projectid ;
$result = $adb -> pquery ( $query );
// cf_2274 - злодей
// cf_1994 - заявитель
if ( $adb -> num_rows ( $result ) == 0 ) {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Проект с id ' . $projectid . ' не найден' . PHP_EOL , FILE_APPEND );
return 'Проект не найден' ;
} else {
$accountid = $adb -> query_result ( $result , 0 , 'accountid' );
$acc1 = $adb -> query_result ( $result , 0 , 'acc1' );
$acc2 = $adb -> query_result ( $result , 0 , 'acc2' );
$userid = $adb -> query_result ( $result , 0 , 'userid' );
$name = str_replace ( '"' , '"' , $adb -> query_result ( $result , 0 , 'accountname' ));
$name = str_replace ( '«' , '"' , $name );
$name = str_replace ( '»' , '"' , $name );
//$name = str_replace('"', '', $name);
//$name = addslashes($name);
$offname = str_replace ( '"' , '"' , $adb -> query_result ( $result , 0 , 'offname' ));
$offname = str_replace ( '«' , '"' , $offname );
$offname = str_replace ( '»' , '"' , $offname );
//$offname = str_replace('"', '', $offname);
//$offname = addslashes($offname);
// Данные отправителя
$source = [
'type' => 'organization' ,
'taxId' => $adb -> query_result ( $result , 0 , 'inn' ),
'name' => $name ,
'email' => $adb -> query_result ( $result , 0 , 'email1' )
];
if ( empty ( $adb -> query_result ( $result , 0 , 'ship_code' ))) {
$source [ 'address' ] = $adb -> query_result ( $result , 0 , 'ship_street' );
} else {
$source [ 'address' ] = $adb -> query_result ( $result , 0 , 'ship_code' ) . ', ' . $adb -> query_result ( $result , 0 , 'ship_city' ) . ', ' . $adb -> query_result ( $result , 0 , 'ship_street' );
}
// Данные получателя
if ( strlen ( trim ( $adb -> query_result ( $result , 0 , 'inn' ))) == 10 ) {
$destination = [ 'type' => 'organization' , 'taxId' => $adb -> query_result ( $result , 0 , 'inn' )];
} else {
$destination = [ 'type' => 'individual' ];
}
$destination [ 'name' ] = $offname ;
if ( empty ( $adb -> query_result ( $result , 0 , 'offindex' ))) {
$destination [ 'address' ] = $adb -> query_result ( $result , 0 , 'offstreet' );
} else {
$destination [ 'address' ] = $adb -> query_result ( $result , 0 , 'offindex' ) . ', ' . $adb -> query_result ( $result , 0 , 'offcity' ) . ', ' . $adb -> query_result ( $result , 0 , 'offstreet' );
}
// Файлы для отправки
$claim = getClaim ( $projectid , $type ); // Ищем основной документ для отправки - исковое заявление или претензию
if ( $claim [ 'result' ] == 'NO' ) {
// Н е нашлось основного документа в Проекте
if ( $type == 'исковое' ) {
2025-10-16 11:17:21 +03:00
return 'В Проекте ' . $projectid . ' отсутствует Исковое заявление' ;
2025-09-26 10:43:05 +03:00
} elseif ( $type == 'претензионное' ) {
2025-10-16 11:17:21 +03:00
return 'В Проекте ' . $projectid . ' отсутствует претензионное письмо' ;
2025-09-26 10:43:05 +03:00
}
} else {
$document = new CURLFile ( $claim [ 'filepath' ], 'application/pdf' ); // Есть основной документ - добавляем е г о в массив
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - добавили в массив файл "' . $claim [ 'filename' ] . '"' . PHP_EOL , FILE_APPEND );
2025-10-16 11:17:21 +03:00
// Устанавливаем правильное имя для основного документа
$document_name = 'Исковое заявление.pdf' ;
if ( $type == 'претензионное' ) {
$document_name = 'Претензионное письмо.pdf' ;
}
2025-09-26 10:43:05 +03:00
$authdoc = getAuthDoc ( $accountid , $userid ); // Поднимаем доверку на представителя Заявителя (он же ответственный по Проекту)
if ( $authdoc [ 'result' ] == 'NO' ) {
// Нет у представителя Заявителя доверки
return 'У Ответственного по Проекту ' . $projectid . ' в Контрагенте ' . $accountid . ' нет доверенности от Заявителя' ;
} else {
$attachments = [];
// $attachments[0] = fopen($authdoc['filepath'], 'r'); // Есть доверка - добавляем е е в массив
$attachments [ 0 ] = new CURLFile ( $authdoc [ 'filepath' ], 'application/pdf' ); // Есть доверка - добавляем е е в массив
$attachment_names [ 0 ] = 'Доверенность.pdf' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - добавили в массив файл "' . $authdoc [ 'filepath' ] . '" и дали ему имя: ' . $attachment_names [ 0 ] . PHP_EOL , FILE_APPEND );
// А дальше разница - если отправка искового, то надо добыть все документы для суда. А для отправки претензии - только добавить заявление терпилы
if ( $type == 'исковое' ) {
$otherDocs = getOtherDocs ( $projectid , $accountid , $acc1 , $acc2 ); // Получили массив всех прочих документов Проекта и связанных Контрагентов
if ( count ( $otherDocs ) > 0 ) {
2025-10-16 11:17:21 +03:00
$attachmentIndex = 1 ; // Начинаем с индекса 1 (0 занят доверенностью)
2025-09-26 10:43:05 +03:00
for ( $i = 0 ; $i < count ( $otherDocs ); $i ++ ) {
2025-10-16 11:17:21 +03:00
// Проверяем, что у файла есть валидный путь
if ( ! empty ( $otherDocs [ $i ][ 'filepath' ]) && file_exists ( $otherDocs [ $i ][ 'filepath' ])) {
$attachments [ $attachmentIndex ] = new CURLFile ( $otherDocs [ $i ][ 'filepath' ], 'application/pdf' );
$attachment_names [ $attachmentIndex ] = $otherDocs [ $i ][ 'description' ] . '.pdf' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - добавили в массив файл "' . $otherDocs [ $i ][ 'filepath' ] . '"; и дали ему имя: ' . $attachment_names [ $attachmentIndex ] . PHP_EOL , FILE_APPEND );
$attachmentIndex ++ ;
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - пропускаем файл "' . $otherDocs [ $i ][ 'description' ] . '" - нет файла или файл недоступен' . PHP_EOL , FILE_APPEND );
}
2025-09-26 10:43:05 +03:00
}
}
} elseif ( $type == 'претензионное' ) {
$plea = getPlea ( $projectid ); // Поднимаем точечно заявление терпилы
if ( $plea [ 'result' ] == 'NO' ) {
// В Проекте нет заявления потерпевшего
return 'В Проекте ' . $projectid . ' нет заявления потерпевшего' ;
} else {
// $attachments[1] = fopen($plea['filepath'], 'r');
$attachments [ 1 ] = new CURLFile ( $plea [ 'filepath' ], 'application/pdf' );
$attachment_names [ 1 ] = 'Заявление.pdf' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - добавили в массив файл "' . $plea [ 'filepath' ] . '" и дали ему имя: ' . $attachment_names [ 1 ] . PHP_EOL , FILE_APPEND );
}
}
// Создание массива данных для отправки
$data = [];
$data [ 'source' ] = json_encode ( $source );
$data [ 'destination' ] = json_encode ( $destination );
$data [ 'document' ] = $document ;
2025-10-16 11:17:21 +03:00
$data [ 'document_name' ] = $document_name ; // Добавляем правильное имя для основного документа
2025-09-26 10:43:05 +03:00
for ( $i = 0 ; $i < count ( $attachments ); $i ++ ) {
$attstr = 'attachments[' . $i . ']' ;
$data [ $attstr ] = $attachments [ $i ];
$attstr = 'attachment_names[' . $i . ']' ;
$data [ $attstr ] = $attachment_names [ $i ];
// Вместо
// $data['attachments[0]'] = $attachments[0];
// $data['attachments[1]'] = $attachments[1];
// $data['attachments[2]'] = $attachments[2];
}
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - итоговый массив для отправки: ' . json_encode ( $data ) . PHP_EOL , FILE_APPEND );
// Инициализация cURL
$ch = curl_init ();
// $token = 'ead6ccca0c820b63286cd0f2fca5821d'; // Тестовый
// $token = '9e9dce7a0cef9d90404169286762669f'; // Боевой
$token = '8da7669523a916b2862824dbf77a4198' ; // Боевой
curl_setopt ( $ch , CURLOPT_URL , 'https://api.pochta-sud.ru/letter' );
curl_setopt ( $ch , CURLOPT_POST , 1 );
curl_setopt ( $ch , CURLOPT_POSTFIELDS , $data );
curl_setopt ( $ch , CURLOPT_HTTPHEADER , [
'Authorization: Bearer ' . $token ,
2025-10-16 11:17:21 +03:00
// Content-Type: multipart/form-data автоматически добавляется cURL с правильным boundary
2025-09-26 10:43:05 +03:00
]);
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
// Выполнение запроса
$output = curl_exec ( $ch );
// Проверка на ошибки
if ( curl_errno ( $ch )) {
$output = 'Ошибка:' . curl_error ( $ch );
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - получили ошибку от сервера: ' . curl_error ( $ch ) . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - получили корректный ответ от сервера: ' . $output . PHP_EOL , FILE_APPEND );
$arr = json_decode ( $output , true );
$output = $arr [ 'letter_id' ];
if ( ! is_numeric ( $output )) {
// Что-то пошло не так - получили корректный ответ о б ошибке, без взрыва. Вытащим е г о
$output = $arr [ 'message' ];
}
}
// Закрытие cURL сессии
curl_close ( $ch );
2025-10-16 11:17:21 +03:00
// Очищаем временные файлы
$tempFiles = array ();
if ( isset ( $claim [ 'is_temp_file' ]) && $claim [ 'is_temp_file' ]) {
$tempFiles [] = $claim ;
}
if ( isset ( $authdoc [ 'is_temp_file' ]) && $authdoc [ 'is_temp_file' ]) {
$tempFiles [] = $authdoc ;
}
if ( isset ( $otherDocs )) {
foreach ( $otherDocs as $doc ) {
if ( isset ( $doc [ 'is_temp_file' ]) && $doc [ 'is_temp_file' ]) {
$tempFiles [] = $doc ;
}
}
}
if ( isset ( $plea [ 'is_temp_file' ]) && $plea [ 'is_temp_file' ]) {
$tempFiles [] = $plea ;
}
cleanupTempFiles ( $tempFiles );
2025-09-26 10:43:05 +03:00
}
}
}
return $output ;
}
function getAuthDoc ( $accountid , $userid ) {
// Возвращает доверенность от терпилы заявителю
global $adb ;
$output = [];
$query = ' select
n . title , ncf . cf_1953 as pages ,
case when a . storedname is not null
then concat ( a . `path` , a . attachmentsid , " _ " , a . storedname )
else concat ( a . `path` , a . attachmentsid , " _ " , a . name )
end as filepath ,
case when a . storedname is not null
then concat ( a . attachmentsid , " _ " , a . storedname )
else concat ( a . attachmentsid , " _ " , a . name )
end as filename ,
2025-10-16 11:17:21 +03:00
a . `type` , n . filename as s3_filename , n . s3_bucket , n . s3_key , n . filelocationtype
2025-09-26 10:43:05 +03:00
from vtiger_senotesrel r
left join vtiger_notes n on n . notesid = r . notesid
left join vtiger_crmentity e on e . crmid = r . notesid
left join vtiger_notescf ncf on ncf . notesid = r . notesid
left join vtiger_seattachmentsrel r2 on r2 . crmid = r . notesid
left join vtiger_attachments a on a . attachmentsid = r2 . attachmentsid
where e . smownerid = ? and r . crmid = ? and e . deleted = 0 and n . filename like " %по дтве р жда ющий_по лно мо чия% " ' ;
$result = $adb -> pquery ( $query , array ( $userid , $accountid ));
if ( $adb -> num_rows ( $result ) == 0 ) {
$output [ 'result' ] = 'NO' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - доверенность с подстрокой "по дтве р жда ющий_по лно мо чия" в Контрагенте ' . $accountid . ' не найдена' . PHP_EOL , FILE_APPEND );
} else {
$output [ 'result' ] = 'YES' ;
$output [ 'description' ] = $adb -> query_result ( $result , 0 , 'title' );
if ( ! is_numeric ( substr ( $output [ 'description' ], 0 , 1 ))) {
2025-10-16 11:17:21 +03:00
$output [ 'description' ] = '0_' . $output [ 'description' ];
2025-09-26 10:43:05 +03:00
}
$output [ 'description' ] = str_replace ( ' ' , '_' , $output [ 'description' ]);
2025-10-16 11:17:21 +03:00
// Проверяем тип размещения файла
$filelocationtype = $adb -> query_result ( $result , 0 , 'filelocationtype' );
$s3_filename = $adb -> query_result ( $result , 0 , 's3_filename' );
$s3_bucket = $adb -> query_result ( $result , 0 , 's3_bucket' );
$s3_key = $adb -> query_result ( $result , 0 , 's3_key' );
if ( $filelocationtype == 'E' && ! empty ( $s3_bucket ) && ! empty ( $s3_key )) {
// Файл в S3 - скачиваем во временную папку
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - доверенность найдена в S3, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
$tempFilename = 'auth_doc_' . time () . '.pdf' ;
$tempPath = getTempFileFromS3 ( $s3_bucket , $s3_key , $tempFilename );
if ( $tempPath ) {
$output [ 'filepath' ] = $tempPath ;
$output [ 'is_temp_file' ] = true ; // Флаг для последующей очистки
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - S3 файл доверенности успешно скачан во временную папку' . PHP_EOL , FILE_APPEND );
} else {
$output [ 'result' ] = 'NO' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - не удалось скачать доверенность из S3' . PHP_EOL , FILE_APPEND );
return $output ;
}
} else {
// Локальный файл (оригинальная логика)
$output [ 'filepath' ] = $adb -> query_result ( $result , 0 , 'filepath' );
}
2025-09-26 10:43:05 +03:00
$output [ 'filename' ] = $adb -> query_result ( $result , 0 , 'title' ) . '.pdf' ;
if ( ! is_numeric ( substr ( $output [ 'filename' ], 0 , 1 ))) {
2025-10-16 11:17:21 +03:00
$output [ 'filename' ] = '0_' . $output [ 'filename' ];
2025-09-26 10:43:05 +03:00
}
$output [ 'filename' ] = str_replace ( ' ' , '_' , $output [ 'filename' ]);
$output [ 'type' ] = $adb -> query_result ( $result , 0 , 'type' );
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Нашли доверенность в Контрагенте ' . $accountid . PHP_EOL , FILE_APPEND );
}
return $output ;
}
function getClaim ( $projectid , $type ) {
// Возвращает основной документ-требование по Проекту. Это может быть исковое заявление или претензионное письмо
global $adb ;
$output = [];
$query = ' select
n . title , ncf . cf_1953 as pages ,
case when a . storedname is not null
then concat ( a . `path` , a . attachmentsid , " _ " , a . storedname )
else concat ( a . `path` , a . attachmentsid , " _ " , a . name )
end as filepath ,
case when a . storedname is not null
then concat ( a . attachmentsid , " _ " , a . storedname )
else concat ( a . attachmentsid , " _ " , a . name )
end as filename ,
2025-10-16 11:17:21 +03:00
a . `type` , n . filename as s3_filename , n . s3_bucket , n . s3_key , n . filelocationtype
2025-09-26 10:43:05 +03:00
from vtiger_senotesrel r
left join vtiger_notes n on n . notesid = r . notesid
left join vtiger_crmentity e on e . crmid = r . notesid
left join vtiger_notescf ncf on ncf . notesid = r . notesid
left join vtiger_seattachmentsrel r2 on r2 . crmid = r . notesid
left join vtiger_attachments a on a . attachmentsid = r2 . attachmentsid
where r . crmid = ? and e . deleted = 0 and ' ;
if ( $type == 'исковое' ) {
2025-10-16 11:17:21 +03:00
// Ищем исковые заявления по нескольким критериям
$query .= '(n.filename like "%Ис ко во е _за явле ние %" OR n.title like "%Ис ко во е _за явле ние %" OR n.title like "%исковое%" OR n.filename like "%исковое%")' ;
2025-09-26 10:43:05 +03:00
} elseif ( $type == 'претензионное' ) {
$query .= 'n.notecontent = "претензия почта api"' ; // Так у нас кодируется признак претензионного письма
} else {
return false ;
}
$result = $adb -> pquery ( $query , array ( $projectid ));
if ( $adb -> num_rows ( $result ) == 0 ) {
$output [ 'result' ] = 'NO' ;
2025-10-16 11:17:21 +03:00
if ( $type == 'исковое' ) {
2025-09-26 10:43:05 +03:00
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Исковое заявление с подстрокой "Ис ко во е _за явле ние " в Проекте ' . $projectid . ' не найдено' . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Претензионное письмо с о строкой "претензия почта api" в Проекте ' . $projectid . ' не найдено' . PHP_EOL , FILE_APPEND );
}
} else {
$output [ 'result' ] = 'YES' ;
$output [ 'description' ] = $adb -> query_result ( $result , 0 , 'title' );
if ( ! is_numeric ( substr ( $output [ 'description' ], 0 , 1 ))) {
$output [ 'description' ] = '0_' . $output [ 'description' ];
}
$output [ 'description' ] = str_replace ( ' ' , '_' , $output [ 'description' ]);
2025-10-16 11:17:21 +03:00
// Проверяем тип размещения файла
$filelocationtype = $adb -> query_result ( $result , 0 , 'filelocationtype' );
$s3_filename = $adb -> query_result ( $result , 0 , 's3_filename' );
$s3_bucket = $adb -> query_result ( $result , 0 , 's3_bucket' );
$s3_key = $adb -> query_result ( $result , 0 , 's3_key' );
if ( $filelocationtype == 'E' && ! empty ( $s3_bucket ) && ! empty ( $s3_key )) {
// Файл в S3 - скачиваем во временную папку
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - основной документ найден в S3, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
$tempFilename = 'claim_doc_' . time () . '.pdf' ;
$tempPath = getTempFileFromS3 ( $s3_bucket , $s3_key , $tempFilename );
if ( $tempPath ) {
$output [ 'filepath' ] = $tempPath ;
$output [ 'is_temp_file' ] = true ; // Флаг для последующей очистки
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - S3 файл основного документа успешно скачан во временную папку' . PHP_EOL , FILE_APPEND );
} else {
$output [ 'result' ] = 'NO' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - не удалось скачать основной документ из S3' . PHP_EOL , FILE_APPEND );
return $output ;
}
} else {
// Локальный файл (оригинальная логика)
$output [ 'filepath' ] = $adb -> query_result ( $result , 0 , 'filepath' );
}
2025-09-26 10:43:05 +03:00
$output [ 'filename' ] = $adb -> query_result ( $result , 0 , 'title' ) . '.pdf' ;
if ( ! is_numeric ( substr ( $output [ 'filename' ], 0 , 1 ))) {
$output [ 'filename' ] = '0_' . $output [ 'filename' ];
}
$output [ 'filename' ] = str_replace ( ' ' , '_' , $output [ 'filename' ]);
$output [ 'type' ] = $adb -> query_result ( $result , 0 , 'type' );
if ( $processType = 'исковое' ) {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Нашли исковое заявление в Проекте ' . $projectid . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Нашли претензионное письмо в Проекте ' . $projectid . PHP_EOL , FILE_APPEND );
}
}
return $output ;
}
function getPlea ( $projectid ) {
// Возвращает заявление терпилы
global $adb ;
$output = [];
$query = ' select
n . title , ncf . cf_1953 as pages ,
case when a . storedname is not null
then concat ( a . `path` , a . attachmentsid , " _ " , a . storedname )
else concat ( a . `path` , a . attachmentsid , " _ " , a . name )
end as filepath ,
case when a . storedname is not null
then concat ( a . attachmentsid , " _ " , a . storedname )
else concat ( a . attachmentsid , " _ " , a . name )
end as filename ,
2025-10-16 11:17:21 +03:00
a . `type` , n . filename as s3_filename , n . s3_bucket , n . s3_key , n . filelocationtype
2025-09-26 10:43:05 +03:00
from vtiger_senotesrel r
left join vtiger_notes n on n . notesid = r . notesid
left join vtiger_crmentity e on e . crmid = r . notesid
left join vtiger_notescf ncf on ncf . notesid = r . notesid
left join vtiger_seattachmentsrel r2 on r2 . crmid = r . notesid
left join vtiger_attachments a on a . attachmentsid = r2 . attachmentsid
where r . crmid = ? and e . deleted = 0 and n . notecontent = " заявление почта api " ' ;
$result = $adb -> pquery ( $query , array ( $projectid ));
if ( $adb -> num_rows ( $result ) == 0 ) {
$output [ 'result' ] = 'NO' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Заявление потерпевшего с о строкой "заявление почта api" в Проекте ' . $projectid . ' не найдено' . PHP_EOL , FILE_APPEND );
} else {
$output [ 'result' ] = 'YES' ;
$output [ 'description' ] = $adb -> query_result ( $result , 0 , 'title' );
if ( ! is_numeric ( substr ( $output [ 'description' ], 0 , 1 ))) {
$output [ 'description' ] = '0_' . $output [ 'description' ];
}
$output [ 'description' ] = str_replace ( ' ' , '_' , $output [ 'description' ]);
2025-10-16 11:17:21 +03:00
// Проверяем тип размещения файла
$filelocationtype = $adb -> query_result ( $result , 0 , 'filelocationtype' );
$s3_filename = $adb -> query_result ( $result , 0 , 's3_filename' );
$s3_bucket = $adb -> query_result ( $result , 0 , 's3_bucket' );
$s3_key = $adb -> query_result ( $result , 0 , 's3_key' );
if ( $filelocationtype == 'E' && ! empty ( $s3_bucket ) && ! empty ( $s3_key )) {
// Файл в S3 - скачиваем во временную папку
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - заявление потерпевшего найдено в S3, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
$tempFilename = 'plea_doc_' . time () . '.pdf' ;
$tempPath = getTempFileFromS3 ( $s3_bucket , $s3_key , $tempFilename );
if ( $tempPath ) {
$output [ 'filepath' ] = $tempPath ;
$output [ 'is_temp_file' ] = true ; // Флаг для последующей очистки
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - S3 файл заявления потерпевшего успешно скачан во временную папку' . PHP_EOL , FILE_APPEND );
} else {
$output [ 'result' ] = 'NO' ;
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - не удалось скачать заявление потерпевшего из S3' . PHP_EOL , FILE_APPEND );
return $output ;
}
} else {
// Локальный файл (оригинальная логика)
$output [ 'filepath' ] = $adb -> query_result ( $result , 0 , 'filepath' );
}
2025-09-26 10:43:05 +03:00
$output [ 'filename' ] = $adb -> query_result ( $result , 0 , 'title' ) . '.pdf' ;
if ( ! is_numeric ( substr ( $output [ 'filename' ], 0 , 1 ))) {
$output [ 'filename' ] = '0_' . $output [ 'filename' ];
}
$output [ 'filename' ] = str_replace ( ' ' , '_' , $output [ 'filename' ]);
$output [ 'type' ] = $adb -> query_result ( $result , 0 , 'type' );
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - Нашли заявление потерпевшего в Проекте ' . $projectid . PHP_EOL , FILE_APPEND );
}
return $output ;
}
function getOtherDocs ( $projectid , $accountid , $acc1 , $acc2 ) {
global $adb ;
$output = [];
// Сначала вытащим доки из Проекта, но только те, которые лежат в папке "Суд"
$query = ' select
n . title , ncf . cf_1953 as pages ,
case when a . storedname is not null
then concat ( a . `path` , a . attachmentsid , " _ " , a . storedname )
else concat ( a . `path` , a . attachmentsid , " _ " , a . name )
end as filepath ,
case when a . storedname is not null
then concat ( a . attachmentsid , " _ " , a . storedname )
else concat ( a . attachmentsid , " _ " , a . name )
end as filename ,
2025-10-16 11:17:21 +03:00
a . `type` , n . filename as s3_filename , n . s3_bucket , n . s3_key , n . filelocationtype
2025-09-26 10:43:05 +03:00
from vtiger_senotesrel r
left join vtiger_notes n on n . notesid = r . notesid
left join vtiger_crmentity e on e . crmid = r . notesid
left join vtiger_notescf ncf on ncf . notesid = r . notesid
left join vtiger_seattachmentsrel r2 on r2 . crmid = r . notesid
left join vtiger_attachments a on a . attachmentsid = r2 . attachmentsid
2025-10-16 11:17:21 +03:00
where r . crmid = ? and e . deleted = 0 and n . folderid = 3 and (
a . `type` = " application/pdf " or
a . `type` = " application/octet-stream " or
n . filename like " %.pdf " or
a . name like " %.pdf " or
a . storedname like " %.pdf "
) and (
n . title not like " %Ис ко во е _за явле ние % " and
n . title not like " %исковое% " and
n . filename not like " %Ис ко во е _за явле ние % " and
n . filename not like " %исковое% "
) ' ;
2025-09-26 10:43:05 +03:00
$result = $adb -> pquery ( $query , array ( $projectid ));
if ( $adb -> num_rows ( $result ) > 0 ) {
for ( $i = 0 ; $i < $adb -> num_rows ( $result ); $i ++ ) {
$output [ $i ][ 'description' ] = $adb -> query_result ( $result , $i , 'title' );
if ( ! is_numeric ( substr ( $output [ $i ][ 'description' ], 0 , 1 ))) {
$output [ $i ][ 'description' ] = $i . '_' . $output [ $i ][ 'description' ];
}
$output [ $i ][ 'description' ] = str_replace ( ' ' , '_' , $output [ $i ][ 'description' ]);
2025-10-16 11:17:21 +03:00
// Проверяем тип размещения файла
$filelocationtype = $adb -> query_result ( $result , $i , 'filelocationtype' );
$s3_filename = $adb -> query_result ( $result , $i , 's3_filename' );
$s3_bucket = $adb -> query_result ( $result , $i , 's3_bucket' );
$s3_key = $adb -> query_result ( $result , $i , 's3_key' );
if ( $filelocationtype == 'E' && ! empty ( $s3_bucket ) && ! empty ( $s3_key )) {
// Файл в S3 - скачиваем во временную папку
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - дополнительный документ из проекта найден в S3, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
$tempFilename = 'other_doc_' . $i . '_' . time () . '.pdf' ;
$tempPath = getTempFileFromS3 ( $s3_bucket , $s3_key , $tempFilename );
if ( $tempPath ) {
$output [ $i ][ 'filepath' ] = $tempPath ;
$output [ $i ][ 'is_temp_file' ] = true ; // Флаг для последующей очистки
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - S3 файл дополнительного документа успешно скачан во временную папку: ' . $tempPath . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - ошибка скачивания S3 файла дополнительного документа из проекта, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
// Устанавливаем пустой filepath, чтобы избежать ошибки
$output [ $i ][ 'filepath' ] = '' ;
$output [ $i ][ 'is_temp_file' ] = false ;
}
} else {
// Локальный файл (оригинальная логика)
$output [ $i ][ 'filepath' ] = $adb -> query_result ( $result , $i , 'filepath' );
}
2025-09-26 10:43:05 +03:00
$output [ $i ][ 'filename' ] = $adb -> query_result ( $result , $i , 'title' ) . '.pdf' ;
if ( ! is_numeric ( substr ( $output [ $i ][ 'filename' ], 0 , 1 ))) {
$output [ $i ][ 'filename' ] = $i . '_' . $output [ $i ][ 'filename' ];
}
$output [ $i ][ 'filename' ] = str_replace ( ' ' , '_' , $output [ $i ][ 'filename' ]);
$output [ $i ][ 'type' ] = $adb -> query_result ( $result , $i , 'type' );
}
}
// А теперь из Контрагентов (трех), но только те, которые лежат в папке "Суд"
2025-10-16 11:17:21 +03:00
$query = ' select n . title , ncf . cf_1953 as pages , concat ( a . `path` , a . attachmentsid , " _ " , a . storedname ) as filepath , concat ( a . attachmentsid , " _ " , a . storedname ) as filename , a . `type` , n . filename as s3_filename , n . s3_bucket , n . s3_key , n . filelocationtype
2025-09-26 10:43:05 +03:00
from vtiger_senotesrel r
left join vtiger_notes n on n . notesid = r . notesid
left join vtiger_crmentity e on e . crmid = r . notesid
left join vtiger_notescf ncf on ncf . notesid = r . notesid
left join vtiger_seattachmentsrel r2 on r2 . crmid = r . notesid
left join vtiger_attachments a on a . attachmentsid = r2 . attachmentsid
2025-10-16 11:17:21 +03:00
where r . crmid in ( ? , ? , ? ) and e . deleted = 0 and n . folderid = 3 and (
a . `type` = " application/pdf " or
a . `type` = " application/octet-stream " or
n . filename like " %.pdf " or
a . name like " %.pdf " or
a . storedname like " %.pdf "
) and (
n . title not like " %Ис ко во е _за явле ние % " and
n . title not like " %исковое% " and
n . filename not like " %Ис ко во е _за явле ние % " and
n . filename not like " %исковое% "
) ' ;
2025-09-26 10:43:05 +03:00
$result = $adb -> pquery ( $query , array ( $accountid , $acc1 , $acc2 ));
if ( $adb -> num_rows ( $result ) > 0 ) {
for ( $j = 0 ; $j < $adb -> num_rows ( $result ); $j ++ ) {
$output [ $i ][ 'description' ] = $adb -> query_result ( $result , $j , 'title' );
if ( ! is_numeric ( substr ( $output [ $i ][ 'description' ], 0 , 1 ))) {
$output [ $i ][ 'description' ] = $i . '_' . $output [ $i ][ 'description' ];
}
$output [ $i ][ 'description' ] = str_replace ( ' ' , '_' , $output [ $i ][ 'description' ]);
2025-10-16 11:17:21 +03:00
// Проверяем тип размещения файла
$filelocationtype = $adb -> query_result ( $result , $j , 'filelocationtype' );
$s3_filename = $adb -> query_result ( $result , $j , 's3_filename' );
$s3_bucket = $adb -> query_result ( $result , $j , 's3_bucket' );
$s3_key = $adb -> query_result ( $result , $j , 's3_key' );
if ( $filelocationtype == 'E' && ! empty ( $s3_bucket ) && ! empty ( $s3_key )) {
// Файл в S3 - скачиваем во временную папку
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - дополнительный документ из контрагента найден в S3, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
$tempFilename = 'contractor_doc_' . $i . '_' . time () . '.pdf' ;
$tempPath = getTempFileFromS3 ( $s3_bucket , $s3_key , $tempFilename );
if ( $tempPath ) {
$output [ $i ][ 'filepath' ] = $tempPath ;
$output [ $i ][ 'is_temp_file' ] = true ; // Флаг для последующей очистки
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - S3 файл дополнительного документа из контрагента успешно скачан во временную папку: ' . $tempPath . PHP_EOL , FILE_APPEND );
} else {
file_put_contents ( 'logs/Letters.log' , date ( 'Y-m-d H:i:s' ) . ' - ошибка скачивания S3 файла дополнительного документа из контрагента, bucket: ' . $s3_bucket . ', key: ' . $s3_key . PHP_EOL , FILE_APPEND );
// Устанавливаем пустой filepath, чтобы избежать ошибки
$output [ $i ][ 'filepath' ] = '' ;
$output [ $i ][ 'is_temp_file' ] = false ;
}
} else {
// Локальный файл (оригинальная логика)
$output [ $i ][ 'filepath' ] = $adb -> query_result ( $result , $j , 'filepath' );
}
2025-09-26 10:43:05 +03:00
$output [ $i ][ 'filename' ] = $adb -> query_result ( $result , $j , 'title' ) . '.pdf' ;
if ( ! is_numeric ( substr ( $output [ $i ][ 'filename' ], 0 , 1 ))) {
$output [ $i ][ 'filename' ] = $i . '_' . $output [ $i ][ 'filename' ];
}
$output [ $i ][ 'filename' ] = str_replace ( ' ' , '_' , $output [ $i ][ 'filename' ]);
$output [ $i ][ 'type' ] = $adb -> query_result ( $result , $j , 'type' );
$output [ $i ][ 'pages' ] = $adb -> query_result ( $result , $j , 'pages' );
if ( empty ( $output [ $i ][ 'pages' ]) or $output [ $i ][ 'pages' ] == 0 ) {
$output [ $i ][ 'pages' ] = getPDFPageCount ( $output [ $i ][ 'filepath' ]);
}
$i ++ ;
}
}
return $output ;
}
function getUserId ( $crmid ) {
global $adb ;
$query = ' select smownerid as userid
from vtiger_crmentity
where deleted = 0 and crmid = ? ' ;
$result = $adb -> pquery ( $query , array ( $crmid ));
if ( $adb -> num_rows ( $result ) == 1 ) {
// Что-то нашлось
$output = $adb -> query_result ( $result , 0 , 'userid' );
} else {
// Активных Проектов нет, а может быть несколько - значит ответственным будет админ
$output = 1 ;
}
return $output ;
}
?>