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

1312 lines
65 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
class ChatsCianAvito {
private $db = null;
private $dbpg = null;
private $service = 0;
public function __construct($db = null) {
if($db){
$this->db = $db;
} else {
$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$this->db = $pdo;
}
// PostgreSQL может быть недоступен в окружении (например, на dev — нет PG-сервера).
// MysqlPdo для PG-ветки бросает RuntimeException, если хост недоступен (2-сек fsockopen-check).
// В этом случае $this->dbpg остаётся null; методы, использующие его, должны сами это учитывать.
// can_chat() PG не использует — он работает только на MySQL, поэтому остальная логика не страдает.
// Используем catch (Exception) для совместимости с PHP 5.x.
try {
if (defined('hstpg') && defined('ndbpg') && defined('passpg')) {
$pdopg = new MysqlPdo(hstpg, ndbpg, 'u0305746_jw', passpg, false, '5432', true);
$sql = "SET NAMES 'utf8'";
$pdopg->query($sql);
$this->dbpg = $pdopg;
}
} catch (Exception $e) {
// PG недоступен — оставляем dbpg = null.
}
}
public function setService($service){
$this->service = $service;
}
public function ajax_can_chat($data){
$user_id = $data->user_id;
$user = new User();
$user->checkPermissions($user_id);
return $this->can_chat($user, $data->service_id);
}
public function ajax_get_user($data){
$user_id = $data->user_id;
return $this->get_user($user_id);
}
public function can_chat($global_user, $service_id){
$agency_id = $global_user->agencyId;
$sql = "SELECT * FROM users_api WHERE agency_id = {$agency_id} AND service_id = {$service_id} AND is_messages = 1";
$q = $this->db->query($sql);
if($this->db->num_rows($q) == 0) return false;
if($global_user->agency == 0 && $global_user->users_admin == 0 && (int)$global_user->individual == 0) {
$sql_api = "SELECT * FROM user_api_keys WHERE user_id = {$global_user->id}";
//echo $sql_api;
$q_api = $this->db->query($sql_api);
$r_api = $this->db->fetch_assoc($q_api);
if($service_id == 1){
// var_dump($r_api['avito_id'] == 0 && $r_api['is_id_object'] == 0 && $r_api['is_all_avito'] == 0);
if($r_api['avito_id'] == 0 && $r_api['is_id_object'] == 0 && $r_api['is_all_avito'] == 0) return false;
} else if ($service_id == 2){
if($r_api['cian_id'] == 0 && $r_api['is_id_object_cian'] == 0 && $r_api['is_all_cian'] == 0) return false;
}
}
return true;
}
public function get_user($user_id){
$result = array();
if($user_id > 0){
$sql = "SELECT * FROM users WHERE id = {$user_id}";
$q = $this->db->query($sql);
$result = $this->db->fetch_assoc($q);
$sql_api = "SELECT * FROM user_api_keys WHERE user_id = {$user_id}";
$q_api = $this->db->query($sql_api);
$r_api = $this->db->fetch_assoc($q_api);
$result['cian_id'] = 0;
$result['avito_id'] = 0;
$result['is_all_cian'] = 0;
$result['is_all_avito'] = 0;
$result['is_id_object'] = 0;
$result['is_id_object_cian'] = 0;
if(isset($r_api['user_id'])){
$result['cian_id'] = $r_api['cian_id'];
$result['avito_id'] = $r_api['avito_id'];
$result['is_all_cian'] = $r_api['is_all_cian'];
$result['is_all_avito'] = $r_api['is_all_avito'];
$result['is_id_object'] = $r_api['is_id_object'];
$result['is_id_object_cian'] = $r_api['is_id_object_cian'];
}
if ($result['id_manager'] == 0 && $result['agency'] == 0) {
// частник
$result['individual'] = 1;
} else {
$result['individual'] = 0;
}
}
return $result;
}
/**
*
*/
public function get_api_chat($api_id){
$result = array();
$sql = "SELECT * FROM `users_api` AS `api` WHERE `api`.`id` = '$api_id' LIMIT 1";
$q = $this->db->query($sql);
$api = $this->db->fetch_assoc($q);
if(!empty($api)){
$result = $api;
}
return $result;
}
public function add_message($arrayMess){
$object_id_mes = 0;
$user_id_mes = 0;
if(!empty($arrayMess['cian_id'])){
$sql_user = "SELECT * FROM user_api_keys WHERE cian_id = {$arrayMess['cian_id']}";
$q_user = $this->db->query($sql_user);
if($this->db->num_rows($q_user) > 0){
$r_user = $this->db->fetch_assoc($q_user);
$arrayMess['user_id'] = $r_user['user_id'];
}
}
if((int)$arrayMess['object_id'] > 0){
$object_id_mes = $arrayMess['object_id'];
$user_id_mes = $arrayMess['user_id'];
$sql_user_obj = "SELECT * FROM user_api_keys WHERE user_id = (SELECT id_add_user FROM objects WHERE id = {$arrayMess['object_id']}) AND is_id_object_cian = 1";
$q_user_obj = $this->db->query($sql_user_obj);
if($this->db->num_rows($q_user_obj) > 0){
$r_user_obj = $this->db->fetch_assoc($q_user_obj);
$arrayMess['user_id'] = $r_user_obj['user_id'];
$user_id_mes = $arrayMess['user_id'];
}
}
unset($arrayMess['object_id']);
unset($arrayMess['cian_id']);
$columns = array_keys($arrayMess);
$arrayMess['details'] = pg_escape_string($arrayMess['details']);
$sql = "INSERT INTO cian_chat (".implode(',', $columns).") VALUES ('".implode('\',\'',$arrayMess)."')";
$this->dbpg->query($sql);
$mess_id = $this->dbpg->insert_id(); //Id сообщения в базе
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_mes_chat.txt", date('d.m.y H:i:s')." ".$mess_id."\n", FILE_APPEND);
if($arrayMess['agency_id'] != 12061){
$this->send_message($object_id_mes, $user_id_mes, 2, $arrayMess['details'], [], $mess_id, $arrayMess['agency_id']);
}
}
/**
* Добавление чатов Авито
*/
public function add_message_avito($data){
$object_id_mes = 0;
$user_id_mes = 0;
$obj_mes = array();
$user_id_chat = $data['payload']['value']['user_id'];
$chat_id = $data['payload']['value']['chat_id'];
$user_id = 0;
$agency_id = 0;
$sql_user = "SELECT * FROM user_api_keys WHERE avito_id = {$user_id_chat}";
$q_user = $this->db->query($sql_user);
if($this->db->num_rows($q_user) > 0){
$r_user = $this->db->fetch_assoc($q_user);
$user_id = $r_user['user_id'];
}
$api_result = $this->get_api_chat($data['api']);
/* */
// if(isset($avito) && $avito['success']){
//unset($data['api']);
$arrayMess['user_id'] = $user_id;
$agency_id = $arrayMess['agency_id'] = $api_result['agency_id'];
$arrayMess['chat_id'] = $chat_id;
$arrayMess['details'] = pg_escape_string(json_encode($data, JSON_UNESCAPED_UNICODE));
$arrayMess['create_at_real'] = $data['payload']['value']['created'];
$arrayMess['update_at_real'] = $data['timestamp'];
$arrayMess['new'] = 0;
if($data['payload']['value']['user_id'] == $data['payload']['value']['author_id']){
$arrayMess['new'] = 0;
} else {
$arrayMess['new'] = 1;
}
// var_dump($arrayMess);
$columns = array_keys($arrayMess);
$sql = "INSERT INTO chat_avito_messages (".implode(',', $columns).") VALUES ('".implode('\',\'',$arrayMess)."')";
// file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql."\n", FILE_APPEND);
$this->dbpg->query($sql);
$mess_id = $this->dbpg->insert_id(); //Id сообщения в базе
// }
$arrayMess = array();
$sql = "SELECT * FROM chat_avito WHERE chat_id = '{$chat_id}'";
// file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql."\n", FILE_APPEND);
//echo $sql;
$q = $this->dbpg->query($sql);
if($this->dbpg->num_rows($q) == 0){
$api = new AdvertStats();
$avito = $api->get_chat($api_result, $chat_id);
if($avito['success']){
$arrayMess['user_id'] = $user_id;
$arrayMess['agency_id'] = $api_result['agency_id'];
$arrayMess['chat_id'] = $chat_id;
unset($avito['success']);
$arrayMess['details'] = pg_escape_string(json_encode($avito, JSON_UNESCAPED_UNICODE));
$arrayMess['create_at_real'] = $avito['created'];
$arrayMess['update_at_real'] = $avito['updated'];
$columns = array_keys($arrayMess);
$sql = "INSERT INTO chat_avito (".implode(',', $columns).") VALUES ('".implode('\',\'',$arrayMess)."')";
// file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql."\n", FILE_APPEND);
// echo $sql;
$this->dbpg->query($sql);
}
} else {
$chat_avito = $this->dbpg->fetch_assoc($q);
$api = new AdvertStats();
$avito = $api->get_chat($api_result, $chat_id);
if($avito['success']){
$details = pg_escape_string(json_encode($avito, JSON_UNESCAPED_UNICODE));
$sql = "UPDATE chat_avito SET details = '{$details}', create_at_real = {$avito['created']}, update_at_real = {$avito['updated']} WHERE id = {$chat_avito['id']}";
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql."\n", FILE_APPEND);
$this->dbpg->query($sql);
}
}
if(isset($avito)){
$id_avito = (int)$avito['context']['value']['id'];
if($id_avito > 0){
$objectUrls = 'https://www.avito.ru/items/'.$id_avito;
$sql_obj_stat = "SELECT object_id, url FROM ads_stats WHERE service_id = 1 AND agency_id = {$agency_id} AND url = '{$objectUrls}'";
//echo $sql_obj_stat;
$q_obj_stat = $this->db->query($sql_obj_stat);
while($r_obj_stat = $this->db->fetch_assoc($q_obj_stat)){
if((int)$r_obj_stat['object_id'] > 0){
$object_id = (int)$r_obj_stat['object_id'];
}
}
if(isset($object_id) && $object_id > 0){
if($user_id == 0 || $user_id == $agency_id){
$sql_obj = "SELECT id, id_add_user, adres FROM objects WHERE id = {$object_id}";
$q_obj = $this->db->query($sql_obj, true);
$obj = $this->db->fetch_assoc($q_obj);
if((int)$obj['id_add_user'] > 0){
$user_id = (int)$obj['id_add_user'];
$object_id_mes = $object_id;
$user_id_mes = $user_id;
$obj_mes = $obj;
}
}
}
if(isset($object_id) && $object_id > 0){
$sql_up_user = "UPDATE chat_avito_messages SET user_id = $user_id WHERE chat_id = '{$chat_id}'";
// file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql_up_user."\n", FILE_APPEND);
$this->dbpg->query($sql_up_user);
$sql_up_user = "UPDATE chat_avito SET user_id = $user_id, object_id={$object_id} WHERE chat_id = '{$chat_id}'";
// file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_sql.txt", $sql_up_user."\n", FILE_APPEND);
$this->dbpg->query($sql_up_user);
}
if($object_id_mes > 0 && $user_id_mes > 0){
if($agency_id != 11916 && $agency_id != 12061){
$this->send_message($object_id_mes, $user_id_mes, 1, $data, $obj_mes, $mess_id, $agency_id);
}
}
}
}
}
/**
* Отправка сообщений телеграмм
*/
public function send_message($object_id, $user_id, $servise, $details, $obj=[], $mess_id = 0, $agency_id = 0){
$keyboardArr = [];
$attachments = [];
$tel = new Telegram(false);
$max = new MaxClass();
$is_send = false;
$is_send_max = false;
if($user_id > 0 && $object_id > 0){
$chat_id = 0;
$sql = "SELECT * FROM users WHERE id = {$user_id}";
$q = $this->db->query($sql);
$user = $this->db->fetch_assoc($q);
if($user['telegramm_notice'] == 1 AND $user['telegramm_chat_id'] > 0){
$chat_id = $user['telegramm_chat_id'];
if($user['id'] == 14398 || $user['id'] == 19476){
$chat_id = 0;
}
}
if($user['max_notice'] == 1 AND $user['max_user_id'] > 0){
$max_user_id = $user['max_user_id'];
if($user['id'] == 14398 || $user['id'] == 19476){
$max_user_id = 0;
}
}
//$max_user_id = 18529338;
if($chat_id > 0 || $max_user_id > 0){
$text = "Получено новое сообщение из чата ";
if($servise == 1){
$text .= "АВИТО";
} else if($servise == 2){
$text .= "ЦИАН";
}
$text .= "\nпо объекту ID ".$object_id;
if($servise == 2){
$chat = json_decode($details, true);
} else {
$chat = $details;
}
$userName = '';
if($servise == 2){
if($mess_id > 0){
$keyboardArr = [
[
[
'text' => 'Прочитано',
'callback_data' => serialize(array('action'=>5,'id'=>$mess_id))
],
[
'text' => 'Ответить',
'callback_data' => serialize(array('action'=>4,'id'=>$mess_id))
],
],
[
[
'text' => 'Создать заявку',
'callback_data' => serialize(array('action'=>6,'id'=>$mess_id))
]
]
];
$attachments = [
array(
'type'=>'inline_keyboard',
'payload' => array(
'buttons' => [
[
[
"type" => "callback",
'text' => 'Прочитано',
'payload' => serialize(array('action'=>5,'id'=>$mess_id))
],
[
"type" => "callback",
'text' => 'Ответить',
'payload' => serialize(array('action'=>4,'id'=>$mess_id))
]
],
[
[
"type" => "callback",
'text' => 'Создать заявку',
'payload' => serialize(array('action'=>6,'id'=>$mess_id))
]
]
]
)
)
];
}
if(is_numeric($chat['users'][0]['name'])){
$userName = "Пользователь ID ".$chat['users'][0]['name'];
} else {
$userName = $chat['users'][0]['name'];
}
$address = $chat['offers'][0]['address'];
$text .= " ".$address;
$mesages = $chat['chats'][0]['messages'];
foreach($mesages as $mesages){
if($mesages['direction'] == 'in'){
$text .="\n\n";
$text .= "Отправитель ".$userName."\n";
$text .= $mesages['content']['text']."\n";
if($chat_id > 0)
$is_send = true;
if($max_user_id > 0)
$is_send_max = true;
}
}
} else if($servise == 1) {
if($mess_id > 0){
$keyboardArr = [
[
[
'text' => 'Прочитано',
'callback_data' => serialize(array('action'=>2,'id'=>$mess_id))
],
[
'text' => 'Ответить',
'callback_data' => serialize(array('action'=>1,'id'=>$mess_id))
],
],
[
[
'text' => 'Создать заявку',
'callback_data' => serialize(array('action'=>3,'id'=>$mess_id))
]
]
];
$attachments = [
array(
'type'=>'inline_keyboard',
'payload' => array(
'buttons' => [
[
[
"type" => "callback",
'text' => 'Прочитано',
'payload' => serialize(array('action'=>2,'id'=>$mess_id))
],
[
"type" => "callback",
'text' => 'Ответить',
'payload' => serialize(array('action'=>1,'id'=>$mess_id))
]
],
[
[
"type" => "callback",
'text' => 'Создать заявку',
'payload' => serialize(array('action'=>3,'id'=>$mess_id))
]
]
]
)
)
];
}
$address = $obj['adres'];
$text .= " ".$address;
$mesages = $details['payload'];
if($mesages['type'] == 'message'){
$mes_user_id = $mesages['value']['user_id'];
$mes_author_id = $mesages['value']['author_id'];
if($mes_user_id != $mes_author_id){
if($chat_id > 0)
$is_send = true;
if($max_user_id > 0)
$is_send_max = true;
$chat_id_avito = $mesages['value']['chat_id'];
$sql_chat = "SELECT * FROM chat_avito WHERE chat_id = '{$chat_id_avito}'";
$q_chat = $this->dbpg->query($sql_chat);
$r_chat = $this->dbpg->fetch_assoc($q_chat);
$details_chat = json_decode($r_chat['details'], true);
$userName = $details_chat['users'][0]['name'];
if($mes_author_id == $details_chat['users'][1]['id']){
$userName = $details_chat['users'][1]['name'];
}
$text .="\n\n";
$text .= "Отправитель ".$userName."\n";
$text .= $mesages['value']['content']['text']."\n";
}
}
}
$text .= "\nОтветить на сообщение можно в чатах JoyWork";
if($is_send){
//if($servise == 2)
//file_put_contents($_SERVER['DOCUMENT_ROOT']."/telegramm_mes_chat.txt", date('d.m.y H:i:s').' '.$mess_id.' '.$text.' '.json_encode($chat, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
if($agency_id == 20197)
$chat_id=7712131344;
$tel->send($text, $chat_id, null, $keyboardArr);
// $tel->send($text, 689521489);
}
if($is_send_max){
$max->send_messages_to_user($max_user_id, $text, $attachments);
}
}
}
}
/**
* Получение последних чатов
*/
public function get_messages($data){
$agency_id = (int)$data->agency_id;
$user_id = (int)$data->user_id;
$user = $data->user;
if(empty($user)) die();
$result['chats'] = array();
$objectIds = array();
$objects = array();
$sql = "SELECT * FROM cian_chat WHERE agency_id = {$agency_id}";
if($user->agency > 0 || $user->users_admin > 0 || $user->is_all_cian > 0 || $user->individual){
// $sql .= " AND agency_id = {$agency_id}";
} else {
$sql .= " AND agency_id = {$agency_id} AND user_id = {$user_id}";
}
$sql .= " order by id desc limit 10000";
//echo $sql;
$q = $this->dbpg->query($sql);
$row = $this->dbpg->num_rows($q);
while($rez = $this->dbpg->fetch_assoc($q)){
//$rez['is_active'] = ;
//$result['details'][$rez['id']] = json_decode($rez['details'], true);
//var_dump($result['details'][$rez['id']]);
$result_temp = json_decode($rez['details'], true);
if(isset($result_temp['chats'][0]['messages'])){
foreach($result_temp['chats'][0]['messages'] as $key => $mes){
$result_temp['chats'][0]['messages'][0]['new'] = $rez['new'];
$result_temp['chats'][0]['messages'][$key]['createdAt'] = date('d.m.Y H:i', strtotime($result_temp['chats'][0]['messages'][$key]['createdAt']));
$userName = '';
if(is_numeric($result_temp['users'][0]['name'])){
$userName = "Пользователь ID ".$result_temp['users'][0]['name'];
} else {
$userName = $result_temp['users'][0]['name'];
}
$result_temp['chats'][0]['messages'][$key]['userName'] = $userName;
$objectIds[] = (int)$result_temp['offers'][0]['externalId'];
$rez['objectId'] = (int)$result_temp['offers'][0]['externalId'];
$result_temp['objectId'] = (int)$result_temp['offers'][0]['externalId'];
$result['details'][$rez['id']] = $result_temp;
$result['details'][$rez['id']]['chats'][0]['update_at'] = date('d.m.Y H:i', strtotime($result['details'][$rez['id']]['chats'][0]['updatedAt']));
}
}
$result['chats'][] = $rez;
}
// $result['total_new'] = $row;
//while($r = $this->db->fetch_assoc($q)){
//$result
//}
$objectIds = array_unique($objectIds);
//$result['objects_ids'] = $objectIds;
if(!empty($objectIds)){
$db_sphinx = new MysqlPdo(hstsph2, null, null, null, true, '9306');
$sql_obj = "SELECT id, id_add_user FROM objects WHERE id in (".implode(',', $objectIds).") LIMIT 1000000 OPTION max_matches=1000000";
$q_obj = $db_sphinx->query($sql_obj, true);
while($obj = $db_sphinx->fetch_assoc($q_obj)){
$objects[$obj['id']] = $obj;
}
}
foreach($result['chats'] as $key => $chat){
if(isset($objects[$chat['objectId']])){
$result['chats'][$key]['id_add_user'] = (int)$objects[$chat['objectId']]['id_add_user'];
$result['details'][$chat['id']]['id_add_user'] = (int)$objects[$chat['objectId']]['id_add_user'];
}
}
//$result['objects'] = $objects;
return $result;
}
/**
* Получение последних чатов авито
*/
public function get_messages_avito($data){
$agency_id = (int)$data->agency_id;
$user_id = (int)$data->user_id;
$user = $data->user;
$chats = array();
$chats_list = array();
//$user = $this->get_user($user_id);
if(empty($user)) die();
$result['chats'] = array();
$messages = array();
$objects = array();
$objectIds = array();
$objectUrls = array();
$urls = array();
$sql = "SELECT * FROM chat_avito WHERE agency_id = {$agency_id}";
if($user->agency > 0 || $user->users_admin > 0 || $user->is_all_avito > 0 || $user->individual){
// $sql .= " AND agency_id = {$agency_id}";
} else {
$sql .= " AND user_id = {$user_id}";
}
$sql .= " order by update_at_real desc limit 1000";
if($_SESSION['id'] == 13154){
//echo $sql;
}
$q = $this->dbpg->query($sql);
//$row = $this->db->num_rows($q);
while($r = $this->dbpg->fetch_assoc($q)){
if(!in_array($r['chat_id'], $chats)){
$chats[] = $r['chat_id'];
$chats_list[$r['chat_id']] = $r;
}
}
if(!empty($chats)){
$sql = "SELECT * FROM chat_avito_messages WHERE agency_id = {$agency_id} AND chat_id in ('".implode('\',\'', $chats)."')";
if($user->agency > 0 || $user->users_admin > 0 || $user->is_all_avito > 0 || $user->individual){
//$sql .= " AND agency_id = {$agency_id}";
} else {
$sql .= " AND user_id = {$user_id}";
}
$sql .= " order by update_at_real limit 10000";
$q = $this->dbpg->query($sql);
//$row = $this->db->num_rows($q);
while($rez = $this->dbpg->fetch_assoc($q)){
$rez['details'] = json_decode($rez['details'], true);
$messages[$rez['chat_id']][] = $rez;
}
}
foreach($chats_list as $rez){
// var_dump($rez);
// if(!in_array($rez['chat_id'], $chats)){
// $chats[] = $rez['chat_id'];
//var_dump($messages[$rez['chat_id']]);
if(isset($messages[$rez['chat_id']])){
$rez['details'] = json_decode($rez['details'], true);
if(!empty($rez['details'])){
if((int)$rez['object_id'] == 0 && (int)$rez['details']['context']['value']['id'] != 0){
// var_dump($rez['details']['context']['value']);
$objectUrls[] = 'https://www.avito.ru/items/'.$rez['details']['context']['value']['id'];
$urls[(int)'https://www.avito.ru/items/'.$rez['details']['context']['value']['id']] = 0;
}
$rez['update'] = date('d.m.Y H:i', $rez['update_at_real']);
$rez['details']['context']['value']['images']['main']['img'] = $rez['details']['context']['value']['images']['main']['140x105'];
$rez['new_mess'] = 0;
$rez['is_active'] = false;
foreach($messages[$rez['chat_id']] as $key => $mes){
$userName = $rez['details']['users'][0]['name'];
if($mes['details']['payload']['value']['author_id'] == $rez['details']['users'][1]['id']){
$userName = $rez['details']['users'][1]['name'];
}
$messages[$rez['chat_id']][$key]['userName'] = $userName;
$messages[$rez['chat_id']][$key]['create'] = date('d.m.Y H:i', $mes['details']['payload']['value']['created']);
if($mes['new'] == 1){
$rez['new_mess']++;
}
}
$rez['messages'] = $messages[$rez['chat_id']];
$result['chats']['chat'.$rez['id']] = $rez;
} else {
$sql_up = "UPDATE chat_avito_messages SET new = 0 WHERE chat_id = '{$rez['chat_id']}' and new = 1";
$this->dbpg->query($sql_up);
}
}
// }
}
$result['urls'] = $objectUrls;
if(!empty($objectUrls)){
$sql_stat = "SELECT object_id, url FROM ads_stats WHERE service_id = 1 AND agency_id = {$agency_id} AND url in ('".implode('\',\'', $objectUrls)."')";
$q_stat = $this->db->query($sql_stat);
while($r_stat = $this->db->fetch_assoc($q_stat)){
$objectIds[] = $r_stat['object_id'];
$urls[(int)str_replace('https://www.avito.ru/items/','',$r_stat['url'])] = $r_stat['object_id'];
}
$objectIds = array_unique($objectIds);
//$result['objects_ids'] = $objectIds;
if(!empty($objectIds)){
$db_sphinx = new MysqlPdo(hstsph2, null, null, null, true, '9306');
$sql_obj = "SELECT id, id_add_user FROM objects WHERE id in (".implode(',', $objectIds).") LIMIT 1000000 OPTION max_matches=1000000";
$q_obj = $db_sphinx->query($sql_obj, true);
while($obj = $db_sphinx->fetch_assoc($q_obj)){
$objects[$obj['id']] = $obj;
}
}
foreach($result['chats'] as $key => $chat){
if((int)$result['chats'][$key]['object_id'] == 0){
$result['chats'][$key]['object_id'] = $urls[(int)$chat['details']['context']['value']['id']];
$result['chats'][$key]['id_add_user'] = (int)$objects[$urls[(int)$chat['details']['context']['value']['id']]]['id_add_user'];
if($chat['user_id'] == 0 || $chat['user_id'] == $chat['agency_id']){
$user_id = (int)$objects[$urls[(int)$chat['details']['context']['value']['id']]]['id_add_user'];
$sql_up_user = "UPDATE chat_avito_messages SET user_id = $user_id WHERE chat_id = '{$chat['chat_id']}'";
$this->dbpg->query($sql_up_user);
$sql_up_user = "UPDATE chat_avito SET user_id = $user_id WHERE chat_id = '{$chat['chat_id']}'";
$this->dbpg->query($sql_up_user);
}
}
}
}
return $result;
}
public function get_new_messages($data){
$agency_id = (int)$data->agency_id;
$user_id = (int)$data->user_id;
$user = $data->user;
if(empty($user)) die();
$sql = "SELECT * FROM cian_chat WHERE new=1";
if($user->agency > 0 || $user->users_admin > 0 || $user->is_all_cian > 0 || $user->individual > 0){
$sql .= " AND agency_id = {$agency_id}";
} else {
$sql .= " AND agency_id = {$agency_id} AND user_id = {$user_id}";
}
$sql .= " order by id desc limit 10000";
$result = array('total_new'=>0, 'chats' => array());
//$sql = "SELECT * FROM cian_chat where new=1 order by id desc limit 100";
$q = $this->dbpg->query($sql);
$row = $this->dbpg->num_rows($q);
while($rez = $this->dbpg->fetch_assoc($q)){
$result['chats'][] = $rez;
// $result['details'][$rez['id']] = json_decode($rez['details'], true);
//var_dump($result['details'][$rez['id']]);
$result_temp = json_decode($rez['details'], true);
if(isset($result_temp['chats'][0]['messages'])){
foreach($result_temp['chats'][0]['messages'] as $key => $mes){
$result_temp['chats'][0]['messages'][$key]['new'] = $rez['new'];
$result_temp['chats'][0]['messages'][$key]['createdAt'] = date('d.m.Y H:i', strtotime($result_temp['chats'][0]['messages'][$key]['createdAt']));
$userName = '';
if(is_numeric($result_temp['users'][0]['name'])){
$userName = "Пользователь ID ".$result_temp['users'][0]['name'];
} else {
$userName = $result_temp['users'][0]['name'];
}
$result_temp['chats'][0]['messages'][$key]['userName'] = $userName;
$result['details'][$rez['id']] = $result_temp;
$result['details'][$rez['id']]['chats'][0]['update_at'] = date('d.m.Y H:i', strtotime($result['details'][$rez['id']]['chats'][0]['updatedAt']));
}
}
}
$result['total_new'] = $row;
//while($r = $this->db->fetch_assoc($q)){
//$result
//}
return $result;
}
/**
* Получение новых сообщений авито
*/
public function get_new_messages_avito($data){
$agency_id = (int)$data->agency_id;
$user_id = (int)$data->user_id;
$user = $data->user;
if(empty($user)) die();
$sql = "SELECT * FROM chat_avito_messages WHERE new=1";
if($user->agency > 0 || $user->users_admin > 0 || $user->is_all_avito > 0 || $user->individual > 0){
$sql .= " AND agency_id = {$agency_id}";
} else {
$sql .= " AND agency_id = {$agency_id} AND user_id = {$user_id}";
}
$sql .= " order by id desc limit 10000";
$result = array('total_new'=>0, 'messages' => array());
//$sql = "SELECT * FROM cian_chat where new=1 order by id desc limit 100";
$q = $this->dbpg->query($sql);
$row = $this->dbpg->num_rows($q);
while($rez = $this->dbpg->fetch_assoc($q)){
$result['messages'][$rez['id']] = $rez['id'];
}
$result['total_new'] = $row;
//while($r = $this->db->fetch_assoc($q)){
//$result
//}
return $result;
}
/**
* Получение сообщений по чату
*/
public function get_message_chat($data){
/*ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);*/
// var_dump($data);
$chatId = $data->chatId;
$chatId = str_replace('chat','',$chatId);
$sql_up = "UPDATE cian_chat SET new = 0 WHERE chatId = {$chatId}";
$this->dbpg->query($sql_up);
$sql = "SELECT * FROM cian_chat WHERE chatid = {$chatId} order by id";
$q = $this->dbpg->query($sql);
$result = array();
$temp_chats = array();
$i = 0;
$mesages = array();
while($rez = $this->dbpg->fetch_assoc($q)){
$temp_chats[$i] = json_decode($rez['details'], true);
foreach($temp_chats[$i]['chats'][0]['messages'] as $key => $mes){
$temp_chats[$i]['chat_id'] = $rez['chatid'];
$mes['new'] = $rez['new'];
$mess_id = $mes['messageId'];
$mes['createdAt'] = date('d.m.Y H:i', strtotime($mes['createdAt']));
$userName = '';
$userMesId = $mes['userId'];
foreach($temp_chats[$i]['users'] as $userMes){
if($userMes['userId'] == $userMesId){
if(is_numeric($userMes['name'])){
$userName = "Пользователь ID ".$userMes['name'];
} else {
$userName = $userMes['name'];
}
}
}
$mes['userName'] = $userName;
$mesages[$mess_id] = $mes;
}
$temp_chats[$i]['count_mes'] = count($temp_chats[$i]['chats'][0]['messages']);
$i++;
}
if(!empty($temp_chats) && !empty($temp_chats[0])){
$result_temp = $temp_chats[0];
$messages = array();
foreach($mesages as $mes){
$messages[] = $mes;
}
$result_temp['chats'][0]['messages'] = $messages;
$result[0] = $result_temp;
}
return $result;
}
/**
*
*/
public function get_message_chat_avito($data){
$chatId = $data->chatId;
$chatId = str_replace('chat','',$chatId);
$sql = "SELECT * FROM chat_avito WHERE id = {$chatId}";
$q = $this->dbpg->query($sql);
$r = $this->dbpg->fetch_assoc($q);
$sql_up = "UPDATE chat_avito_messages SET new = 0 WHERE chat_id = '{$r['chat_id']}'";
$this->dbpg->query($sql_up);
}
/**
* Отметка прочитано
*/
public function update_read_message($mess_id){
if($this->service > 0 && $mess_id > 0){
$table = false;
if($this->service == 1) $table = 'chat_avito_messages';
if($this->service == 2) $table = 'cian_chat';
if($table !== false){
$sql = "UPDATE {$table} SET new = 0 WHERE id = {$mess_id}";
if(!$this->dbpg->query($sql)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' '.$sql."\n", FILE_APPEND);
return array('result'=>'error');
} else {
return array('result'=>'done');
}
}
} else {
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id."\n", FILE_APPEND);
return array('result'=>'error');
}
}
/**
* Запрос на отправка сообщения из телеграм
*/
public function query_send_answer($mess_id, $chat_id, $max = false){
$errors = array();
$stage = 0;
$table_event = 'telegram_events';
$user_field = 'chat_id';
if($max){
$table_event = 'max_events';
$user_field = 'max_user_id';
}
if($this->service > 0 && $mess_id > 0){
$this->db->query("UPDATE {$table_event} SET status = 1 WHERE {$user_field} = {$chat_id}");
$description = date('d-m-Y H:i:s').' - Запрос на ответ';
$sql = "INSERT INTO {$table_event} ({$user_field}, mess_id, event, stage, service, description)
VALUE ({$chat_id}, {$mess_id}, 'answer', 1, {$this->service}, '{$description}')";
if(!$this->db->query($sql)){
$errors[] = $this->db->error();
}
}
if(!empty($errors)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." ".json_encode($errors, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
return array('result'=>'error');
}
return array('result'=>'done', 'stage'=>$stage);
}
/**
* Отправка сообщения ответа из бота телеграм
*/
public function send_answer($mess_id, $text){
/* error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);*/
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' id:'.$mess_id." text ".$text."\n", FILE_APPEND);
$service_id = (int)$this->service;
$service_name = '';
$table = false;
if($service_id == 1){
$table = 'chat_avito_messages';
$service_name = 'avito';
} else if ($service_id == 2){
$table = 'cian_chat';
$service_name = 'cian';
}
if($table){
$sql_mess = "SELECT * FROM {$table} WHERE id = {$mess_id}";
$q_mess = $this->dbpg->query($sql_mess);
if($this->dbpg->num_rows($q_mess) > 0){
$r_mess = $this->dbpg->fetch_assoc($q_mess);
$agency_id = (int)$r_mess['agency_id'];
if($service_id == 1){
$chat_id = $r_mess['chat_id'];
} else if ($service_id == 2)
$chat_id = $r_mess['chatid'];
$sql = "SELECT * FROM `users_api` AS `api` WHERE `api`.`service_id` = '$service_id' AND `api`.`agency_id` = '$agency_id'";
if ($query = $this->db->query($sql)) {
while($credits = $this->db->fetch_assoc($query)){
$api = new AdvertStats();
$results = $api->send_message($service_name, $credits['client_id'], $credits['secret_key'], $credits['ext_user_id'], $text, $chat_id);
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." text ".json_encode($results, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
}
} else {
//echo $this->db->error();
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." error ".$this->db->error()."\n", FILE_APPEND);
}
}
}
}
/**
* Отмена отправки сообщения из телеграм
*/
public function cancel_answer($mess_id, $chat_id, $max= false){
$table_event = ($max) ? 'max_events' : 'telegram_events';
$field_user = ($max) ? 'max_user_id' : 'telegramm_chat_id';
$field_user_event = ($max) ? 'max_user_id' : 'chat_id';
$errors = array();
$stage = 0;
if($this->service > 0 && $mess_id > 0 && $chat_id > 0){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND mess_id = {$mess_id} AND event = 'answer' AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$r_ev = $this->db->fetch_assoc($q_ev);
$description = mysql_real_escape_string($r_ev['description'] . ' ' . date('d.m.Y H:i:s') . ' - Отправка сообщения отменена');
$this->db->query("UPDATE {$table_event} SET description = '{$description}', status = 1 WHERE id = {$r_ev['id']}");
$result['result'] = 'cancel_answer';
}
}
if(!empty($errors)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." ".json_encode($errors, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
return array('result'=>'error');
}
return array('result'=>'done', 'stage'=>$stage);
}
/**
* Добавление заявки
*/
public function add_req($mess_id, $chat_id, $stage, $mess = null, $event_table = [], $max = false) {
$errors = array();
$result = array();
$table_event = ($max) ? 'max_events' : 'telegram_events';
$field_user = ($max) ? 'max_user_id' : 'telegramm_chat_id';
$field_user_event = ($max) ? 'max_user_id' : 'chat_id';
if($this->service > 0 && $mess_id > 0 && $chat_id > 0){
switch ($stage){
case 0: {
$service_id = (int)$this->service;
$service_name = '';
$table = false;
if($service_id == 1){
$table = 'chat_avito_messages';
} else if ($service_id == 2){
$table = 'cian_chat';
}
if($table){
$objectId = 0;
$sql_mess = "SELECT * FROM {$table} WHERE id = {$mess_id}";
$q_mess = $this->dbpg->query($sql_mess);
$r_mess = $this->dbpg->fetch_assoc($q_mess);
$details = json_decode($r_mess['details'], true);
if($service_id == 1){
$chatid = $r_mess['chat_id'];
$sql_chat = "SELECT id, object_id FROM chat_avito WHERE chat_id = '{$chatid}'";
$q_chat = $this->dbpg->query($sql_chat);
$r_chat = $this->dbpg->fetch_assoc($q_chat);
if($r_chat) $objectId = (int)$r_chat['object_id'];
} else if ($service_id == 2){
$objectId = (int)$details['offers'][0]['externalId'];
}
$user_id = 0;
$sql_user = "SELECT * FROM users WHERE {$field_user} = {$chat_id}";
$q_user = $this->db->query($sql_user);
$r_user = $this->db->fetch_assoc($q_user);
$user_id = (int)$r_user['id'];
$agency_id = (int)$r_user['company_id'] > 0 ? $r_user['company_id'] : $user_id;
if($objectId == 0)
$errors[] = "Объект не найден стадия 1";
$this->db->query("UPDATE {$table_event} SET status = 1 WHERE {$field_user_event} = {$chat_id}");
$description = date('d-m-Y H:i:s').' - Запрос на добавление';
$sql = "INSERT INTO {$table_event} ({$field_user_event}, mess_id, event, stage, service, description, user_id, agency_id, object_id)
VALUE ({$chat_id}, {$mess_id}, 'add_req', 1, {$service_id}, '{$description}', {$user_id}, {$agency_id}, {$objectId})";
if(!$this->db->query($sql)){
$errors[] = $this->db->error();
}
$stage = 1;
} else {
$errors[] = "Неверный сервис";
}
$result = array('result'=>'add_req', 'stage'=>$stage);
break;
}
case 1:{
if(empty($mess)) $errors[] = "Пустое сообщение";
$phone = '+'.str_replace(['(', ')', ' ', '-', '+'], '', trim($mess));
if(empty($event_table)){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$event_table = $this->db->fetch_assoc($q_ev);
}
}
if(empty($event_table)) $errors[] = "Не найдено связаное событие";
if($event_table['object_id'] == 0) $errors[] = "Не найден объект стадия 2";
if($event_table['user_id'] == 0) $errors[] = "Не определен user_id";
if(empty($errors)){
$agency_id = $event_table['agency_id'];
$usersIds = array();
$wb = new WebHookIn();
$usersIds = $wb->getAllUserAgency($agency_id);
$sql = "SELECT `id`, `stage`, `deleted`, `fio` FROM `clients` WHERE cancel=0 AND (phone = '$phone' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$phone')) and (id_agent in (".implode(',', $usersIds).") or who_work in (".implode(',', $usersIds)."))";
$client = $this->db->fetch_assoc($this->db->query($sql));
if(!empty($client) && $client){
$client_id = $client['id'];
$description = mysql_real_escape_string($event_table['description'] . ' ' . date('d.m.Y H:i:s') . ' - Найден клиент: ' . $client_id);
//if($max === false)
$this->db->query("UPDATE {$table_event} SET description = '{$description}', client_id={$client_id}, stage=2, status=0 WHERE id = {$event_table['id']}");
$stage = 2;
$Funnel = new Funnel();
$Funnel->set_agency_id($agency_id);
$Funnel->set_user_id($event_table['user_id']);
$funnels = $Funnel->get_funnels('requisitions');
$result = array('result'=>'add_req', 'stage'=>$stage, 'funnels'=>$funnels, 'service' => $event_table['service'], 'mess_id' => $event_table['mess_id']);
} else {
$description = mysql_real_escape_string($event_table['description'] . ' ' . date('d.m.Y H:i:s') . ' - Сохранен номер: ' . $phone);
$this->db->query("UPDATE {$table_event} SET phone_temp='{$phone}', stage=4 WHERE id = {$event_table['id']}");
$stage = 4;
$result = array('result'=>'add_req', 'stage'=>$stage, 'service' => $event_table['service'], 'mess_id' => $event_table['mess_id']);
}
}
break;
}
case 3: {
if(empty($event_table)){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND event='add_req' AND mess_id = $mess_id AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$event_table = $this->db->fetch_assoc($q_ev);
}
}
if(empty($event_table)) $errors[] = "Не найдено связаное событие";
if($event_table['object_id'] == 0) $errors[] = "Не найден объект стадия 2";
if($event_table['user_id'] == 0) $errors[] = "Не определен user_id";
if($event_table['client_id'] == 0) $errors[] = "Не определен client_id";
if(empty($errors)){
$client_id = $event_table['client_id'];
$object_id = $event_table['object_id'];
$user_id = $event_table['user_id'];
$funnel_id_req = $mess;
$client = $this->db->fetch_assoc($this->db->query("SELECT * FROM clients WHERE id = {$client_id}"));
$name = "Спрос по нашему объекту для ".$client['fio'];
$opis = "Создана в боте ТГ";
if($max){
$opis = "Создана в боте MAX";
}
$sql_req = "INSERT INTO requisitions SET
client_id={$client_id},
name='{$name}',
description='{$opis}',
user_id={$user_id},
who_work={$user_id},
type_id=4,
confirm=1,
funnel_id={$funnel_id_req},
stage=1,
object_id = '{$object_id}',
integration = 15
";
$this->db->query($sql_req);
$req_id = $this->db->insert_id();
if($req_id > 0 && $funnel_id_req > 0){
$reqClass = new Requisitions($this->db, true);
$reqClass->get_class_etap($req_id, $funnel_id_req);
}
$description = mysql_real_escape_string($event_table['description'] . ' ' . date('d.m.Y H:i:s') . ' - Выбрана воронка: ' . $funnel_id_req . ' Добавлена заявка: '.$req_id);
$this->db->query("UPDATE {$table_event} SET description = '{$description}', funnel_id_req={$mess}, stage=3, status=1, req_id={$req_id} WHERE id = {$event_table['id']}");
$stage = 0;
$result = array('result'=>'add_req', 'stage'=>0);
}
break;
}
case 4:{
if(empty($mess)) $errors[] = "Пустое сообщение";
// $phone = '+'.str_replace(['(', ')', ' ', '-', '+'], '', trim($mess));
if(empty($event_table)){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$event_table = $this->db->fetch_assoc($q_ev);
}
}
if(empty($event_table)) $errors[] = "Не найдено связаное событие";
if($event_table['object_id'] == 0) $errors[] = "Не найден объект стадия 2";
if($event_table['user_id'] == 0) $errors[] = "Не определен user_id";
if(empty($errors)){
$agency_id = $event_table['agency_id'];
$description = mysql_real_escape_string($event_table['description'] . ' ' . date('d.m.Y H:i:s') . ' - Сохранено имя клиента: ' . $mess);
$this->db->query("UPDATE {$table_event} SET fio_temp='{$mess}', description = '{$description}', stage=5 WHERE id = {$event_table['id']}");
$stage = 5;
$Funnel = new Funnel();
$Funnel->set_agency_id($agency_id);
$Funnel->set_user_id($event_table['user_id']);
$funnels = $Funnel->get_funnels('clients');
$result = array('result'=>'add_req', 'stage'=>$stage, 'funnels'=>$funnels, 'service' => $event_table['service'], 'mess_id' => $event_table['mess_id']);
}
//$stage = 5;
//$result = array('result'=>'add_req', 'stage'=>$stage);
break;
}
case 6: {
if(empty($event_table)){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND event='add_req' AND mess_id = $mess_id AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$event_table = $this->db->fetch_assoc($q_ev);
}
}
if(empty($event_table)) $errors[] = "Не найдено связаное событие";
if($event_table['object_id'] == 0) $errors[] = "Не найден объект стадия 2";
if($event_table['user_id'] == 0) $errors[] = "Не определен user_id";
if(empty($errors)){
$agency_id = $event_table['agency_id'];
$user_id = $event_table['user_id'];
$funnel_id = $mess;
$fio = $event_table['fio_temp'];
$phone = $event_table['phone_temp'];
$opis = "Создан в боте ТГ";
if($max){
$opis = "Создан в боте MAX";
}
$date_add = date('Y-m-d H:i:s');
$sql_req = "INSERT INTO clients SET
fio='{$fio}',
date_add = '{$date_add}',
phone='{$phone}',
opis='{$opis}',
id_agent={$user_id},
who_work={$user_id},
confirm=1,
funnel_id={$funnel_id},
stage=1,
integration = 15
";
$this->db->query($sql_req);
$client_id = $this->db->insert_id();
if($client_id > 0 && $funnel_id > 0){
$clientClass = new Clients();
$clientClass->get_class_etap($client_id, $funnel_id);
}
$description = mysql_real_escape_string($event_table['description'] . ' ' . date('d.m.Y H:i:s') . ' - Выбрана воронка: ' . $funnel_id . ' Добавлен клиент: '.$client_id);
$this->db->query("UPDATE {$table_event} SET description = '{$description}', funnel_id={$mess}, stage=2, status=0, client_id={$client_id} WHERE id = {$event_table['id']}");
$stage = 2;
$Funnel = new Funnel();
$Funnel->set_agency_id($agency_id);
$Funnel->set_user_id($event_table['user_id']);
$funnels = $Funnel->get_funnels('requisitions');
$result = array('result'=>'add_req', 'stage'=>$stage, 'funnels'=>$funnels, 'service' => $event_table['service'], 'mess_id' => $event_table['mess_id']);
}
}
break;
}
} else {
$errors[] = 'Empty data';
}
if(empty($result)){
$errors[] = "Путой rezult";
}
if(!empty($errors)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." ".json_encode($errors, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
return array('result'=>'error');
}
return $result;
}
/**
* Отмена добавления заявки
*/
public function cancel_add_req($mess_id, $chat_id, $max = false){
$table_event = ($max) ? 'max_events' : 'telegram_events';
$field_user = ($max) ? 'max_user_id' : 'telegramm_chat_id';
$field_user_event = ($max) ? 'max_user_id' : 'chat_id';
$errors = array();
$stage = 0;
if($this->service > 0 && $mess_id > 0 && $chat_id > 0){
$sql_ev = "SELECT * FROM {$table_event} WHERE {$field_user_event} = {$chat_id} AND mess_id = {$mess_id} AND event = 'add_req' AND status = 0 ORDER BY id DESC LIMIT 1";
$q_ev = $this->db->query($sql_ev);
if($this->db->num_rows($q_ev) > 0){
$r_ev = $this->db->fetch_assoc($q_ev);
$description = mysql_real_escape_string($r_ev['description'] . ' ' . date('d.m.Y H:i:s') . ' - Создание заявки отменено');
$this->db->query("UPDATE {$table_event} SET description = '{$description}', status = 1 WHERE id = {$r_ev['id']}");
$result['result'] = 'cancel_add_req';
}
}
if(!empty($errors)){
file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_avito_cian_sql.txt", date('d.m.y H:i:s').' service '.$this->service.' id:'.$mess_id." ".json_encode($errors, JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND);
return array('result'=>'error');
}
return array('result'=>'done', 'stage'=>$stage);
}
}