| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796 |
- <?php
- /**
- * This file is part of workerman.
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the MIT-LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @author walkor<walkor@workerman.net>
- * @copyright walkor<walkor@workerman.net>
- * @link http://www.workerman.net/
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
- /**
- * 用于检测业务代码死循环或者长时间阻塞等问题
- * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
- * 然后观察一段时间workerman.log看是否有process_timeout异常
- */
- //declare(ticks=1);
- use \GatewayWorker\Lib\Gateway;
- use Workerman\Lib\Timer;
- /**
- * 主逻辑
- * 主要是处理 onConnect onMessage onClose 三个方法
- * onConnect 和 onClose 如果不需要可以不用实现并删除
- */
- class Events
- {
- /**
- * 新建一个类的静态成员,用来保存数据库实例
- */
- public static $db = null;
- public static $global = null;
- /**
- * 进程启动后初始化数据库连接
- */
- public static function onWorkerStart($worker)
- {
- if (empty(self::$db)) {
- self::$db = new \Workerman\MySQL\Connection('192.168.2.186', '3306', 'root', '', 'customer_service');
- }
- if (empty(self::$global)) {
- self::$global = new \GlobalData\Client('127.0.0.1:2207');
- // 客服列表
- if (is_null(self::$global->kfList)) {
- self::$global->kfList = [];
- }
- // 会员列表[动态的,这里面只是目前未被分配的会员信息]
- if (is_null(self::$global->userList)) {
- self::$global->userList = [];
- }
- // 会员以 uid 为key的信息简表,只有在用户退出的时候,才去执行修改
- if (is_null(self::$global->uidSimpleList)) {
- self::$global->uidSimpleList = [];
- }
- // 当天的累积接入值
- $key = date('Ymd') . 'total_in';
- if (is_null(self::$global->$key)) {
- self::$global->$key = 0;
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- unset($oldKey, $key);
- }
- // 成功接入值
- $key = date('Ymd') . 'success_in';
- if (is_null(self::$global->$key)) {
- self::$global->$key = 0;
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- unset($oldKey, $key);
- }
- }
- // 定时统计数据
- if (0 === $worker->id) {
- self::writeLogKfStatus(0, 0, 0);
- // 1分钟统计一次实时数据
- Timer::add(60 * 1, function () {
- self::writeLog(1);
- });
- // 40分钟写一次当前日期点数的log数据
- Timer::add(60 * 40, function () {
- self::writeLog(2);
- });
- //每1分钟发一次本组排队数
- Timer::add(60 * 1, function () {
- self::lineup();
- });
- //初始化.....
- self::upsystemconfig();
- //每5分钟更新一次系统配置文件
- Timer::add(60 * 10, function () {
- self::upsystemconfig();
- });
- // 检查对话时效给出.
- Timer::add(60, function () {
- self::overTime();
- });
- // 实时监控.
- Timer::add(60, function () {
- $adminList = self::$global->adminList ?? [];
- self::systemMonitoring($adminList);
- });
- }
- }
- /**
- * 每分钟定时向客服发送一次排队情况
- */
- public static function lineup()
- {
- $userlist = self::$global->userList;
- $kflist = self::$global->kfList;
- if (empty($userlist) || empty($kflist)) {
- return;
- }
- $return = [];
- foreach ($userlist as $val) {
- $return[$val['group']] = isset($return[$val['group']]) ? $return[$val['group']] + 1 : 1;
- }
- $krgroupclientid = [];
- foreach ($kflist as $gid => $sval) {
- foreach ($sval as $tval) {
- $krgroupclientid[$gid][] = $tval['client_id'];
- }
- }
- foreach ($return as $fgroup => $fval) {
- foreach ($krgroupclientid as $sikey => $sival) {
- if ($fgroup == $sikey) {
- Gateway::sendToClient($sival, json_encode(['type' => 'lineupCount', $fval], 256));
- }
- }
- }
- return;
- }
- /**
- * 当客户端连接时触发
- * 如果业务不需此回调可以删除onConnect
- *
- * @param int $client_id 连接id
- */
- public static function onConnect($client_id)
- {
- // 检测是否开启自动应答
- $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 1');
- if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
- $hello = [
- 'message_type' => 'helloMessage',
- 'data' => [
- 'name' => '智能助手',
- 'time' => date('H:i'),
- 'content' => $sayHello['0']['word']
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($hello, 256));
- unset($hello);
- }
- unset($sayHello);
- // 检测是否开启广告
- $advertisement = self::$db->query('select `*` from `ws_advertisement` where `advertisement_status` = 1');
- if (!empty($advertisement)) {
- $chat_message = [
- 'message_type' => 'advertisement',
- 'data' => $advertisement
- ];
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- unset($chat_message);
- }
- unset($advertisement);
- }
- /**
- * 当客户端发来消息时触发
- * @param int $client_id 连接id
- * @param mixed $message 具体消息
- */
- public static function onMessage($client_id, $message)
- {
- if ($message == '{"type":"ping"}' || $message == '{"type":"pong"}') {
- //Gateway::sendToCurrentClient('{"type":"pong"}');
- return;
- } else {
- //echo "onMessage: " . $message . "\r\n";
- //print_r([self::$global->kfList, self::$global->userList, self::$global->uidSimpleList, self::$global->userToKf]);
- }
- $message = json_decode($message, true);
- if (isset($message['type'])) {
- switch ($message['type']) {
- // 管理员初始化
- case 'adminInit':
- $token = $message['token'];
- self::adminInit($client_id, $token);
- break;
- // 客服初始化
- case 'init':
- $data = $message['data'];
- self::Kfinit($client_id, $data);
- break;
- // 顾客初始化
- case 'userInit';
- $data = $message['data'];
- self::userInitEnt($client_id, $data);
- break;
- //在线客服信息
- case 'getkfonlines':
- Gateway::sendToCurrentClient(json_encode(self::getkfonlines(), 256));
- break;
- case 'chatMessage':
- $client = Gateway::getClientIdByUid($message['data']['to_id']);
- if (!empty($client)) {
- $chat_message = [
- 'message_type' => 'chatMessage',
- 'data' => [
- 'name' => $message['data']['from_name'],
- 'id' => $message['data']['from_id'],
- 'time' => date('H:i'),
- 'content' => $message['data']['content'],
- ]
- ];
- Gateway::sendToClient($client['0'], json_encode($chat_message));
- unset($chat_message);
- // 聊天信息入库
- $serviceLog = [
- 'from_id' => $message['data']['from_id'],
- 'from_name' => $message['data']['from_name'],
- 'to_id' => $message['data']['to_id'],
- 'to_name' => $message['data']['to_name'],
- 'content' => $message['data']['content'],
- 'servicelog_id' => $message['data']['conversationId'],
- 'time_line' => time()
- ];
- self::$db->insert('ws_chat_log')->cols($serviceLog)->query();
- unset($serviceLog);
- }
- if (isset($message['data']['isFirst']) && $message['data']['isFirst']) {
- $servicelog_id = $message['data']['conversationId'];
- $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
- $corresponding = time() - $serviceLog[0]['start_time'];
- self::$db->query("update `ws_alarm` set `alarm_corresponding` = '$corresponding',alarm_respond=2 where `servicelog_id`= '$servicelog_id'");
- }
- break;
- // 转接
- case 'changeGroup':
- // 通知客户端转接中
- $simpleList = self::$global->uidSimpleList;
- if (!isset($simpleList[$message['uid']])) { // 客户已经退出
- return;
- }
- $userClient = $simpleList[$message['uid']]['0'];
- $userGroup = $simpleList[$message['uid']]['1']; // 会员原来的分组也是客服的分组
- $reLink = [
- 'message_type' => 'relinkMessage'
- ];
- Gateway::sendToClient($userClient, json_encode($reLink, 256));
- unset($reLink);
- // 记录该客服与该会员的服务结束
- $servicelog_id = $message['data']['conversationId'];
- self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `servicelog_id`= '" . $servicelog_id . "'");
- // 修改会话时长
- $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
- $cvtOvertime = time() - $serviceLog[0]['start_time'];
- self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime' where `servicelog_id`= '$servicelog_id'");
- // 从当前客服的服务表中删除这个会员
- $old = $kfList = self::$global->kfList;
- if (!isset($kfList[$userGroup])) {
- $waitMsg = '暂时没有相关客服上班,请稍后再咨询。';
- // 逐一通知
- foreach (self::$global->userList as $vo) {
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => $waitMsg,
- ]
- ];
- Gateway::sendToClient($userClient, json_encode($waitMessage, 256));
- unset($waitMessage);
- }
- return;
- }
- $myList = $kfList[$userGroup]; // 该客服分组数组
- foreach ($myList as $key => $vo) {
- if (in_array($userClient, $vo['user_info'])) {
- // 维护现在的该客服的服务信息
- $kfList[$userGroup][$key]['task'] -= 1; // 当前服务的人数 -1
- foreach ($vo['user_info'] as $k => $v) {
- if ($userClient == $v) {
- unset($kfList[$userGroup][$key]['user_info'][$k]);
- break;
- }
- }
- break;
- }
- }
- while (!self::$global->cas('kfList', $old, $kfList)) {
- }; // 刷新内存中客服的服务列表
- unset($old, $kfList, $myList);
- // 将会员加入队列中
- $userList = self::$global->userList;
- do {
- $NewUserList = $userList;
- $NewUserList[$message['uid']] = [
- 'id' => $message['uid'],
- 'name' => $message['name'],
- 'avatar' => $message['avatar'],
- 'ip' => $message['ip'],
- 'group' => $message['group'], // 指定要链接的分组
- 'client_id' => $userClient
- ];
- } while (!self::$global->cas('userList', $userList, $NewUserList));
- unset($NewUserList, $userList);
- // 执行会员分配通知双方
- self::userOnlineTask($userClient, $message['group']);
- unset($userClient, $userGroup);
- break;
- case 'closeUser':
- $userInfo = self::$global->uidSimpleList;
- if (isset($userInfo[$message['uid']])) {
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => '暂时没有客服上班,请稍后再咨询。',
- ]
- ];
- Gateway::sendToClient($userInfo[$message['uid']]['0'], json_encode($waitMessage, 256));
- unset($waitMessage);
- }
- unset($userInfo);
- break;
- // 机器人问答.
- case 'toRobot':
- self::toRobot($client_id, $message);
- break;
- // 评价.
- case 'evaluate':
- self::evaluate($client_id, $message);
- break;
- // 客服关闭会话.
- case 'kfCloseUser':
- $userId = $message['data']['to_id'];
- $client = Gateway::getClientIdByUid($userId);
- if (!empty($client)) {
- $clientId = $client['0'];
- self::serverClose($clientId, $message['data']['conversationId']);
- }
- break;
- // 客服更改状态.
- case 'kfOnline':
- $kfList = self::$global->kfList;
- $userId = $message['data']['uid'];
- $status = $message['data']['status'];
- foreach ($kfList as $k => $v) {
- foreach ($v as $ke => $va) {
- if ($ke == $userId) {
- $kfList[$k][$ke]['status'] = $status;
- }
- }
- }
- self::$global->kfList = $kfList;
- self::writeLogKfStatus($userId, $status);
- break;
- case 'changeOtherhKeFu';
- self::changeOtherhKeFu($client_id, $message);
- break;
- // 弹出评价.
- case 'getEvaluate';
- $client = Gateway::getClientIdByUid($message['data']['to_id']);
- if (!empty($client)) {
- $chat_message = [
- 'message_type' => 'getEvaluate',
- 'data' => [
- 'content' => '欢迎你的咨询,请对我们的服务做出评价',
- ]
- ];
- Gateway::sendToClient($client['0'], json_encode($chat_message, 256));
- unset($chat_message);
- }
- }
- }
- }
- //获取在线客服列表
- public static function getkfonlines()
- {
- $return = [
- 'message_type' => 'onlinekfs',
- 'data' => [],
- ];
- $nowkfid = $_SESSION['uid'];
- $kfs = self::$global->kfList;
- $groupnamemap = self::$global->groupmap;
- if (!$kfs || empty($nowkfid)) {
- return $return;
- }
- $ret = [];
- foreach ($kfs as $gruop => $users) {
- foreach ($users as $uid=>$uinfo){
- if ($uid != $nowkfid){
- $ret[] = ['groupid'=>$gruop,'groupname'=>$groupnamemap[$gruop],'kfuid'=>$uid,'kfname'=>$uinfo['name'],'kfjobname'=>$uinfo['job_name']];
- }
- }
- }
- $return['data'] = $ret;
- return $return;
- }
- //客户工单内部组转接
- public static function changeOtherhKeFu($client_id, $smessage)
- {
- $message = $smessage['data'];
- $groupid = isset($message['group']) ? intval($message['group']) : 0;
- $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
- $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
- $uid = isset($message['uid']) ? $message['uid'] : 0;
- $word = isset($message['word']) ? $message['word'] : '';
- if (empty($groupid) || empty($toukfid) || empty($fromkfuid) || empty($uid) || empty($word) || ($toukfid == $fromkfuid)) {
- return false;
- }
- if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
- return false;
- }
- $tokfidclientid = Gateway::getClientIdByUid($toukfid);
- $tokfidclientid = $tokfidclientid['0'];
- $uidclientid = Gateway::getClientIdByUid($uid);
- $uidclientid = $uidclientid['0'];
- $kfList = $kfList_new = self::$global->kfList;
- $userToKf = $userToKf_new = self::$global->userToKf;
- if (!isset($kfList[$groupid]) || !isset($kfList[$groupid][$toukfid]) || !isset($kfList[$groupid][$fromkfuid])) {
- return false;
- }
- if ($kfList[$groupid][$toukfid]['status'] != 1) {
- return false;
- }
- foreach ($kfList[$groupid] as $key => $val) {
- if ($key == $fromkfuid) {
- $kfList_new[$groupid][$fromkfuid]['task']--;
- foreach ($kfList[$groupid][$key]['user_info'] as $skey => $sval) {
- if ($sval == $uidclientid) {
- unset($kfList_new[$groupid][$key]['user_info'][$skey]);
- }
- }
- }
- if ($key == $toukfid) {
- $kfList_new[$groupid][$toukfid]['task']++;
- array_push($kfList_new[$groupid][$key]['user_info'], $uidclientid);
- }
- }
- do {
- } while (!self::$global->cas('kfList', $kfList, $kfList_new));
- if (isset($userToKf[$uid])) {
- $userToKf_new[$uid]['1'] = $toukfid;
- }
- do {
- } while (!self::$global->cas('userToKf', $userToKf, $userToKf_new));
- /////////取消原有会话,开启新会话
- $histarttimelimit = time() - 3600 * 24;
- $bindval = ['user_id' => $uid, 'client_id' => $uidclientid, 'kf_id' => intval(trim($fromkfuid, 'KF')), 'histime' => $histarttimelimit];
- $oldlog = self::$db->select('*')->from('ws_service_log')->where('user_id= :user_id and client_id=:client_id and kf_id=:kf_id and status!=2 and start_time>=:histime ')->bindValues($bindval)->row();
- if (!$oldlog) {
- return false;
- }
- self::$db->update('ws_service_log')->cols(['status' => 2, 'end_time' => time()])->where('servicelog_id=' . $oldlog['servicelog_id'])->query();
- unset($oldlog['servicelog_id']);
- // 修改会话时长
- $servicelog_id = $oldlog['servicelog_id'];
- $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
- $cvtOvertime = time() - $serviceLog[0]['start_time'];
- self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime' where `servicelog_id`= '$servicelog_id'");
- $oldlog = array_merge($oldlog, ['kf_id' => intval(trim($toukfid, 'KF')), 'start_time' => time(), 'end_time' => 0, 'status' => 1, 'evaluate_id' => 0]);
- $new_id = self::$db->insert('ws_service_log')->cols($oldlog)->query();
- if (!$new_id) {
- return false;
- }
- ///通知消息发送--------------
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $toukfid,
- 'conversationId' => $new_id,
- 'kf_name' => Gateway::getSession(Gateway::getClientIdByUid($toukfid)['0'])['name'],
- 'serverInfo' => self::$global->kfList[$groupid][$toukfid],
- ]
- ];
- Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
- unset($noticeUser);
- // 通知客服端绑定会员的信息
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $uid,
- 'conversationId' => $new_id,
- ]
- ];
- Gateway::sendToClient($tokfidclientid, json_encode($noticeKf, 256));
- unset($noticeKf);
- //回转接人,转接成功
- Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1], 256]));
- return;
- }
- //客服接入sock,及初始化
- public static function Kfinit($client_id, $message)
- {
- $kfList = self::$global->kfList;
- //客服登陆验证 不符合的直接断掉
- //$logcheck = true; //开发时使用
- $kfinfo = self::KfloginChedk($client_id, $message);
- if (empty($kfinfo)) {
- Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
- Gateway::closeCurrentClient();
- return true;
- } elseif ($kfinfo['status'] != 1) {
- Gateway::sendToClient($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
- Gateway::closeCurrentClient();
- return true;
- }
- if (isset($kfList[$message['group']][$message['uid']])) {
- Gateway::sendToCurrentClient(json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号已经登陆过,请先退出再登陆'], 256));
- Gateway::closeCurrentClient();
- return;
- }
- // 如果该客服未在内存中记录则记录
- if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
- do {
- $newKfList = $kfList;
- $newKfList[$message['group']][$message['uid']] = [
- 'id' => 'KF' . $kfinfo['id'],
- 'name' => $kfinfo['user_name'],
- 'job_name' => $kfinfo['user_job_number'],
- 'avatar' => $kfinfo['user_avatar'],
- 'client_id' => $client_id,
- 'task' => 0,
- 'signature' => $kfinfo['signature'],
- 'status' => 2,// 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
- 'user_info' => []
- ];
- } while (!self::$global->cas('kfList', $kfList, $newKfList));
- unset($newKfList, $kfList);
- } else if (isset($kfList[$message['group']][$message['uid']])) {
- do {
- $newKfList = $kfList;
- $newKfList[$message['group']][$message['uid']]['client_id'] = $client_id;
- } while (!self::$global->cas('kfList', $kfList, $newKfList));
- unset($newKfList, $kfList);
- }
- // 绑定 client_id 和 uid
- Gateway::bindUid($client_id, $message['uid']);
- $_SESSION['group'] = $message['group'];
- $_SESSION['iskefu'] = 1;
- $_SESSION['uid'] = $message['uid'];
- $_SESSION['name'] = $message['name'];
- Gateway::joinGroup($client_id, 'group_' . $message['group']);
- $chat_message = [
- 'message_type' => 'loginSuccess',
- ];
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- unset($chat_message);
- self::writeLogKfStatus($message['uid'], 2);
- // TODO 尝试拉取用户来服务 [二期规划]
- }
- /**
- * 管理员
- * @param $client_id 服务ID
- * @param $message 数据
- */
- public static function adminInit($client_id, $token)
- {
- // 查询token是否存在.
- $systemConfigData = self::$db->query("SELECT `id` FROM `ws_admins` where `token`= '$token'");
- //print_r(self::$global->adminList);
- if ($systemConfigData) {
- $adminList = self::$global->adminList;
- $adminList[] = $client_id;
- self::$global->adminList = $adminList;
- self::systemMonitoring([$client_id]);
- } else {
- Gateway::closeClient($client_id);
- }
- }
- //客服登陆验证
- public static function KfloginChedk($client, $messageArray)
- {
- $uid = isset($messageArray['uid']) ? $messageArray['uid'] : '';
- $token = isset($messageArray['token']) ? $messageArray['token'] : '';
- if (empty($uid) || empty($token)) {
- return false;
- }
- $expire_time_vali = time() - 60 * 60 * 24 * 3;
- $kfid = intval(substr($uid, 2));
- $ret = self::$db->select('*')->from('ws_users')->where('id= :id and token=:token and expire_time>=:expire_time')->bindValues(array('id' => $kfid, 'token' => $token, 'expire_time' => $expire_time_vali))->row();
- if ($ret) {
- self::$db->update('ws_users')->cols(array('online_status' => 1, 'online_connectid' => $client))->where('id=' . $kfid)->query();
- return $ret;
- }
- return false;
- }
- //用户发送邦定用户事件
- public static function userInitEnt($client_id, $message)
- {
- $userList = self::$global->userList;
- // 如果该顾客未在内存中记录则记录
- $uidSimpleList = self::$global->uidSimpleList;
- if (isset($uidSimpleList[$message['uid']])) {
- $uidSimpleList = self::$global->uidSimpleList;
- $oldclientid = $uidSimpleList[$message['uid']]['0'];
- Gateway::sendToClient($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
- Gateway::closeClient($oldclientid);
- sleep(2);
- }
- $group = $message['group'];
- $onlinekf = self::$global->kfList;
- if (!isset($onlinekf[$group]) || count($onlinekf[$group]) <= 0) {
- Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
- sleep(2);
- Gateway::closeClient($client_id);
- return;
- }
- if (!array_key_exists($message['uid'], $userList)) {
- do {
- $NewUserList = $userList;
- $NewUserList[$message['uid']] = [
- 'id' => $message['uid'],
- 'name' => $message['name'],
- 'avatar' => $message['avatar'],
- 'website' => $_SESSION['origin'],//$_SERVER['HTTP_ORIGIN'],
- 'browse' => Gateway::browse_info(),
- 'system' => Gateway::get_os(),
- 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
- 'group' => $message['group'],
- 'intime' => time(),
- 'client_id' => $client_id
- ];
- } while (!self::$global->cas('userList', $userList, $NewUserList));
- unset($NewUserList, $userList);
- // 维护 UID对应的client_id 数组
- do {
- $old = $newList = self::$global->uidSimpleList;
- $newList[$message['uid']] = [
- $client_id,
- $message['group']
- ];
- } while (!self::$global->cas('uidSimpleList', $old, $newList));
- unset($old, $newList);
- // 写入接入值
- $key = date('Ymd') . 'total_in';
- self::$global->$key = 0;
- do {
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- } while (!self::$global->increment($key));
- unset($key);
- }
- // 绑定 client_id 和 uid
- Gateway::bindUid($client_id, $message['uid']);
- $_SESSION['iskefu'] = 0;
- $_SESSION['uid'] = $message['uid'];
- // 尝试分配新会员进入服务
- self::userOnlineTask($client_id, $message['group'], $message['uid']);
- }
- /**
- * 当用户断开连接时触发
- * @param int $client_id 连接id
- *
- * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
- * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
- */
- public static function onClose($client_id)
- {
- $isKefuoff = isset($_SESSION['iskefu']) ? $_SESSION['iskefu'] : 0;
- $uid = isset($_SESSION['uid']) ? $_SESSION['uid'] : false;
- //echo "下线:$uid - $client_id - $isKefuoff \n";
- $adminList = self::$global->adminList ?? [];
- $key = array_search($client_id ,$adminList);
- if (strlen($key)) {
- array_splice($adminList,$key,1);
- self::$global->adminList = $adminList;
- }
- if (empty($uid)) {
- return;
- }
- if ($isKefuoff) {
- self::serviceOffline($client_id, $uid);
- } else {
- self::guestOffline($client_id, $uid);
- }
- return;
- }
- //客服下线了
- public static function serviceOffline($client_id, $uid)
- {
- $group = $_SESSION['group'];
- $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
- $user_info = $kefuinfo_old_new[$group][$uid]['user_info'];
- $simpliUsers = self::$global->uidSimpleList;
- $simpliUsersID_UID_Arr = [];
- if (!empty($simpliUsers)) {
- foreach ($simpliUsers as $key => $val) {
- $simpliUsersID_UID_Arr[$val['0']] = $key;
- }
- }
- $now = time();
- if (!empty($user_info)) {
- foreach ($user_info as $val) {
- Gateway::sendToClient($val, json_encode(['type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
- if (isset($simpliUsersID_UID_Arr[$val])) {
- self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2 ");
- // 修改会话时长
- $serviceLog = self::$db->query("select `start_time`,`servicelog_id` from `ws_service_log` where `user_id`= '$simpliUsersID_UID_Arr[$val]' and kf_id='$uid' and group_id=$group and `status`!=2");
- $servicelog_id = $serviceLog[0]['servicelog_id'];
- $cvtOvertime = time() - $serviceLog[0]['start_time'];
- self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime' where `servicelog_id`= '$servicelog_id'");
- }
- Gateway::closeClient($val);
- }
- }
- unset($kefuinfo_old_new[$group][$uid]);
- $kfid = intval(substr($uid, 2));
- self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
- do {
- } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
- self::writeLogKfStatus($uid, 0);
- return;
- }
- //用户下线了
- public static function guestOffline($client_id, $uid)
- {
- $kfuid = -1;
- $krclient_id = 0;
- $kfgroup = -1;
- $userToKf = $userToKfNew = self::$global->userToKf;
- if (isset($userToKfNew[$uid])) {
- $kfuid = isset($userToKfNew[$uid]['1']) ? $userToKfNew[$uid]['1'] : -1;
- $krclient_id = isset(Gateway::getClientIdByUid($kfuid)['0']) ? Gateway::getClientIdByUid($kfuid)['0'] : 0;
- unset($userToKfNew[$uid]);
- do {
- } while (!self::$global->cas('userToKf', $userToKf, $userToKfNew));
- }
- $uidSimpleList = $uidSimpleListNew = self::$global->uidSimpleList;
- if (isset($uidSimpleListNew[$uid])) {
- $kfgroup = $uidSimpleListNew[$uid]['1'];
- unset($uidSimpleListNew[$uid]);
- do {
- } while (!self::$global->cas('uidSimpleList', $uidSimpleList, $uidSimpleListNew));
- }
- $userList = $userListNew = self::$global->userList;
- $group_wait_count = 0;
- if (!empty($userList)) {
- $ischange = 0;
- foreach ($userList as $key => $val) {
- if ($val['group'] == $kfuid) {
- $group_wait_count++;
- }
- if ($val['id'] == $uid) {
- unset($userListNew[$key]);
- $ischange = 1;
- $group_wait_count--;
- break;
- }
- }
- if ($ischange) {
- do {
- } while (!self::$global->cas('userList', $userList, $userListNew));
- Gateway::sendToGroup('group_' . $kfgroup, json_encode(['message_type' => 'kfqueuelength', 'leng' => $group_wait_count], 256));
- }
- }
- if ($kfuid != -1 && $kfgroup != -1) {
- $kefuinfo_old = $kefuinfo_old_new = self::$global->kfList;
- $ischange_kf_list = 0;
- if (isset($kefuinfo_old[$kfgroup][$kfuid])) {
- $infos = $kefuinfo_old[$kfgroup][$kfuid]['user_info'];
- if ($infos) {
- if (is_array($infos)) {
- foreach ($infos as $key => $val) {
- if ($val == $client_id) {
- $ischange_kf_list = 1;
- unset($kefuinfo_old_new[$kfgroup][$kfuid]['user_info'][$key]);
- $kefuinfo_old_new[$kfgroup][$kfuid]['task'] = $kefuinfo_old_new[$kfgroup][$kfuid]['task'] - 1;
- }
- }
- }
- if ($ischange_kf_list) {
- do {
- } while (!self::$global->cas('kfList', $kefuinfo_old, $kefuinfo_old_new));
- $chat_message = [
- 'message_type' => 'userClose',
- 'data' => [
- 'content' => '用户连接已断开',
- 'id' => $uid,
- 'time' => date('H:i'),
- ]
- ];
- $now = time();
- $kf__uid = substr($kfuid, 2);
- $sql = "update `ws_service_log` set `status` = '3',end_time=$now where `user_id`= '$uid' and kf_id='$kf__uid' and group_id=$kfgroup and status=1 ";
- //echo "客户退出:". $sql ."\n";
- self::$db->query($sql);
- Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
- }
- }
- }
- }
- }
- /**
- * 客服结束会话
- * @param int $client_id 连接id
- *
- * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
- * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
- */
- public static function serverClose($client_id, $servicelog_id)
- {
- // 返回.
- $chat_message = [
- 'message_type' => 'closeBysever',
- 'data' => [
- 'content' => '客服停止了该会话',
- 'time' => date('H:i'),
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- Gateway::closeClient($client_id);
- $now = time();
- $sql = "update `ws_service_log` set `status`='2',end_time=$now where `servicelog_id`= '$servicelog_id'";
- //echo "客户退出:". $sql ."\n";
- self::$db->query($sql);
- $isServiceUserOut = false;
- // 修改会话时长
- $serviceLog = self::$db->query("select `start_time` from `ws_service_log` where `servicelog_id`= '$servicelog_id'");
- $cvtOvertime = time() - $serviceLog[0]['start_time'];
- self::$db->query("update `ws_alarm` set `alarm_cvtOvertime` = '$cvtOvertime' where `servicelog_id`= '$servicelog_id'");
- // 将会员服务信息,从客服的服务列表中移除
- $old = $kfList = self::$global->kfList;
- foreach ($kfList as $k => $v) {
- foreach ($v as $key => $vo) {
- if (in_array($client_id, $vo['user_info'])) {
- $isServiceUserOut = true;
- // 根据client id 去更新会话工单一些信息
- self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $client_id . "'");
- // 从会员的内存表中检索出该会员的信息,并更新内存
- $oldSimple = $simpleList = self::$global->uidSimpleList;
- $outUser = [];
- foreach ($simpleList as $u => $c) {
- if ($c['0'] == $client_id) {
- $outUser[] = [
- 'user_id' => $u,
- 'group_id' => $c['1']
- ];
- unset($simpleList[$u]);
- break;
- }
- }
- while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
- };
- unset($oldSimple, $simpleList);
- $outUser = self::$db->query("select `user_id`,`group_id` from `ws_service_log` where `client_id`= '" . $client_id . "'");
- // 通知 客服删除退出的用户
- if (!empty($outUser)) {
- $del_message = [
- 'message_type' => 'delUser',
- 'data' => [
- 'id' => $outUser['0']['user_id']
- ]
- ];
- Gateway::sendToClient($vo['client_id'], json_encode($del_message, 256));
- unset($del_message);
- // 尝试分配新会员进入服务
- self::userOfflineTask($outUser['0']['group_id']);
- }
- unset($outUser);
- // 维护现在的该客服的服务信息
- $kfList[$k][$key]['task'] -= 1; // 当前服务的人数 -1
- foreach ($vo['user_info'] as $m => $l) {
- if ($client_id == $l) {
- unset($kfList[$k][$key]['user_info'][$m]);
- break;
- }
- }
- // 刷新内存中客服的服务列表
- while (!self::$global->cas('kfList', $old, $kfList)) {
- };
- unset($old, $kfList);
- break;
- }
- }
- if ($isServiceUserOut) break;
- }
- // 尝试从排队的用户中删除退出的客户端
- if (false == $isServiceUserOut) {
- $old = $userList = self::$global->userList;
- foreach (self::$global->userList as $key => $vo) {
- if ($client_id == $vo['client_id']) {
- $isServiceUserOut = true;
- unset($userList[$key]);
- break;
- }
- }
- while (!self::$global->cas('userList', $old, $userList)) {
- };
- // 从会员的内存表中检索出该会员的信息,并更新内存
- $oldSimple = $simpleList = self::$global->uidSimpleList;
- foreach ($simpleList as $u => $c) {
- if ($c['0'] == $client_id) {
- unset($simpleList[$u]);
- break;
- }
- }
- while (!self::$global->cas('uidSimpleList', $oldSimple, $simpleList)) {
- };
- unset($oldSimple, $simpleList);
- }
- // 尝试是否是客服退出
- if (false == $isServiceUserOut) {
- $old = $kfList = self::$global->kfList;
- foreach (self::$global->kfList as $k => $v) {
- foreach ($v as $key => $vo) {
- // 客服服务列表中无数据,才去删除客服内存信息
- if ($client_id == $vo['client_id'] && (0 == count($vo['user_info']))) {
- unset($kfList[$k][$key]);
- break;
- }
- }
- }
- while (!self::$global->cas('kfList', $old, $kfList)) {
- };
- }
- }
- /**
- * 有人退出
- * @param $group
- */
- private static function userOfflineTask($group)
- {
- // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
- $maxNumber = self::getMaxServiceNum();
- $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber);
- unset($maxNumber);
- if (1 == $res['code']) {
- while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
- }; // 更新客服数据
- while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
- }; // 更新会员数据
- // 服务信息入库
- $serviceLog = [
- 'user_id' => $res['data']['3']['id'],
- 'client_id' => $res['data']['3']['client_id'],
- 'user_name' => $res['data']['3']['name'],
- 'user_ip' => $res['data']['3']['ip'],
- 'user_avatar' => $res['data']['3']['avatar'],
- 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
- 'start_time' => time(),
- 'group_id' => $group,
- 'website' => $res['data']['3']['website'],
- 'system' => $res['data']['3']['system'],
- 'browse' => $res['data']['3']['browse'],
- 'status' => 1,
- 'intime' => $res['data']['3']['intime'],
- 'end_time' => 0
- ];
- $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
- if (!$hisSession) {
- $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
- } else {
- self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
- $conversationId = $hisSession['servicelog_id'];
- }
- unset($serviceLog);
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $res['data']['0'],
- 'kf_name' => $res['data']['1'],
- 'conversationId' => $conversationId,
- 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
- ]
- ];
- Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
- unset($noticeUser);
- // 通知客服端绑定会员的信息
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $res['data']['3'],
- 'conversationId' => $conversationId,
- ]
- ];
- Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
- unset($noticeKf);
- // 逐一通知
- $number = 1;
- foreach (self::$global->userList as $vo) {
- $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => $waitMsg,
- ]
- ];
- Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
- $number++;
- }
- unset($waitMessage, $number);
- // 写入接入值
- $key = date('Ymd') . 'success_in';
- self::$global->$key = 0;
- do {
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- } while (!self::$global->increment($key));
- unset($key);
- } else {
- switch ($res['code']) {
- case -1:
- $waitMsg = '暂时没有客服上班,请稍后再咨询。';
- // 逐一通知
- foreach (self::$global->userList as $vo) {
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => $waitMsg,
- ]
- ];
- Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
- }
- break;
- case -2:
- break;
- case -3:
- break;
- case -4:
- // 逐一通知
- $number = 1;
- foreach (self::$global->userList as $vo) {
- $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => $waitMsg,
- ]
- ];
- Gateway::sendToClient($vo['client_id'], json_encode($waitMessage, 256));
- $number++;
- }
- break;
- }
- unset($waitMessage, $number);
- }
- }
- /**
- * 有人进入执行分配
- * @param $client_id
- * @param $group
- * @param $uid
- */
- private static function userOnlineTask($client_id, $group, $uid = 0)
- {
- // TODO 此处查询最大的可服务人数,后面可以用其他的方式,存储这个数值,让其更高效的访问
- $maxNumber = self::getMaxServiceNum();
- $res = self::assignmentTask(self::$global->kfList, self::$global->userList, $group, $maxNumber, $uid);
- unset($maxNumber);
- if (1 == $res['code']) {
- while (!self::$global->cas('kfList', self::$global->kfList, $res['data']['4'])) {
- }; // 更新客服数据
- while (!self::$global->cas('userList', self::$global->userList, $res['data']['5'])) {
- }; // 更新会员数据
- $userToKf = self::$global->userToKf;
- $userToKf[$res['data']['3']['id']] = [
- $res['data']['3']['id'],
- $res['data']['0']
- ];
- self::$global->userToKf = $userToKf;
- // 服务信息入库
- $serviceLog = [
- 'user_id' => $res['data']['3']['id'],
- 'client_id' => $res['data']['3']['client_id'],
- 'user_name' => $res['data']['3']['name'],
- 'user_ip' => $res['data']['3']['ip'],
- 'user_avatar' => $res['data']['3']['avatar'],
- 'kf_id' => intval(ltrim($res['data']['0'], 'KF')),
- 'start_time' => time(),
- 'group_id' => $group,
- 'website' => $res['data']['3']['website'],
- 'system' => $res['data']['3']['system'],
- 'browse' => $res['data']['3']['browse'],
- 'status' => 1,
- 'intime' => $res['data']['3']['intime'],
- 'end_time' => 0
- ];
- $hisSession = self::$db->select('*')->from('ws_service_log')->where('user_id=:user_id and kf_id=:kf_id and group_id=:group_id and status in (1,3)')->bindValues(array('user_id' => $res['data']['3']['id'], 'kf_id' => intval(ltrim($res['data']['0'], 'KF')), 'group_id' => $group))->row();
- if (!$hisSession) {
- $conversationId = self::$db->insert('ws_service_log')->cols($serviceLog)->query();
- $alarmData = [
- 'servicelog_id' => $conversationId,
- ];
- self::$db->insert('ws_alarm')->cols($alarmData)->query();
- } else {
- self::$db->update('ws_service_log')->cols(['status' => 1])->where('servicelog_id=' . $hisSession['servicelog_id'])->query();
- $conversationId = $hisSession['servicelog_id'];
- }
- unset($serviceLog);
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $res['data']['0'],
- 'conversationId' => $conversationId,
- 'serverInfo' => self::$global->kfList[$group][$res['data']['0']],
- 'kf_name' => $res['data']['1']
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($noticeUser, 256));
- unset($noticeUser);
- // 发送客服欢迎语
- $sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
- if (!empty($sayHello) && 1 == $sayHello['0']['status']) {
- $chat_message = [
- 'message_type' => 'chatMessage',
- 'data' => [
- 'name' => $res['data']['1'],
- //'avatar' => self::$global->kfList[$group][$res['data']['0']],
- 'id' => $res['data']['0'],
- 'time' => date('H:i'),
- 'content' => $sayHello['0']['word']
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- unset($chat_message);
- }
- unset($sayHello);
- // 通知客服端绑定会员的信息
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $res['data']['3'],
- 'conversationId' => $conversationId,
- ]
- ];
- Gateway::sendToClient($res['data']['2'], json_encode($noticeKf, 256));
- unset($noticeKf);
- // 写入接入值
- $key = date('Ymd') . 'success_in';
- self::$global->$key = 0;
- do {
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- } while (!self::$global->increment($key));
- unset($key);
- } else {
- $waitMsg = '';
- switch ($res['code']) {
- case -1:
- $waitMsg = '暂时没有客服上班,请稍后再咨询。';
- break;
- case -2:
- break;
- case -3:
- break;
- case -4:
- $number = count(self::$global->userList);
- $waitMsg = '您前面还有 ' . $number . ' 位会员在等待。';
- break;
- }
- $waitMessage = [
- 'message_type' => 'wait',
- 'data' => [
- 'content' => $waitMsg,
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($waitMessage, 256));
- unset($waitMessage);
- }
- $userlist = self::$global->userList;
- $waitcount = 0;
- if ($userlist) {
- foreach ($userlist as $val) {
- if ($val['group'] == $group) {
- $waitcount++;
- }
- }
- Gateway::sendToGroup('group_' . $group, json_encode(['message_type' => 'kfqueuelength', 'leng' => $waitcount], 256));
- }
- }
- /**
- * 给客服分配会员【均分策略】
- * @param $kfList
- * @param $userList
- * @param $group
- * @param $total
- */
- private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
- {
- // 注:修改为已上线(status为1上线status为2不接受分配)
- $onlineKF = [];
- foreach ($kfList as $k => $v) {
- foreach ($v as $ke => $va) {
- if ($va['status'] == 1) {
- $onlineKF[$k][$ke] = $va;
- }
- }
- }
- // 没有客服上线
- if (empty($onlineKF) || empty($onlineKF[$group])) {
- return ['code' => -1];
- }
- // 没有待分配的会员
- if (empty($userList)) {
- return ['code' => -2];
- }
- // 未设置每个客服可以服务多少人
- if (0 == $total) {
- return ['code' => -3];
- }
- // 查看该组的客服是否在线
- if (!isset($onlineKF[$group])) {
- return ['code' => -1];
- }
- //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --1
- $odltalksession = false;
- $user = $user_first = array_shift($userList);
- if ($uid > 0 && $user['id'] != $uid && count($userList) > 1) {
- $timevalielimit = time() - 60 * 5;
- $odltalksession = self::$db->select('*')->from('ws_service_log')->where('user_id=:uid and `group`=:group and `status`=3 and end_time>=:timevalielimit"')->bindValues(array('uid' => $uid, 'group' => $group, 'timevalielimit' => $timevalielimit))->row();
- if ($odltalksession) {
- foreach ($userList as $ttkey => $ttval) {
- if ($ttval['id'] == $uid) {
- array_unshift($userList, $user);
- $user = $userList[$ttkey];
- unset($userList[$ttkey]);
- break;
- }
- }
- }
- }
- //上次用户掉线后,还可以继续上一次 (如果没有关闭) 的会话 --2
- if ($odltalksession) {
- $oldkrid = 'KF' . $odltalksession['kf_id'];
- if (isset($onlineKF[$group][$oldkrid])) {
- $kf = $onlineKF[$group][$oldkrid];
- $min = $kf['task'];
- $flag = $kf['id'];
- unset($onlineKF[$group][$oldkrid]);
- } else {
- goto NOSIGNKF;
- }
- } else {
- NOSIGNKF:
- $kf = $onlineKF[$group];
- $kf = array_shift($kf);
- $min = $kf['task'];
- $flag = $kf['id'];
- foreach ($onlineKF[$group] as $key => $vo) {
- if ($vo['task'] < $min) {
- $min = $vo['task'];
- $flag = $key;
- }
- }
- unset($kf);
- }
- // 需要排队了
- if ($onlineKF[$group][$flag]['task'] == $total) {
- array_unshift($userList, $user);
- return ['code' => -4];
- }
- $kfList[$group][$flag]['task'] += 1;
- array_push($kfList[$group][$flag]['user_info'], $user['client_id']); // 被分配的用户信息
- return [
- 'code' => 1,
- 'data' => [
- $onlineKF[$group][$flag]['id'],
- $onlineKF[$group][$flag]['name'],
- $onlineKF[$group][$flag]['client_id'],
- $user,
- $kfList,
- $userList
- ]
- ];
- }
- /**
- * 获取最大的服务人数
- * @return int
- */
- private static function getMaxServiceNum()
- {
- $maxNumber = self::$db->query('select `max_service` from `ws_kf_config` where `id` = 1');
- if (!empty($maxNumber)) {
- $maxNumber = 5;
- } else {
- $maxNumber = $maxNumber['0']['max_service'];
- }
- return $maxNumber;
- }
- /**
- * 将内存中的数据写入统计表
- * @param int $flag
- */
- private static function writeLog($flag = 1)
- {
- // 上午 8点 到 22 点开始统计
- if (date('H') < 8 || date('H') > 22) {
- return;
- }
- // 当前正在接入的人 和 在线客服数
- $kfList = self::$global->kfList;
- $nowTalking = 0;
- $onlineKf = 0;
- if (!empty($kfList)) {
- foreach ($kfList as $key => $vo) {
- $onlineKf += count($vo);
- foreach ($vo as $k => $v) {
- $nowTalking += count($v['user_info']);
- }
- }
- }
- // 在队列中的用户
- $inQueue = count(self::$global->userList);
- $key = date('Ymd') . 'total_in';
- $key2 = date('Ymd') . 'success_in';
- $param = [
- 'is_talking' => $nowTalking,
- 'in_queue' => $inQueue,
- 'online_kf' => $onlineKf,
- 'success_in' => self::$global->$key2,
- 'total_in' => self::$global->$key,
- 'now_date' => date('Y-m-d')
- ];
- self::$db->update('ws_now_data')->cols($param)->where('id=1')->query();
- if (2 == $flag) {
- $param = [
- 'is_talking' => $nowTalking,
- 'in_queue' => $inQueue,
- 'online_kf' => $onlineKf,
- 'success_in' => self::$global->$key2,
- 'total_in' => self::$global->$key,
- 'add_date' => date('Y-m-d'),
- 'add_hour' => date('H'),
- 'add_minute' => date('i'),
- ];
- self::$db->insert('ws_service_data')->cols($param)->query();
- }
- unset($kfList, $nowTalking, $inQueue, $onlineKf, $key, $key2, $param);
- }
- /**
- * 机器人问答
- * @param $client_id 服务ID
- * @param $message 数据
- */
- private static function toRobot($client_id, $message)
- {
- $groups_id = $message['data']['groups_id'];
- $robot_name = $message['data']['robot_name'];
- $robotgroups_id = $message['data']['robotgroups_id'];
- // 查询问题.
- $getRobot = self::$db->query("select `robot_content` from `ws_robot` where `robot_status`= 1 and `groups_id`= '" . $groups_id . "' and `robot_name`= '" . $robot_name . "' and `robotgroups_id`= '" . $robotgroups_id . "'");
- $chat_message = [
- 'message_type' => 'robotMessage',
- //'message_type' => 'chatMessage',
- 'data' => [
- 'name' => '智能助手',
- 'time' => date('H:i'),
- 'content' => $getRobot ? $getRobot[0]['robot_content'] : 'error',
- ]
- ];
- sleep(1);
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- }
- /**
- * 评价
- * @param $client_id 服务ID
- * @param $message 数据
- */
- private static function evaluate($client_id, $message)
- {
- // 修改数据库.
- $evaluate_id = $message['data']['evaluate_id'];
- $result = self::$db->query("UPDATE `ws_service_log` SET `evaluate_id` = '" . $evaluate_id . "' WHERE `client_id`='" . $client_id . "'");
- if ($result) {
- $chat_message = [
- 'message_type' => 'evaluate',
- 'data' => [
- 'status' => 1,
- 'time' => date('H:i'),
- ]
- ];
- } else {
- $chat_message = [
- 'message_type' => 'evaluate',
- 'data' => [
- 'status' => 2,
- 'time' => date('H:i'),
- ]
- ];
- }
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- }
- //获取系统配置
- private static function upsystemconfig()
- {
- $systemConfigData = self::$db->query("SELECT * FROM `ws_systemconfig`");
- $arr = [];
- if ($systemConfigData) {
- foreach ($systemConfigData as $item) {
- $arr[$item['systemconfig_enName']] = $item;
- }
- self::$global->systemconfig = $arr;
- }
- $group = self::$db->query("SELECT * FROM `ws_groups`");
- $arr = [];
- if ($group){
- foreach ($group as $val){
- $arr[$val['id']] = $val['name'];
- }
- self::$global->groupmap = $arr;
- }
- }
- /**
- * 超时
- * @param $client_id 服务ID
- * @param $message 数据
- */
- private static function overTime()
- {
- // 查询对话时效设置.
- $systemConfigData = self::$db->query("SELECT `systemconfig_data`,`systemconfig_enName`,`systemconfig_content` FROM `ws_systemconfig`");
- foreach ($systemConfigData as $k => $v) {
- if ($v['systemconfig_enName'] == 'overtime') {
- self::$global->overtime = $v;
- } elseif ($v['systemconfig_enName'] == 'unoperated') {
- self::$global->unoperated = $v;
- } elseif ($v['systemconfig_enName'] == 'noResponse') {
- self::$global->noResponse = $v;
- }
- }
- // 查询未断开的工单.
- $serviceLog = self::$db->query("SELECT `servicelog_id`,`client_id`,`start_time` FROM `ws_service_log` WHERE `status`='1' OR `status`='3'");
- $whereOr = '1=0';
- foreach ($serviceLog as $k => $v) {
- if ($k == 0) {
- $whereOr = "`servicelog_id`=" . $v['servicelog_id'];
- } else {
- $whereOr .= " OR `servicelog_id`=" . $v['servicelog_id'];
- }
- }
- // 查询最后一次会话.
- //$chatLog = self::$db->query("SELECT `servicelog_id`,MAX(`time_line`) FROM `ws_chat_log` WHERE ".$whereOr." group by `servicelog_id`");
- $chatLog = self::$db->query("
- select * from ws_chat_log as a where time_line=(
- select max(b.time_line) from ws_chat_log as b where a.servicelog_id = b.servicelog_id and (" . $whereOr . ") group by servicelog_id
- )
- ");
- $setOvertime = strtotime('-' . (self::$global->overtime['systemconfig_data'] - 60) . ' second');
- $overtime = strtotime('-' . (self::$global->overtime['systemconfig_data']) . ' second');
- $setUnoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data'] - 60) . ' second');
- $unoperated = strtotime('-' . (self::$global->unoperated['systemconfig_data']) . ' second');
- $noResponse = strtotime('-' . (self::$global->noResponse['systemconfig_data']) . ' second');
- foreach ($serviceLog as $k => $v) {//注意该循环时间
- if (!strlen(array_search($v['servicelog_id'], array_column($chatLog, 'servicelog_id')))) {
- // 如果小于设定时间则关闭会话.
- if ($v['start_time'] <= $unoperated) {
- self::serverClose($v['client_id'], $v['servicelog_id']);
- // 如果小于设定时间前一分钟则给出提示.
- } elseif ($v['start_time'] <= $setUnoperated) {
- $chat_message = [
- 'message_type' => 'overtime',
- 'data' => [
- 'content' => self::$global->unoperated['systemconfig_content'],
- ]
- ];
- Gateway::sendToClient($v['client_id'], json_encode($chat_message, 256));
- }
- }
- }
- // 循环检测会话时效.
- foreach ($chatLog as $k => $v) {
- $toWho = substr($v['to_id'], 0, 2);
- // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
- if ($v['time_line'] <= $overtime) {
- $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
- self::serverClose($serviceLog[$found_key]['client_id'], $v['servicelog_id']);
- // 如果对话为客服的最后一次对话且时间小于设定时间前一分钟则给出提示.
- } elseif ($v['time_line'] <= $setOvertime) {
- $chat_message = [
- 'message_type' => 'overtime',
- 'data' => [
- 'content' => self::$global->overtime['systemconfig_content'],
- ]
- ];
- $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
- Gateway::sendToClient($serviceLog[$found_key]['client_id'], json_encode($chat_message, 256));
- }
- }
- }
- /**
- * 系统监控
- * @param $message 数据
- */
- private static function systemMonitoring($adminList)
- {
- // 查询未结束工单.
- $serviceLog = self::$db->query("select ws_service_log.servicelog_id,ws_users.user_name as server_name,ws_service_log.user_name,kf_id,start_time,end_time,ws_service_log.group_id,evaluate_id,intime,ws_service_log.status,alarm_userSensitive,alarm_serverSensitive,alarm_corresponding
- from `ws_service_log`
- join `ws_alarm` on ws_service_log.servicelog_id=ws_alarm.servicelog_id
- join `ws_users` on ws_service_log.kf_id=ws_users.id
- WHERE ws_service_log.status='1' OR ws_service_log.status='3'");
- // 查询系统设置表.
- $systemconfig = self::$db->query("SELECT `systemconfig_data` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
- $found_key = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
- // 质检会话响应时长.
- $verifyReturnTime = $systemconfig[$found_key]['systemconfig_data'];
- $found_key = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
- // 质检会话时长.
- $verifyAllTime = $systemconfig[$found_key]['systemconfig_data'];
- // 差评次数.
- $evaluateCount = 0;
- // 未结束工单id.
- $servicelog_ids = '';
- $overtimeNumber = 0; // 会话超时次数.
- $overtimeTime = []; // 会话超时时间.
- $userSensitive = 0; // 用户敏感词报警次数.
- $serverSensitive = 0; // 客服敏感词报警次数.
- $csdNumber = 0; // 响应超时次数.
- $csdTime = []; // 响应超时时间.
- foreach ($serviceLog as $k => $v) {
- // 工单报警总次数.
- $allCount = 0;
- // 差评次数.
- if ($v['evaluate_id'] == 3) {
- $evaluateCount++;
- $allCount++;
- }
- $duration = time() - $v['start_time'];
- // 会话超时.
- if ($duration > $verifyAllTime) {
- $overtimeNumber++;
- $allCount++;
- $overtimeTime[] = $duration;
- }
- // 敏感词报警.
- $userSensitive += $v['alarm_userSensitive'];
- $allCount += $v['alarm_userSensitive'];
- $serverSensitive += $v['alarm_serverSensitive'];
- $allCount += $v['alarm_serverSensitive'];
- // 响应超时.
- if ($v['alarm_corresponding'] > $verifyReturnTime) {
- $csdTime[] = $v['alarm_corresponding'];
- $csdNumber++;
- $allCount++;
- }
- $serviceLog[$k]['allCount'] = $allCount;
- }
- // 查询对话时效设置.
- foreach ($adminList as $v) {
- $chat_message = [
- 'message_type' => 'monitor',
- 'data' => [
- 'cvtList' => $serviceLog,
- 'userSensitive' => $userSensitive,
- 'serverSensitive' => $serverSensitive,
- 'csdNumber' => $csdNumber,
- 'csdTime' => $csdTime,
- 'overtimeNumber' => $overtimeNumber,
- 'overtimeTime' => $overtimeTime,
- 'evaluateCount' => $evaluateCount,
- ]
- ];
- Gateway::sendToClient($v, json_encode($chat_message, 256));
- }
- }
- //客服在线状态写组
- private static function writeLogKfStatus($kf, $status, $flag = 1)
- {
- if ($flag == 1) {
- $status = intval($status);
- if ($status == 0) {
- self::$db->delete('ws_kfonline')->where("uid='$kf'")->query();
- } else {
- $now = date('Y-m-d H:i;s');
- $sql = "insert into ws_kfonline(uid,status,uptime) values('$kf',$status,'$now') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
- self::$db->query($sql);
- }
- } else {
- self::$db->query("delete from ws_kfonline ");
- }
- }
- //用户下线通知
- private static function userCloseNotice($client_id, $cuid, $group)
- {
- }
- //踢掉同一用户的旧用户
- private static function tickOlduser($uid)
- {
- }
- }
|