'undefined', 1 => 'mangoAbonentAnswer', 2 => 'abonentMangoAnswer', 3 => 'mangoAbonentNoAnswer', 4 => 'abonentMangoNoAnswer']; private $phone_type; private $users = array(); private $client_stage = 0; private $db = null; private $dbpg = null; public function __construct($key, $salt, $db=null) { $this->api_key = $key; $this->api_salt = $salt; if (!is_null($db)) { $this->db = $db; } else { $pdo = new MysqlPdo(hst, ndb, user, pass); $pdo->query("SET NAMES 'utf8'"); $this->db = $pdo; } $this->dbpg = new MysqlPdo(hstpg, ndbpg, userpg, passpg, false, '5432', true); } public function validate_agency($agencyId){ $result = false; $sql = "SELECT id from users where now() <= DATE_ADD(date_tarif, INTERVAL( SELECT t.period FROM tariffs t WHERE t.id=id_tarif LIMIT 1) DAY) AND id=$agencyId"; $r = mysql_query($sql); $row = mysql_num_rows($r); if($row > 0){ $result = true; } return $result; } /** * Для виджета mango проверка есть ли агентство в системе и подключено ои оно к телефонии */ public function validate_agency_apikey(){ $result = false; $agency_id = 0; $sql = "SELECT * FROM agency_mango WHERE `api_key` = '{$this->api_key}'"; $q = $this->db->query($sql); $agency_mango = $this->db->fetch_assoc($q); if(isset($agency_mango['agency_id']) && $agency_mango['agency_id'] > 0){ $agency_id = (int)$agency_mango['agency_id']; if($this->validate_agency($agency_id)){ $result = $agency_id; } } return $result; } public function set_users($users){ $this->users = $users; } //Установка стадии клиента private function set_client_stage($stage){ $this -> client_stage = $stage; } //Получение стадии клиента public function get_client_stage(){ return $this -> client_stage; } public function get_phone_type($phone){ $this->type_phone($phone); return $this -> phone_type; } private function sendCurl($post = true){ $response = 0; $url = $this->base_url . $this->metod; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if($post){ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post); } $response = curl_exec($ch); curl_close($ch); return $response; } public function request($metod, $jsonParams = false){ $this->metod = $metod; if($jsonParams !== false){ $json = $jsonParams; } else { $json = json_encode($this->params); } $sign = hash('sha256', $this->api_key . $json . $this->api_salt); $this->post = array( 'vpbx_api_key' => $this->api_key, 'sign' => $sign, 'json' => $json ); $res = $this->sendCurl(); return $res; } private function requestGet($metod){ $this->metod = $metod; $sign = hash('sha256', $this -> api_key . $this -> params['time'] . $this-> params['recording_id'] . $this->api_salt); $this->metod .= $this-> params['recording_id']."/".$this-> params['action']."/". $this -> api_key."/".$this -> params['time'] ."/".$sign; $this -> sendCurl(false); } public function requestPhones(){ $res = json_decode($this ->request('stats/request')); // var_dump($res); $this->request_key = (is_object($res) && isset($res->key)) ? $res->key : null; //echo $this->request_key; } public function resultPhones(){ $this->params = array( "key" => $this->request_key ); $res = $this ->request('stats/result'); return $res; } public function recordingQuery(){ $res = $this -> requestGet('queries/recording/link/'); return $res; } public function recordingSave(){ if (empty($this->params['action'])) { $this->params['action'] = 'download'; } $json = json_encode($this->params); $url = $this->base_url."queries/recording/post"; $sign = hash('sha256', $this->api_key . $json . $this->api_salt); $postdata = array( 'vpbx_api_key' => $this->api_key, 'sign' => $sign, 'json' => $json ); $post = http_build_query($postdata); $opts = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $post, 'timeout' => 15, ) ); $context = stream_context_create($opts); $data = @file_get_contents(trim($url), false, $context); if ($data !== false) { file_put_contents($_SERVER['DOCUMENT_ROOT'].'/server/mango/'.$this->params['recording_id'].'.mp3', $data); } } public function configUsers($userParams = false){ /* $json = false; if($userParams !== false){ $json = json_encode($userParams); }*/ $json = '{ "ext_fields" : [ "general.user_id", "general.sips", "groups", "general.access_role_id", "telephony.dial_alg", "telephony.numbers.schedule", "telephony.line_id", "telephony.trunk_number_id", "general.mobile", "general.login", "general.use_status", "general.use_cc_numbers" ] }'; $metod = 'config/users/request'; $res = $this->request($metod, $json); return $res; } public function groups(){ $metod = 'groups'; $res = $this->request($metod); return $res; } public function incominglines(){ $metod = 'incominglines'; $res = $this->request($metod); return $res; } private function type_phone($phone){ $type = 0; if(!isset($phone['answer']) || $phone['answer'] == 0){ if(empty($phone['from_extension'])){ $type = 4; } else { $type = 3; } } else { if(empty($phone['from_extension'])){ $type = 2; } else { $type = 1; } } $this->phone_type = $this->phone_types[$type]; } public function ver_phone($phone){ $phone_client = $phone; if(strlen($phone_client) < 11){ if(strlen($phone_client) == 10){ $phone_client = '+7' . $phone_client; } else if(strlen($phone_client) == 7) { $phone_client = '+7812' . $phone_client; } } elseif(strlen($phone_client) == 11) { if(substr($phone_client, 0, 1) == "8"){ $phone_client = substr_replace($phone_client, '+7', 0, 1); } else { $phone_client = '+' . $phone_client; } } return $phone_client; } 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 cancel=0 AND (phone = '$phone_client' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = '$phone_client')) and (id_agent in (".implode(',', $this->users)."))"; if($no){ $sql_cl = "SELECT `id`, `stage` FROM `clients` WHERE cancel=0 AND (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 find_client_info($phone){ $client = array(); $phone_client = $this->ver_phone($phone); $sql_cl = "SELECT * FROM `clients` WHERE cancel=0 AND (phone = '$phone_client') and (who_work in (".implode(',', $this->users).") or id_agent in (".implode(',', $this->users)."))"; //echo $sql_cl.'****************'; $q_cl = mysql_query($sql_cl); if(mysql_num_rows($q_cl) > 0){ $r_cl = mysql_fetch_assoc($q_cl); $client = $r_cl; } return $client; } public function find_user($phone, $agency_id=0){ $user_id = 0; if( strpos($phone, 'sip:') !== false){ $sql_user = "SELECT user_id FROM mango_users WHERE mango_sip = '".$phone."'"; } else { $sql_user = "SELECT user_id FROM mango_users WHERE mango_tel = '".$phone."'"; } $q_user = mysql_query($sql_user); if(mysql_num_rows($q_user) > 0){ $r_user = mysql_fetch_assoc($q_user); $user_id = $r_user['user_id']; } return $user_id; } //Запись статистики звонков public function stat($call, $agency_id){ // echo $this->phone_type."\n"; $id = 0; $idpg = 0; $poles = array(); if(!empty($call['start'])){ if($this->phone_type == 'mangoAbonentAnswer' || $this->phone_type == 'mangoAbonentNoAnswer'){ $call['entry_id'] = $call['to_number']; } //Проверка есть ли запись $sql = "SELECT id FROM mango_calls WHERE start='".$call['start']."' AND finish = '".$call['finish']."' AND to_number = '".$call['to_number']."'"; // $q = mysql_query($sql); $qpg = $this->dbpg->query($sql); //Записываем $pole_cols = array(); $pole_vals = array(); /* if(mysql_num_rows($q) == 0){ foreach ($call as $key => $val) { $poles[] = $key . " = '".$val."'"; } $poles[] = "agency_id = '".$agency_id."'"; $insert = "INSERT INTO mango_calls set ".implode(', ', $poles); mysql_query($insert); $id = mysql_insert_id(); } else { $r = mysql_fetch_assoc($q); $id = (int)$r['id']; }*/ if($this->dbpg->num_rows($qpg) == 0){ foreach ($call as $key => $val) { $pole_cols[] = $key; $pole_vals[] = $val; } $pole_cols[] = "agency_id"; $pole_vals[] = $agency_id; $insert = "INSERT INTO mango_calls (".implode(',', $pole_cols).") VALUES ('".implode('\',\'', $pole_vals)."')"; $this->dbpg->query($insert); $idpg = $this->dbpg->insert_id(); } else { $r = $this->dbpg->fetch_assoc($qpg); foreach ($call as $key => $val) { $poles[] = $key . " = '".$val."'"; } $up = "UPDATE mango_calls set ".implode(', ', $poles)." WHERE id = {$r['id']}"; $this->dbpg->query($up); // echo $up."\n"; $idpg = (int)$r['id']; } } $result['id'] = $id; $result['idpg'] = $idpg; return $result; } //Сохранение данных пользователя телефонии public function saveUser($user, $agensy_id){ $user_id = $user->general->user_id; $poles = array(); //Проверка есть ли запись $sql = "SELECT id FROM mango_call_users WHERE user_id='".$user_id."'"; $q = mysql_query($sql); //Записываем if(mysql_num_rows($q) == 0){ $poles[] = "user_id = '".$user_id."'"; if(!empty($user->general->name)) $poles[] = "fio = '".$user->general->name."'"; if(!empty($user->telephony->numbers)){ foreach ($user->telephony->numbers as $key => $number) { if($number->protocol == "sip"){ $poles[] = "number_sip = '".$number->number."'"; } if($number->protocol == "tel" && $number->order == 1){ $poles[] = "number_phone = '".$number->number."'"; } } } //$poles[] = "number_sip = '".$user->telephony->numbers[0]->number."'"; if(!empty($user->telephony->extension)) $poles[] = "extension = '".$user->telephony->extension."'"; /* if(!empty($user->groups)) $poles[] = "groups = '".json_encode($user->groups)."'";*/ if(!empty($user->general->department)) $poles[] = "department = '".$user->general->department."'"; if(!empty($user->general->position)) $poles[] = "position = '".$user->general->position."'"; $poles[] = "agency_id = '".$agensy_id."'"; $insert = "INSERT INTO `mango_call_users` set ".implode(', ', $poles); mysql_query($insert); } } //Запись групп public function saveGroups($groups, $agensy_id){ if (empty($groups)) { return; } $poles = array(); foreach ($groups as $key => $group) { //Проверка есть ли запись $sql = "SELECT id FROM mango_call_groups WHERE group_id = ".$group->id; $q = mysql_query($sql); //Записываем if(mysql_num_rows($q) == 0){ $insert = "INSERT INTO mango_call_groups set group_id = ".$group->id.", name = '".$group->name."', extension = '".$group->extension."'"; mysql_query($insert); } } } 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 setUsers($agency_id){ $usersIds = array(); $usersIds[] = $agency_id; $agentsOfAgency = User::getAgentsOfManager($agency_id, true); foreach($agentsOfAgency as $ag){ $usersIds[] = $ag['id']; } $agentsOfManager = User::getAllManagers($agency_id); foreach($agentsOfManager as $manager){ $usersIds[] = $manager['id']; $agentsOfAgency = User::getAgentsOfManager($manager['id'], true); foreach($agentsOfAgency as $ag){ $usersIds[] = $ag['id']; } } $this->set_users($usersIds); } 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)"; //file_put_contents($_SERVER['DOCUMENT_ROOT']."/webhooks/log_call_sql.txt", $sql_in."\n", FILE_APPEND); $this->dbpg->query($sql_in); } } } }