'beelineAbonentNoAnswer', 1 => 'beelineAbonentAnswer', 2 => 'abonentBeelineAnswer', 3 => 'abonentBeelineNoAnswer']; private $client_stage = 0; public $subscription_url; private $dbpg = null; public function __construct($api_key){ $this->api_key = $api_key; $this->header = ['Content-type:application/json', 'X-MPBX-API-AUTH-TOKEN:'.$api_key]; $this->dbpg = new MysqlPdo(hstpg, ndbpg, userpg, passpg, false, '5432', true); } public function set_users($users){ $this->users = $users; } public function checkSubscription($id) { $sql = "SELECT * FROM call_subscription WHERE batc_id = $id"; $subscription = mysql_fetch_assoc(mysql_query($sql)); if(!$subscription){ $result = $this->setSubscription(); if(isset($result['subscriptionId'])) { $sql = "INSERT INTO `call_subscription`(`batc_id`, `api_key`, `subscriptionId`, `expires`) VALUES ($id,'".$this->api_key."','".$result['subscriptionId']."',".$result['expires'].")"; mysql_query($sql); } } else { $result = $this->doSubscription($subscription); if(isset($result['subscriptionId'])){ if($result['expires'] > 172800){ $sql = "UPDATE `call_subscription` SET `expires`=".$result['expires']." WHERE id=".$subscription['id']; mysql_query($sql); } else { $result = $this->setSubscription(); if(!empty($result['subscriptionId'])) { $sql = "UPDATE `call_subscription` SET `expires`=" . $result['expires'] . ", `subscriptionId`='" . $result['subscriptionId'] . "' WHERE id=" . $subscription['id']; mysql_query($sql); $this->deleteSubscription($subscription); } } } else { $result = $this->setSubscription(); if(!empty($result['subscriptionId'])) { $sql = "UPDATE `call_subscription` SET `expires`=" . $result['expires'] . ", `subscriptionId`='" . $result['subscriptionId'] . "' WHERE id=" . $subscription['id']; mysql_query($sql); $this->deleteSubscription($subscription); } } } } public function renewSubscription($subscriptionId){ $sql = "SELECT * FROM call_subscription WHERE subscriptionId = '$subscriptionId'"; $subscription = mysql_fetch_assoc(mysql_query($sql)); if($subscription){ $this->api_key = $subscription['api_key']; $result = $this->setSubscription(); if(!empty($result['subscriptionId'])) { $sql = "UPDATE `call_subscription` SET `expires`=" . $result['expires'] . ", `subscriptionId`='" . $result['subscriptionId'] . "' WHERE id=" . $subscription['id']; mysql_query($sql); } } } private function doSubscription($subscription){ $subscriptionId = $subscription['subscriptionId']; $this->metod = "subscription?subscriptionId=$subscriptionId"; return json_decode($this->sendCurl(),true); } private function deleteSubscription($subscription){ $subscriptionId = $subscription['subscriptionId']; $this->metod = "subscription?subscriptionId= $subscriptionId"; return json_decode($this->sendCurl(false, ["type"=>"DELETE", "body"=>""]),true); } private function setSubscription(){ $this->metod = 'subscription'; $body = [ "expires" => 2592000, "subscriptionType" => "BASIC_CALL", "url" => $this->subscription_url, ]; return json_decode($this->sendCurl(false,['type'=>"PUT","body"=>json_encode($body)]), true); } private function sendCurl($post = false, $custom = false){ $response = 0; $url = $this->base_url . $this->metod; // echo $url.'
'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //if($header){ curl_setopt($ch, CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); if($post){ $this->header = ['X-MPBX-API-AUTH-TOKEN:'.$this->api_key]; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post); } curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header); if($custom){ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $custom['type']); curl_setopt($ch, CURLOPT_POSTFIELDS,$custom['body']); } $response = curl_exec($ch); // var_dump($response); if($errno = curl_errno($ch)) { $error_message = curl_strerror($errno); echo "cURL error ({$errno}):\n {$error_message}"; } curl_close($ch); return $response; } public function callTransfer($user_id,$call_id,$phone) { $this->metod = "abonents/$user_id/callTransfer"; $this->post = "callId=$call_id&phoneNumber=$phone"; $res = $this->sendCurl(true); //$result['ps'] = "abonents/$user_id/callTransfer callId=$call_id&phoneNumber=$phone"; return $res; } public function callTransferConsult($user_id,$call_id,$phone) { $this->metod = "abonents/$user_id/callTransferConsult"; $this->post = "callId=$call_id&callIdConsult=$phone"; $this->sendCurl(true); } public function callrelease($user_id,$call_id,$phone) { $this->metod = "abonents/$user_id/callTransferConsult"; $this->post = "callId=$call_id&callIdConsult=$phone"; $this->sendCurl(true); } public function getRoute(){ $this->metod = "icr/route"; $res = $this->sendCurl(); return $res; } public function put_route($phone, $extension){ $phone = str_replace('+7', '', $phone); $this->metod = 'icr/route'; $body = [array( "inboundNumber" => $phone, "extension" => $extension, ) ]; return json_decode($this->sendCurl(false,['type'=>"PUT","body"=>json_encode($body)]), true); } public function checkRoute($call, $agency_id){ $department = isset($call->department) ? $call->department : ''; if(strpos(mb_strtolower($department), 'sip') !== false){ $phone = $call->phone; $extension = $call->abonent->extension; if(!empty($phone) && !empty($extension)){ $sql = "SELECT * FROM rule_route WHERE phone = '{$phone}' AND extension = '{$extension}' AND agency_id = {$agency_id}"; $q = $this->dbpg->query($sql); if($this->dbpg->num_rows($q) == 0){ $result = $this->put_route($phone, $extension); if($result[0]['status'] == 'SUCCESS'){ $sql_in = "INSERT INTO rule_route (phone, extension, agency_id) VALUES ('{$phone}', '{$extension}', {$agency_id})"; $this->dbpg->query($sql_in); } } } } } public function getUsers(){ $this->metod = 'abonents'; $res = $this->sendCurl(false); return $res; } public function stat_records($start_datetime, $lastId = false){ $this->metod = 'records?dateFrom='.$start_datetime;//.'&dateTo='.$end_date;//api/ver1.0/client/'.$this->client_id.'/call_history/?start_datetime='.$start_datetime.'&order=asc&end_datetime='.$end_datetime.'&per_page=100000&page=1'; if($lastId > 0){ $this->metod = 'records?id='.$lastId; } // echo $this->metod."\n"; $res = $this->sendCurl(false); return $res; } public function calls($start_datetime){ $this->metod = 'statistics?dateFrom='.$start_datetime.'&page=0&pageSize=100'; $res = $this->sendCurl(false); return $res; } public function get_record($record_uuid){ $this->metod = 'v2/records/'.$record_uuid.'/download'; $res = $this->sendCurl(false); return $res; } private function type_phone($call){ //call); //var_dump($call); $result = ''; $find_user = ''; //$result = $call->result; //if(isset($call->abonent->)) $find_user = $call->abonent->userId; $part_user = explode('@', $call->abonent->userId); if(isset($part_user[0])){ $find_user = $part_user[0]; } if(isset($call->status) && $call->status == 'MISSED'){ if($call->direction == 'INBOUND'){ $type = 3; } else { $type = 0; } } else { if($call->direction == 'INBOUND'){ $type = 2; } else { $type = 1; } } $this->phone_type = $this->phone_types[$type]; // echo $find_user.'*****
'; return $find_user; } public function get_phone_type($phone){ $find_user = $this->type_phone($phone); return json_encode(array('type'=>$this->phone_type, 'find_user'=>$find_user)); } //Установка стадии клиента private function set_client_stage($stage){ $this -> client_stage = $stage; } public function find_user($phone, $agency_id=0){ // echo $phone."\n"; $user_id = 0; $part_user = explode('@', $phone); if(isset($part_user[0])){ $phone = $part_user[0]; } $phone = $this->ver_phone($phone); $sql_user = "SELECT id FROM users WHERE phone = '".$phone."' and blocked=0"; // echo $sql_user."\n"; $q_user = mysql_query($sql_user); if(mysql_num_rows($q_user) > 0){ $r_user = mysql_fetch_assoc($q_user); $user_id = $r_user['id']; } return $user_id; } public function find_client($phone, $no = false){ $this -> set_client_stage(0); $client_id = 0; $phone_client = $this -> ver_phone($phone); $sql_cl = "SELECT `id`, `stage` FROM `clients` WHERE (phone = '$phone_client' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$phone_client')) and (who_work in (".implode(',', $this->users).") or id_agent in (".implode(',', $this->users)."))"; if($no){ $sql_cl = "SELECT `id`, `stage` FROM `clients` WHERE (phone = '$phone_client' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$phone_client'))"; } //echo $sql_cl.'****************'; $q_cl = mysql_query($sql_cl); if(mysql_num_rows($q_cl) > 0){ $r_cl = mysql_fetch_assoc($q_cl); $client_id = $r_cl['id']; $this -> set_client_stage($r_cl['stage']); } return $client_id; } public function recordSave($p){ if (!is_dir($_SERVER['DOCUMENT_ROOT'] . "/server/beeline")) { mkdir($_SERVER['DOCUMENT_ROOT'] . "/server/beeline", 0777); } $records = array(); $records[] = $p->externalId; $file = trim($this->get_record($p->id)); $name = $p->externalId.'.mp3'; if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/server/beeline/'.$name)){ file_put_contents($_SERVER['DOCUMENT_ROOT'].'/server/beeline/'.$name, $file); } //var_dump($file);*/ return json_encode($records); } public function find_user_comment($call, $type){ $number = $call->abonent->userId; $mes = ''; $sql = "SELECT fio FROM mango_call_users WHERE number_sip = '".$number."'"; //echo $sql; $q = mysql_query($sql); if(mysql_num_rows($q) > 0){ $r = mysql_fetch_assoc($q); $mes = '(Сотрудник '.$r['fio'].')'; } return $mes; } public function stat($call, $agency_id){ $id = 0; $idpg = 0; $from_extension = ''; $to_extension = ''; if($call->direction == 'INBOUND'){ $to_number = $call->abonent->userId; $from_number = $call->phone; $to_extension = $call->abonent->extension; if(empty($to_extension)){ $to_extension = $call->abonent->userId; } $entry_id = $call->abonent->userId; } else { $to_number = $call->phone; $from_number = $call->abonent->userId; $from_extension = $call->abonent->extension; if(empty($from_extension)){ $from_extension = $call->abonent->userId; } $entry_id = $call->phone; } $call_id = false; $operator_call_id = 0; if(isset($call->callId)){ $operator_call_id = (int)str_replace(['callhalf-',':'],'',$call->callId); } if(!isset($call->id)){ $call->id = $call->startDate+$call->duration; } //echo $to_number.'
'; $sql = "SELECT id FROM mango_calls WHERE uuid = '".$call->id."'"; $q = mysql_query($sql); $qpg = $this->dbpg->query($sql); $date = floor($call->date/1000); /* if(mysql_num_rows($q) == 0){ if(isset($call->externalId)){ $record = $this->recordSave($call); } else { $record = json_encode([]); } $answerResult = 'answered'; $answer = $date; if(isset($call->status) && $call->status == 'MISSED'){ $answerResult = 'not answered'; $answer = 0; } $start = $date; $finish = floor(($call->date + $call->duration)/1000); // проверка записанных звонков с виджета $update = false; if($call->direction == 'INBOUND'){ //$uuid = $entry_id .".".($call->startDate); $_sql = "SELECT id FROM mango_calls WHERE operator_id = 2 and `operator_call_id`=$operator_call_id"; if(!empty($from_number)){ $_sql .= "and from_number = '$from_number'"; } $_c = mysql_fetch_assoc(mysql_query($sql)); if(isset($_c['id'])){ $update = true; } } if($update){ $in = "UPDATE `mango_calls` SET `records`='" . $record . "', `start`= $start, `finish`=$finish, `to_extension`='" . $to_extension . "', `operator_id`=2, `operator_call_id`=$operator_call_id, `uuid`='" . $call->id . "' WHERE id =".$_c['id']; $id = (int)$_c['id']; } else { $in = "INSERT INTO `mango_calls` SET `records`='" . $record . "', `start`= $start, `finish`=$finish, `answer`=$answer, `from_extension`='" . $from_extension . "', `from_number`= '" . $from_number . "', `to_extension`='" . $to_extension . "', `to_number`='" . $to_number . "', `disconnect_reason`='" . $answerResult . "', `entry_id`='" . $entry_id . "', `line_number`='beeline', `location`='', `uuid`='" . $call->id . "', `agency_id`=$agency_id, `operator_id`=2, `operator_call_id`=$operator_call_id, `vpbx_id`='" . $call->abonent->userId ."' "; } mysql_query($in); if(!$update){ $id = mysql_insert_id(); } } else { $r = mysql_fetch_assoc($q); $id = (int)$r['id']; } */ if($this->dbpg->num_rows($qpg) == 0){ if(isset($call->externalId)){ $record = $this->recordSave($call); } else { $record = json_encode([]); } $answerResult = 'answered'; $answer = $date; if(isset($call->status) && $call->status == 'MISSED'){ $answerResult = 'not answered'; $answer = 0; } $start = $date; $finish = floor(($call->date + $call->duration)/1000); // проверка записанных звонков с виджета $update = false; if($call->direction == 'INBOUND'){ //$uuid = $entry_id .".".($call->startDate); $_sql = "SELECT id FROM mango_calls WHERE operator_id = 2 and operator_call_id='{$operator_call_id}'"; if(!empty($from_number)){ $_sql .= "and from_number = '$from_number'"; } $_c = $this->dbpg->fetch_assoc($this->dbpg->query($sql)); if(isset($_c['id'])){ $update = true; } } if($update){ $in = "UPDATE mango_calls SET records='" . $record . "', start= $start, finish=$finish, to_extension='" . $to_extension . "', from_extension='".$from_extension."', operator_id=2, operator_call_id='{$operator_call_id}', uuid='" . $call->id . "' WHERE id =".$_c['id']; $id = (int)$_c['id']; } else { $in = "INSERT INTO mango_calls (records, start, finish, answer, from_extension, from_number, to_extension, to_number, disconnect_reason, entry_id, line_number, location, uuid, agency_id, operator_id, operator_call_id, vpbx_id ) VALUES ( '" . $record . "', $start, $finish, $answer, '" . $from_extension . "', '" . $from_number . "', '" . $to_extension . "', '" . $to_number . "', '" . $answerResult . "', '" . $entry_id . "', 'beeline', '', '" . $call->id . "', $agency_id, 2, '{$operator_call_id}', '" . $call->abonent->userId ."' )"; } //file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_call_sql.txt", $in."\n", FILE_APPEND); $this->dbpg->query($in); if(!$update){ $idpg = $this->dbpg->insert_id(); } } else { $r = $this->dbpg->fetch_assoc($qpg); $idpg = (int)$r['id']; } $result['id'] = $id; $result['idpg'] = $idpg; $result['call_id'] = $call->id; return $result; } public function saveUser($user, $agency_id){ $phone = ''; if(isset($user->email) && !empty($user->email)){ $user_id = $user->userId; $part_user = explode('@', $user_id); if(isset($part_user[0])){ $user_id = $part_user[0]; } $sql = "SELECT id, number_phone FROM mango_call_users WHERE user_id='".$user_id."'"; $q = mysql_query($sql); $sql_p = "SELECT phone FROM users WHERE email = '".$user->email."' AND company_id = {$agency_id}"; if($agency_id == 19895){ //echo $sql_p."\n"; } $q_p = mysql_query($sql_p); if(mysql_num_rows($q_p) > 0){ $r_p = mysql_fetch_assoc($q_p); $phone = $r_p['phone']; } else { $part_phone = str_replace('@ip.beeline.ru', '', $user_id); $in_vdx = "'".$user_id."', '".$part_phone."', '".$this->ver_phone($part_phone)."'"; $sql_p = "SELECT phone FROM users WHERE vpbx_id in ({$in_vdx}) AND company_id = {$agency_id}"; if($agency_id == 19895){ //echo $sql_p."\n"; } $q_p = mysql_query($sql_p); if(mysql_num_rows($q_p) > 0){ $r_p = mysql_fetch_assoc($q_p); $phone = $r_p['phone']; } } $user_name = ''; if(isset($user->lastName) && !empty($user->lastName)){ $user_name .= $user->lastName; } if(isset($user->firstName) && !empty($user->firstName)){ if($user_name != ''){ $user_name .= ' '; } $user_name .= $user->firstName; } $department = ''; if(isset($user->department)){ $department = $user->department; } //Записываем if(mysql_num_rows($q) == 0){ /*f($phone == ''){ $phone = mysql_fetch_assoc($q)['number_phone']; }*/ $in = "INSERT INTO `mango_call_users` SET user_id = '".$user_id."', fio = '".$user_name."', number_phone = '".$phone."', number_sip = '".$user_id."', department = '".trim($department)."', extension = '".(isset($user->extension) ? $user->extension : '')."', agency_id = $agency_id "; // echo $in."\n"; mysql_query($in); } else { $up = "UPDATE `mango_call_users` SET fio = '".$user_name."', number_phone = '".$phone."', number_sip = '".$user_id."', department = '".trim($department)."', extension = '".(isset($user->extension) ? $user->extension : '')."', agency_id = $agency_id WHERE user_id = '".$user_id."'"; // echo $up."\n"; mysql_query($up); } } return $phone; } public function findSource($phone){ $source = 0; $sql = "SELECT * FROM advertising_phone WHERE phone = '".$phone."'"; $q = mysql_query($sql); if(mysql_num_rows($q) > 0){ $r = mysql_fetch_assoc($q); $sql_v = "SELECT id FROM advertising_sources WHERE id = ".$r['adv_id']." AND user_id in (".implode(', ',$this->users).")"; $q_v = mysql_query($sql_v); if(mysql_num_rows($q_v) > 0){ $r_v = mysql_fetch_assoc($q_v); $source = $r_v['id']; } } return $source; } public function save_user_call($id_call, $user_find, $main_user, $agency_id=0){ $user_id = 0; if($id_call > 0){ $user_id = (int)$this->find_user($user_find); if($user_id == 0){ $user_id = (int)$main_user; } } if($user_id > 0){ $sql = "SELECT id FROM user_call WHERE call_id = {$id_call}"; $q = mysql_query($sql); if(mysql_num_rows($q) == 0){ $sql_in = "INSERT INTO user_call SET call_id = {$id_call}, user_id = {$user_id}"; mysql_query($sql_in); } } } public function save_user_call_pg($id_call, $user_find, $main_user, $agency_id=0){ $user_id = 0; if($id_call > 0){ $user_id = (int)$this->find_user($user_find); if($user_id == 0){ $user_id = (int)$main_user; } } if($user_id > 0){ $sql = "SELECT id FROM user_call WHERE call_id = {$id_call}"; $q = $this->dbpg->query($sql); if($this->dbpg->num_rows($q) == 0){ $sql_in = "INSERT INTO user_call (call_id, user_id) VALUES ($id_call, $user_id)"; if($agency_id == 11916){ //file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_call_sql.txt", $sql_in."\n", FILE_APPEND); } $this->dbpg->query($sql_in); } } } }