| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360 |
- <?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) {
- // 1分钟统计一次实时数据
- Timer::add(60 * 1, function () {
- self::writeLog(1);
- });
- // 40分钟写一次当前日期点数的log数据
- Timer::add(60 * 40, function () {
- self::writeLog(2);
- });
- }
- // 检查对话时效给出.
- Timer::add(3, function () {
- // 查询对话时效设置.
- $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' => htmlspecialchars(self::$global->unoperated['systemconfig_content']),
- ]
- ];
- Gateway::sendToClient($v['client_id'], json_encode($chat_message));
- }
- }
- }
- // 循环检测会话时效.
- foreach ($chatLog as $k => $v) {
- $toWho = substr($v['to_id'],0,2);
- // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
- if ($toWho != 'KF' && $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 ($toWho != 'KF' && $v['time_line'] <= $setOvertime) {
- $chat_message = [
- 'message_type' => 'overtime',
- 'data' => [
- 'content' => htmlspecialchars(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));
- }
- }
- });
- }
- /**
- * 当客户端连接时触发
- * 如果业务不需此回调可以删除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' => htmlspecialchars($sayHello['0']['word'])
- ]
- ];
- Gateway::sendToClient($client_id, json_encode($hello, 256));
- unset($hello);
- }
- unset($sayHello);
- }
- /**
- * 当客户端发来消息时触发
- * @param int $client_id 连接id
- * @param mixed $message 具体消息
- */
- public static function onMessage($client_id, $message)
- {
- if ($message == '{"type":"ping"}') {
- 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);
- switch ($message['type']) {
- // 客服初始化
- case 'init':
- self::Kfinit($client_id, $message);
- break;
- // 顾客初始化
- case 'userInit';
- self::userInitEnt($client_id, $message);
- break;
- // 聊天
- case 'chatMessage':
- $client = Gateway::getClientIdByUid($message['data']['to_id']);
- if (!empty($client)) {
- $chat_message = [
- 'message_type' => 'chatMessage',
- 'data' => [
- 'name' => $message['data']['from_name'],
- 'avatar' => $message['data']['from_avatar'],
- 'id' => $message['data']['from_id'],
- 'time' => date('H:i'),
- 'content' => htmlspecialchars($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'],
- 'from_avatar' => $message['data']['from_avatar'],
- '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);
- }
- 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));
- unset($reLink);
- // 记录该客服与该会员的服务结束
- self::$db->query("update `ws_service_log` set `end_time` = " . time() . " , `status` = '2' where `client_id`= '" . $userClient . "'");
- // 从当前客服的服务表中删除这个会员
- $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':
- $client = Gateway::getClientIdByUid($userId);
- if (!empty($client)) {
- $userId = $message['data']['to_id'];
- $kfId = $message['data']['kf_id'];
- $groupId = $message['data']['group_id'];
- $clientId = $client['0'];
- $sql = "select 'servicelog_id' from `ws_service_log` where `user_id`= '$userId' and `client_id`= '$clientId' and `status`!= '2' and `group_id`!= '$groupId' and `kf_id`!= '$kfId'";
- $serviceLog = self::$db->query($sql);
- self::serverClose($clientId, $serviceLog[0]['servicelog_id']);
- }
- 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;
- break;
- case 'changeOtherhKeFu';
- self::changeOtherhKeFu($client_id, $message);
- break;
- // default:
- // Gateway::closeClient($client_id);
- }
- }
- //客户工单内部组转接
- public static function changeOtherhKeFu($client_id, $message)
- {
- $groupid = isset($message['group']) ? intval($message['group']) : 0;
- $toukfid = isset($message['toukfuid']) ? intval($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;
- }
- 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,'kf_id'=>intval(trim($toukfid,'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,'endtime'=>time()])->where('servicelog_id='.$oldlog['servicelog_id'])->query();
- unset($oldlog['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,
- 'kf_name' => Gateway::getSession($toukfid)['name'],
- ]
- ];
- Gateway::sendToClient($uidclientid, json_encode($noticeUser, 256));
- unset($noticeUser);
- // 通知客服端绑定会员的信息
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $uidclientid
- ]
- ];
- 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; //开发时使用
- //$logcheck = self::KfloginChedk($client_id, $message);
- if (!$logcheck) {
- Gateway::closeCurrentClient();
- return true;
- }
- // 如果该客服未在内存中记录则记录
- if (!isset($kfList[$message['group']]) || !array_key_exists($message['uid'], $kfList[$message['group']])) {
- do {
- $newKfList = $kfList;
- $newKfList[$message['group']][$message['uid']] = [
- 'id' => $message['uid'],
- 'name' => $message['name'],
- 'avatar' => $message['avatar'],
- 'client_id' => $client_id,
- 'task' => 0,
- 'status' => 2,// 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)
- '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'];
- // TODO 尝试拉取用户来服务 [二期规划]
- }
- //客服登陆验证
- 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);
- }
- 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'],
- '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;
- 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 ");
- }
- 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));
- 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;
- if (!empty($userList)) {
- $ischange = 0;
- foreach ($userList as $key => $val) {
- if ($val['id'] == $uid) {
- unset($userListNew[$key]);
- $ischange = 1;
- break;
- }
- }
- if ($ischange) {
- do {
- } while (!self::$global->cas('userList', $userList, $userListNew));
- }
- }
- 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' => '用户连接已断开',
- '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;
- // 将会员服务信息,从客服的服务列表中移除
- $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'])) {
- }; // 更新会员数据
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $res['data']['0'],
- 'kf_name' => $res['data']['1']
- ]
- ];
- Gateway::sendToClient($res['data']['3']['client_id'], json_encode($noticeUser, 256));
- unset($noticeUser);
- // 通知客服端绑定会员的信息
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $res['data']['3']
- ]
- ];
- 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,
- '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'],
- 'conversationId' => $conversationId,
- 'kf_name' => $res['data']['1']
- ]
- ];
- Gateway::sendToClient($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);
- // 写入接入值
- $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);
- }
- }
- /**
- * 给客服分配会员【均分策略】
- * @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) {
- return ['code' => -4];
- }
- $kfList[$group][$flag]['task'] += 1;
- array_push($onlineKF[$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' => 'chatMessage',
- 'data' => [
- 'name' => '智能助手',
- 'time' => date('H:i'),
- 'content' => $getRobot ? htmlspecialchars($getRobot[0]['robot_content']) : 'error',
- ]
- ];
- 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));
- }
- //踢掉同一用户的旧用户
- private static function tickOlduser($uid)
- {
- }
- }
|