| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161 |
- <?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 $redis = null;
- public static $logic = null;
- const KFINFOKEY = 'KFINFO'; //客服信息hash表
- const USERINFOKEY = 'USERINFO'; //用户信息hash表
- const USERLIST = 'USERLIST'; //用户排队表
- /**
- * 进程启动后初始化数据库连接
- */
- public static function onWorkerStart($worker)
- {
- include_once(__DIR__ . DIRECTORY_SEPARATOR . "Mlogic.php");
- self::$logic = Mlogic::GetInstance();
- self::$db = self::$logic->getDb();
- self::$redis = self::$logic->getRedis();
- self::$global = self::$logic->getGlbData();
- self::TimerThing($worker);
- }
- /**
- * 每分钟定时向客服发送一次排队情况
- */
- public static function lineup()
- {
- }
- /**
- * 当客户端连接时触发
- * 如果业务不需此回调可以删除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"}') {
- Gateway::sendToCurrentClient('{"type":"pong"}');
- return;
- } else {
- self::DebugOut($message, "OnMessage");
- }
- $message = json_decode($message, true);
- if (isset($message['type'])) {
- switch ($message['type']) {
- case 'mydebug':
- self::mydebug($client_id, $message['data']);
- break;
- // 管理员初始化
- 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 'kfgetuserinfo':
- $tmp_id = isset($message['data']['id']) ? $message['data']['id'] : 0;
- self::kfgetuserinfo($client_id, intval($tmp_id));
- break;
- case 'chatMessage':
- break;
- // 转接
- case 'changeGroup':
- break;
- case 'closeUser':
- break;
- // 机器人问答.
- case 'toRobot':
- self::toRobot($client_id, $message);
- break;
- // 评价.
- case 'evaluate':
- self::evaluate($client_id, $message);
- break;
- // 客服关闭会话.
- case 'kfCloseUser':
- break;
- // 客服更改状态.
- case 'kfOnline':
- break;
- case 'changeOtherhKeFu';
- break;
- // 弹出评价.
- case 'getEvaluate';
- break;
- }
- }
- }
- //得到一个用户详细信息
- public static function kfgetuserinfo($clientid, $id)
- {
- $ret = self::$db->select('*')->from('ws_account')->where('id=:id')->bindValues(['id' => $id])->row();
- Gateway::sendToClient($clientid, json_encode(['message_type' => 'userdetailinfo', 'data' => $ret]));
- return;
- }
- //获取在线客服列表
- public static function getkfonlines()
- {
- }
- //客户工单内部组转接
- public static function changeOtherhKeFu($client_id, $smessage)
- {
- return;
- }
- //获取某个用户全部信息
- public static function getClientIndo($id)
- {
- $ret = self::$db->from('ws_accounts')->select("*")->where(['id' => $id])->row();
- return $ret;
- }
- //客服接入sock,及初始化
- public static function Kfinit($client_id, $message)
- {
- $uid = self::getPars($message, 'uid');
- $group = intval(self::getPars($message, 'group', 0));
- if (empty($uid) || empty($group) || !isset(self::$global->groupmap[$group])) {
- self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "客服登陆参数错误"], 256));
- Gateway::closeCurrentClient();
- return;
- }
- //客服登陆验证 不符合的直接断掉
- $kfinfo = self::KfloginCheck($client_id, $message);
- if (empty($kfinfo)) {
- self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "验证失败"], 256));
- Gateway::closeCurrentClient();
- return true;
- } elseif ($kfinfo['status'] != 1) {
- self::MySendMsg($client_id, json_encode(["message_type" => 'checkfalse', 'data' => "禁用中..."], 256));
- Gateway::closeCurrentClient();
- return true;
- }
- $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
- if ($loginstate == 1) {
- self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
- Gateway::closeClient($oldcontid);
- return;
- }
- if ($loginstate == 2) {
- $oldcontids = Gateway::getClientIdByUid($uid);
- Gateway::sendToClient($oldcontids['0'], (json_encode(['message_type' => 'reLoginErr', 'msg' => '你的账号在其它登陆,本次下线'], 256)));
- Gateway::closeClient($oldcontids['0']);
- sleep(2);
- }
- self::$redis->hset('loginTmp:' . $uid, 'uid', time());
- self::$redis->expire('loginTmp:' . $uid, 5);
- $newinfo =
- [
- 'id' => 'KF' . $kfinfo['id'],
- 'name' => $kfinfo['user_name'],
- 'job_name' => $kfinfo['user_job_number'],
- 'avatar' => $kfinfo['user_avatar'],
- 'group' => $group,
- 'client_id' => $client_id,
- 'task' => 0,
- 'signature' => $kfinfo['signature'],
- 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
- 'user_info' => [], //在会话的用户cid
- 'serverids' => [],
- ];
- self::$redis->hset(self::KFINFOKEY, $uid, json_encode($newinfo, 256));
- $_SESSION['info'] = $newinfo;
- // 绑定 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',
- ];
- self::MySendMsg($client_id, json_encode($chat_message, 256));
- unset($chat_message);
- self::writeLogKfStatus($message['uid'], 2);
- return;
- }
- /**
- * 管理员
- * @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 KfloginCheck($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;
- $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)
- {
- $uid = intval($message['uid']);
- $group = intval($message['group']);
- if (isset(self::$global->groupmap[$group])) {
- self::MySendMsg($client_id, (json_encode(['message_type' => 'reLoginErr', 'msg' => '不存在客服组....'], 256)));
- Gateway::closeClient($oldcontid);
- }
- $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
- if ($loginstate == 1) {
- self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
- Gateway::closeClient($oldcontid);
- return;
- }
- $hisdata = self::$redis->hget(self::USERINFOKEY, $uid);
- if ($hisdata) {
- $hisdata = json_decode($hisdata, true);
- $oldclientid = $hisdata['client_id'];
- self::MySendMsg($oldclientid, json_encode(['type' => 'reLoginErr', 'msg' => '相同账号登陆,本次退出'], 256));
- Gateway::closeClient($oldclientid);
- sleep(1);
- }
- $onlinekf = self::getOnlineKfData($group, 1);
- if (empty($onlinekf)) {
- Gateway::sendToClient($client_id, json_encode(['message_type' => 'notice', 'content' => '暂时没有客服上班,请稍后再咨询。'], 256));
- Gateway::closeClient($client_id);
- return;
- }
- self::$redis->hset('loginTmp:' . $uid, 'uid', time());
- self::$redis->expire('loginTmp:' . $uid, 5);
- $data = [
- 'id' => $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(),
- 'kfuid' => '',
- 'serverid' => 0,
- 'client_id' => $client_id
- ];
- self::$redis->hset(self::USERLIST, $uid, json_encode($data, 256));
- self::$redis->hset(self::USERINFOKEY, $uid, json_encode($data, 256));
- // 写入接入值
- $key = date('Ymd') . 'total_in';
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- self::$global->increment($key);
- // 绑定 client_id 和 uid
- Gateway::bindUid($client_id, $uid);
- $_SESSION['iskefu'] = 0;
- $_SESSION['uid'] = $message['uid'];
- // 尝试分配新会员进入服务
- self::userOnlineTask($group, $uid = 0);
- }
- /**
- * 当用户断开连接时触发
- * @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: $uid - cid: $client_id - iskf: $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'];
- $uinfo = self::$redis->hget(self::KFINFOKEY, $uid);
- $uinfo = json_decode($uinfo, true);
- $user_info = $uinfo['user_info'];
- $kfid = self::getkfid($uid);
- $now = time();
- $starttime = $now - 86400 * 7;
- $serlogs = self::$db->select('servicelog_id')->from('ws_service_log')->where(" start_time>=$starttime kf_id=$kfid AND status !=2 ")->query();
- if (!empty($user_info)) {
- foreach ($user_info as $val) {
- self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
- Gateway::closeClient($val);
- }
- }
- self::$db->query("update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4 where kf_id=$uiiid and group_id=$group and `status`!=2 ");
- self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
- self::writeLogKfStatus($uid, 0);
- return;
- }
- //用户下线了 系统调用,不能手动调用
- public static function guestOffline($client_id, $uid)
- {
- $uid = intval($uid);
- $krclient_id = 0;
- $data = self::$redis->hget(self::USERINFOKEY, $uid);
- if (empty($data)) {
- return;
- }
- $info = json_decode($data, true);
- self::$redis->hdel(self::USERLIST, $uid);
- self::$redis->hdel(self::USERINFOKEY, $uid);
- if (!empty($info['kfuid'])) {
- $kfinfo = self::$redis->hget(self::KFINFOKEY, $info['kfuid']);
- if (!empty($kfinfo)) {
- $kfinfoArr = json_decode($kfinfo, true);
- $krclient_id = $kfinfoArr['client_id'];
- $kfinfoArr['user_info'] = self::ArrayDataopt($kfinfoArr['user_info'], $client_id, 0);
- $kfinfoArr['task'] = count($kfinfoArr['user_info']);
- self::$redis->hset(self::KFINFOKEY, $info['kfuid'], json_encode($kfinfoArr, 256));
- }
- }
- $chat_message = [
- 'message_type' => 'userClose',
- 'data' => [
- 'content' => '用户连接已断开',
- 'id' => $uid,
- 'time' => date('H:i'),
- ]
- ];
- $now = time();
- $serverid = intval($info['serverid']);
- if ($serverid) {
- $sql = "update `ws_service_log` set `status` = '3' where servicelog_id=$serverid ";
- self::$db->query($sql);
- }
- if ($krclient_id) {
- Gateway::sendToClient($krclient_id, json_encode($chat_message, 256));
- }
- return;
- }
- /**
- * 客服结束会话
- *
- * tips: 未有$client_id的关闭
- */
- public static function closeUser($servicelog_id, $userId, $kf_id, $groupId)
- {
- }
- /**
- * 客服结束会话
- * @param int $client_id 连接id
- *
- * tips: 当服务端主动退出的时候,会出现 exit status 9.原因是:服务端主动断开之后,连接的客户端会走这个方法,而短时间内进程
- * 需要处理这多的逻辑,又有cas操作,导致进程退出会超时,然后会被内核杀死,从而报出错误 9.实际对真正的业务没有任何的影响。
- */
- public static function serverClose($client_id, $servicelog_id, $userId, $kf_id, $groupId)
- {
- }
- /**
- * 有人退出
- * @param $group
- */
- private static function userOfflineTask($group)
- {
- }
- /**
- * 有人进入执行分配
- * @param $client_id
- * @param $group
- * @param $uid
- */
- private static function userOnlineTask($group = 0, $uid = 0)
- {
- $alluser = self::$redis->hgetall(self::USERLIST);
- if (empty($alluser)) {
- return true;
- }
- $allusergkarr = [];
- foreach ($alluser as $val) {
- $now = json_decode($val, 256);
- if ($now) {
- //用户分组后的数组
- $allusergkarr[$now['group']][] = $now;
- }
- }
- if (!$allusergkarr) {
- return false;
- }
- unset($alluser);
- $allkfs = self::$redis->hgetall(self::KFINFOKEY);
- if (empty($allkfs)) {
- return true;
- }
- $allkfgkarr = [];
- foreach ($allkfs as $val) {
- $now = json_decode($val, 256);
- if ($now && $now['status'] == 1) {
- //客分组后的数组
- $allkfgkarr[$now['group']][] = $now;
- }
- }
- if (!$allkfgkarr) {
- return false;
- }
- //客服每组按任务数由小到大排序
- foreach ($allkfgkarr as $group => $nowgroups) {
- usort($allkfgkarr[$group], function ($a, $b) {
- if ($a['task'] == $b['task']) {
- return 0;
- }
- return ($a > $b) ? 1 : -1;
- });
- }
- unset($allkfs);
- $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
- $maxset = inval($maxset);
- if ($group && $uid) {
- // 指定用指定组 [可能存在断线重连的情况] 如果存在旧的会话,直接连线客服和用户
- //否则按先到后到以及客服最大服务数限制
- $last = self::UserHasOldTalk($uid);
- if ($last) {
- self::BeginTalk(self::getkfuid($last['kf_id']), $uid, $last['group_id'], $last['servicelog_id']);
- return;
- }
- }
- //系统定时调用时,无组,无用户
- foreach ($allusergkarr as $group => $gusersArr) {
- if (isset($allkfgkarr[$group])) {
- //所属客服组无人在线
- continue;
- }
- $nowkfs = $allkfgkarr[$group];
- foreach ($gusersArr as $user) {
- }
- }
- return;
- }
- //开启一个会话
- private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0)
- {
- }
- //找到用户是否有一条未关闭的会话
- private static function UserHasOldTalk($uid)
- {
- $uid = intval($uid);
- $ret = self::$db->select('*')->from('ws_service_log')->where("user_id=$uid and status!=2")->orderByDESC(['id'])->row();
- return $ret;
- }
- //今天排序累加
- private static function todayqueuelength()
- {
- $dtype = 'user.queue.day.length';
- $today = date("Y-m-d");
- $sret = self::$db->select('*')->from('ws_countmidtable')->where('dtype=:dtype and mdate=:mdate')->bindValues(array('dtype' => $dtype, 'mdate' => $today))->row();
- if ($sret) {
- self::$db->update('ws_countmidtable')->cols(array('dcontent' => intval($sret['dcontent']) + 1))->where('id=' . $sret['id'])->query();
- } else {
- self::$db->insert('ws_countmidtable')->cols(array(
- 'dtype' => $dtype,
- 'mdate' => $today,
- 'datatype' => 1,
- 'dcontent' => 1))->query();
- }
- }
- //客服工单转单
- private static function servicetrutoother($type, $owen, $otherkfid, $serverid, $clientuid)
- {
- $owen = intval(substr($owen, 2));
- $otherkfid = intval(substr($otherkfid, 2));
- self::$db->insert('ws_serviceturn_log')->cols(array(
- 'stype' => $type,
- 'uid' => $owen,
- 'tuid' => $otherkfid,
- 'serverid' => $serverid,
- 'guestuid' => $clientuid
- ))->query();
- }
- /**
- * 给客服分配会员【均分策略】
- * @param $kfList
- * @param $userList
- * @param $group
- * @param $total
- */
- private static function assignmentTask($kfList, $userList, $group, $total, $uid = 0)
- {
- }
- /**
- * 获取最大的服务人数
- * @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)
- {
- }
- /**
- * 机器人问答
- * @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',
- ]
- ];
- 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`,`user_id`,`kf_id`,`group_id` 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 from_id not like 'KF%' 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) {
- $servicelog_id = $v['servicelog_id'];
- self::$db->query("update `ws_service_log` set `servicelog_close_type` = 1 where `servicelog_id`= '$servicelog_id'");
- self::serverClose($v['client_id'], $servicelog_id, $v['user_id'], 'KF' . $v['kf_id'], $v['group_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) {
- // 如果对话为客服的最后一次对话且时间小于设定时间则结束工单.
- if ($v['time_line'] <= $overtime) {
- $found_key = array_search($v['servicelog_id'], array_column($serviceLog, 'servicelog_id'));
- $servicelog_id = $v['servicelog_id'];
- self::$db->query("update `ws_service_log` set `servicelog_close_type` = 2 where `servicelog_id`= '$servicelog_id'");
- self::serverClose($serviceLog[$found_key]['client_id'], $servicelog_id, $serviceLog[$found_key]['user_id'], 'KF' . $serviceLog[$found_key]['kf_id'], $serviceLog[$found_key]['group_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`,`systemconfig_enName` FROM `ws_systemconfig` WHERE `systemconfig_enName`='verifyReturnTime' or `systemconfig_enName`='verifyAllTime'");
- $returnTimeKey = array_search('verifyReturnTime', array_column($systemconfig, 'systemconfig_enName'));
- // 质检会话响应时长.
- $verifyReturnTime = $systemconfig[$returnTimeKey]['systemconfig_data'];
- $allTimeKey = array_search('verifyAllTime', array_column($systemconfig, 'systemconfig_enName'));
- // 质检会话时长.
- $verifyAllTime = $systemconfig[$allTimeKey]['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;
- }
- self::DebugOut([$serviceLog, $csdTime, $verifyReturnTime], 'systemMonitoring');
- // 查询对话时效设置.
- 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');
- $ip = isset($_SESSION['remotip']) ? $_SESSION['remotip'] : '';
- $sql = "insert into ws_kfonline(uid,status,uptime,ip) values('$kf',$status,'$now','$ip') ON DUPLICATE KEY UPDATE status=$status,uptime='$now' ";
- self::$db->query($sql);
- }
- } else {
- self::$db->query("delete from ws_kfonline ");
- }
- }
- public static function resetServiceLog($kfid = 0)
- {
- $t = time() - 24 * 3600 * 7;
- if ($kfid) {
- if ((substr($kfid, 0, 2) == 'KF')) {
- $kfid = intval(substr($kfid, 2));
- }
- $kfid = intval($kfid);
- self::$db->query("update ws_service_log set status=2 where kf_id=$kfid and start_time>=$t and status!=2");
- self::$redis->hdel('KFINFO', 'KF' . $kfid);
- } else {
- self::$redis->del('KFINFO');
- self::$redis->del('USERINFOKEY');
- self::$db->query("update ws_service_log set status=2 where start_time>=$t and status!=2");
- }
- }
- public static function onWorkerStop($businessWorker)
- {
- if ($businessWorker->worker_id == 1) {
- self::resetServiceLog();
- }
- }
- //用户下线通知
- private static function userCloseNotice($client_id, $cuid, $group)
- {
- }
- //踢掉同一用户的旧用户
- private static function tickOlduser($uid)
- {
- }
- private static function DebugOut($msg, $title = '', $type = 'info')
- {
- $config = self::$global->systemconfig;
- if (!isset($config['isdebug']) || empty($config['isdebug']['systemconfig_data'])) {
- return;
- }
- if (!is_string($msg)) {
- $msg = json_encode([$msg], 256);
- }
- $msg = date("Y-m-d H:i:s") . ' - ' . $type . ' - ' . $title . ' - ' . $msg . "\n";
- echo $msg;
- }
- //定时器相关
- private static function TimerThing($worker)
- {
- // 当天的累积接入值
- $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);
- //初始化.....
- self::upsystemconfig();
- //每5分钟更新一次系统配置文件
- Timer::add(60 * 3, function () {
- self::upsystemconfig();
- });
- self::resetServiceLog();
- }
- }
- //调试使用
- public static function mydebug($client_id, $message)
- {
- $date = self::$db->select('*')->from('ws_service_log')->where('servicelog_id= :id')->bindValues(['id' => 1])->row();
- self::$redis->hset('SERVICELOG', 1, json_encode($date, 256));
- }
- public static function MySendMsg($clientId, $msg)
- {
- Gateway::sendToClient($clientId, $msg);
- }
- //得到客服的UID字符值
- public static function getkfuid($uid)
- {
- if (substr($uid, 0, 2) == 'KF') {
- return $uid;
- } else {
- return 'KF' . intval($uid);
- }
- }
- //得到客服的ID整数值
- public static function getkfid($id)
- {
- if ($id == intval($id)) {
- return $id;
- } else {
- return intval(substr($id, 2));
- }
- }
- //从数组中获取参数
- public static function getPars($array, $key, $default = '')
- {
- if (isset($array[$key])) {
- return $array[$key];
- }
- return $default;
- }
- //获取在线客服信息
- public static function getOnlineKfData($group = 0, $status = 0)
- {
- $all = self::$redis->hgetall(self::KFINFOKEY);
- if (!$all) {
- return false;
- }
- $return = [];
- foreach ($all as $val) {
- $now = json_decode($val, true);
- if ($group) {
- if ($now['group'] != $group) {
- continue;
- }
- }
- if ($status) {
- if ($now['status'] != $status) {
- continue;
- }
- }
- $return[$val['id']] = $now;
- }
- return $return;
- }
- //找到在排队的用户按时间先后顺序
- public static function getUselistData($group)
- {
- $all = self::$redis->hgetall(self::USERLIST);
- if (!$all) {
- return false;
- }
- $return = [];
- foreach ($all as $val) {
- $now = json_decode($val, true);
- if ($group == $now['group']) {
- $return[] = $now;
- }
- }
- usort($return, function ($a, $b) {
- if ($a['intime'] == $b['intime']) {
- return 0;
- }
- return $a['intime'] > $b['intime'] ? 1 : -1;
- });
- return $return;
- }
- //对客服的用户user_info数组进行加减操作 $clientid用户连接号 opt=1添加 0删除 $serverid服务工单号
- public static function ArrayDataopt($array, $clientid, $opt, $serverid = 0)
- {
- if (!is_array($array)) {
- return [];
- }
- if ($opt == 0) {
- if (isset($array[$clientid])) {
- unset($array[$clientid]);
- }
- return $array;
- } else {
- $array[$clientid] = $serverid;
- return $array;
- }
- }
- }
|