| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524 |
- <?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'; //用户排队表
- const SERVICELOG = 'SERVICELOG'; //工单信息
- /**
- * 进程启动后初始化数据库连接
- */
- 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);
- // 管理员实时监控.
- /*Timer::add(6, function () {
- // 获取在线管理员总数.
- $adminListCount = self::$redis->lLen('adminList');
- // 获取在线管理员
- $adminList = self::$redis->lrange('adminList', 0, $adminListCount);
- if ($adminList) {
- self::systemMonitoring($adminList);
- }
- });*/
- // 检查对话时效给出.
- Timer::add(6, function () {
- // self::overTime();
- });
- }
- /**
- * 每分钟定时向客服发送一次排队情况
- */
- 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':
- self::chatMessage($message['data']);
- 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':
- self::KFStatusCg($client_id, $message);
- break;
- case 'changeOtherhKeFu';
- self::changeOtherhKeFu($client_id, $message);
- break;
- // 弹出评价.
- case 'getEvaluate';
- break;
- }
- }
- }
- //客服聊天
- public static function chatMessage($message)
- {
- // 获取当前会话工单.
- $data = json_decode(self::$redis->HGET('SERVICELOG', $message['conversationId']), true);
- $chat_message = [
- 'message_type' => 'chatMessage',
- 'data' => [
- 'name' => $message['from_name'],
- 'id' => $message['from_id'],
- 'time' => date('H:i'),
- 'content' => $message['content'],
- ]
- ];
- if (isset($message['isFirst']) && $message['isFirst']) {
- $data['alarm_corresponding'] = time() - $data['start_time'];
- }
- // 发送消息.
- if (substr($message['from_id'], 0, 2) === 'KF') {
- $data['userLastTime'] = time();
- Gateway::sendToClient($data['client_id'], json_encode($chat_message));
- } else {
- $data['serverLastTime'] = time();
- Gateway::sendToClient($data['kf_client_id'], json_encode($chat_message));
- }
- // 保存修改后的工单信息.
- self::$redis->HSET('SERVICELOG', $message['conversationId'], $data);
- // 聊天信息入库
- $insertChatData = [
- '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($insertChatData)->query();
- }
- //得到一个用户详细信息
- 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()
- {
- $return = [
- 'message_type' => 'onlinekfs',
- 'data' => [],
- ];
- $nowkfid = isset($_SESSION['uid']) ? $_SESSION['uid'] : 0;
- $fromgrouupid = isset($_SESSION['group']) ? $_SESSION['group'] : 0;
- if (empty($fromgrouupid) || empty($nowkfid)) {
- return $return;
- }
- $online = self::getOnlineKfData(0, 1);
- if (empty($online)) {
- return $return;
- }
- $groupnamemap = self::$global->groupmap;
- $ret = [];
- foreach ($online as $uinfo) {
- if ($nowkfid == $uinfo['id']) {
- continue;
- }
- $ret[] = ['groupid' => $uinfo['group'], 'groupname' => $groupnamemap[$uinfo['group']], 'kfuid' => $uinfo['id'], 'kfname' => $uinfo['name'], 'kfjobname' => $uinfo['job_name']];
- }
- $return['data'] = $ret;
- return $return;
- }
- public static function KFStatusCg($client_id, $message)
- {
- if (!isset($_SESSION['iskefu']) || $_SESSION['iskefu'] != 1) {
- return;
- }
- $userId = $message['data']['uid'];
- $status = intval($message['data']['status']);
- if (!in_array($status, [1, 2, 3])) {
- return false;
- }
- $oldstatus = '';
- $kfinfo = self::$redis->hget(self::KFINFOKEY, $userId);
- if (empty($kfinfo)) {
- return false;
- }
- $kfinfo = json_decode($kfinfo, true);
- if (!$kfinfo) {
- return false;
- }
- if ($kfinfo['status'] != $status) {
- $oldstatus = $kfinfo['status'];
- $kfinfo['status'] = $status;
- self::$redis->hset(self::KFINFOKEY, $userId, json_encode($kfinfo, 256));
- }
- self::writeLogKfStatus($userId, $status);
- Gateway::sendToCurrentClient(json_encode(['message_type' => 'cgstatus', 'data' => ['new_status' => $status, 'old_status' => $oldstatus]]));
- 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,
- 'intime' => time(),
- 'signature' => $kfinfo['signature'],
- 'status' => 2, // 1为在线(接收分配、接收消息)2为隐身(不接收分配、只接收消息)3、休息
- 'user_info' => [], //在会话的用户cid key为clientid ,值为工单号
- ];
- 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'");
- if ($systemConfigData) {
- $adminList = self::$redis->lpush('adminList', $client_id);
- self::systemMonitoring([$client_id]);
- } else {
- $chat_message = [
- 'message_type' => 'tips',
- 'data' => '管理员不存在'
- ];
- Gateway::sendToClient($client_id, json_encode($chat_message, 256));
- 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::closeCurrentClient();
- }
- $loginstate = self::$logic->userIsLogin($client_id, $uid, $group);
- if ($loginstate == 1) {
- self::MySendMsg($oldcontid, (json_encode(['message_type' => 'reLoginErr', 'msg' => '正在登陆中,请稍后...'], 256)));
- Gateway::closeCurrentClient();
- 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' => '',
- 'ip' => $_SESSION['remotip'],
- '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);
- }
- /**
- * 当用户断开连接时触发
- * @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;
- if (!empty($user_info)) {
- foreach ($user_info as $val => $serverid) {
- //self::serverClose($serverid);
- self::MySendMsg($val, json_encode(['message_type' => 'serviceoffline', 'msg' => '客户人员下线!'], 256));
- Gateway::closeClient($val);
- sleep(1);
- }
- }
- $sql = "update `ws_service_log` set `status` = '2',end_time=$now,`servicelog_close_type` = 4 where start_time>=$starttime and kf_id=$kfid and group_id=$group and `status`!=2 ";
- echo "客服退出: " . $uid . "\n";
- self::$db->query($sql);
- self::$db->update('ws_users')->cols(array('online_status' => 0, 'online_connectid' => ''))->where('id=' . $kfid)->query();
- self::writeLogKfStatus($uid, 0);
- self::$redis->hdel(self::KFINFOKEY, $uid);
- 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($servicelogId)
- {
- // 获取当前工单数据.
- $data = json_decode(self::$redis->HGET('SERVICELOG', $servicelogId), true);
- // 获取当前工单数据.
- $kfInfo = json_decode(self::$redis->HGET('KFINFO', 'KF' . $data['kf_id']), true);
- // 删除当前工单.
- //self::$redis->hdel('SERVICELOG', $servicelogId);
- // 当前服务客服删除当前人员.
- $kfUserList = self::ArrayDataopt($kfInfo['user_info'], $data['client_id'], 0);
- return;
- if (isset($kfInfo)) {
- print_r([$kfInfo, $servicelogId]);
- die;
- }
- // 当前客服所接待人员.
- $kfInfo['user_info'] = $kfUserList;
- $kfInfo['task'] = count($kfUserList);
- // 存入客服信息.
- $redis->HSET('KFINFO', 'KF' . $data['kf_id'], $kfInfo);
- // 将数据存入数据库.
- }
- /**
- * 有人退出
- * @param $group
- */
- private static function userOfflineTask($group)
- {
- }
- /**
- * 有人进入执行分配
- * @param $client_id
- * @param $group
- * @param $uid
- */
- private static function userOnlineTask($group = 0, $uid = 0)
- {
- $allusergkarr = self::getUserListData();
- if (empty($allusergkarr)) {
- return;
- }
- $allkfgkarr = self::getWorkKfData();
- if (empty($allkfgkarr)) {
- return;
- }
- $maxset = (self::$global->systemconfig)['KFMaxServices'] ?? 5;
- $maxset = intval($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]) || count($allkfgkarr[$group]) <= 0) {
- //所属客服组无人在线
- continue;
- }
- $nowkfs = $allkfgkarr[$group];
- $count = count($nowkfs);
- $i = 0;
- foreach ($gusersArr as $user) {
- if ($nowkfs[$i]['task'] > $maxset) {
- break;
- }
- $nowkfs[$i]['task']++;
- self::BeginTalk($nowkfs[$i]['id'], $user['id'], $group, 0, $user);
- self::$redis->hdel(self::USERLIST, $user['id']);
- $i++;
- if ($i >= $count) {
- $i = 0;
- }
- }
- }
- return;
- }
- //开启一个会话
- private static function BeginTalk($kfuid, $uid, $group, $serviceid = 0, $userInfo = false)
- {
- $serviceid = intval($serviceid);
- if (!$userInfo) {
- $userInfo = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
- }
- $kfinfo = json_decode(self::$redis->hget(self::KFINFOKEY, $kfuid), true);
- if (empty($userInfo) || empty($kfinfo)) {
- return false;
- }
- $server = [];
- $armarr = [];
- if ($serviceid) {
- $server = self::$db->select('*')->from('ws_service_log')->where("servicelog_id=$serviceid ")->row();
- if ($server) {
- $armarr = self::$db->select('*')->from('ws_alarm')->where("servicelog_id=$serviceid ")->row();
- }
- }
- if (empty($server)) {
- $array = [
- 'user_id' => $uid,
- 'client_id' => $userInfo['client_id'],
- 'user_name' => $userInfo['name'],
- 'user_avatar' => $userInfo['avatar'],
- 'user_ip' => $userInfo['ip'],
- 'kf_id' => self::getkfid($kfuid),
- 'start_time' => time(),
- 'group_id' => $userInfo['group'],
- 'website' => $userInfo['website'],
- 'system' => $userInfo['system'],
- 'browse' => $userInfo['browse'],
- 'intime' => $userInfo['intime'],
- ];
- $serviceid = self::$db->insert('ws_service_log')->cols($array)->query();
- $server = array_merge(['servicelog_id' => $serviceid], $array);
- $armid = self::$db->insert('ws_alarm')->cols(['servicelog_id' => $serviceid])->query();
- $armarr = self::$db->select('*')->from('ws_alarm')->where("alarm_id=$armid")->row();
- }
- $redisData = array_merge($server, $armarr, ['kf_client_id' => $kfinfo['client_id']]);
- self::$redis->hset(self::SERVICELOG, $serviceid, json_encode($redisData, 256));
- $kfinfo['user_info'] = array_merge($kfinfo['user_info'], [$userInfo['client_id'] => $serviceid]);
- $kfinfo['task'] = count($kfinfo['user_info']);
- self::$redis->hset(self::KFINFOKEY, $kfuid, json_encode($kfinfo, 256));
- $userInfo['serverid'] = $serviceid;
- $userInfo['kfuid'] = $kfuid;
- self::$redis->hset(self::USERINFOKEY, $uid, json_encode($userInfo, 256));
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $kfuid,
- 'conversationId' => $serviceid,
- 'serverInfo' => $kfinfo,
- 'kf_name' => $kfinfo['job_name']
- ]
- ];
- self::MySendMsg($userInfo['client_id'], json_encode($noticeUser, 256));
- $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' => [
- 'id' => self::getkfuid($kfinfo['id']),
- 'name' => $kfinfo['name'],
- 'time' => date('H:i'),
- 'content' => $sayHello['0']['word']
- ]
- ];
- self::MySendMsg($userInfo['client_id'], json_encode($chat_message, 256));
- unset($chat_message);
- }
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $userInfo,
- 'conversationId' => $serviceid,
- ]
- ];
- self::MySendMsg($kfinfo['client_id'], json_encode($noticeKf, 256));
- unset($noticeKf);
- $key = date('Ymd') . 'success_in';
- $oldKey = date('Ymd', strtotime('-1 day')); // 删除前一天的统计值
- unset(self::$global->$oldKey);
- self::$global->increment($key);
- return;
- }
- //用户排队数据 按组
- private static function getUserListData()
- {
- $alluser = self::$redis->hgetall(self::USERLIST);
- if (empty($alluser)) {
- return false;
- }
- $allusergkarr = [];
- foreach ($alluser as $val) {
- $now = json_decode($val, true);
- if ($now) {
- //用户分组后的数组
- $allusergkarr[$now['group']][] = $now;
- }
- }
- foreach ($allusergkarr as $group => $nowgroups) {
- usort($allusergkarr[$group], function ($a, $b) {
- if ($a['intime'] == $b['intime']) {
- return 0;
- }
- return ($a['intime'] > $b['intime']) ? 1 : -1;
- });
- }
- if (!$allusergkarr) {
- return false;
- }
- unset($alluser);
- return $allusergkarr;
- }
- //找到可以接工单的客服 按组
- private static function getWorkKfData()
- {
- $allkfs = self::$redis->hgetall(self::KFINFOKEY);
- if (empty($allkfs)) {
- return false;
- }
- $allkfgkarr = [];
- foreach ($allkfs as $val) {
- $now = json_decode($val, true);
- 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']) {
- if ($a['intime'] == $b['intime']) {
- return 0;
- }
- return ($a['intime'] > $b['intime']) ? 1 : -1;
- }
- return ($a['task'] > $b['task']) ? 1 : -1;
- });
- }
- unset($allkfs);
- return $allkfgkarr;
- }
- //找到用户是否有一条未关闭的会话
- private static function UserHasOldTalk($uid)
- {
- $uid = intval($uid);
- $start_time = time() - 86400;
- $ret = self::$db->select('*')->from('ws_service_log')->where("start_time>=$start_time and user_id=$uid and status!=2 ")->orderByDESC(['servicelog_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;
- }
- //$sayHello = self::$db->query('select `word`,`status` from `ws_reply` where `id` = 2');
- }
- /**
- * 超时
- * @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') {
- $configOvertime = $v;
- } elseif ($v['systemconfig_enName'] == 'unoperated') {
- $configUnoperated = $v;
- }
- }
- // 查询未断开的工单.
- $serviceLog = self::$redis->hGetall('SERVICELOG');
- $setOvertime = strtotime('-' . ($configOvertime['systemconfig_data'] - 60) . ' second');
- $overtime = strtotime('-' . ($configOvertime['systemconfig_data']) . ' second');
- $setUnoperated = strtotime('-' . ($configUnoperated['systemconfig_data'] - 60) . ' second');
- $unoperated = strtotime('-' . ($configUnoperated['systemconfig_data']) . ' second');
- foreach ($serviceLog as $k => $v) {
- // 无效会话关闭.如果没有说一句话.
- $data = json_decode($v, true);
- if (!isset($data['userLastTime'])) {
- if ($data['start_time'] <= $unoperated) {
- self::serverClose($k);
- // 如果小于设定时间前一分钟则给出提示.
- } elseif ($data['start_time'] <= $setUnoperated) {
- $chat_message = [
- 'message_type' => 'overtime',
- 'data' => [
- 'content' => self::$global->unoperated['systemconfig_content'],
- ]
- ];
- Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
- }
- // 双方静默超时.
- } elseif ($data['userLastTime'] <= $overtime && $data['serverLastTime'] <= $overtime) {
- self::serverClose($k);
- // 如果小于设定时间前一分钟则给出提示.
- } elseif ($data['userLastTime'] <= $setOvertime && $data['serverLastTime'] <= $setOvertime) {
- $chat_message = [
- 'message_type' => 'overtime',
- 'data' => [
- 'content' => self::$global->overtime['systemconfig_content'],
- ]
- ];
- Gateway::sendToClient($data['client_id'], json_encode($chat_message, 256));
- }
- }
- }
- /**
- * 系统监控
- * @param $message 数据
- */
- private static function systemMonitoring($adminList)
- {
- // 查询正进行的工单.
- $serviceLog = self::$redis->hGetall('SERVICELOG');
- // 查询系统设置表.
- $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; // 差评总次数.
- $overtimeNumber = 0; // 会话超时总次数.
- $overtimeTime = []; // 每次会话超时时间.
- $userSensitive = 0; // 用户敏感词报警总次数.
- $serverSensitive = 0; // 客服敏感词报警总次数.
- $csdNumber = 0; // 响应超时总次数.
- $csdTime = []; // 每次响应超时时间.
- foreach ($serviceLog as $k => $v) {
- $data = json_decode($v, true);
- // 工单报警次数.
- $allCount = 0;
- if ($data['evaluate_id'] == 3) {
- $evaluateCount++; // 差评次数.
- $allCount++; // 工单报警次数.
- }
- // 会话超时.
- $duration = time() - $data['start_time'];
- if ($duration > $verifyAllTime) {
- $overtimeNumber++; // 会话超时总次数.
- $allCount++; // 工单报警次数.
- $overtimeTime[] = $duration; // 响应超时时间.
- }
- // 敏感词报警.
- $userSensitive += $data['alarm_userSensitive'];
- $allCount += $data['alarm_userSensitive'];
- $serverSensitive += $data['alarm_serverSensitive'];
- $allCount += $data['alarm_serverSensitive'];
- // 响应超时.
- if ($data['alarm_corresponding'] > $verifyReturnTime) {
- $csdTime[] = $data['alarm_corresponding']; // 响应超时时间.
- $csdNumber++; // 响应超时总次数.
- $allCount++; // 工单报警次数.
- }
- $serviceLog[$k] = $data;
- $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));
- }
- }
- //客户工单内部组转接
- public static function changeOtherhKeFu($client_id, $smessage)
- {
- $message = $smessage['data'];
- $groupid = isset($message['fromgroup']) ? intval($message['fromgroup']) : 0;
- $groupidto = isset($message['togroup']) ? intval($message['togroup']) : 0;
- $toukfid = isset($message['toukfuid']) ? $message['toukfuid'] : 0;
- $fromkfuid = isset($message['fromkfuid']) ? $message['fromkfuid'] : 0;
- $uid = isset($message['uid']) ? intval($message['uid']) : 0;
- $word = isset($message['word']) ? $message['word'] : '';
- if (empty($groupid) || empty($groupidto) || empty($toukfid) || empty($fromkfuid) || empty($uid) || ($toukfid == $fromkfuid)) {
- self::DebugOut('changeOtherhKeFu exit1...');
- return false;
- }
- if (!Gateway::isUidOnline($toukfid) || !Gateway::isUidOnline($uid)) {
- self::DebugOut('changeOtherhKeFu exit2...');
- return false;
- }
- $kf_info_from = json_decode(self::$redis->hget(self::KFINFOKEY, $fromkfuid), true);
- $kf_info_to = json_decode(self::$redis->hget(self::KFINFOKEY, $toukfid), true);
- $user_info = json_decode(self::$redis->hget(self::USERINFOKEY, $uid), true);
- $serviceid = intval($user_info['serverid']);
- if (empty($kf_info_from) || empty($kf_info_to) || empty($user_info) || empty($serviceid)) {
- self::DebugOut('changeOtherhKeFu exit23...');
- return false;
- }
- if ($kf_info_to['status'] != 1) {
- self::DebugOut('changeOtherhKeFu exit4...');
- return false;
- }
- /////////取消原有会话,开启新会话
- $oldlog = self::$db->select('*')->from('ws_service_log')->where('servicelog_id=:servicelog_id ')->bindValues(['servicelog_id' => $serviceid])->orderByDESC(['servicelog_id'])->row();
- if (!$oldlog) {
- self::DebugOut('changeOtherhKeFu exit5...');
- return false;
- }
- // self::serverClose($serviceid);
- unset($oldlog['servicelog_id']);
- $oldlog = array_merge($oldlog, ['kf_id' => self::getkfid($toukfid), '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) {
- self::DebugOut('changeOtherhKeFu exit6...');
- return false;
- }
- ///更新redis数据
- $kf_info_from['user_info'] = self::ArrayDataopt($kf_info_from['user_info'], $user_info['client_id'], 0);
- $kf_info_from['task'] = count($kf_info_from['user_info']);
- self::$redis->hset(self::KFINFOKEY, $fromkfuid, json_encode($kf_info_from, 256));
- $kf_info_to['user_info'] = self::ArrayDataopt($kf_info_to['user_info'], $user_info['client_id'], 1, $new_id);
- $kf_info_to['task'] = count($kf_info_to['user_info']);
- self::$redis->hset(self::KFINFOKEY, $toukfid, json_encode($kf_info_to, 256));
- $user_info['kfuid'] = $toukfid;
- $user_info['serverid'] = $new_id;
- self::$redis->hset(self::USERINFOKEY, $uid, json_encode($user_info, 256));
- unset($kf_info_to['user_info']);
- ///通知消息发送--------------
- // 通知会员发送信息绑定客服的id
- $noticeUser = [
- 'message_type' => 'connect',
- 'data' => [
- 'kf_id' => $toukfid,
- 'conversationId' => $new_id,
- 'kf_name' => $kf_info_to['name'],
- 'serverInfo' => $kf_info_to,
- ]
- ];
- Gateway::sendToClient($user_info['client_id'], json_encode($noticeUser, 256));
- unset($noticeUser);
- // 通知客服端绑定会员的信息
- $userinfoarr = ['id' => $uid, 'name' => $oldlog['user_name'], 'avatar' => $oldlog['user_avatar'], 'website' => $oldlog['website'], 'browse' => $oldlog['browse'], 'system' => $oldlog['system'], 'ip' => $oldlog['user_ip'], 'group' => $oldlog['group_id'], 'client_id' => $oldlog['client_id']];
- $noticeKf = [
- 'message_type' => 'connect',
- 'data' => [
- 'user_info' => $userinfoarr,
- 'conversationId' => $new_id,
- ]
- ];
- Gateway::sendToClient($kf_info_to['client_id'], json_encode($noticeKf, 256));
- unset($noticeKf);
- self::servicetrutoother('OUT', $fromkfuid, $toukfid, $serviceid, $uid);
- self::servicetrutoother('IN', $toukfid, $fromkfuid, $new_id, $uid);
- //回转接人,转接成功
- Gateway::sendToCurrentClient(json_encode(['message_type' => 'trunconnect', 'data' => ['status' => 1]], 256));
- self::DebugOut('changekf 转换成功!');
- return;
- }
- //客服在线状态写组
- 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;
- $now = time();
- 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,end_time=$now where start_time>=$t and kf_id=$kfid and status!=2");
- self::$redis->hdel(self::KFINFOKEY, 'KF' . $kfid);
- } else {
- self::$redis->del(self::KFINFOKEY);
- self::$redis->del(self::USERLIST);
- self::$redis->del(self::USERINFOKEY);
- self::$db->query("update ws_service_log set status=2,end_time=$now 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);
- //每5分钟更新一次系统配置文件
- Timer::add(5, function () {
- self::userOnlineTask();
- });
- //初始化.....
- self::upsystemconfig();
- //每5分钟更新一次系统配置文件
- Timer::add(60 * 3, function () {
- self::upsystemconfig();
- });
- self::resetServiceLog();
- }
- }
- //调试使用
- public static function mydebug($client_id, $message)
- {
- }
- 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 (strtolower(substr($id, 0, 2)) == 'kf') {
- return intval(substr($id, 2));
- }
- return intval($id);
- }
- //从数组中获取参数
- 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[$now['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;
- }
- }
- }
|